title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Entity Framework - Validation
In this chapter let us learn about the validation techniques that can be used in ADO.NET Entity Framework to validate the model data. Entity Framework provides a great variety of validation features that can be implemented to a user interface for client-side validation or can be used for server-side validation. In Entity Framework, data validation is part of the solution for catching bad data in an application. In Entity Framework, data validation is part of the solution for catching bad data in an application. Entity Framework validates all data before it is written to the database by default, using a wide range of data validation methods. Entity Framework validates all data before it is written to the database by default, using a wide range of data validation methods. However, Entity Framework comes after the user-interface data validation. So in that case there is a need for entity validation to handle any exceptions that EF throws and show a generic message. However, Entity Framework comes after the user-interface data validation. So in that case there is a need for entity validation to handle any exceptions that EF throws and show a generic message. There are some techniques of data validation to improve your error checking and how to pass error messages back to the user. There are some techniques of data validation to improve your error checking and how to pass error messages back to the user. DbContext has an Overridable method called ValidateEntity. When you call SaveChanges, Entity Framework will call this method for each entity in its cache whose state is not Unchanged. You can put validation logic directly in here as shown in the following example for the Student Entity. public partial class UniContextEntities : DbContext { protected override System.Data.Entity.Validation .DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, System.Collections.Generic.IDictionary<object, object> items) { if (entityEntry.Entity is Student) { if (entityEntry.CurrentValues.GetValue<string>("FirstMidName") == "") { var list = new List<System.Data.Entity .Validation.DbValidationError>(); list.Add(new System.Data.Entity.Validation .DbValidationError("FirstMidName", "FirstMidName is required")); return new System.Data.Entity.Validation .DbEntityValidationResult(entityEntry, list); } } if (entityEntry.CurrentValues.GetValue<string>("LastName") == "") { var list = new List<System.Data.Entity .Validation.DbValidationError>(); list.Add(new System.Data.Entity.Validation .DbValidationError("LastName", "LastName is required")); return new System.Data.Entity.Validation .DbEntityValidationResult(entityEntry, list); } return base.ValidateEntity(entityEntry, items); } } In the above ValidateEntity method, Student entity FirstMidName and LastName properties are checked if any of these property have an empty string, then it will return an error message. Let’s take a look at a simple example in which a new student is created, but the student’s FirstMidName is empty string as shown in the following code. class Program { static void Main(string[] args) { using (var context = new UniContextEntities()) { Console.WriteLine("Adding new Student to the database"); Console.WriteLine(); try { context.Students.Add(new Student() { FirstMidName = "", LastName = "Upston" }); context.SaveChanges(); } catch (DbEntityValidationException dbValidationEx) { foreach (DbEntityValidationResult entityErr in dbValidationEx.EntityValidationErrors) { foreach (DbValidationError error in entityErr.ValidationErrors) { Console.WriteLine("Error: {0}",error.ErrorMessage); } } } Console.ReadKey(); } } } When the above example is compiled and executed, you will receive the following error message on the console window. Adding new Student to the database Error: FirstMidName is required We recommend you to execute the above example in a step-by-step manner for better understanding. 19 Lectures 5 hours Trevoir Williams 33 Lectures 3.5 hours Nilay Mehta 21 Lectures 2.5 hours TELCOMA Global 89 Lectures 7.5 hours Mustafa Radaideh Print Add Notes Bookmark this page
[ { "code": null, "e": 3345, "s": 3032, "text": "In this chapter let us learn about the validation techniques that can be used in ADO.NET Entity Framework to validate the model data. Entity Framework provides a great variety of validation features that can be implemented to a user interface for client-side validation or can be used for server-side validation." }, { "code": null, "e": 3447, "s": 3345, "text": "In Entity Framework, data validation is part of the solution for catching bad data in an application." }, { "code": null, "e": 3549, "s": 3447, "text": "In Entity Framework, data validation is part of the solution for catching bad data in an application." }, { "code": null, "e": 3681, "s": 3549, "text": "Entity Framework validates all data before it is written to the database by default, using a wide range of data validation methods." }, { "code": null, "e": 3813, "s": 3681, "text": "Entity Framework validates all data before it is written to the database by default, using a wide range of data validation methods." }, { "code": null, "e": 4009, "s": 3813, "text": "However, Entity Framework comes after the user-interface data validation. So in that case there is a need for entity validation to handle any exceptions that EF throws and show a generic message." }, { "code": null, "e": 4205, "s": 4009, "text": "However, Entity Framework comes after the user-interface data validation. So in that case there is a need for entity validation to handle any exceptions that EF throws and show a generic message." }, { "code": null, "e": 4330, "s": 4205, "text": "There are some techniques of data validation to improve your error checking and how to pass error messages back to the user." }, { "code": null, "e": 4455, "s": 4330, "text": "There are some techniques of data validation to improve your error checking and how to pass error messages back to the user." }, { "code": null, "e": 4743, "s": 4455, "text": "DbContext has an Overridable method called ValidateEntity. When you call SaveChanges, Entity Framework will call this method for each entity in its cache whose state is not Unchanged. You can put validation logic directly in here as shown in the following example for the Student Entity." }, { "code": null, "e": 6020, "s": 4743, "text": "public partial class UniContextEntities : DbContext {\n\n protected override System.Data.Entity.Validation\n .DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, \n System.Collections.Generic.IDictionary<object, object> items) {\n\n if (entityEntry.Entity is Student) {\n\n if (entityEntry.CurrentValues.GetValue<string>(\"FirstMidName\") == \"\") {\n\n var list = new List<System.Data.Entity\n .Validation.DbValidationError>();\n\n list.Add(new System.Data.Entity.Validation\n .DbValidationError(\"FirstMidName\", \"FirstMidName is required\"));\n\n return new System.Data.Entity.Validation\n .DbEntityValidationResult(entityEntry, list);\n }\n }\n\n if (entityEntry.CurrentValues.GetValue<string>(\"LastName\") == \"\") {\n\n var list = new List<System.Data.Entity\n .Validation.DbValidationError>();\n\n list.Add(new System.Data.Entity.Validation\n .DbValidationError(\"LastName\", \"LastName is required\"));\n\n return new System.Data.Entity.Validation\n .DbEntityValidationResult(entityEntry, list);\n }\n\n return base.ValidateEntity(entityEntry, items);\n }\n}" }, { "code": null, "e": 6205, "s": 6020, "text": "In the above ValidateEntity method, Student entity FirstMidName and LastName properties are checked if any of these property have an empty string, then it will return an error message." }, { "code": null, "e": 6357, "s": 6205, "text": "Let’s take a look at a simple example in which a new student is created, but the student’s FirstMidName is empty string as shown in the following code." }, { "code": null, "e": 7170, "s": 6357, "text": "class Program {\n\n static void Main(string[] args) {\n\n using (var context = new UniContextEntities()) {\n\n Console.WriteLine(\"Adding new Student to the database\");\n Console.WriteLine();\n\n try {\n\n context.Students.Add(new Student() {\n FirstMidName = \"\",\n LastName = \"Upston\"\n });\n\n context.SaveChanges();\n } catch (DbEntityValidationException dbValidationEx) {\n\n foreach (DbEntityValidationResult entityErr in \n dbValidationEx.EntityValidationErrors) {\n\n foreach (DbValidationError error in entityErr.ValidationErrors) {\n Console.WriteLine(\"Error: {0}\",error.ErrorMessage);\n }\n }\n }\n\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 7287, "s": 7170, "text": "When the above example is compiled and executed, you will receive the following error message on the console window." }, { "code": null, "e": 7358, "s": 7287, "text": "Adding new Student to the database \nError: FirstMidName is required \n" }, { "code": null, "e": 7455, "s": 7358, "text": "We recommend you to execute the above example in a step-by-step manner for better understanding." }, { "code": null, "e": 7488, "s": 7455, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 7506, "s": 7488, "text": " Trevoir Williams" }, { "code": null, "e": 7541, "s": 7506, "text": "\n 33 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7554, "s": 7541, "text": " Nilay Mehta" }, { "code": null, "e": 7589, "s": 7554, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7605, "s": 7589, "text": " TELCOMA Global" }, { "code": null, "e": 7640, "s": 7605, "text": "\n 89 Lectures \n 7.5 hours \n" }, { "code": null, "e": 7658, "s": 7640, "text": " Mustafa Radaideh" }, { "code": null, "e": 7665, "s": 7658, "text": " Print" }, { "code": null, "e": 7676, "s": 7665, "text": " Add Notes" } ]
Refresh page after clearing all form fields in jQuery?
To refresh page, use the location.reload() in JavaScript. The sample JavaScript code is as follows − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initialscale=1.0"> <title>Document</title> </head> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <body> <form> <label for="userId"> UserName: <input type="text" > </label> <br> <label for="pass"> Password: <input type="password" > </label> <br> <button type="submit" id="RefreshPage" >Refresh Page</button> </form> <script> $('#RefreshPage').click(function() { location.reload(); }); </script> </body> </html> To run the above program, save the file name “anyName.html(index.html)” and right click on the file. Select the option “Open with Live Server” in VS Code editor. This will produce the following output − After filling the form, the snapshot is as follows − When you click the button “Refresh Page”, the page will refresh and the following output is visible −
[ { "code": null, "e": 1163, "s": 1062, "text": "To refresh page, use the location.reload() in JavaScript. The sample JavaScript code is as follows −" }, { "code": null, "e": 1174, "s": 1163, "text": " Live Demo" }, { "code": null, "e": 1885, "s": 1174, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initialscale=1.0\">\n<title>Document</title>\n</head>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n<body>\n<form>\n<label for=\"userId\">\nUserName:\n<input type=\"text\" >\n</label>\n<br>\n<label for=\"pass\">\nPassword:\n<input type=\"password\" >\n</label>\n<br>\n<button type=\"submit\" id=\"RefreshPage\" >Refresh Page</button>\n</form>\n<script>\n $('#RefreshPage').click(function() {\n location.reload();\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2047, "s": 1885, "text": "To run the above program, save the file name “anyName.html(index.html)” and right click on the\nfile. Select the option “Open with Live Server” in VS Code editor." }, { "code": null, "e": 2088, "s": 2047, "text": "This will produce the following output −" }, { "code": null, "e": 2141, "s": 2088, "text": "After filling the form, the snapshot is as follows −" }, { "code": null, "e": 2243, "s": 2141, "text": "When you click the button “Refresh Page”, the page will refresh and the following output is\nvisible −" } ]
Python | Check if element exists in list of lists
20 Mar, 2019 Given a list of lists, the task is to determine whether the given element exists in any sublist or not. Given below are a few methods to solve the given task.Method #1: Using any() any() method return true whenever a particular element is present in a given iterator. # Python code to demonstrate# finding whether element# exists in listof list # initialising nested listsini_list = [[1, 2, 5, 10, 7], [4, 3, 4, 3, 21], [45, 65, 8, 8, 9, 9]] elem_to_find = 8elem_to_find1 = 0 # element exists in listof listor not?res1 = any(elem_to_find in sublist for sublist in ini_list)res2 = any(elem_to_find1 in sublist for sublist in ini_list) # printing resultprint(str(res1), "\n", str(res2)) True False Method #2: Using operator in The ‘in’ operator is used to check if a value exists in a sequence or not. Evaluates to true if it finds a variable in the specified sequence and false otherwise. # Python code to demonstrate# finding whether element# exists in listof list # initialising nested listsini_list = [[1, 2, 5, 10, 7], [4, 3, 4, 3, 21], [45, 65, 8, 8, 9, 9]] elem = 8elem1 = 0 # element exists in listof listor not?res1 = elem in (item for sublist in ini_list for item in sublist)res2 = elem1 in (item for sublist in ini_list for item in sublist) # printing resultprint(str(res1), "\n", str(res2)) True False Method #3: Using itertools.chain() Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. # Python code to demonstrate# finding whether element# exists in listof listfrom itertools import chain # initialising nested listsini_list = [[1, 2, 5, 10, 7], [4, 3, 4, 3, 21], [45, 65, 8, 8, 9, 9]] elem_to_find = 8elem_to_find1 = 0 # element exists in listof listor not?res1 = elem_to_find in chain(*ini_list)res2 = elem_to_find1 in chain(*ini_list) # printing resultprint(str(res1), "\n", str(res2)) True False Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 53, "s": 25, "text": "\n20 Mar, 2019" }, { "code": null, "e": 234, "s": 53, "text": "Given a list of lists, the task is to determine whether the given element exists in any sublist or not. Given below are a few methods to solve the given task.Method #1: Using any()" }, { "code": null, "e": 321, "s": 234, "text": "any() method return true whenever a particular element is present in a given iterator." }, { "code": "# Python code to demonstrate# finding whether element# exists in listof list # initialising nested listsini_list = [[1, 2, 5, 10, 7], [4, 3, 4, 3, 21], [45, 65, 8, 8, 9, 9]] elem_to_find = 8elem_to_find1 = 0 # element exists in listof listor not?res1 = any(elem_to_find in sublist for sublist in ini_list)res2 = any(elem_to_find1 in sublist for sublist in ini_list) # printing resultprint(str(res1), \"\\n\", str(res2))", "e": 764, "s": 321, "text": null }, { "code": null, "e": 778, "s": 764, "text": "True \n False\n" }, { "code": null, "e": 808, "s": 778, "text": " Method #2: Using operator in" }, { "code": null, "e": 971, "s": 808, "text": "The ‘in’ operator is used to check if a value exists in a sequence or not. Evaluates to true if it finds a variable in the specified sequence and false otherwise." }, { "code": "# Python code to demonstrate# finding whether element# exists in listof list # initialising nested listsini_list = [[1, 2, 5, 10, 7], [4, 3, 4, 3, 21], [45, 65, 8, 8, 9, 9]] elem = 8elem1 = 0 # element exists in listof listor not?res1 = elem in (item for sublist in ini_list for item in sublist)res2 = elem1 in (item for sublist in ini_list for item in sublist) # printing resultprint(str(res1), \"\\n\", str(res2))", "e": 1410, "s": 971, "text": null }, { "code": null, "e": 1424, "s": 1410, "text": "True \n False\n" }, { "code": null, "e": 1460, "s": 1424, "text": " Method #3: Using itertools.chain()" }, { "code": null, "e": 1624, "s": 1460, "text": "Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted." }, { "code": "# Python code to demonstrate# finding whether element# exists in listof listfrom itertools import chain # initialising nested listsini_list = [[1, 2, 5, 10, 7], [4, 3, 4, 3, 21], [45, 65, 8, 8, 9, 9]] elem_to_find = 8elem_to_find1 = 0 # element exists in listof listor not?res1 = elem_to_find in chain(*ini_list)res2 = elem_to_find1 in chain(*ini_list) # printing resultprint(str(res1), \"\\n\", str(res2))", "e": 2056, "s": 1624, "text": null }, { "code": null, "e": 2070, "s": 2056, "text": "True \n False\n" }, { "code": null, "e": 2091, "s": 2070, "text": "Python list-programs" }, { "code": null, "e": 2098, "s": 2091, "text": "Python" }, { "code": null, "e": 2114, "s": 2098, "text": "Python Programs" }, { "code": null, "e": 2212, "s": 2114, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2230, "s": 2212, "text": "Python Dictionary" }, { "code": null, "e": 2272, "s": 2230, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2294, "s": 2272, "text": "Enumerate() in Python" }, { "code": null, "e": 2329, "s": 2294, "text": "Read a file line by line in Python" }, { "code": null, "e": 2355, "s": 2329, "text": "Python String | replace()" }, { "code": null, "e": 2398, "s": 2355, "text": "Python program to convert a list to string" }, { "code": null, "e": 2420, "s": 2398, "text": "Defaultdict in Python" }, { "code": null, "e": 2459, "s": 2420, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2497, "s": 2459, "text": "Python | Convert a list to dictionary" } ]
Virtual base class in C++
14 Mar, 2019 Virtual base classes are used in virtual inheritance in a way of preventing multiple “instances” of a given class appearing in an inheritance hierarchy when using multiple inheritances. Need for Virtual Base Classes:Consider the situation where we have one class A .This class is A is inherited by two other classes B and C. Both these class are inherited into another in a new class D as shown in figure below. As we can see from the figure that data members/function of class A are inherited twice to class D. One through class B and second through class C. When any data / function member of class A is accessed by an object of class D, ambiguity arises as to which data/function member would be called? One inherited through B or the other inherited through C. This confuses compiler and it displays error. Example: To show the need of Virtual Base Class in C++ #include <iostream>using namespace std; class A {public: void show() { cout << "Hello form A \n"; }}; class B : public A {}; class C : public A {}; class D : public B, public C {}; int main(){ D object; object.show();} Compile Errors: prog.cpp: In function 'int main()': prog.cpp:29:9: error: request for member 'show' is ambiguous object.show(); ^ prog.cpp:8:8: note: candidates are: void A::show() void show() ^ prog.cpp:8:8: note: void A::show() How to resolve this issue?To resolve this ambiguity when class A is inherited in both class B and class C, it is declared as virtual base class by placing a keyword virtual as : Syntax for Virtual Base Classes: Syntax 1: class B : virtual public A { }; Syntax 2: class C : public virtual A { }; Note: virtual can be written before or after the public. Now only one copy of data/function member will be copied to class C and class B and class A becomes the virtual base class.Virtual base classes offer a way to save space and avoid ambiguities in class hierarchies that use multiple inheritances. When a base class is specified as a virtual base, it can act as an indirect base more than once without duplication of its data members. A single copy of its data members is shared by all the base classes that use virtual base. Example 1 #include <iostream>using namespace std; class A {public: int a; A() // constructor { a = 10; }}; class B : public virtual A {}; class C : public virtual A {}; class D : public B, public C {}; int main(){ D object; // object creation of class d cout << "a = " << object.a << endl; return 0;} a = 10 Explanation :The class A has just one data member a which is public. This class is virtually inherited in class B and class C. Now class B and class C becomes virtual base class and no duplication of data member a is done. Example 2: #include <iostream>using namespace std; class A {public: void show() { cout << "Hello from A \n"; }}; class B : public virtual A {}; class C : public virtual A {}; class D : public B, public C {}; int main(){ D object; object.show();} Hello from A gyanendra371 C++-Class and Object C++-Inheritance C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ Friend class and function in C++ std::string class in C++ Pair in C++ Standard Template Library (STL) Queue in C++ Standard Template Library (STL) Unordered Sets in C++ Standard Template Library List in C++ Standard Template Library (STL) std::find in C++ Inline Functions in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Mar, 2019" }, { "code": null, "e": 240, "s": 54, "text": "Virtual base classes are used in virtual inheritance in a way of preventing multiple “instances” of a given class appearing in an inheritance hierarchy when using multiple inheritances." }, { "code": null, "e": 466, "s": 240, "text": "Need for Virtual Base Classes:Consider the situation where we have one class A .This class is A is inherited by two other classes B and C. Both these class are inherited into another in a new class D as shown in figure below." }, { "code": null, "e": 865, "s": 466, "text": "As we can see from the figure that data members/function of class A are inherited twice to class D. One through class B and second through class C. When any data / function member of class A is accessed by an object of class D, ambiguity arises as to which data/function member would be called? One inherited through B or the other inherited through C. This confuses compiler and it displays error." }, { "code": null, "e": 920, "s": 865, "text": "Example: To show the need of Virtual Base Class in C++" }, { "code": "#include <iostream>using namespace std; class A {public: void show() { cout << \"Hello form A \\n\"; }}; class B : public A {}; class C : public A {}; class D : public B, public C {}; int main(){ D object; object.show();}", "e": 1166, "s": 920, "text": null }, { "code": null, "e": 1182, "s": 1166, "text": "Compile Errors:" }, { "code": null, "e": 1435, "s": 1182, "text": "prog.cpp: In function 'int main()':\nprog.cpp:29:9: error: request for member 'show' is ambiguous\n object.show();\n ^\nprog.cpp:8:8: note: candidates are: void A::show()\n void show()\n ^\nprog.cpp:8:8: note: void A::show()\n" }, { "code": null, "e": 1613, "s": 1435, "text": "How to resolve this issue?To resolve this ambiguity when class A is inherited in both class B and class C, it is declared as virtual base class by placing a keyword virtual as :" }, { "code": null, "e": 1646, "s": 1613, "text": "Syntax for Virtual Base Classes:" }, { "code": null, "e": 1733, "s": 1646, "text": "Syntax 1:\nclass B : virtual public A \n{\n};\n\nSyntax 2:\nclass C : public virtual A\n{\n};\n" }, { "code": null, "e": 2263, "s": 1733, "text": "Note: virtual can be written before or after the public. Now only one copy of data/function member will be copied to class C and class B and class A becomes the virtual base class.Virtual base classes offer a way to save space and avoid ambiguities in class hierarchies that use multiple inheritances. When a base class is specified as a virtual base, it can act as an indirect base more than once without duplication of its data members. A single copy of its data members is shared by all the base classes that use virtual base." }, { "code": null, "e": 2273, "s": 2263, "text": "Example 1" }, { "code": "#include <iostream>using namespace std; class A {public: int a; A() // constructor { a = 10; }}; class B : public virtual A {}; class C : public virtual A {}; class D : public B, public C {}; int main(){ D object; // object creation of class d cout << \"a = \" << object.a << endl; return 0;}", "e": 2599, "s": 2273, "text": null }, { "code": null, "e": 2607, "s": 2599, "text": "a = 10\n" }, { "code": null, "e": 2830, "s": 2607, "text": "Explanation :The class A has just one data member a which is public. This class is virtually inherited in class B and class C. Now class B and class C becomes virtual base class and no duplication of data member a is done." }, { "code": null, "e": 2841, "s": 2830, "text": "Example 2:" }, { "code": "#include <iostream>using namespace std; class A {public: void show() { cout << \"Hello from A \\n\"; }}; class B : public virtual A {}; class C : public virtual A {}; class D : public B, public C {}; int main(){ D object; object.show();}", "e": 3103, "s": 2841, "text": null }, { "code": null, "e": 3117, "s": 3103, "text": "Hello from A\n" }, { "code": null, "e": 3130, "s": 3117, "text": "gyanendra371" }, { "code": null, "e": 3151, "s": 3130, "text": "C++-Class and Object" }, { "code": null, "e": 3167, "s": 3151, "text": "C++-Inheritance" }, { "code": null, "e": 3171, "s": 3167, "text": "C++" }, { "code": null, "e": 3175, "s": 3171, "text": "CPP" }, { "code": null, "e": 3273, "s": 3175, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3297, "s": 3273, "text": "Sorting a vector in C++" }, { "code": null, "e": 3317, "s": 3297, "text": "Polymorphism in C++" }, { "code": null, "e": 3350, "s": 3317, "text": "Friend class and function in C++" }, { "code": null, "e": 3375, "s": 3350, "text": "std::string class in C++" }, { "code": null, "e": 3419, "s": 3375, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 3464, "s": 3419, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 3512, "s": 3464, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 3556, "s": 3512, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 3573, "s": 3556, "text": "std::find in C++" } ]
Kotlin - Collections
Collections are a common concept for most programming languages. A collection usually contains a number of objects of the same type and Objects in a collection are called elements or items. The Kotlin Standard Library provides a comprehensive set of tools for managing collections. The following collection types are relevant for Kotlin: Kotlin List - List is an ordered collection with access to elements by indices. Elements can occur more than once in a list. Kotlin List - List is an ordered collection with access to elements by indices. Elements can occur more than once in a list. Kotlin Set - Set is a collection of unique elements which means a group of objects without repetitions. Kotlin Set - Set is a collection of unique elements which means a group of objects without repetitions. Kotlin Map - Map (or dictionary) is a set of key-value pairs. Keys are unique, and each of them maps to exactly one value. Kotlin Map - Map (or dictionary) is a set of key-value pairs. Keys are unique, and each of them maps to exactly one value. Kotlin provides the following types of collection: Collection or Immutable Collection Collection or Immutable Collection Mutable Collection Mutable Collection Immutable Collection or simply calling a Collection interface provides read-only methods which means once a collection is created, we can not change it because there is no method available to change the object created. fun main() { val numbers = listOf("one", "two", "three", "four") println(numbers) } When you run the above Kotlin program, it will generate the following output: [one, two, three, four] Mutable collections provides both read and write methods. fun main() { val numbers = mutableListOf("one", "two", "three", "four") numbers.add("five") println(numbers) } When you run the above Kotlin program, it will generate the following output: [one, two, three, four, five] Q 1 - Which of the following is true about Kotlin Collections? A - Kotlin provides mutable and immutable collection B - List, Set and Map are Kotlin Collections C - Kotlin Map can store values in Key-Value pairs D - All of the above All the given statements are true about Kotlin Collections Q 2 - What will be the output of the following program: fun main() { val numbers = listOf("one", "two", "three", "four") numbers = listOf("five") } A - This will print 0 B - This will raise just a warning C - Compilation will stop with error D - None of the above This will stop with error: val cannot be reassigned. Q 2 - Which statement is not correct? A - Kotlin List can have duplicate values B - Kotlin Set can not have duplicate values C - Immutable collection does not provide methods to change/update the collection. D - Kotlin does not provide collection types: sets, lists, and maps Kotlin provides collection types: sets, lists, and maps 68 Lectures 4.5 hours Arnab Chakraborty 71 Lectures 5.5 hours Frahaan Hussain 18 Lectures 1.5 hours Mahmoud Ramadan 49 Lectures 6 hours Catalin Stefan 49 Lectures 2.5 hours Skillbakerystudios 22 Lectures 1 hours CLEMENT OCHIENG Print Add Notes Bookmark this page
[ { "code": null, "e": 2615, "s": 2425, "text": "Collections are a common concept for most programming languages. A collection usually contains a number of objects of the same type and Objects in a collection are called elements or items." }, { "code": null, "e": 2763, "s": 2615, "text": "The Kotlin Standard Library provides a comprehensive set of tools for managing collections. The following collection types are relevant for Kotlin:" }, { "code": null, "e": 2890, "s": 2763, "text": "Kotlin List - List is an ordered collection with access to elements by indices. Elements can occur more than once in a list." }, { "code": null, "e": 3017, "s": 2890, "text": "Kotlin List - List is an ordered collection with access to elements by indices. Elements can occur more than once in a list." }, { "code": null, "e": 3124, "s": 3017, "text": "Kotlin Set - Set is a collection of unique elements which means a group of objects without repetitions." }, { "code": null, "e": 3231, "s": 3124, "text": "Kotlin Set - Set is a collection of unique elements which means a group of objects without repetitions." }, { "code": null, "e": 3355, "s": 3231, "text": "Kotlin Map - Map (or dictionary) is a set of key-value pairs. Keys are unique, and each of them maps to exactly one value." }, { "code": null, "e": 3479, "s": 3355, "text": "Kotlin Map - Map (or dictionary) is a set of key-value pairs. Keys are unique, and each of them maps to exactly one value." }, { "code": null, "e": 3531, "s": 3479, "text": "Kotlin provides the following types of collection:" }, { "code": null, "e": 3566, "s": 3531, "text": "Collection or Immutable Collection" }, { "code": null, "e": 3601, "s": 3566, "text": "Collection or Immutable Collection" }, { "code": null, "e": 3620, "s": 3601, "text": "Mutable Collection" }, { "code": null, "e": 3639, "s": 3620, "text": "Mutable Collection" }, { "code": null, "e": 3858, "s": 3639, "text": "Immutable Collection or simply calling a Collection interface provides read-only methods which means once a collection is created, we can not change it because there is no method available to change the object created." }, { "code": null, "e": 3956, "s": 3858, "text": "fun main() {\n val numbers = listOf(\"one\", \"two\", \"three\", \"four\")\n \n println(numbers)\n}\n" }, { "code": null, "e": 4034, "s": 3956, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 4059, "s": 4034, "text": "[one, two, three, four]\n" }, { "code": null, "e": 4117, "s": 4059, "text": "Mutable collections provides both read and write methods." }, { "code": null, "e": 4251, "s": 4117, "text": "fun main() {\n val numbers = mutableListOf(\"one\", \"two\", \"three\", \"four\")\n \n numbers.add(\"five\")\n \n println(numbers)\n}\n" }, { "code": null, "e": 4329, "s": 4251, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 4360, "s": 4329, "text": "[one, two, three, four, five]\n" }, { "code": null, "e": 4423, "s": 4360, "text": "Q 1 - Which of the following is true about Kotlin Collections?" }, { "code": null, "e": 4476, "s": 4423, "text": "A - Kotlin provides mutable and immutable collection" }, { "code": null, "e": 4521, "s": 4476, "text": "B - List, Set and Map are Kotlin Collections" }, { "code": null, "e": 4572, "s": 4521, "text": "C - Kotlin Map can store values in Key-Value pairs" }, { "code": null, "e": 4593, "s": 4572, "text": "D - All of the above" }, { "code": null, "e": 4652, "s": 4593, "text": "All the given statements are true about Kotlin Collections" }, { "code": null, "e": 4708, "s": 4652, "text": "Q 2 - What will be the output of the following program:" }, { "code": null, "e": 4814, "s": 4708, "text": "fun main() {\n val numbers = listOf(\"one\", \"two\", \"three\", \"four\")\n \n numbers = listOf(\"five\")\n}\n" }, { "code": null, "e": 4836, "s": 4814, "text": "A - This will print 0" }, { "code": null, "e": 4871, "s": 4836, "text": "B - This will raise just a warning" }, { "code": null, "e": 4908, "s": 4871, "text": "C - Compilation will stop with error" }, { "code": null, "e": 4930, "s": 4908, "text": "D - None of the above" }, { "code": null, "e": 4983, "s": 4930, "text": "This will stop with error: val cannot be reassigned." }, { "code": null, "e": 5021, "s": 4983, "text": "Q 2 - Which statement is not correct?" }, { "code": null, "e": 5063, "s": 5021, "text": "A - Kotlin List can have duplicate values" }, { "code": null, "e": 5108, "s": 5063, "text": "B - Kotlin Set can not have duplicate values" }, { "code": null, "e": 5191, "s": 5108, "text": "C - Immutable collection does not provide methods to change/update the collection." }, { "code": null, "e": 5259, "s": 5191, "text": "D - Kotlin does not provide collection types: sets, lists, and maps" }, { "code": null, "e": 5315, "s": 5259, "text": "Kotlin provides collection types: sets, lists, and maps" }, { "code": null, "e": 5350, "s": 5315, "text": "\n 68 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5369, "s": 5350, "text": " Arnab Chakraborty" }, { "code": null, "e": 5404, "s": 5369, "text": "\n 71 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5421, "s": 5404, "text": " Frahaan Hussain" }, { "code": null, "e": 5456, "s": 5421, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5473, "s": 5456, "text": " Mahmoud Ramadan" }, { "code": null, "e": 5506, "s": 5473, "text": "\n 49 Lectures \n 6 hours \n" }, { "code": null, "e": 5522, "s": 5506, "text": " Catalin Stefan" }, { "code": null, "e": 5557, "s": 5522, "text": "\n 49 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5577, "s": 5557, "text": " Skillbakerystudios" }, { "code": null, "e": 5610, "s": 5577, "text": "\n 22 Lectures \n 1 hours \n" }, { "code": null, "e": 5627, "s": 5610, "text": " CLEMENT OCHIENG" }, { "code": null, "e": 5634, "s": 5627, "text": " Print" }, { "code": null, "e": 5645, "s": 5634, "text": " Add Notes" } ]
Pascal - if-then Statement
The if-then statement is the simplest form of control statement, frequently used in decision making and changing the control flow of the program execution. Syntax for if-then statement is − if condition then S Where condition is a Boolean or relational condition and S is a simple or compound statement. Example of an if-then statement is − if (a <= 20) then c:= c+1; If the boolean expression condition evaluates to true, then the block of code inside the if statement will be executed. If boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing end;) will be executed. Pascal assumes any non-zero and non-nil values as true, and if it is either zero or nil, then it is assumed as false value. Let us try a complete example that would illustrate the concept − program ifChecking; var { local variable declaration } a:integer; begin a:= 10; (* check the boolean condition using if statement *) if( a < 20 ) then (* if condition is true then print the following *) writeln('a is less than 20 ' ); writeln('value of a is : ', a); end. When the above code is compiled and executed, it produces the following result − a is less than 20 value of a is : 10 94 Lectures 8.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2239, "s": 2083, "text": "The if-then statement is the simplest form of control statement, frequently used in decision making and changing the control flow of the program execution." }, { "code": null, "e": 2273, "s": 2239, "text": "Syntax for if-then statement is −" }, { "code": null, "e": 2294, "s": 2273, "text": "if condition then S\n" }, { "code": null, "e": 2425, "s": 2294, "text": "Where condition is a Boolean or relational condition and S is a simple or compound statement. Example of an if-then statement is −" }, { "code": null, "e": 2455, "s": 2425, "text": "if (a <= 20) then\n c:= c+1;" }, { "code": null, "e": 2721, "s": 2455, "text": "If the boolean expression condition evaluates to true, then the block of code inside the if statement will be executed. If boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing end;) will be executed." }, { "code": null, "e": 2845, "s": 2721, "text": "Pascal assumes any non-zero and non-nil values as true, and if it is either zero or nil, then it is assumed as false value." }, { "code": null, "e": 2911, "s": 2845, "text": "Let us try a complete example that would illustrate the concept −" }, { "code": null, "e": 3217, "s": 2911, "text": "program ifChecking;\n\nvar\n{ local variable declaration }\n a:integer;\n\nbegin\n a:= 10;\n (* check the boolean condition using if statement *)\n \n if( a < 20 ) then\n (* if condition is true then print the following *) \n writeln('a is less than 20 ' );\n writeln('value of a is : ', a);\nend." }, { "code": null, "e": 3298, "s": 3217, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3336, "s": 3298, "text": "a is less than 20\nvalue of a is : 10\n" }, { "code": null, "e": 3371, "s": 3336, "text": "\n 94 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3394, "s": 3371, "text": " Stone River ELearning" }, { "code": null, "e": 3401, "s": 3394, "text": " Print" }, { "code": null, "e": 3412, "s": 3401, "text": " Add Notes" } ]
How to plot a wav file using Matplotlib?
To plot a .wav file using matplotlib, we can take following the steps − To read a .wav file, we can use the read() method. To read a .wav file, we can use the read() method. After reading the .wav file, we will get a tuple. At the 0 th index, rate would be there and at the 1st index, array sample data. After reading the .wav file, we will get a tuple. At the 0 th index, rate would be there and at the 1st index, array sample data. Use the plot() method to plot the .wav file. Use the plot() method to plot the .wav file. Set y and x labels using ylabel and xlabel with “Amplitude” and “Time” label, respectively. Set y and x labels using ylabel and xlabel with “Amplitude” and “Time” label, respectively. To display the figure, use the show() method. To display the figure, use the show() method. from scipy.io.wavfile import read import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True input_data = read("my_audio.wav") audio = input_data[1] plt.plot(audio[0:1024]) plt.ylabel("Amplitude") plt.xlabel("Time") plt.show()
[ { "code": null, "e": 1134, "s": 1062, "text": "To plot a .wav file using matplotlib, we can take following the steps −" }, { "code": null, "e": 1185, "s": 1134, "text": "To read a .wav file, we can use the read() method." }, { "code": null, "e": 1236, "s": 1185, "text": "To read a .wav file, we can use the read() method." }, { "code": null, "e": 1366, "s": 1236, "text": "After reading the .wav file, we will get a tuple. At the 0 th index, rate would be there and at the 1st index, array sample data." }, { "code": null, "e": 1496, "s": 1366, "text": "After reading the .wav file, we will get a tuple. At the 0 th index, rate would be there and at the 1st index, array sample data." }, { "code": null, "e": 1541, "s": 1496, "text": "Use the plot() method to plot the .wav file." }, { "code": null, "e": 1586, "s": 1541, "text": "Use the plot() method to plot the .wav file." }, { "code": null, "e": 1678, "s": 1586, "text": "Set y and x labels using ylabel and xlabel with “Amplitude” and “Time” label, respectively." }, { "code": null, "e": 1770, "s": 1678, "text": "Set y and x labels using ylabel and xlabel with “Amplitude” and “Time” label, respectively." }, { "code": null, "e": 1816, "s": 1770, "text": "To display the figure, use the show() method." }, { "code": null, "e": 1862, "s": 1816, "text": "To display the figure, use the show() method." }, { "code": null, "e": 2149, "s": 1862, "text": "from scipy.io.wavfile import read\nimport matplotlib.pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\ninput_data = read(\"my_audio.wav\")\naudio = input_data[1]\nplt.plot(audio[0:1024])\nplt.ylabel(\"Amplitude\")\nplt.xlabel(\"Time\")\nplt.show()" } ]
ML | Handling Imbalanced Data with SMOTE and Near Miss Algorithm in Python - GeeksforGeeks
13 Dec, 2021 In Machine Learning and Data Science we often come across a term called Imbalanced Data Distribution, generally happens when observations in one of the class are much higher or lower than the other classes. As Machine Learning algorithms tend to increase accuracy by reducing the error, they do not consider the class distribution. This problem is prevalent in examples such as Fraud Detection, Anomaly Detection, Facial recognition etc. Standard ML techniques such as Decision Tree and Logistic Regression have a bias towards the majority class, and they tend to ignore the minority class. They tend only to predict the majority class, hence, having major misclassification of the minority class in comparison with the majority class. In more technical words, if we have imbalanced data distribution in our dataset then our model becomes more prone to the case when minority class has negligible or very lesser recall. Imbalanced Data Handling Techniques: There are mainly 2 mainly algorithms that are widely used for handling imbalanced class distribution. SMOTENear Miss Algorithm SMOTE Near Miss Algorithm SMOTE (synthetic minority oversampling technique) is one of the most commonly used oversampling methods to solve the imbalance problem.It aims to balance class distribution by randomly increasing minority class examples by replicating them.SMOTE synthesises new minority instances between existing minority instances. It generates the virtual training records by linear interpolation for the minority class. These synthetic training records are generated by randomly selecting one or more of the k-nearest neighbors for each example in the minority class. After the oversampling process, the data is reconstructed and several classification models can be applied for the processed data.More Deep Insights of how SMOTE Algorithm work ! Step 1: Setting the minority class set A, for each , the k-nearest neighbors of x are obtained by calculating the Euclidean distance between x and every other sample in set A. Step 2: The sampling rate N is set according to the imbalanced proportion. For each , N examples (i.e x1, x2, ...xn) are randomly selected from its k-nearest neighbors, and they construct the set . Step 3: For each example (k=1, 2, 3...N), the following formula is used to generate a new example:in which rand(0, 1) represents the random number between 0 and 1.NearMiss Algorithm – UndersamplingNearMiss is an under-sampling technique. It aims to balance class distribution by randomly eliminating majority class examples. When instances of two different classes are very close to each other, we remove the instances of the majority class to increase the spaces between the two classes. This helps in the classification process.To prevent problem of information loss in most under-sampling techniques, near-neighbor methods are widely used.The basic intuition about the working of near-neighbor methods is as follows: NearMiss is an under-sampling technique. It aims to balance class distribution by randomly eliminating majority class examples. When instances of two different classes are very close to each other, we remove the instances of the majority class to increase the spaces between the two classes. This helps in the classification process.To prevent problem of information loss in most under-sampling techniques, near-neighbor methods are widely used.The basic intuition about the working of near-neighbor methods is as follows: Step 1: The method first finds the distances between all instances of the majority class and the instances of the minority class. Here, majority class is to be under-sampled. Step 2: Then, n instances of the majority class that have the smallest distances to those in the minority class are selected. Step 3: If there are k instances in the minority class, the nearest method will result in k*n instances of the majority class.For finding n closest instances in the majority class, there are several variations of applying NearMiss Algorithm :NearMiss – Version 1 : It selects samples of the majority class for which average distances to the k closest instances of the minority class is smallest.NearMiss – Version 2 : It selects samples of the majority class for which average distances to the k farthest instances of the minority class is smallest.NearMiss – Version 3 : It works in 2 steps. Firstly, for each minority class instance, their M nearest-neighbors will be stored. Then finally, the majority class instances are selected for which the average distance to the N nearest-neighbors is the largest.This article helps in better understanding and hands-on practice on how to choose best between different imbalanced data handling techniques.Load libraries and data fileThe dataset consists of transactions made by credit cards. This dataset has 492 fraud transactions out of 284, 807 transactions. That makes it highly unbalanced, the positive class (frauds) account for 0.172% of all transactions.The dataset can be downloaded from here.# import necessary modules import pandas as pdimport matplotlib.pyplot as pltimport numpy as npfrom sklearn.linear_model import LogisticRegressionfrom sklearn.preprocessing import StandardScalerfrom sklearn.metrics import confusion_matrix, classification_report # load the data setdata = pd.read_csv('creditcard.csv') # print info about columns in the dataframeprint(data.info())Output:RangeIndex: 284807 entries, 0 to 284806 Data columns (total 31 columns): Time 284807 non-null float64 V1 284807 non-null float64 V2 284807 non-null float64 V3 284807 non-null float64 V4 284807 non-null float64 V5 284807 non-null float64 V6 284807 non-null float64 V7 284807 non-null float64 V8 284807 non-null float64 V9 284807 non-null float64 V10 284807 non-null float64 V11 284807 non-null float64 V12 284807 non-null float64 V13 284807 non-null float64 V14 284807 non-null float64 V15 284807 non-null float64 V16 284807 non-null float64 V17 284807 non-null float64 V18 284807 non-null float64 V19 284807 non-null float64 V20 284807 non-null float64 V21 284807 non-null float64 V22 284807 non-null float64 V23 284807 non-null float64 V24 284807 non-null float64 V25 284807 non-null float64 V26 284807 non-null float64 V27 284807 non-null float64 V28 284807 non-null float64 Amount 284807 non-null float64 Class 284807 non-null int64 # normalise the amount columndata['normAmount'] = StandardScaler().fit_transform(np.array(data['Amount']).reshape(-1, 1)) # drop Time and Amount columns as they are not relevant for prediction purpose data = data.drop(['Time', 'Amount'], axis = 1) # as you can see there are 492 fraud transactions.data['Class'].value_counts()Output: 0 284315 1 492 Split the data into test and train setsfrom sklearn.model_selection import train_test_split # split into 70:30 rationX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 0) # describes info about train and test setprint("Number transactions X_train dataset: ", X_train.shape)print("Number transactions y_train dataset: ", y_train.shape)print("Number transactions X_test dataset: ", X_test.shape)print("Number transactions y_test dataset: ", y_test.shape)Output: Number transactions X_train dataset: (199364, 29) Number transactions y_train dataset: (199364, 1) Number transactions X_test dataset: (85443, 29) Number transactions y_test dataset: (85443, 1) Now train the model without handling the imbalanced class distribution# logistic regression objectlr = LogisticRegression() # train the model on train setlr.fit(X_train, y_train.ravel()) predictions = lr.predict(X_test) # print classification reportprint(classification_report(y_test, predictions))Output: precision recall f1-score support 0 1.00 1.00 1.00 85296 1 0.88 0.62 0.73 147 accuracy 1.00 85443 macro avg 0.94 0.81 0.86 85443 weighted avg 1.00 1.00 1.00 85443 The accuracy comes out to be 100% but did you notice something strange ?The recall of the minority class in very less. It proves that the model is more biased towards majority class. So, it proves that this is not the best model.Now, we will apply different imbalanced data handling techniques and see their accuracy and recall results.Using SMOTE AlgorithmYou can check all the parameters from here.print("Before OverSampling, counts of label '1': {}".format(sum(y_train == 1)))print("Before OverSampling, counts of label '0': {} \n".format(sum(y_train == 0))) # import SMOTE module from imblearn library# pip install imblearn (if you don't have imblearn in your system)from imblearn.over_sampling import SMOTEsm = SMOTE(random_state = 2)X_train_res, y_train_res = sm.fit_sample(X_train, y_train.ravel()) print('After OverSampling, the shape of train_X: {}'.format(X_train_res.shape))print('After OverSampling, the shape of train_y: {} \n'.format(y_train_res.shape)) print("After OverSampling, counts of label '1': {}".format(sum(y_train_res == 1)))print("After OverSampling, counts of label '0': {}".format(sum(y_train_res == 0)))Output:Before OverSampling, counts of label '1': [345] Before OverSampling, counts of label '0': [199019] After OverSampling, the shape of train_X: (398038, 29) After OverSampling, the shape of train_y: (398038, ) After OverSampling, counts of label '1': 199019 After OverSampling, counts of label '0': 199019 Look! that SMOTE Algorithm has oversampled the minority instances and made it equal to majority class. Both categories have equal amount of records. More specifically, the minority class has been increased to the total number of majority class.Now see the accuracy and recall results after applying SMOTE algorithm (Oversampling).Prediction and Recalllr1 = LogisticRegression()lr1.fit(X_train_res, y_train_res.ravel())predictions = lr1.predict(X_test) # print classification reportprint(classification_report(y_test, predictions))Output: precision recall f1-score support 0 1.00 0.98 0.99 85296 1 0.06 0.92 0.11 147 accuracy 0.98 85443 macro avg 0.53 0.95 0.55 85443 weighted avg 1.00 0.98 0.99 85443 Wow, We have reduced the accuracy to 98% as compared to previous model but the recall value of minority class has also improved to 92 %. This is a good model compared to the previous one. Recall is great.Now, we will apply NearMiss technique to Under-sample the majority class and see its accuracy and recall results.NearMiss Algorithm:You can check all the parameters from here.print("Before Undersampling, counts of label '1': {}".format(sum(y_train == 1)))print("Before Undersampling, counts of label '0': {} \n".format(sum(y_train == 0))) # apply near missfrom imblearn.under_sampling import NearMissnr = NearMiss() X_train_miss, y_train_miss = nr.fit_sample(X_train, y_train.ravel()) print('After Undersampling, the shape of train_X: {}'.format(X_train_miss.shape))print('After Undersampling, the shape of train_y: {} \n'.format(y_train_miss.shape)) print("After Undersampling, counts of label '1': {}".format(sum(y_train_miss == 1)))print("After Undersampling, counts of label '0': {}".format(sum(y_train_miss == 0)))Output:Before Undersampling, counts of label '1': [345] Before Undersampling, counts of label '0': [199019] After Undersampling, the shape of train_X: (690, 29) After Undersampling, the shape of train_y: (690, ) After Undersampling, counts of label '1': 345 After Undersampling, counts of label '0': 345 The NearMiss Algorithm has undersampled the majority instances and made it equal to majority class. Here, the majority class has been reduced to the total number of minority class, so that both classes will have equal number of records.Prediction and Recall# train the model on train setlr2 = LogisticRegression()lr2.fit(X_train_miss, y_train_miss.ravel())predictions = lr2.predict(X_test) # print classification reportprint(classification_report(y_test, predictions))Output: precision recall f1-score support 0 1.00 0.56 0.72 85296 1 0.00 0.95 0.01 147 accuracy 0.56 85443 macro avg 0.50 0.75 0.36 85443 weighted avg 1.00 0.56 0.72 85443 This model is better than the first model because it classifies better and also the recall value of minority class is 95 %. But due to undersampling of majority class, its recall has decreased to 56 %. So in this case, SMOTE is giving me a great accuracy and recall, I’ll go ahead and use that model! My Personal Notes arrow_drop_upSave For finding n closest instances in the majority class, there are several variations of applying NearMiss Algorithm : NearMiss – Version 1 : It selects samples of the majority class for which average distances to the k closest instances of the minority class is smallest.NearMiss – Version 2 : It selects samples of the majority class for which average distances to the k farthest instances of the minority class is smallest.NearMiss – Version 3 : It works in 2 steps. Firstly, for each minority class instance, their M nearest-neighbors will be stored. Then finally, the majority class instances are selected for which the average distance to the N nearest-neighbors is the largest. NearMiss – Version 1 : It selects samples of the majority class for which average distances to the k closest instances of the minority class is smallest. NearMiss – Version 2 : It selects samples of the majority class for which average distances to the k farthest instances of the minority class is smallest. NearMiss – Version 3 : It works in 2 steps. Firstly, for each minority class instance, their M nearest-neighbors will be stored. Then finally, the majority class instances are selected for which the average distance to the N nearest-neighbors is the largest. This article helps in better understanding and hands-on practice on how to choose best between different imbalanced data handling techniques. The dataset consists of transactions made by credit cards. This dataset has 492 fraud transactions out of 284, 807 transactions. That makes it highly unbalanced, the positive class (frauds) account for 0.172% of all transactions.The dataset can be downloaded from here. # import necessary modules import pandas as pdimport matplotlib.pyplot as pltimport numpy as npfrom sklearn.linear_model import LogisticRegressionfrom sklearn.preprocessing import StandardScalerfrom sklearn.metrics import confusion_matrix, classification_report # load the data setdata = pd.read_csv('creditcard.csv') # print info about columns in the dataframeprint(data.info()) Output: RangeIndex: 284807 entries, 0 to 284806 Data columns (total 31 columns): Time 284807 non-null float64 V1 284807 non-null float64 V2 284807 non-null float64 V3 284807 non-null float64 V4 284807 non-null float64 V5 284807 non-null float64 V6 284807 non-null float64 V7 284807 non-null float64 V8 284807 non-null float64 V9 284807 non-null float64 V10 284807 non-null float64 V11 284807 non-null float64 V12 284807 non-null float64 V13 284807 non-null float64 V14 284807 non-null float64 V15 284807 non-null float64 V16 284807 non-null float64 V17 284807 non-null float64 V18 284807 non-null float64 V19 284807 non-null float64 V20 284807 non-null float64 V21 284807 non-null float64 V22 284807 non-null float64 V23 284807 non-null float64 V24 284807 non-null float64 V25 284807 non-null float64 V26 284807 non-null float64 V27 284807 non-null float64 V28 284807 non-null float64 Amount 284807 non-null float64 Class 284807 non-null int64 # normalise the amount columndata['normAmount'] = StandardScaler().fit_transform(np.array(data['Amount']).reshape(-1, 1)) # drop Time and Amount columns as they are not relevant for prediction purpose data = data.drop(['Time', 'Amount'], axis = 1) # as you can see there are 492 fraud transactions.data['Class'].value_counts() Output: 0 284315 1 492 from sklearn.model_selection import train_test_split # split into 70:30 rationX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 0) # describes info about train and test setprint("Number transactions X_train dataset: ", X_train.shape)print("Number transactions y_train dataset: ", y_train.shape)print("Number transactions X_test dataset: ", X_test.shape)print("Number transactions y_test dataset: ", y_test.shape) Output: Number transactions X_train dataset: (199364, 29) Number transactions y_train dataset: (199364, 1) Number transactions X_test dataset: (85443, 29) Number transactions y_test dataset: (85443, 1) # logistic regression objectlr = LogisticRegression() # train the model on train setlr.fit(X_train, y_train.ravel()) predictions = lr.predict(X_test) # print classification reportprint(classification_report(y_test, predictions)) Output: precision recall f1-score support 0 1.00 1.00 1.00 85296 1 0.88 0.62 0.73 147 accuracy 1.00 85443 macro avg 0.94 0.81 0.86 85443 weighted avg 1.00 1.00 1.00 85443 The accuracy comes out to be 100% but did you notice something strange ?The recall of the minority class in very less. It proves that the model is more biased towards majority class. So, it proves that this is not the best model.Now, we will apply different imbalanced data handling techniques and see their accuracy and recall results. You can check all the parameters from here. print("Before OverSampling, counts of label '1': {}".format(sum(y_train == 1)))print("Before OverSampling, counts of label '0': {} \n".format(sum(y_train == 0))) # import SMOTE module from imblearn library# pip install imblearn (if you don't have imblearn in your system)from imblearn.over_sampling import SMOTEsm = SMOTE(random_state = 2)X_train_res, y_train_res = sm.fit_sample(X_train, y_train.ravel()) print('After OverSampling, the shape of train_X: {}'.format(X_train_res.shape))print('After OverSampling, the shape of train_y: {} \n'.format(y_train_res.shape)) print("After OverSampling, counts of label '1': {}".format(sum(y_train_res == 1)))print("After OverSampling, counts of label '0': {}".format(sum(y_train_res == 0))) Output: Before OverSampling, counts of label '1': [345] Before OverSampling, counts of label '0': [199019] After OverSampling, the shape of train_X: (398038, 29) After OverSampling, the shape of train_y: (398038, ) After OverSampling, counts of label '1': 199019 After OverSampling, counts of label '0': 199019 Look! that SMOTE Algorithm has oversampled the minority instances and made it equal to majority class. Both categories have equal amount of records. More specifically, the minority class has been increased to the total number of majority class.Now see the accuracy and recall results after applying SMOTE algorithm (Oversampling). lr1 = LogisticRegression()lr1.fit(X_train_res, y_train_res.ravel())predictions = lr1.predict(X_test) # print classification reportprint(classification_report(y_test, predictions)) Output: precision recall f1-score support 0 1.00 0.98 0.99 85296 1 0.06 0.92 0.11 147 accuracy 0.98 85443 macro avg 0.53 0.95 0.55 85443 weighted avg 1.00 0.98 0.99 85443 Wow, We have reduced the accuracy to 98% as compared to previous model but the recall value of minority class has also improved to 92 %. This is a good model compared to the previous one. Recall is great.Now, we will apply NearMiss technique to Under-sample the majority class and see its accuracy and recall results. You can check all the parameters from here. print("Before Undersampling, counts of label '1': {}".format(sum(y_train == 1)))print("Before Undersampling, counts of label '0': {} \n".format(sum(y_train == 0))) # apply near missfrom imblearn.under_sampling import NearMissnr = NearMiss() X_train_miss, y_train_miss = nr.fit_sample(X_train, y_train.ravel()) print('After Undersampling, the shape of train_X: {}'.format(X_train_miss.shape))print('After Undersampling, the shape of train_y: {} \n'.format(y_train_miss.shape)) print("After Undersampling, counts of label '1': {}".format(sum(y_train_miss == 1)))print("After Undersampling, counts of label '0': {}".format(sum(y_train_miss == 0))) Output: Before Undersampling, counts of label '1': [345] Before Undersampling, counts of label '0': [199019] After Undersampling, the shape of train_X: (690, 29) After Undersampling, the shape of train_y: (690, ) After Undersampling, counts of label '1': 345 After Undersampling, counts of label '0': 345 The NearMiss Algorithm has undersampled the majority instances and made it equal to majority class. Here, the majority class has been reduced to the total number of minority class, so that both classes will have equal number of records. # train the model on train setlr2 = LogisticRegression()lr2.fit(X_train_miss, y_train_miss.ravel())predictions = lr2.predict(X_test) # print classification reportprint(classification_report(y_test, predictions)) Output: precision recall f1-score support 0 1.00 0.56 0.72 85296 1 0.00 0.95 0.01 147 accuracy 0.56 85443 macro avg 0.50 0.75 0.36 85443 weighted avg 1.00 0.56 0.72 85443 This model is better than the first model because it classifies better and also the recall value of minority class is 95 %. But due to undersampling of majority class, its recall has decreased to 56 %. So in this case, SMOTE is giving me a great accuracy and recall, I’ll go ahead and use that model! tanwarsinghvaibhav Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Search Algorithms in AI Python | Decision tree implementation Decision Tree Introduction with example Elbow Method for optimal value of k in KMeans Support Vector Machine Algorithm 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": 24744, "s": 24716, "text": "\n13 Dec, 2021" }, { "code": null, "e": 25182, "s": 24744, "text": "In Machine Learning and Data Science we often come across a term called Imbalanced Data Distribution, generally happens when observations in one of the class are much higher or lower than the other classes. As Machine Learning algorithms tend to increase accuracy by reducing the error, they do not consider the class distribution. This problem is prevalent in examples such as Fraud Detection, Anomaly Detection, Facial recognition etc." }, { "code": null, "e": 25664, "s": 25182, "text": "Standard ML techniques such as Decision Tree and Logistic Regression have a bias towards the majority class, and they tend to ignore the minority class. They tend only to predict the majority class, hence, having major misclassification of the minority class in comparison with the majority class. In more technical words, if we have imbalanced data distribution in our dataset then our model becomes more prone to the case when minority class has negligible or very lesser recall." }, { "code": null, "e": 25803, "s": 25664, "text": "Imbalanced Data Handling Techniques: There are mainly 2 mainly algorithms that are widely used for handling imbalanced class distribution." }, { "code": null, "e": 25828, "s": 25803, "text": "SMOTENear Miss Algorithm" }, { "code": null, "e": 25834, "s": 25828, "text": "SMOTE" }, { "code": null, "e": 25854, "s": 25834, "text": "Near Miss Algorithm" }, { "code": null, "e": 26589, "s": 25854, "text": "SMOTE (synthetic minority oversampling technique) is one of the most commonly used oversampling methods to solve the imbalance problem.It aims to balance class distribution by randomly increasing minority class examples by replicating them.SMOTE synthesises new minority instances between existing minority instances. It generates the virtual training records by linear interpolation for the minority class. These synthetic training records are generated by randomly selecting one or more of the k-nearest neighbors for each example in the minority class. After the oversampling process, the data is reconstructed and several classification models can be applied for the processed data.More Deep Insights of how SMOTE Algorithm work !" }, { "code": null, "e": 26765, "s": 26589, "text": "Step 1: Setting the minority class set A, for each , the k-nearest neighbors of x are obtained by calculating the Euclidean distance between x and every other sample in set A." }, { "code": null, "e": 26964, "s": 26765, "text": "Step 2: The sampling rate N is set according to the imbalanced proportion. For each , N examples (i.e x1, x2, ...xn) are randomly selected from its k-nearest neighbors, and they construct the set ." }, { "code": null, "e": 27685, "s": 26964, "text": "Step 3: For each example (k=1, 2, 3...N), the following formula is used to generate a new example:in which rand(0, 1) represents the random number between 0 and 1.NearMiss Algorithm – UndersamplingNearMiss is an under-sampling technique. It aims to balance class distribution by randomly eliminating majority class examples. When instances of two different classes are very close to each other, we remove the instances of the majority class to increase the spaces between the two classes. This helps in the classification process.To prevent problem of information loss in most under-sampling techniques, near-neighbor methods are widely used.The basic intuition about the working of near-neighbor methods is as follows:" }, { "code": null, "e": 28208, "s": 27685, "text": "NearMiss is an under-sampling technique. It aims to balance class distribution by randomly eliminating majority class examples. When instances of two different classes are very close to each other, we remove the instances of the majority class to increase the spaces between the two classes. This helps in the classification process.To prevent problem of information loss in most under-sampling techniques, near-neighbor methods are widely used.The basic intuition about the working of near-neighbor methods is as follows:" }, { "code": null, "e": 28383, "s": 28208, "text": "Step 1: The method first finds the distances between all instances of the majority class and the instances of the minority class. Here, majority class is to be under-sampled." }, { "code": null, "e": 28509, "s": 28383, "text": "Step 2: Then, n instances of the majority class that have the smallest distances to those in the minority class are selected." }, { "code": null, "e": 37789, "s": 28509, "text": "Step 3: If there are k instances in the minority class, the nearest method will result in k*n instances of the majority class.For finding n closest instances in the majority class, there are several variations of applying NearMiss Algorithm :NearMiss – Version 1 : It selects samples of the majority class for which average distances to the k closest instances of the minority class is smallest.NearMiss – Version 2 : It selects samples of the majority class for which average distances to the k farthest instances of the minority class is smallest.NearMiss – Version 3 : It works in 2 steps. Firstly, for each minority class instance, their M nearest-neighbors will be stored. Then finally, the majority class instances are selected for which the average distance to the N nearest-neighbors is the largest.This article helps in better understanding and hands-on practice on how to choose best between different imbalanced data handling techniques.Load libraries and data fileThe dataset consists of transactions made by credit cards. This dataset has 492 fraud transactions out of 284, 807 transactions. That makes it highly unbalanced, the positive class (frauds) account for 0.172% of all transactions.The dataset can be downloaded from here.# import necessary modules import pandas as pdimport matplotlib.pyplot as pltimport numpy as npfrom sklearn.linear_model import LogisticRegressionfrom sklearn.preprocessing import StandardScalerfrom sklearn.metrics import confusion_matrix, classification_report # load the data setdata = pd.read_csv('creditcard.csv') # print info about columns in the dataframeprint(data.info())Output:RangeIndex: 284807 entries, 0 to 284806\nData columns (total 31 columns):\nTime 284807 non-null float64\nV1 284807 non-null float64\nV2 284807 non-null float64\nV3 284807 non-null float64\nV4 284807 non-null float64\nV5 284807 non-null float64\nV6 284807 non-null float64\nV7 284807 non-null float64\nV8 284807 non-null float64\nV9 284807 non-null float64\nV10 284807 non-null float64\nV11 284807 non-null float64\nV12 284807 non-null float64\nV13 284807 non-null float64\nV14 284807 non-null float64\nV15 284807 non-null float64\nV16 284807 non-null float64\nV17 284807 non-null float64\nV18 284807 non-null float64\nV19 284807 non-null float64\nV20 284807 non-null float64\nV21 284807 non-null float64\nV22 284807 non-null float64\nV23 284807 non-null float64\nV24 284807 non-null float64\nV25 284807 non-null float64\nV26 284807 non-null float64\nV27 284807 non-null float64\nV28 284807 non-null float64\nAmount 284807 non-null float64\nClass 284807 non-null int64\n# normalise the amount columndata['normAmount'] = StandardScaler().fit_transform(np.array(data['Amount']).reshape(-1, 1)) # drop Time and Amount columns as they are not relevant for prediction purpose data = data.drop(['Time', 'Amount'], axis = 1) # as you can see there are 492 fraud transactions.data['Class'].value_counts()Output: 0 284315\n 1 492\nSplit the data into test and train setsfrom sklearn.model_selection import train_test_split # split into 70:30 rationX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 0) # describes info about train and test setprint(\"Number transactions X_train dataset: \", X_train.shape)print(\"Number transactions y_train dataset: \", y_train.shape)print(\"Number transactions X_test dataset: \", X_test.shape)print(\"Number transactions y_test dataset: \", y_test.shape)Output: Number transactions X_train dataset: (199364, 29)\n Number transactions y_train dataset: (199364, 1)\n Number transactions X_test dataset: (85443, 29)\n Number transactions y_test dataset: (85443, 1)\nNow train the model without handling the imbalanced class distribution# logistic regression objectlr = LogisticRegression() # train the model on train setlr.fit(X_train, y_train.ravel()) predictions = lr.predict(X_test) # print classification reportprint(classification_report(y_test, predictions))Output:\n precision recall f1-score support\n\n 0 1.00 1.00 1.00 85296\n 1 0.88 0.62 0.73 147\n\n accuracy 1.00 85443\n macro avg 0.94 0.81 0.86 85443\nweighted avg 1.00 1.00 1.00 85443\nThe accuracy comes out to be 100% but did you notice something strange ?The recall of the minority class in very less. It proves that the model is more biased towards majority class. So, it proves that this is not the best model.Now, we will apply different imbalanced data handling techniques and see their accuracy and recall results.Using SMOTE AlgorithmYou can check all the parameters from here.print(\"Before OverSampling, counts of label '1': {}\".format(sum(y_train == 1)))print(\"Before OverSampling, counts of label '0': {} \\n\".format(sum(y_train == 0))) # import SMOTE module from imblearn library# pip install imblearn (if you don't have imblearn in your system)from imblearn.over_sampling import SMOTEsm = SMOTE(random_state = 2)X_train_res, y_train_res = sm.fit_sample(X_train, y_train.ravel()) print('After OverSampling, the shape of train_X: {}'.format(X_train_res.shape))print('After OverSampling, the shape of train_y: {} \\n'.format(y_train_res.shape)) print(\"After OverSampling, counts of label '1': {}\".format(sum(y_train_res == 1)))print(\"After OverSampling, counts of label '0': {}\".format(sum(y_train_res == 0)))Output:Before OverSampling, counts of label '1': [345]\nBefore OverSampling, counts of label '0': [199019] \n\nAfter OverSampling, the shape of train_X: (398038, 29)\nAfter OverSampling, the shape of train_y: (398038, ) \n\nAfter OverSampling, counts of label '1': 199019\nAfter OverSampling, counts of label '0': 199019\nLook! that SMOTE Algorithm has oversampled the minority instances and made it equal to majority class. Both categories have equal amount of records. More specifically, the minority class has been increased to the total number of majority class.Now see the accuracy and recall results after applying SMOTE algorithm (Oversampling).Prediction and Recalllr1 = LogisticRegression()lr1.fit(X_train_res, y_train_res.ravel())predictions = lr1.predict(X_test) # print classification reportprint(classification_report(y_test, predictions))Output: precision recall f1-score support\n\n 0 1.00 0.98 0.99 85296\n 1 0.06 0.92 0.11 147\n\n accuracy 0.98 85443\n macro avg 0.53 0.95 0.55 85443\nweighted avg 1.00 0.98 0.99 85443\nWow, We have reduced the accuracy to 98% as compared to previous model but the recall value of minority class has also improved to 92 %. This is a good model compared to the previous one. Recall is great.Now, we will apply NearMiss technique to Under-sample the majority class and see its accuracy and recall results.NearMiss Algorithm:You can check all the parameters from here.print(\"Before Undersampling, counts of label '1': {}\".format(sum(y_train == 1)))print(\"Before Undersampling, counts of label '0': {} \\n\".format(sum(y_train == 0))) # apply near missfrom imblearn.under_sampling import NearMissnr = NearMiss() X_train_miss, y_train_miss = nr.fit_sample(X_train, y_train.ravel()) print('After Undersampling, the shape of train_X: {}'.format(X_train_miss.shape))print('After Undersampling, the shape of train_y: {} \\n'.format(y_train_miss.shape)) print(\"After Undersampling, counts of label '1': {}\".format(sum(y_train_miss == 1)))print(\"After Undersampling, counts of label '0': {}\".format(sum(y_train_miss == 0)))Output:Before Undersampling, counts of label '1': [345]\nBefore Undersampling, counts of label '0': [199019] \n\nAfter Undersampling, the shape of train_X: (690, 29)\nAfter Undersampling, the shape of train_y: (690, ) \n\nAfter Undersampling, counts of label '1': 345\nAfter Undersampling, counts of label '0': 345\nThe NearMiss Algorithm has undersampled the majority instances and made it equal to majority class. Here, the majority class has been reduced to the total number of minority class, so that both classes will have equal number of records.Prediction and Recall# train the model on train setlr2 = LogisticRegression()lr2.fit(X_train_miss, y_train_miss.ravel())predictions = lr2.predict(X_test) # print classification reportprint(classification_report(y_test, predictions))Output: precision recall f1-score support\n\n 0 1.00 0.56 0.72 85296\n 1 0.00 0.95 0.01 147\n\n accuracy 0.56 85443\n macro avg 0.50 0.75 0.36 85443\nweighted avg 1.00 0.56 0.72 85443\nThis model is better than the first model because it classifies better and also the recall value of minority class is 95 %. But due to undersampling of majority class, its recall has decreased to 56 %. So in this case, SMOTE is giving me a great accuracy and recall, I’ll go ahead and use that model! My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 37906, "s": 37789, "text": "For finding n closest instances in the majority class, there are several variations of applying NearMiss Algorithm :" }, { "code": null, "e": 38472, "s": 37906, "text": "NearMiss – Version 1 : It selects samples of the majority class for which average distances to the k closest instances of the minority class is smallest.NearMiss – Version 2 : It selects samples of the majority class for which average distances to the k farthest instances of the minority class is smallest.NearMiss – Version 3 : It works in 2 steps. Firstly, for each minority class instance, their M nearest-neighbors will be stored. Then finally, the majority class instances are selected for which the average distance to the N nearest-neighbors is the largest." }, { "code": null, "e": 38626, "s": 38472, "text": "NearMiss – Version 1 : It selects samples of the majority class for which average distances to the k closest instances of the minority class is smallest." }, { "code": null, "e": 38781, "s": 38626, "text": "NearMiss – Version 2 : It selects samples of the majority class for which average distances to the k farthest instances of the minority class is smallest." }, { "code": null, "e": 39040, "s": 38781, "text": "NearMiss – Version 3 : It works in 2 steps. Firstly, for each minority class instance, their M nearest-neighbors will be stored. Then finally, the majority class instances are selected for which the average distance to the N nearest-neighbors is the largest." }, { "code": null, "e": 39182, "s": 39040, "text": "This article helps in better understanding and hands-on practice on how to choose best between different imbalanced data handling techniques." }, { "code": null, "e": 39452, "s": 39182, "text": "The dataset consists of transactions made by credit cards. This dataset has 492 fraud transactions out of 284, 807 transactions. That makes it highly unbalanced, the positive class (frauds) account for 0.172% of all transactions.The dataset can be downloaded from here." }, { "code": "# import necessary modules import pandas as pdimport matplotlib.pyplot as pltimport numpy as npfrom sklearn.linear_model import LogisticRegressionfrom sklearn.preprocessing import StandardScalerfrom sklearn.metrics import confusion_matrix, classification_report # load the data setdata = pd.read_csv('creditcard.csv') # print info about columns in the dataframeprint(data.info())", "e": 39835, "s": 39452, "text": null }, { "code": null, "e": 39843, "s": 39835, "text": "Output:" }, { "code": null, "e": 40969, "s": 39843, "text": "RangeIndex: 284807 entries, 0 to 284806\nData columns (total 31 columns):\nTime 284807 non-null float64\nV1 284807 non-null float64\nV2 284807 non-null float64\nV3 284807 non-null float64\nV4 284807 non-null float64\nV5 284807 non-null float64\nV6 284807 non-null float64\nV7 284807 non-null float64\nV8 284807 non-null float64\nV9 284807 non-null float64\nV10 284807 non-null float64\nV11 284807 non-null float64\nV12 284807 non-null float64\nV13 284807 non-null float64\nV14 284807 non-null float64\nV15 284807 non-null float64\nV16 284807 non-null float64\nV17 284807 non-null float64\nV18 284807 non-null float64\nV19 284807 non-null float64\nV20 284807 non-null float64\nV21 284807 non-null float64\nV22 284807 non-null float64\nV23 284807 non-null float64\nV24 284807 non-null float64\nV25 284807 non-null float64\nV26 284807 non-null float64\nV27 284807 non-null float64\nV28 284807 non-null float64\nAmount 284807 non-null float64\nClass 284807 non-null int64\n" }, { "code": "# normalise the amount columndata['normAmount'] = StandardScaler().fit_transform(np.array(data['Amount']).reshape(-1, 1)) # drop Time and Amount columns as they are not relevant for prediction purpose data = data.drop(['Time', 'Amount'], axis = 1) # as you can see there are 492 fraud transactions.data['Class'].value_counts()", "e": 41298, "s": 40969, "text": null }, { "code": null, "e": 41306, "s": 41298, "text": "Output:" }, { "code": null, "e": 41345, "s": 41306, "text": " 0 284315\n 1 492\n" }, { "code": "from sklearn.model_selection import train_test_split # split into 70:30 rationX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 0) # describes info about train and test setprint(\"Number transactions X_train dataset: \", X_train.shape)print(\"Number transactions y_train dataset: \", y_train.shape)print(\"Number transactions X_test dataset: \", X_test.shape)print(\"Number transactions y_test dataset: \", y_test.shape)", "e": 41800, "s": 41345, "text": null }, { "code": null, "e": 41808, "s": 41800, "text": "Output:" }, { "code": null, "e": 42031, "s": 41808, "text": " Number transactions X_train dataset: (199364, 29)\n Number transactions y_train dataset: (199364, 1)\n Number transactions X_test dataset: (85443, 29)\n Number transactions y_test dataset: (85443, 1)\n" }, { "code": "# logistic regression objectlr = LogisticRegression() # train the model on train setlr.fit(X_train, y_train.ravel()) predictions = lr.predict(X_test) # print classification reportprint(classification_report(y_test, predictions))", "e": 42263, "s": 42031, "text": null }, { "code": null, "e": 42271, "s": 42263, "text": "Output:" }, { "code": null, "e": 42600, "s": 42271, "text": "\n precision recall f1-score support\n\n 0 1.00 1.00 1.00 85296\n 1 0.88 0.62 0.73 147\n\n accuracy 1.00 85443\n macro avg 0.94 0.81 0.86 85443\nweighted avg 1.00 1.00 1.00 85443\n" }, { "code": null, "e": 42937, "s": 42600, "text": "The accuracy comes out to be 100% but did you notice something strange ?The recall of the minority class in very less. It proves that the model is more biased towards majority class. So, it proves that this is not the best model.Now, we will apply different imbalanced data handling techniques and see their accuracy and recall results." }, { "code": null, "e": 42981, "s": 42937, "text": "You can check all the parameters from here." }, { "code": "print(\"Before OverSampling, counts of label '1': {}\".format(sum(y_train == 1)))print(\"Before OverSampling, counts of label '0': {} \\n\".format(sum(y_train == 0))) # import SMOTE module from imblearn library# pip install imblearn (if you don't have imblearn in your system)from imblearn.over_sampling import SMOTEsm = SMOTE(random_state = 2)X_train_res, y_train_res = sm.fit_sample(X_train, y_train.ravel()) print('After OverSampling, the shape of train_X: {}'.format(X_train_res.shape))print('After OverSampling, the shape of train_y: {} \\n'.format(y_train_res.shape)) print(\"After OverSampling, counts of label '1': {}\".format(sum(y_train_res == 1)))print(\"After OverSampling, counts of label '0': {}\".format(sum(y_train_res == 0)))", "e": 43717, "s": 42981, "text": null }, { "code": null, "e": 43725, "s": 43717, "text": "Output:" }, { "code": null, "e": 44033, "s": 43725, "text": "Before OverSampling, counts of label '1': [345]\nBefore OverSampling, counts of label '0': [199019] \n\nAfter OverSampling, the shape of train_X: (398038, 29)\nAfter OverSampling, the shape of train_y: (398038, ) \n\nAfter OverSampling, counts of label '1': 199019\nAfter OverSampling, counts of label '0': 199019\n" }, { "code": null, "e": 44364, "s": 44033, "text": "Look! that SMOTE Algorithm has oversampled the minority instances and made it equal to majority class. Both categories have equal amount of records. More specifically, the minority class has been increased to the total number of majority class.Now see the accuracy and recall results after applying SMOTE algorithm (Oversampling)." }, { "code": "lr1 = LogisticRegression()lr1.fit(X_train_res, y_train_res.ravel())predictions = lr1.predict(X_test) # print classification reportprint(classification_report(y_test, predictions))", "e": 44545, "s": 44364, "text": null }, { "code": null, "e": 44553, "s": 44545, "text": "Output:" }, { "code": null, "e": 44881, "s": 44553, "text": " precision recall f1-score support\n\n 0 1.00 0.98 0.99 85296\n 1 0.06 0.92 0.11 147\n\n accuracy 0.98 85443\n macro avg 0.53 0.95 0.55 85443\nweighted avg 1.00 0.98 0.99 85443\n" }, { "code": null, "e": 45199, "s": 44881, "text": "Wow, We have reduced the accuracy to 98% as compared to previous model but the recall value of minority class has also improved to 92 %. This is a good model compared to the previous one. Recall is great.Now, we will apply NearMiss technique to Under-sample the majority class and see its accuracy and recall results." }, { "code": null, "e": 45243, "s": 45199, "text": "You can check all the parameters from here." }, { "code": "print(\"Before Undersampling, counts of label '1': {}\".format(sum(y_train == 1)))print(\"Before Undersampling, counts of label '0': {} \\n\".format(sum(y_train == 0))) # apply near missfrom imblearn.under_sampling import NearMissnr = NearMiss() X_train_miss, y_train_miss = nr.fit_sample(X_train, y_train.ravel()) print('After Undersampling, the shape of train_X: {}'.format(X_train_miss.shape))print('After Undersampling, the shape of train_y: {} \\n'.format(y_train_miss.shape)) print(\"After Undersampling, counts of label '1': {}\".format(sum(y_train_miss == 1)))print(\"After Undersampling, counts of label '0': {}\".format(sum(y_train_miss == 0)))", "e": 45892, "s": 45243, "text": null }, { "code": null, "e": 45900, "s": 45892, "text": "Output:" }, { "code": null, "e": 46202, "s": 45900, "text": "Before Undersampling, counts of label '1': [345]\nBefore Undersampling, counts of label '0': [199019] \n\nAfter Undersampling, the shape of train_X: (690, 29)\nAfter Undersampling, the shape of train_y: (690, ) \n\nAfter Undersampling, counts of label '1': 345\nAfter Undersampling, counts of label '0': 345\n" }, { "code": null, "e": 46439, "s": 46202, "text": "The NearMiss Algorithm has undersampled the majority instances and made it equal to majority class. Here, the majority class has been reduced to the total number of minority class, so that both classes will have equal number of records." }, { "code": "# train the model on train setlr2 = LogisticRegression()lr2.fit(X_train_miss, y_train_miss.ravel())predictions = lr2.predict(X_test) # print classification reportprint(classification_report(y_test, predictions))", "e": 46652, "s": 46439, "text": null }, { "code": null, "e": 46660, "s": 46652, "text": "Output:" }, { "code": null, "e": 46989, "s": 46660, "text": " precision recall f1-score support\n\n 0 1.00 0.56 0.72 85296\n 1 0.00 0.95 0.01 147\n\n accuracy 0.56 85443\n macro avg 0.50 0.75 0.36 85443\nweighted avg 1.00 0.56 0.72 85443\n" }, { "code": null, "e": 47291, "s": 46989, "text": "This model is better than the first model because it classifies better and also the recall value of minority class is 95 %. But due to undersampling of majority class, its recall has decreased to 56 %. So in this case, SMOTE is giving me a great accuracy and recall, I’ll go ahead and use that model! " }, { "code": null, "e": 47310, "s": 47291, "text": "tanwarsinghvaibhav" }, { "code": null, "e": 47327, "s": 47310, "text": "Machine Learning" }, { "code": null, "e": 47334, "s": 47327, "text": "Python" }, { "code": null, "e": 47351, "s": 47334, "text": "Machine Learning" }, { "code": null, "e": 47449, "s": 47351, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 47458, "s": 47449, "text": "Comments" }, { "code": null, "e": 47471, "s": 47458, "text": "Old Comments" }, { "code": null, "e": 47495, "s": 47471, "text": "Search Algorithms in AI" }, { "code": null, "e": 47533, "s": 47495, "text": "Python | Decision tree implementation" }, { "code": null, "e": 47573, "s": 47533, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 47619, "s": 47573, "text": "Elbow Method for optimal value of k in KMeans" }, { "code": null, "e": 47652, "s": 47619, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 47680, "s": 47652, "text": "Read JSON file using Python" }, { "code": null, "e": 47730, "s": 47680, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 47752, "s": 47730, "text": "Python map() function" } ]
Count Hexadecimal Number in C++
We are given a range having start and end and the task is to calculate the count of hexadecimal numbers or alphabets present in the given range. In computer terms, hexadecimal numbers are those numbers that are having base 16 which means the binary digit can be represented in 16-bit. It consists of integer numbers starting from 0-15. Where 10 is represented as A, 11 as B, 12 as C, 13 as D, 14 as E and 15 as F. So, in the below program our task is to find whether the range consists of hexadecimal alphabets or not. Input − start = 10, End = 13 Output − 4 Explanation − There are 4 hexadecimal numbers between 10 and 13 i.e. 10 being A, 11 being B, 12 being C and 13 being D. Input − start = 15, End = 16 Output − 1 Explanation − There is only one hexadecimal alphabet i.e. 15 as F and 16 is represented as 10 respectively. Input the range starting from variable let’s say, start and end. Input the range starting from variable let’s say, start and end. Declare a variable count to store the count and initialises it with 0 Declare a variable count to store the count and initialises it with 0 Start a loop for with i to start and till i is less than or equals to end Start a loop for with i to start and till i is less than or equals to end Inside the loop, check if i is greater than or equals to 10 and i is also greater than or equals to 15 then increase the count by 1 Inside the loop, check if i is greater than or equals to 10 and i is also greater than or equals to 15 then increase the count by 1 Else, check if i is greater than 15 Else, check if i is greater than 15 Then, set a temporary variable temp with the value of i and traverse while k is not equals to 0 Then, set a temporary variable temp with the value of i and traverse while k is not equals to 0 And check if k%16 is greater than or equals to 10 And check if k%16 is greater than or equals to 10 Increase the count by 1 Increase the count by 1 and , set the temp by temp/16 and , set the temp by temp/16 Return the value of count Return the value of count Print the result . Print the result . Live Demo #include <iostream> using namespace std; // Function to count the // total number hexadecimal alphabet int counthexa(int start, int end){ int result = 0; for (int i = start; i <= end; i++){ // All hexadecimal alphabets // from 10 to 15 if (i >= 10 && i <= 15){ result++; } // If i > 15 then perform mod by 16 repeatedly // till the number is > 0 // If number % 16 > 10 then increase count else if (i > 15){ int k = i; while (k != 0){ if (k % 16 >= 10){ result++; } k = k / 16; } } } return result; } // Main Function int main(){ int start = 10, end = 60; cout << "count is: "<<counthexa(start, end); return 0; } If we run the above code it will generate the following output − count is: 21
[ { "code": null, "e": 1207, "s": 1062, "text": "We are given a range having start and end and the task is to calculate the count of\nhexadecimal numbers or alphabets present in the given range." }, { "code": null, "e": 1476, "s": 1207, "text": "In computer terms, hexadecimal numbers are those numbers that are having base 16\nwhich means the binary digit can be represented in 16-bit. It consists of integer numbers\nstarting from 0-15. Where 10 is represented as A, 11 as B, 12 as C, 13 as D, 14 as E\nand 15 as F." }, { "code": null, "e": 1581, "s": 1476, "text": "So, in the below program our task is to find whether the range consists of hexadecimal\nalphabets or not." }, { "code": null, "e": 1621, "s": 1581, "text": "Input − start = 10, End = 13\nOutput − 4" }, { "code": null, "e": 1741, "s": 1621, "text": "Explanation − There are 4 hexadecimal numbers between 10 and 13 i.e. 10 being A, 11 being B, 12 being C and 13 being D." }, { "code": null, "e": 1781, "s": 1741, "text": "Input − start = 15, End = 16\nOutput − 1" }, { "code": null, "e": 1889, "s": 1781, "text": "Explanation − There is only one hexadecimal alphabet i.e. 15 as F and 16 is represented as 10 respectively." }, { "code": null, "e": 1954, "s": 1889, "text": "Input the range starting from variable let’s say, start and end." }, { "code": null, "e": 2019, "s": 1954, "text": "Input the range starting from variable let’s say, start and end." }, { "code": null, "e": 2089, "s": 2019, "text": "Declare a variable count to store the count and initialises it with 0" }, { "code": null, "e": 2159, "s": 2089, "text": "Declare a variable count to store the count and initialises it with 0" }, { "code": null, "e": 2233, "s": 2159, "text": "Start a loop for with i to start and till i is less than or equals to end" }, { "code": null, "e": 2307, "s": 2233, "text": "Start a loop for with i to start and till i is less than or equals to end" }, { "code": null, "e": 2439, "s": 2307, "text": "Inside the loop, check if i is greater than or equals to 10 and i is also greater than or equals to 15 then increase the count by 1" }, { "code": null, "e": 2571, "s": 2439, "text": "Inside the loop, check if i is greater than or equals to 10 and i is also greater than or equals to 15 then increase the count by 1" }, { "code": null, "e": 2607, "s": 2571, "text": "Else, check if i is greater than 15" }, { "code": null, "e": 2643, "s": 2607, "text": "Else, check if i is greater than 15" }, { "code": null, "e": 2739, "s": 2643, "text": "Then, set a temporary variable temp with the value of i and traverse while k is not equals to 0" }, { "code": null, "e": 2835, "s": 2739, "text": "Then, set a temporary variable temp with the value of i and traverse while k is not equals to 0" }, { "code": null, "e": 2885, "s": 2835, "text": "And check if k%16 is greater than or equals to 10" }, { "code": null, "e": 2935, "s": 2885, "text": "And check if k%16 is greater than or equals to 10" }, { "code": null, "e": 2959, "s": 2935, "text": "Increase the count by 1" }, { "code": null, "e": 2983, "s": 2959, "text": "Increase the count by 1" }, { "code": null, "e": 3013, "s": 2983, "text": "and , set the temp by temp/16" }, { "code": null, "e": 3043, "s": 3013, "text": "and , set the temp by temp/16" }, { "code": null, "e": 3069, "s": 3043, "text": "Return the value of count" }, { "code": null, "e": 3095, "s": 3069, "text": "Return the value of count" }, { "code": null, "e": 3114, "s": 3095, "text": "Print the result ." }, { "code": null, "e": 3133, "s": 3114, "text": "Print the result ." }, { "code": null, "e": 3144, "s": 3133, "text": " Live Demo" }, { "code": null, "e": 3918, "s": 3144, "text": "#include <iostream>\nusing namespace std;\n// Function to count the\n// total number hexadecimal alphabet\nint counthexa(int start, int end){\n int result = 0;\n for (int i = start; i <= end; i++){\n // All hexadecimal alphabets\n // from 10 to 15\n if (i >= 10 && i <= 15){\n result++;\n }\n // If i > 15 then perform mod by 16 repeatedly\n // till the number is > 0\n // If number % 16 > 10 then increase count\n else if (i > 15){\n int k = i;\n while (k != 0){\n if (k % 16 >= 10){\n result++;\n }\n k = k / 16;\n }\n }\n }\n return result;\n}\n// Main Function\nint main(){\n int start = 10, end = 60;\n cout << \"count is: \"<<counthexa(start, end);\n return 0;\n}" }, { "code": null, "e": 3983, "s": 3918, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 3996, "s": 3983, "text": "count is: 21" } ]
An AI agent learns to play tic-tac-toe (part 3): training a Q-learning RL agent | by Paul Hiemstra | Towards Data Science
This article is part of a series that lets a computer play tic-tac-toe using reinforcement learning. You can find all the articles here. The goal is to provide a complete implementation that you can really pick apart and learn reinforcement learning from. It is probably best to read the articles in order. The article including all the code can be found on Github. In part 1 and 2 of this series we built the opponent for our reinforcement learning (RL) agent, so now we can start working on the actual RL agent itself. Before we go into the actual implementation, I want to spend some time on how Q learning works. As we learned in part 1, RL is based on the following key concepts: The goal of the agent is to find an efficient policy, i.e. what action is optimal in a given situation. In the case of tic-tac-toe this means what move is optimal given the state on the board. Notice that the policy focuses on long-term value Q, not soley on short term reward R. More mathematically speaking, the policy is the function Q(S,a) with state s and action a, and reinforcement learning is the way to learn this function. Q-learning is a common reinforcement learning approach. At the core of this approach is the Q-table which stores all the combinations of states and actions, essentially representing a discrete version of the Q function. In this article, we store the qtable using a dictionary. Given a certain boardstate, we can determine which action has the highest Q value: 'e' Given board_state_1, the best move we can make is e (the center square) as it has the highest Q value. With the Q table defined, our main challenge is to learn the appropriate Q values. The following pseudocode describes the learning process: for all episodes: if not boardstate in qtable: qtable[boardstate] = 0 for all actions if (pick random action with chance epsilon) pick random action else pick action with highest q value for boardstate Q[boardstate, action] = update_qtable(Q[boardstate, action], reward for action, Q[next_boardstates]) tree search makes move So we just play a lot of tic-tac-toe games (episodes) against the tree search, and slowly update the Q values. Some important observations: We initialize our qtable with 0, starting out with no clear indication of what is a good move. If multiple moves exist with the maximum Q value, we choose a random action from those moves. This is to stimulate exploration of boardstates. Having multiple maximum values is very common at the start of our training process. We do not always pick the optimal move from the Q table (exploitation), but take a random move with chance ε. This is to stimulate the learning process by exploring random new boardstates that might have good rewards. This ensures we do not quickly end up in a local minimum, but continuine the search for better moves. This exploitation versus exploration dynamic is an important part of efficiently learning our Q table. The reward for an action is +10 points if we win, -10 points if we lose and +5 points if we draw. The most important step in Q learning is updating the Q values in the table. The following pseudo-equation describes how it works: new Q value = old Q value + instantaneous reward + maximum Q for next states after the action we took So the new Q value takes into account the previous Q-value, the reward we got for taking action a in state S and the Q-values of the possibles moves after taking a in state S. Note that to learn the longterm Q value, we only ever look ahead a single move to the next maximum possible Q value. This is in sharp contrast to the tree search approach which looks ahead all the way to the end of the game. Being able to learn the longterm reward by only looking ahead a single move makes Q-learning rather magical for me. A downside ofcourse is that we need to play a lot of games in order to slowly let all the Q-values spread itself throughout the Q table. The following equation expresses the update rule more formally: where (1−α)Q(s_t,a_t) equals the old Q-value of taking action a_t in state s_t, αr_t equals the instantaneous reward, and αγ max(s_t+1,a) the maximum Q-value we can get for our next move after taking action a and ending up in state s_t+1. The equation includes a number of coefficients: α the learning rate which determines how fast Q values are updated given new information. If the learning rate is zero, the new value is simply the old value. This essentially means the algorithm is not learning anything new. An alpha value of 1 simply discards this old value and completely relies on the new Q value calculated by the other terms. Values in between 0 and 1 allow you to control how fast learning progresses. A balance between learning fast enough, but not getting focused too quickly in one particular Q value is part of the challenge of Q learning. γ the discount factor. This determines if we focus mainly on short term reward (small γ) or on long term value (large γ). With the theoretical foundation out of the way, we can go into actually training our RL agent. The Python script train_qlearning.py on Github performs our entire training loop following the pseudo-code training approach we defined earlier. The first dozen lines initialize the tree we built and optimized, this will serve as the opponent for our RL agent. Next we initialize two objects: The first object tracks the tic-tac-toe board state. It allows one to make a move, check if the game is done, and hands out rewards at the end of the game. The file support_functions.py on GitHub contains all the details. The second object player_tree represents our RL agent which plays the game and slowly updates its Q table. Note we tweaked the values for alpha, gamma and epsilon manually, but the our learning does not seem to overly sensitive to these values. Probably tic-tac-toe is not really a challenging problem for Q learning. The training loop uses these Python objects to play tic-tac-toe and slowly learn the Q table: Here we play 10000 tic-tac-toe games. As the benchmark for our trained RL agent, we first let an untrained agent play against the tree search. We simply create a player from scratch and let it play against the tree search without Q learning: -10.0 768 5.0 232dtype: int64 The untrained agent mostly loses its games (-10) or plays the tree to a draw (5). This is abysmal performance given we are allowed to start the game. In contrast, running the same analysis for an agent that has been trained for 100.000 games using train_qlearning.py: 5.0 1000dtype: int64 shows that the RL agent has become very adept at playing against the tree, always playing it to a draw. To drill down a bit more into how Q learning has learned how to play tic-tac-toe we focus on the contents of the Q-table. The following figure shows the final Q-table at the end of the 100.000 training games. Remember that we are the X player and that blue means a good Q value and red a negative Q value: The Q-table contains the information the RL agent has about the tic-tac-toe policy. Good examples are: Where we learned that the corners are good moves to make initially, which is obvious from the darker blue color. In addition, we (X) learned to block moves by the tree search (O). Here the blocking move is blue, and the other moves are deeply red. In addition to the final learned Q table, the following youtube movie nicely illustrates how the Q table slowly develops over 100.000 games played. As new states are introduced, the table grows. In addition, the white color is slowly replaced by positive (blue) and negative (red) values showing that the agent learns what good and bad moves are. In our next part, we will focus on how I visualised the Q table. My name is Paul Hiemstra, and I work as a teacher and data scientist in the Netherlands. I am a mix between a scientist and a software engineer, and have a broad interest in everything related to data science. You can follow me here on medium, or on LinkedIn. If you enjoyed this article, you might also enjoy some of my other articles: There is no data science like applied data science Altair plot deconstruction: visualizing the correlation structure of weather data Advanced functional programming for data science: building code architectures with function operators
[ { "code": null, "e": 538, "s": 172, "text": "This article is part of a series that lets a computer play tic-tac-toe using reinforcement learning. You can find all the articles here. The goal is to provide a complete implementation that you can really pick apart and learn reinforcement learning from. It is probably best to read the articles in order. The article including all the code can be found on Github." }, { "code": null, "e": 789, "s": 538, "text": "In part 1 and 2 of this series we built the opponent for our reinforcement learning (RL) agent, so now we can start working on the actual RL agent itself. Before we go into the actual implementation, I want to spend some time on how Q learning works." }, { "code": null, "e": 857, "s": 789, "text": "As we learned in part 1, RL is based on the following key concepts:" }, { "code": null, "e": 1290, "s": 857, "text": "The goal of the agent is to find an efficient policy, i.e. what action is optimal in a given situation. In the case of tic-tac-toe this means what move is optimal given the state on the board. Notice that the policy focuses on long-term value Q, not soley on short term reward R. More mathematically speaking, the policy is the function Q(S,a) with state s and action a, and reinforcement learning is the way to learn this function." }, { "code": null, "e": 1650, "s": 1290, "text": "Q-learning is a common reinforcement learning approach. At the core of this approach is the Q-table which stores all the combinations of states and actions, essentially representing a discrete version of the Q function. In this article, we store the qtable using a dictionary. Given a certain boardstate, we can determine which action has the highest Q value:" }, { "code": null, "e": 1654, "s": 1650, "text": "'e'" }, { "code": null, "e": 1757, "s": 1654, "text": "Given board_state_1, the best move we can make is e (the center square) as it has the highest Q value." }, { "code": null, "e": 1897, "s": 1757, "text": "With the Q table defined, our main challenge is to learn the appropriate Q values. The following pseudocode describes the learning process:" }, { "code": null, "e": 2343, "s": 1897, "text": "for all episodes: if not boardstate in qtable: qtable[boardstate] = 0 for all actions if (pick random action with chance epsilon) pick random action else pick action with highest q value for boardstate Q[boardstate, action] = update_qtable(Q[boardstate, action], reward for action, Q[next_boardstates]) tree search makes move" }, { "code": null, "e": 2483, "s": 2343, "text": "So we just play a lot of tic-tac-toe games (episodes) against the tree search, and slowly update the Q values. Some important observations:" }, { "code": null, "e": 2578, "s": 2483, "text": "We initialize our qtable with 0, starting out with no clear indication of what is a good move." }, { "code": null, "e": 2805, "s": 2578, "text": "If multiple moves exist with the maximum Q value, we choose a random action from those moves. This is to stimulate exploration of boardstates. Having multiple maximum values is very common at the start of our training process." }, { "code": null, "e": 3228, "s": 2805, "text": "We do not always pick the optimal move from the Q table (exploitation), but take a random move with chance ε. This is to stimulate the learning process by exploring random new boardstates that might have good rewards. This ensures we do not quickly end up in a local minimum, but continuine the search for better moves. This exploitation versus exploration dynamic is an important part of efficiently learning our Q table." }, { "code": null, "e": 3326, "s": 3228, "text": "The reward for an action is +10 points if we win, -10 points if we lose and +5 points if we draw." }, { "code": null, "e": 3457, "s": 3326, "text": "The most important step in Q learning is updating the Q values in the table. The following pseudo-equation describes how it works:" }, { "code": null, "e": 3559, "s": 3457, "text": "new Q value = old Q value + instantaneous reward + maximum Q for next states after the action we took" }, { "code": null, "e": 4213, "s": 3559, "text": "So the new Q value takes into account the previous Q-value, the reward we got for taking action a in state S and the Q-values of the possibles moves after taking a in state S. Note that to learn the longterm Q value, we only ever look ahead a single move to the next maximum possible Q value. This is in sharp contrast to the tree search approach which looks ahead all the way to the end of the game. Being able to learn the longterm reward by only looking ahead a single move makes Q-learning rather magical for me. A downside ofcourse is that we need to play a lot of games in order to slowly let all the Q-values spread itself throughout the Q table." }, { "code": null, "e": 4277, "s": 4213, "text": "The following equation expresses the update rule more formally:" }, { "code": null, "e": 4564, "s": 4277, "text": "where (1−α)Q(s_t,a_t) equals the old Q-value of taking action a_t in state s_t, αr_t equals the instantaneous reward, and αγ max(s_t+1,a) the maximum Q-value we can get for our next move after taking action a and ending up in state s_t+1. The equation includes a number of coefficients:" }, { "code": null, "e": 5132, "s": 4564, "text": "α the learning rate which determines how fast Q values are updated given new information. If the learning rate is zero, the new value is simply the old value. This essentially means the algorithm is not learning anything new. An alpha value of 1 simply discards this old value and completely relies on the new Q value calculated by the other terms. Values in between 0 and 1 allow you to control how fast learning progresses. A balance between learning fast enough, but not getting focused too quickly in one particular Q value is part of the challenge of Q learning." }, { "code": null, "e": 5254, "s": 5132, "text": "γ the discount factor. This determines if we focus mainly on short term reward (small γ) or on long term value (large γ)." }, { "code": null, "e": 5642, "s": 5254, "text": "With the theoretical foundation out of the way, we can go into actually training our RL agent. The Python script train_qlearning.py on Github performs our entire training loop following the pseudo-code training approach we defined earlier. The first dozen lines initialize the tree we built and optimized, this will serve as the opponent for our RL agent. Next we initialize two objects:" }, { "code": null, "e": 6182, "s": 5642, "text": "The first object tracks the tic-tac-toe board state. It allows one to make a move, check if the game is done, and hands out rewards at the end of the game. The file support_functions.py on GitHub contains all the details. The second object player_tree represents our RL agent which plays the game and slowly updates its Q table. Note we tweaked the values for alpha, gamma and epsilon manually, but the our learning does not seem to overly sensitive to these values. Probably tic-tac-toe is not really a challenging problem for Q learning." }, { "code": null, "e": 6276, "s": 6182, "text": "The training loop uses these Python objects to play tic-tac-toe and slowly learn the Q table:" }, { "code": null, "e": 6314, "s": 6276, "text": "Here we play 10000 tic-tac-toe games." }, { "code": null, "e": 6518, "s": 6314, "text": "As the benchmark for our trained RL agent, we first let an untrained agent play against the tree search. We simply create a player from scratch and let it play against the tree search without Q learning:" }, { "code": null, "e": 6555, "s": 6518, "text": "-10.0 768 5.0 232dtype: int64" }, { "code": null, "e": 6823, "s": 6555, "text": "The untrained agent mostly loses its games (-10) or plays the tree to a draw (5). This is abysmal performance given we are allowed to start the game. In contrast, running the same analysis for an agent that has been trained for 100.000 games using train_qlearning.py:" }, { "code": null, "e": 6847, "s": 6823, "text": "5.0 1000dtype: int64" }, { "code": null, "e": 6951, "s": 6847, "text": "shows that the RL agent has become very adept at playing against the tree, always playing it to a draw." }, { "code": null, "e": 7257, "s": 6951, "text": "To drill down a bit more into how Q learning has learned how to play tic-tac-toe we focus on the contents of the Q-table. The following figure shows the final Q-table at the end of the 100.000 training games. Remember that we are the X player and that blue means a good Q value and red a negative Q value:" }, { "code": null, "e": 7360, "s": 7257, "text": "The Q-table contains the information the RL agent has about the tic-tac-toe policy. Good examples are:" }, { "code": null, "e": 7608, "s": 7360, "text": "Where we learned that the corners are good moves to make initially, which is obvious from the darker blue color. In addition, we (X) learned to block moves by the tree search (O). Here the blocking move is blue, and the other moves are deeply red." }, { "code": null, "e": 7756, "s": 7608, "text": "In addition to the final learned Q table, the following youtube movie nicely illustrates how the Q table slowly develops over 100.000 games played." }, { "code": null, "e": 7955, "s": 7756, "text": "As new states are introduced, the table grows. In addition, the white color is slowly replaced by positive (blue) and negative (red) values showing that the agent learns what good and bad moves are." }, { "code": null, "e": 8020, "s": 7955, "text": "In our next part, we will focus on how I visualised the Q table." }, { "code": null, "e": 8280, "s": 8020, "text": "My name is Paul Hiemstra, and I work as a teacher and data scientist in the Netherlands. I am a mix between a scientist and a software engineer, and have a broad interest in everything related to data science. You can follow me here on medium, or on LinkedIn." }, { "code": null, "e": 8357, "s": 8280, "text": "If you enjoyed this article, you might also enjoy some of my other articles:" }, { "code": null, "e": 8408, "s": 8357, "text": "There is no data science like applied data science" }, { "code": null, "e": 8490, "s": 8408, "text": "Altair plot deconstruction: visualizing the correlation structure of weather data" } ]
React useState Hook
The React useState Hook allows us to track state in a function component. State generally refers to data or properties that need to be tracking in an application. To use the useState Hook, we first need to import it into our component. At the top of your component, import the useState Hook. import { useState } from "react"; Notice that we are destructuring useState from react as it is a named export. To learn more about destructuring, check out the ES6 section. We initialize our state by calling useState in our function component. useState accepts an initial state and returns two values: The current state. A function that updates the state. Initialize state at the top of the function component. import { useState } from "react"; function FavoriteColor() { const [color, setColor] = useState(""); } Notice that again, we are destructuring the returned values from useState. The first value, color, is our current state. The second value, setColor, is the function that is used to update our state. These names are variables that can be named anything you would like. Lastly, we set the initial state to an empty string: useState("") We can now include our state anywhere in our component. Use the state variable in the rendered component. import { useState } from "react"; import ReactDOM from "react-dom/client"; function FavoriteColor() { const [color, setColor] = useState("red"); return <h1>My favorite color is {color}!</h1> } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<FavoriteColor />); Run Example » To update our state, we use our state updater function. We should never directly update state. Ex: color = "red" is not allowed. Use a button to update the state: import { useState } from "react"; import ReactDOM from "react-dom/client"; function FavoriteColor() { const [color, setColor] = useState("red"); return ( <> <h1>My favorite color is {color}!</h1> <button type="button" onClick={() => setColor("blue")} >Blue</button> </> ) } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<FavoriteColor />); Run Example » The useState Hook can be used to keep track of strings, numbers, booleans, arrays, objects, and any combination of these! We could create multiple state Hooks to track individual values. Create multiple state Hooks: import { useState } from "react"; import ReactDOM from "react-dom/client"; function Car() { const [brand, setBrand] = useState("Ford"); const [model, setModel] = useState("Mustang"); const [year, setYear] = useState("1964"); const [color, setColor] = useState("red"); return ( <> <h1>My {brand}</h1> <p> It is a {color} {model} from {year}. </p> </> ) } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Car />); Run Example » Or, we can just use one state and include an object instead! Create a single Hook that holds an object: import { useState } from "react"; import ReactDOM from "react-dom/client"; function Car() { const [car, setCar] = useState({ brand: "Ford", model: "Mustang", year: "1964", color: "red" }); return ( <> <h1>My {car.brand}</h1> <p> It is a {car.color} {car.model} from {car.year}. </p> </> ) } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Car />); Run Example » Since we are now tracking a single object, we need to reference that object and then the property of that object when rendering the component. (Ex: car.brand) When state is updated, the entire state gets overwritten. What if we only want to update the color of our car? If we only called setCar({color: "blue"}), this would remove the brand, model, and year from our state. We can use the JavaScript spread operator to help us. Use the JavaScript spread operator to update only the color of the car: import { useState } from "react"; import ReactDOM from "react-dom/client"; function Car() { const [car, setCar] = useState({ brand: "Ford", model: "Mustang", year: "1964", color: "red" }); const updateColor = () => { setCar(previousState => { return { ...previousState, color: "blue" } }); } return ( <> <h1>My {car.brand}</h1> <p> It is a {car.color} {car.model} from {car.year}. </p> <button type="button" onClick={updateColor} >Blue</button> </> ) } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Car />); Run Example » Because we need the current value of state, we pass a function into our setCar function. This function receives the previous value. We then return an object, spreading the previousState and overwriting only the color. Complete this statement to keep track of a "count" variable using the useState Hook. import { useState } from "react"; function KeepCount() { const [, ] = useState(0); } Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 74, "s": 0, "text": "The React useState Hook allows us to track state in a function component." }, { "code": null, "e": 163, "s": 74, "text": "State generally refers to data or properties that need to be tracking in an application." }, { "code": null, "e": 236, "s": 163, "text": "To use the useState Hook, we first need to import it into our component." }, { "code": null, "e": 292, "s": 236, "text": "At the top of your component, import the useState Hook." }, { "code": null, "e": 327, "s": 292, "text": "import { useState } from \"react\";\n" }, { "code": null, "e": 405, "s": 327, "text": "Notice that we are destructuring useState from react as it is a named export." }, { "code": null, "e": 467, "s": 405, "text": "To learn more about destructuring, check out the ES6 section." }, { "code": null, "e": 538, "s": 467, "text": "We initialize our state by calling useState in our function component." }, { "code": null, "e": 596, "s": 538, "text": "useState accepts an initial state and returns two values:" }, { "code": null, "e": 615, "s": 596, "text": "The current state." }, { "code": null, "e": 650, "s": 615, "text": "A function that updates the state." }, { "code": null, "e": 705, "s": 650, "text": "Initialize state at the top of the function component." }, { "code": null, "e": 812, "s": 705, "text": "import { useState } from \"react\";\n\nfunction FavoriteColor() {\n const [color, setColor] = useState(\"\");\n}\n" }, { "code": null, "e": 887, "s": 812, "text": "Notice that again, we are destructuring the returned values from useState." }, { "code": null, "e": 933, "s": 887, "text": "The first value, color, is our current state." }, { "code": null, "e": 1011, "s": 933, "text": "The second value, setColor, is the function that is used to update our state." }, { "code": null, "e": 1080, "s": 1011, "text": "These names are variables that can be named anything you would like." }, { "code": null, "e": 1146, "s": 1080, "text": "Lastly, we set the initial state to an empty string: useState(\"\")" }, { "code": null, "e": 1202, "s": 1146, "text": "We can now include our state anywhere in our component." }, { "code": null, "e": 1252, "s": 1202, "text": "Use the state variable in the rendered component." }, { "code": null, "e": 1552, "s": 1252, "text": "import { useState } from \"react\";\nimport ReactDOM from \"react-dom/client\";\n\nfunction FavoriteColor() {\n const [color, setColor] = useState(\"red\");\n\n return <h1>My favorite color is {color}!</h1>\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<FavoriteColor />);\n" }, { "code": null, "e": 1569, "s": 1552, "text": "\nRun \nExample »\n" }, { "code": null, "e": 1625, "s": 1569, "text": "To update our state, we use our state updater function." }, { "code": null, "e": 1698, "s": 1625, "text": "We should never directly update state. Ex: color = \"red\" is not allowed." }, { "code": null, "e": 1732, "s": 1698, "text": "Use a button to update the state:" }, { "code": null, "e": 2157, "s": 1732, "text": "import { useState } from \"react\";\nimport ReactDOM from \"react-dom/client\";\n\nfunction FavoriteColor() {\n const [color, setColor] = useState(\"red\");\n\n return (\n <>\n <h1>My favorite color is {color}!</h1>\n <button\n type=\"button\"\n onClick={() => setColor(\"blue\")}\n >Blue</button>\n </>\n )\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<FavoriteColor />);\n" }, { "code": null, "e": 2174, "s": 2157, "text": "\nRun \nExample »\n" }, { "code": null, "e": 2296, "s": 2174, "text": "The useState Hook can be used to keep track of strings, numbers, booleans, arrays, objects, and any combination of these!" }, { "code": null, "e": 2361, "s": 2296, "text": "We could create multiple state Hooks to track individual values." }, { "code": null, "e": 2390, "s": 2361, "text": "Create multiple state Hooks:" }, { "code": null, "e": 2883, "s": 2390, "text": "import { useState } from \"react\";\nimport ReactDOM from \"react-dom/client\";\n\nfunction Car() {\n const [brand, setBrand] = useState(\"Ford\");\n const [model, setModel] = useState(\"Mustang\");\n const [year, setYear] = useState(\"1964\");\n const [color, setColor] = useState(\"red\");\n\n return (\n <>\n <h1>My {brand}</h1>\n <p>\n It is a {color} {model} from {year}.\n </p>\n </>\n )\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Car />);\n" }, { "code": null, "e": 2900, "s": 2883, "text": "\nRun \nExample »\n" }, { "code": null, "e": 2961, "s": 2900, "text": "Or, we can just use one state and include an object instead!" }, { "code": null, "e": 3004, "s": 2961, "text": "Create a single Hook that holds an object:" }, { "code": null, "e": 3446, "s": 3004, "text": "import { useState } from \"react\";\nimport ReactDOM from \"react-dom/client\";\n\nfunction Car() {\n const [car, setCar] = useState({\n brand: \"Ford\",\n model: \"Mustang\",\n year: \"1964\",\n color: \"red\"\n });\n\n return (\n <>\n <h1>My {car.brand}</h1>\n <p>\n It is a {car.color} {car.model} from {car.year}.\n </p>\n </>\n )\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Car />);\n" }, { "code": null, "e": 3463, "s": 3446, "text": "\nRun \nExample »\n" }, { "code": null, "e": 3622, "s": 3463, "text": "Since we are now tracking a single object,\nwe need to reference that object and then the property of that object when rendering the component.\n(Ex: car.brand)" }, { "code": null, "e": 3680, "s": 3622, "text": "When state is updated, the entire state gets overwritten." }, { "code": null, "e": 3733, "s": 3680, "text": "What if we only want to update the color of our car?" }, { "code": null, "e": 3837, "s": 3733, "text": "If we only called setCar({color: \"blue\"}), this would remove the brand, model, and year from our state." }, { "code": null, "e": 3891, "s": 3837, "text": "We can use the JavaScript spread operator to help us." }, { "code": null, "e": 3963, "s": 3891, "text": "Use the JavaScript spread operator to update only the color of the car:" }, { "code": null, "e": 4614, "s": 3963, "text": "import { useState } from \"react\";\nimport ReactDOM from \"react-dom/client\";\n\nfunction Car() {\n const [car, setCar] = useState({\n brand: \"Ford\",\n model: \"Mustang\",\n year: \"1964\",\n color: \"red\"\n });\n\n const updateColor = () => {\n setCar(previousState => {\n return { ...previousState, color: \"blue\" }\n });\n }\n\n return (\n <>\n <h1>My {car.brand}</h1>\n <p>\n It is a {car.color} {car.model} from {car.year}.\n </p>\n <button\n type=\"button\"\n onClick={updateColor}\n >Blue</button>\n </>\n )\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Car />);\n" }, { "code": null, "e": 4631, "s": 4614, "text": "\nRun \nExample »\n" }, { "code": null, "e": 4763, "s": 4631, "text": "Because we need the current value of state, we pass a function into our setCar function.\nThis function receives the previous value." }, { "code": null, "e": 4849, "s": 4763, "text": "We then return an object, spreading the previousState and overwriting only the color." }, { "code": null, "e": 4934, "s": 4849, "text": "Complete this statement to keep track of a \"count\" variable using the useState Hook." }, { "code": null, "e": 5023, "s": 4934, "text": "import { useState } from \"react\";\n\nfunction KeepCount() {\n const [, ] = useState(0);\n}\n" }, { "code": null, "e": 5042, "s": 5023, "text": "Start the Exercise" }, { "code": null, "e": 5075, "s": 5042, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 5117, "s": 5075, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 5224, "s": 5117, "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": 5243, "s": 5224, "text": "[email protected]" } ]
Console.SetError() Method in C# - GeeksforGeeks
11 Mar, 2019 The Console.SetError(TextWriter) Method sets the Error property of the specified StreamWriter i.e., it redirects the standard error stream to a file. As the console is set with this StreamWriter object, the WriteLine() method can be called to write the error into the file. Syntax: public static void SetError (System.IO.StreamWriter newError); Parameter:newError: It is a stream which is the new standard error output. Exception: This method will throw the ArgumentNullException if the parameter passed is null. Also, since it uses the StreamWriter object, it’s exceptions should also be taken care of. Example: In this example, the SetError() method is used to set the StreamWriter object to the console, and the error messages will be written into a log file from the Console. // C# program to demonstrate // the SetError() methodusing System;using System.IO; class GFG { // Main Method static void Main() { // Define file to receive error stream. string fn = "F:\\gfg_error.log"; // Define the new error StreamWriter object StreamWriter errStream = new StreamWriter(fn); // Redirect standard error stream to file. Console.SetError(errStream); // Write the error message into the Log file Console.Error.WriteLine("Error line is written into the log file."); Console.Error.WriteLine("Keep coding geeks!"); // Close redirected error stream. Console.Error.Close(); }} Output: The gfg_error.log file will now have the error messages in it. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.console.seterror?view=netframework-4.7.2#System_Console_SetError_System_IO_TextWriter_ CSharp-Console-Class CSharp-method Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# Convert String to Character Array in C# C# | How to insert an element in an Array? Linked List Implementation in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n11 Mar, 2019" }, { "code": null, "e": 25821, "s": 25547, "text": "The Console.SetError(TextWriter) Method sets the Error property of the specified StreamWriter i.e., it redirects the standard error stream to a file. As the console is set with this StreamWriter object, the WriteLine() method can be called to write the error into the file." }, { "code": null, "e": 25892, "s": 25821, "text": "Syntax: public static void SetError (System.IO.StreamWriter newError);" }, { "code": null, "e": 25967, "s": 25892, "text": "Parameter:newError: It is a stream which is the new standard error output." }, { "code": null, "e": 26151, "s": 25967, "text": "Exception: This method will throw the ArgumentNullException if the parameter passed is null. Also, since it uses the StreamWriter object, it’s exceptions should also be taken care of." }, { "code": null, "e": 26327, "s": 26151, "text": "Example: In this example, the SetError() method is used to set the StreamWriter object to the console, and the error messages will be written into a log file from the Console." }, { "code": "// C# program to demonstrate // the SetError() methodusing System;using System.IO; class GFG { // Main Method static void Main() { // Define file to receive error stream. string fn = \"F:\\\\gfg_error.log\"; // Define the new error StreamWriter object StreamWriter errStream = new StreamWriter(fn); // Redirect standard error stream to file. Console.SetError(errStream); // Write the error message into the Log file Console.Error.WriteLine(\"Error line is written into the log file.\"); Console.Error.WriteLine(\"Keep coding geeks!\"); // Close redirected error stream. Console.Error.Close(); }}", "e": 27015, "s": 26327, "text": null }, { "code": null, "e": 27086, "s": 27015, "text": "Output: The gfg_error.log file will now have the error messages in it." }, { "code": null, "e": 27097, "s": 27086, "text": "Reference:" }, { "code": null, "e": 27235, "s": 27097, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.console.seterror?view=netframework-4.7.2#System_Console_SetError_System_IO_TextWriter_" }, { "code": null, "e": 27256, "s": 27235, "text": "CSharp-Console-Class" }, { "code": null, "e": 27270, "s": 27256, "text": "CSharp-method" }, { "code": null, "e": 27277, "s": 27270, "text": "Picked" }, { "code": null, "e": 27280, "s": 27277, "text": "C#" }, { "code": null, "e": 27378, "s": 27280, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27401, "s": 27378, "text": "Extension Method in C#" }, { "code": null, "e": 27429, "s": 27401, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27446, "s": 27429, "text": "C# | Inheritance" }, { "code": null, "e": 27468, "s": 27446, "text": "Partial Classes in C#" }, { "code": null, "e": 27497, "s": 27468, "text": "C# | Generics - Introduction" }, { "code": null, "e": 27537, "s": 27497, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27560, "s": 27537, "text": "Switch Statement in C#" }, { "code": null, "e": 27600, "s": 27560, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 27643, "s": 27600, "text": "C# | How to insert an element in an Array?" } ]
Flutter - Dark Theme - GeeksforGeeks
17 Feb, 2021 Nowadays almost all the mobile application uses a dark theme, for example, Instagram, Whatsapp, Youtube, etc. It’s easy to implement in Flutter, Just a few lines of code require to achieve this. But before doing that let’s explore some important concept in flutter which are used to achieve the dark theme ThemeData class defines the theme for App. It’s used inside MaterialApp, It helps to configure the appearance of the entire app. We can override it as per our requirement and make changes. Now let’s dig into the code and explore the new things in the ThemeData class. Dart MaterialApp( theme: ThemeData( primaryColor: Colors.blue, accentColor: Colors.yellow, textTheme: TextTheme(bodyText2: TextStyle(color: Colors.purple)), ), home: Scaffold( appBar: AppBar( title: const Text('ThemeData Example'), ), floatingActionButton: FloatingActionButton( child: const Icon(Icons.add), onPressed: () {}, ), body: Center( child: Text( 'Geeks For Geeks', ), ), ),) 1. Brightness : Describes the contrast of a theme or color palette. Example: Dart ThemeData( brightness:Brightness.light, ), ThemeData( brightness:Brightness.light, ) 2. visualDensity : Visual density is the vertical and horizontal “compactness” of the components in the UI. Note: horizontal and vertical density must be less than or equal to max Horizontal or MaximumVeriticalDensity i.e. 4.0 Example: Dart ThemeData( brightness: Brightness.light, visualDensity: VisualDensity( horizontal: 2.0, vertical: 2.0 )), 3. primaryColor : Defines the primary color for the app, similarly, we can define the primary color for a light theme and a dark theme. Example: Dart ThemeData( primaryColor: Colors.blue,), Similarly, we can define the accentColor, accentColorLight, accentColorDark, feel free to use them in your app. 4. IconThemeData: Defines the color, opacity, and size of icons. Dart ThemeData( iconTheme: IconThemeData( color: Colors.amber, size: 15.0, opacity: 10 )), Similarly, you can have other properties in flutter official docs. I personally recommend visiting at least once in Flutter official docs. Now we get enough knowledge to accomplish our goal, let’s get started. We are going to use the Provider package, this is not mandatory we can do the dark theme implementation without Provider But for better architecture, we are using it. Add provider package into pubspec.yaml file. This is our main class the execution starts from this class. Just take a look at the theme properties of the MaterialApp(), all the things we have discussed above are written here, I guess you get some clarity here. Dart import 'package:dark_theme_app/Button_tap_listener.dart';import 'package:dark_theme_app/dark_theme_screen.dart';import 'package:flutter/material.dart';import 'package:provider/provider.dart'; void main() { runApp(MyApp());}class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return ChangeNotifierProvider<ButtonTapListenerClass>( create: (context) => ButtonTapListenerClass(), child: MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter Demo', // Themes darkTheme: ThemeData.dark(), home: DarkThemeExample(), theme: ThemeData( brightness: Brightness.dark, visualDensity: VisualDensity(horizontal: 2.0, vertical: 2.0), primaryColorLight: Color(0xff03203C), primaryColorDark: Color(0xff242B2E), // Icon Theme iconTheme: IconThemeData(color: Colors.amber, size: 15.0, opacity: 10), accentColor: Colors.amber, accentColorBrightness: Brightness.light), ), ); }} This class contains our UI part of the app, when we tap on the bulb image it will call the clickEvent() which is defined in our business class. Here we just toggle one boolean variable to get a dark theme and light theme. Dart import 'package:dark_theme_app/Button_tap_listener.dart';import 'package:flutter/material.dart';import 'package:provider/provider.dart'; class DarkThemeExample extends StatefulWidget { @override _DarkThemeExampleState createState() => _DarkThemeExampleState();} class _DarkThemeExampleState extends State<DarkThemeExample> { @override Widget build(BuildContext context) { // initialise the provider class final object = Provider.of<ButtonTapListenerClass>(context); return Scaffold( backgroundColor: object.isClicked ? Theme.of(context).primaryColorDark : Theme.of(context).primaryColorLight, // appbar appBar: AppBar( backgroundColor: Colors.green, title: Text("Geeks For Geeks"), centerTitle: true, ), body: Container( margin: EdgeInsets.symmetric(horizontal: 150.0), child: GestureDetector( child: object.isClicked ? Image.asset( "assets/light.png", height: 450.0, ) : Image.asset( "assets/dark.png", height: 450.0, ), onTap: () { object.clickEvent(); }, ), ), ); }} This class is the business class that is we do all the business logic or operation here. For our example, the functionality of this class is less, But this is the right approach to separate our UI and business logic & follow good architecture to build an app. In this class, we extend the ChangeNotifier class which is in the provider package. Just notice the clickEvent() , there we are using notifyListner(). When we call this function we just tell the listeners to rebuild it to get updated value or new value. In our case, we just toggle the boolean value. By looking at it, you can think in this way this is a mess, why we do all these things for this small app. But believe me, we need to follow at least one architecture pattern. If you do not want to use it feel free to use a simple approach. Dart import 'package:flutter/material.dart'; class ButtonTapListenerClass extends ChangeNotifier { bool isClicked = false; void clickEvent() { isClicked = !isClicked; notifyListeners(); }} dark theme(tap on the bulb) light theme(Tap on the bulb) android Flutter Flutter UI-components Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - Flexible Widget Flutter - Stack Widget Android Studio Setup for Flutter Development Flutter - Custom Bottom Navigation Bar Flutter Tutorial Flutter - Flexible Widget Flutter - Stack Widget Flutter - Dialogs
[ { "code": null, "e": 25287, "s": 25259, "text": "\n17 Feb, 2021" }, { "code": null, "e": 25593, "s": 25287, "text": "Nowadays almost all the mobile application uses a dark theme, for example, Instagram, Whatsapp, Youtube, etc. It’s easy to implement in Flutter, Just a few lines of code require to achieve this. But before doing that let’s explore some important concept in flutter which are used to achieve the dark theme" }, { "code": null, "e": 25782, "s": 25593, "text": "ThemeData class defines the theme for App. It’s used inside MaterialApp, It helps to configure the appearance of the entire app. We can override it as per our requirement and make changes." }, { "code": null, "e": 25861, "s": 25782, "text": "Now let’s dig into the code and explore the new things in the ThemeData class." }, { "code": null, "e": 25866, "s": 25861, "text": "Dart" }, { "code": "MaterialApp( theme: ThemeData( primaryColor: Colors.blue, accentColor: Colors.yellow, textTheme: TextTheme(bodyText2: TextStyle(color: Colors.purple)), ), home: Scaffold( appBar: AppBar( title: const Text('ThemeData Example'), ), floatingActionButton: FloatingActionButton( child: const Icon(Icons.add), onPressed: () {}, ), body: Center( child: Text( 'Geeks For Geeks', ), ), ),)", "e": 26297, "s": 25866, "text": null }, { "code": null, "e": 26315, "s": 26297, "text": "1. Brightness : " }, { "code": null, "e": 26367, "s": 26315, "text": "Describes the contrast of a theme or color palette." }, { "code": null, "e": 26376, "s": 26367, "text": "Example:" }, { "code": null, "e": 26381, "s": 26376, "text": "Dart" }, { "code": "ThemeData( brightness:Brightness.light, ), ThemeData( brightness:Brightness.light, )", "e": 26471, "s": 26381, "text": null }, { "code": null, "e": 26492, "s": 26471, "text": "2. visualDensity : " }, { "code": null, "e": 26701, "s": 26492, "text": "Visual density is the vertical and horizontal “compactness” of the components in the UI. Note: horizontal and vertical density must be less than or equal to max Horizontal or MaximumVeriticalDensity i.e. 4.0" }, { "code": null, "e": 26710, "s": 26701, "text": "Example:" }, { "code": null, "e": 26715, "s": 26710, "text": "Dart" }, { "code": "ThemeData( brightness: Brightness.light, visualDensity: VisualDensity( horizontal: 2.0, vertical: 2.0 )),", "e": 26825, "s": 26715, "text": null }, { "code": null, "e": 26844, "s": 26825, "text": "3. primaryColor : " }, { "code": null, "e": 26962, "s": 26844, "text": "Defines the primary color for the app, similarly, we can define the primary color for a light theme and a dark theme." }, { "code": null, "e": 26971, "s": 26962, "text": "Example:" }, { "code": null, "e": 26976, "s": 26971, "text": "Dart" }, { "code": "ThemeData( primaryColor: Colors.blue,),", "e": 27016, "s": 26976, "text": null }, { "code": null, "e": 27128, "s": 27016, "text": "Similarly, we can define the accentColor, accentColorLight, accentColorDark, feel free to use them in your app." }, { "code": null, "e": 27147, "s": 27128, "text": "4. IconThemeData: " }, { "code": null, "e": 27194, "s": 27147, "text": "Defines the color, opacity, and size of icons." }, { "code": null, "e": 27199, "s": 27194, "text": "Dart" }, { "code": "ThemeData( iconTheme: IconThemeData( color: Colors.amber, size: 15.0, opacity: 10 )),", "e": 27291, "s": 27199, "text": null }, { "code": null, "e": 27430, "s": 27291, "text": "Similarly, you can have other properties in flutter official docs. I personally recommend visiting at least once in Flutter official docs." }, { "code": null, "e": 27713, "s": 27430, "text": "Now we get enough knowledge to accomplish our goal, let’s get started. We are going to use the Provider package, this is not mandatory we can do the dark theme implementation without Provider But for better architecture, we are using it. Add provider package into pubspec.yaml file." }, { "code": null, "e": 27929, "s": 27713, "text": "This is our main class the execution starts from this class. Just take a look at the theme properties of the MaterialApp(), all the things we have discussed above are written here, I guess you get some clarity here." }, { "code": null, "e": 27934, "s": 27929, "text": "Dart" }, { "code": "import 'package:dark_theme_app/Button_tap_listener.dart';import 'package:dark_theme_app/dark_theme_screen.dart';import 'package:flutter/material.dart';import 'package:provider/provider.dart'; void main() { runApp(MyApp());}class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return ChangeNotifierProvider<ButtonTapListenerClass>( create: (context) => ButtonTapListenerClass(), child: MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter Demo', // Themes darkTheme: ThemeData.dark(), home: DarkThemeExample(), theme: ThemeData( brightness: Brightness.dark, visualDensity: VisualDensity(horizontal: 2.0, vertical: 2.0), primaryColorLight: Color(0xff03203C), primaryColorDark: Color(0xff242B2E), // Icon Theme iconTheme: IconThemeData(color: Colors.amber, size: 15.0, opacity: 10), accentColor: Colors.amber, accentColorBrightness: Brightness.light), ), ); }}", "e": 29083, "s": 27934, "text": null }, { "code": null, "e": 29306, "s": 29083, "text": "This class contains our UI part of the app, when we tap on the bulb image it will call the clickEvent() which is defined in our business class. Here we just toggle one boolean variable to get a dark theme and light theme. " }, { "code": null, "e": 29311, "s": 29306, "text": "Dart" }, { "code": "import 'package:dark_theme_app/Button_tap_listener.dart';import 'package:flutter/material.dart';import 'package:provider/provider.dart'; class DarkThemeExample extends StatefulWidget { @override _DarkThemeExampleState createState() => _DarkThemeExampleState();} class _DarkThemeExampleState extends State<DarkThemeExample> { @override Widget build(BuildContext context) { // initialise the provider class final object = Provider.of<ButtonTapListenerClass>(context); return Scaffold( backgroundColor: object.isClicked ? Theme.of(context).primaryColorDark : Theme.of(context).primaryColorLight, // appbar appBar: AppBar( backgroundColor: Colors.green, title: Text(\"Geeks For Geeks\"), centerTitle: true, ), body: Container( margin: EdgeInsets.symmetric(horizontal: 150.0), child: GestureDetector( child: object.isClicked ? Image.asset( \"assets/light.png\", height: 450.0, ) : Image.asset( \"assets/dark.png\", height: 450.0, ), onTap: () { object.clickEvent(); }, ), ), ); }}", "e": 30531, "s": 29311, "text": null }, { "code": null, "e": 30791, "s": 30531, "text": "This class is the business class that is we do all the business logic or operation here. For our example, the functionality of this class is less, But this is the right approach to separate our UI and business logic & follow good architecture to build an app." }, { "code": null, "e": 31333, "s": 30791, "text": "In this class, we extend the ChangeNotifier class which is in the provider package. Just notice the clickEvent() , there we are using notifyListner(). When we call this function we just tell the listeners to rebuild it to get updated value or new value. In our case, we just toggle the boolean value. By looking at it, you can think in this way this is a mess, why we do all these things for this small app. But believe me, we need to follow at least one architecture pattern. If you do not want to use it feel free to use a simple approach." }, { "code": null, "e": 31338, "s": 31333, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; class ButtonTapListenerClass extends ChangeNotifier { bool isClicked = false; void clickEvent() { isClicked = !isClicked; notifyListeners(); }}", "e": 31534, "s": 31338, "text": null }, { "code": null, "e": 31562, "s": 31534, "text": "dark theme(tap on the bulb)" }, { "code": null, "e": 31591, "s": 31562, "text": "light theme(Tap on the bulb)" }, { "code": null, "e": 31599, "s": 31591, "text": "android" }, { "code": null, "e": 31607, "s": 31599, "text": "Flutter" }, { "code": null, "e": 31629, "s": 31607, "text": "Flutter UI-components" }, { "code": null, "e": 31634, "s": 31629, "text": "Dart" }, { "code": null, "e": 31642, "s": 31634, "text": "Flutter" }, { "code": null, "e": 31740, "s": 31642, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31779, "s": 31740, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 31805, "s": 31779, "text": "ListView Class in Flutter" }, { "code": null, "e": 31831, "s": 31805, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 31854, "s": 31831, "text": "Flutter - Stack Widget" }, { "code": null, "e": 31899, "s": 31854, "text": "Android Studio Setup for Flutter Development" }, { "code": null, "e": 31938, "s": 31899, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 31955, "s": 31938, "text": "Flutter Tutorial" }, { "code": null, "e": 31981, "s": 31955, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 32004, "s": 31981, "text": "Flutter - Stack Widget" } ]
PYGLET – Media Player - GeeksforGeeks
27 Aug, 2021 In this article we will see how we can create a simple media player in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a “heavyweight” object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire screen (fullscreen). In order to load a file i.e resource we use resource module of pyglet. This module allows applications to specify a search path for resources. Pyglet can play WAV files, and if FFmpeg is installed, many other audio and video formats. Playback is handled by the Player class, which reads raw data from Source objects and provides methods for pausing, seeking, adjusting the volume, and so on. The Player class implements the best available audio device.We can create a window and player object with the help of commands given below # creating a window window = pyglet.window.Window(width, height, title) # creating a player for media player = pyglet.media.Player() In order to play a media in pyglet we have to do the following 1. Create pyglet window 2. Create a player object 3. Load the media by player from the path of media 4. Add loaded media in the queue of player 5. Play the video 6. Create a key press event handler which is used to pause and resume the video Below is the implementation Python3 # importing pyglet moduleimport pyglet # width of windowwidth = 500 # height of windowheight = 500 # caption i.e title of the windowtitle = "Geeksforgeeks" # creating a windowwindow = pyglet.window.Window(width, height, title) # video pathvidPath ="media.mp4" # creating a media player objectplayer = pyglet.media.Player() # creating a source objectsource = pyglet.media.StreamingSource() # load the media from the sourceMediaLoad = pyglet.media.load(vidPath) # add this media in the queueplayer.queue(MediaLoad) # play the videoplayer.play() # on draw [email protected] on_draw(): # clea the window window.clear() # if player source exist # and video format exist if player.source and player.source.video_format: # get the texture of video and # make surface to display on the screen player.get_texture().blit(0, 0) # key press event @window.eventdef on_key_press(symbol, modifier): # key "p" get press if symbol == pyglet.window.key.P: # printing the message print("Key : P is pressed") # pause the video player.pause() # printing message print("Video is paused") # key "r" get press if symbol == pyglet.window.key.R: # printing the message print("Key : R is pressed") # resume the video player.play() # printing message print("Video is resumed") # run the pyglet applicationpyglet.app.run() Output : Key : P is pressed Video is paused Key : R is pressed Video is resumed Key : P is pressed Video is paused Key : R is pressed Video is resumed surinderdawra388 rajeev0719singh Python-gui Python-Pyglet Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n27 Aug, 2021" }, { "code": null, "e": 26448, "s": 25537, "text": "In this article we will see how we can create a simple media player in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a “heavyweight” object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire screen (fullscreen). In order to load a file i.e resource we use resource module of pyglet. This module allows applications to specify a search path for resources. Pyglet can play WAV files, and if FFmpeg is installed, many other audio and video formats. Playback is handled by the Player class, which reads raw data from Source objects and provides methods for pausing, seeking, adjusting the volume, and so on. The Player class implements the best available audio device.We can create a window and player object with the help of commands given below " }, { "code": null, "e": 26582, "s": 26448, "text": "# creating a window\nwindow = pyglet.window.Window(width, height, title)\n\n# creating a player for media\nplayer = pyglet.media.Player()" }, { "code": null, "e": 26891, "s": 26584, "text": "In order to play a media in pyglet we have to do the following 1. Create pyglet window 2. Create a player object 3. Load the media by player from the path of media 4. Add loaded media in the queue of player 5. Play the video 6. Create a key press event handler which is used to pause and resume the video " }, { "code": null, "e": 26921, "s": 26891, "text": "Below is the implementation " }, { "code": null, "e": 26929, "s": 26921, "text": "Python3" }, { "code": "# importing pyglet moduleimport pyglet # width of windowwidth = 500 # height of windowheight = 500 # caption i.e title of the windowtitle = \"Geeksforgeeks\" # creating a windowwindow = pyglet.window.Window(width, height, title) # video pathvidPath =\"media.mp4\" # creating a media player objectplayer = pyglet.media.Player() # creating a source objectsource = pyglet.media.StreamingSource() # load the media from the sourceMediaLoad = pyglet.media.load(vidPath) # add this media in the queueplayer.queue(MediaLoad) # play the videoplayer.play() # on draw [email protected] on_draw(): # clea the window window.clear() # if player source exist # and video format exist if player.source and player.source.video_format: # get the texture of video and # make surface to display on the screen player.get_texture().blit(0, 0) # key press event @window.eventdef on_key_press(symbol, modifier): # key \"p\" get press if symbol == pyglet.window.key.P: # printing the message print(\"Key : P is pressed\") # pause the video player.pause() # printing message print(\"Video is paused\") # key \"r\" get press if symbol == pyglet.window.key.R: # printing the message print(\"Key : R is pressed\") # resume the video player.play() # printing message print(\"Video is resumed\") # run the pyglet applicationpyglet.app.run()", "e": 28480, "s": 26929, "text": null }, { "code": null, "e": 28491, "s": 28480, "text": "Output : " }, { "code": null, "e": 28635, "s": 28493, "text": "Key : P is pressed\nVideo is paused\nKey : R is pressed\nVideo is resumed\nKey : P is pressed\nVideo is paused\nKey : R is pressed\nVideo is resumed" }, { "code": null, "e": 28654, "s": 28637, "text": "surinderdawra388" }, { "code": null, "e": 28670, "s": 28654, "text": "rajeev0719singh" }, { "code": null, "e": 28681, "s": 28670, "text": "Python-gui" }, { "code": null, "e": 28695, "s": 28681, "text": "Python-Pyglet" }, { "code": null, "e": 28702, "s": 28695, "text": "Python" }, { "code": null, "e": 28800, "s": 28702, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28832, "s": 28800, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28874, "s": 28832, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28916, "s": 28874, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28943, "s": 28916, "text": "Python Classes and Objects" }, { "code": null, "e": 28999, "s": 28943, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29021, "s": 28999, "text": "Defaultdict in Python" }, { "code": null, "e": 29060, "s": 29021, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29091, "s": 29060, "text": "Python | os.path.join() method" }, { "code": null, "e": 29120, "s": 29091, "text": "Create a directory in Python" } ]
Save Pages as HTML in ElectronJS - GeeksforGeeks
06 Jan, 2022 ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime. All Chromium browsers support saving webpages as HTML files onto the native system. Usually, this functionality is triggered by a simple Ctrl+S Keyboard shortcut on any webpage in the Chromium Browser. Electron also exhibits this behaviour and allows us to save the BrowserWindow Instances as HTML files on the native System using the instance methods of the BrowserWindow Object and the webContents property. Every BrowserWindow instance runs in its own individual Renderer Process. Every Renderer Process is isolated and has its own HTML, CSS and JavaScript files associated with it. We can either save only the HTML file or we can save the HTML and its associated CSS and JS files respectively depending upon the options provided to the instance method of the webContents property. This tutorial will demonstrate how to save BrowserWindow instances as HTML files on the native System in Electron. We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system. Project Structure: Example: Follow the Steps given in Desktop Operations in ElectronJS to setup the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. The basic steps required to setup the Electron application remain the same. package.json: { "name": "electron-html", "version": "1.0.0", "description": "Save HTML Page in Electron", "main": "main.js", "scripts": { "start": "electron ." }, "keywords": [ "electron" ], "author": "Radhesh Khanna", "license": "ISC", "dependencies": { "electron": "^8.3.0" } } Create the assets folder according to the project structure. We will be using the assets folder as the default path to save the HTML and its associated files generated by the application. Create the index.css file according to the project structure. This file is created only for demo purposes and we are going to keep this file blank. Output: At this point, our basic Electron Application is set up. Upon launching the application, we should see the following result. Saving HTML files in Electron: The BrowserWindow Instance and webContents Property are part of the Main Process. To import and use BrowserWindow in the Renderer Process, we will be using Electron remote module. index.html: Add the following snippet in that file. The Save This Page as HTML and Save GeeksForGeeks Page as HTML buttons do not have any functionality associated with them yet. html <head> <link rel="stylesheet" href="index.css"></head> <body> <h3>Save Pages as HTML file</h3> <button id="save"> Save This Page as HTML </button> <button id="load"> Save GeeksForGeeks Page as HTML </button></body> index.js: Add the following snippet in that file. javascript const electron = require('electron');const path = require('path');// Importing BrowserWindow using Electron remoteconst BrowserWindow = electron.remote.BrowserWindow; let win = BrowserWindow.getFocusedWindow();// let win = BrowserWindow.getAllWindows()[0]; // Specifying the assets folder as the default pathconst filepathlocal = path.join(__dirname, '../assets/page.html');const filepathload = path.join(__dirname, '../assets/geeksforgeeks.html'); var save = document.getElementById('save');save.addEventListener('click', () => { // Works for the Local Page win.webContents.savePage(filepathlocal, 'HTMLComplete').then(() => { console.log('Page was saved successfully.') }).catch(err => { console.log(err); });}); var load = document.getElementById('load');load.addEventListener('click', (event) => { // Creating a New BrowserWindow Instance, Loading GeeksForGeeks.org // And Saving it as an External Page let window = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }); window.loadURL('https://www.geeksforgeeks.org/'); window.webContents.openDevTools(); window.webContents.on('did-finish-load', async () => { window.webContents.savePage(filepathload, 'HTMLOnly').then(() => { console.log('Page was saved successfully.') }).catch(err => { console.log(err) }); });}); The win.webContents.savePage(filepath, saveType) Instance method is used to save the current BrowserWindow Instance as HTML file onto the native System depending upon the saveType parameter. It returns a Promise and it resolves when the webpage is saved successfully. It takes in the following parameters. filepath: String This parameter cannot be empty. It specifies the filepath where we would like to save the generated HTML and associated files on the native system. In our code, we have specified the filepath to the assets folder along with the name of the files using the path module. saveType: String This parameter cannot be empty. It specifies the type of save operations that needs to be performed on the BrowserWindow Instance. It can take in any one of the following values.HTMLOnly: This value of the saveType property saves only the HTML file of the current BrowserWindow Instance without any associated files.HTMLComplete: This value of the saveType property saves the complete webpage of the current BrowserWindow Instance including the HTML file and the associated JavaScript and CSS files respectively at the specified filepath. This value creates a new folder page_files within the specified filepath. This folder contains the additional CSS and JS files of the saved webpage.MHTML: This value of the saveType property saves the HTML file of the BrowserWindow Instance as MHTML. It stands for MIME HTML and it is a MIME encapsulation of the aggregate HTML document. It is a web page format which is used to combine the HTML code and its resources (such as images, audio, video files, etc) that are represented by external hyperlinks in the code, into a single HTML file. The contents of the MHTML file are encoded using using the MIME content type multipart/related. HTMLOnly: This value of the saveType property saves only the HTML file of the current BrowserWindow Instance without any associated files. HTMLComplete: This value of the saveType property saves the complete webpage of the current BrowserWindow Instance including the HTML file and the associated JavaScript and CSS files respectively at the specified filepath. This value creates a new folder page_files within the specified filepath. This folder contains the additional CSS and JS files of the saved webpage. MHTML: This value of the saveType property saves the HTML file of the BrowserWindow Instance as MHTML. It stands for MIME HTML and it is a MIME encapsulation of the aggregate HTML document. It is a web page format which is used to combine the HTML code and its resources (such as images, audio, video files, etc) that are represented by external hyperlinks in the code, into a single HTML file. The contents of the MHTML file are encoded using using the MIME content type multipart/related. The did-finish-load Instance Event belongs to the webContents Property. It is emitted when the navigation of the webpage (specified by the window.loadURL() Instance method) is done and the page is completely loaded. This happens when the spinner of the page has stopped spinning, and the onload event has been dispatched. In our code, we have used this Instance event to wait for the GeeksForGeeks.org website to completely load into our BrowserWindow Instance before we can save the HTML file onto our System.To get the current BrowserWindow Instance in the Renderer Process, we can use some of the Static Methods provided by the BrowserWindow object. BrowserWindow.getAllWindows(): This method returns an Array of active/opened BrowserWindow Instances. In this application, we have only one active BrowserWindow Instance and it can be directly referred from the Array as shown in the code. BrowserWindow.getFocusedWindow(): This method returns the BrowserWindow Instance which is focused in the Application. If no current BrowserWindow Instance is found, it returns null. In this application, we only have one active BrowserWindow Instance and it can be directly referred using this method as shown in the code. Output: Saving the current BrowserWindow Instance by specifying win.webContents.savePage(filepathlocal, ‘MHTML’), Generated MHTML Output file. khushboogoyal499 ElectronJS CSS HTML JavaScript Node.js Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a web page using HTML and CSS How to set space between the flexbox ? Form validation using jQuery Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26905, "s": 26877, "text": "\n06 Jan, 2022" }, { "code": null, "e": 27205, "s": 26905, "text": "ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime." }, { "code": null, "e": 28105, "s": 27205, "text": "All Chromium browsers support saving webpages as HTML files onto the native system. Usually, this functionality is triggered by a simple Ctrl+S Keyboard shortcut on any webpage in the Chromium Browser. Electron also exhibits this behaviour and allows us to save the BrowserWindow Instances as HTML files on the native System using the instance methods of the BrowserWindow Object and the webContents property. Every BrowserWindow instance runs in its own individual Renderer Process. Every Renderer Process is isolated and has its own HTML, CSS and JavaScript files associated with it. We can either save only the HTML file or we can save the HTML and its associated CSS and JS files respectively depending upon the options provided to the instance method of the webContents property. This tutorial will demonstrate how to save BrowserWindow instances as HTML files on the native System in Electron." }, { "code": null, "e": 28275, "s": 28105, "text": "We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system." }, { "code": null, "e": 28294, "s": 28275, "text": "Project Structure:" }, { "code": null, "e": 28755, "s": 28294, "text": "Example: Follow the Steps given in Desktop Operations in ElectronJS to setup the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. The basic steps required to setup the Electron application remain the same. " }, { "code": null, "e": 28770, "s": 28755, "text": "package.json: " }, { "code": null, "e": 29072, "s": 28770, "text": "{\n \"name\": \"electron-html\",\n \"version\": \"1.0.0\",\n \"description\": \"Save HTML Page in Electron\",\n \"main\": \"main.js\",\n \"scripts\": {\n \"start\": \"electron .\"\n },\n \"keywords\": [\n \"electron\"\n ],\n \"author\": \"Radhesh Khanna\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"electron\": \"^8.3.0\"\n }\n}" }, { "code": null, "e": 29542, "s": 29072, "text": "Create the assets folder according to the project structure. We will be using the assets folder as the default path to save the HTML and its associated files generated by the application. Create the index.css file according to the project structure. This file is created only for demo purposes and we are going to keep this file blank. Output: At this point, our basic Electron Application is set up. Upon launching the application, we should see the following result. " }, { "code": null, "e": 29753, "s": 29542, "text": "Saving HTML files in Electron: The BrowserWindow Instance and webContents Property are part of the Main Process. To import and use BrowserWindow in the Renderer Process, we will be using Electron remote module." }, { "code": null, "e": 29933, "s": 29753, "text": "index.html: Add the following snippet in that file. The Save This Page as HTML and Save GeeksForGeeks Page as HTML buttons do not have any functionality associated with them yet." }, { "code": null, "e": 29938, "s": 29933, "text": "html" }, { "code": "<head> <link rel=\"stylesheet\" href=\"index.css\"></head> <body> <h3>Save Pages as HTML file</h3> <button id=\"save\"> Save This Page as HTML </button> <button id=\"load\"> Save GeeksForGeeks Page as HTML </button></body>", "e": 30179, "s": 29938, "text": null }, { "code": null, "e": 30232, "s": 30182, "text": "index.js: Add the following snippet in that file." }, { "code": null, "e": 30245, "s": 30234, "text": "javascript" }, { "code": "const electron = require('electron');const path = require('path');// Importing BrowserWindow using Electron remoteconst BrowserWindow = electron.remote.BrowserWindow; let win = BrowserWindow.getFocusedWindow();// let win = BrowserWindow.getAllWindows()[0]; // Specifying the assets folder as the default pathconst filepathlocal = path.join(__dirname, '../assets/page.html');const filepathload = path.join(__dirname, '../assets/geeksforgeeks.html'); var save = document.getElementById('save');save.addEventListener('click', () => { // Works for the Local Page win.webContents.savePage(filepathlocal, 'HTMLComplete').then(() => { console.log('Page was saved successfully.') }).catch(err => { console.log(err); });}); var load = document.getElementById('load');load.addEventListener('click', (event) => { // Creating a New BrowserWindow Instance, Loading GeeksForGeeks.org // And Saving it as an External Page let window = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }); window.loadURL('https://www.geeksforgeeks.org/'); window.webContents.openDevTools(); window.webContents.on('did-finish-load', async () => { window.webContents.savePage(filepathload, 'HTMLOnly').then(() => { console.log('Page was saved successfully.') }).catch(err => { console.log(err) }); });});", "e": 31685, "s": 30245, "text": null }, { "code": null, "e": 31992, "s": 31685, "text": "The win.webContents.savePage(filepath, saveType) Instance method is used to save the current BrowserWindow Instance as HTML file onto the native System depending upon the saveType parameter. It returns a Promise and it resolves when the webpage is saved successfully. It takes in the following parameters. " }, { "code": null, "e": 32278, "s": 31992, "text": "filepath: String This parameter cannot be empty. It specifies the filepath where we would like to save the generated HTML and associated files on the native system. In our code, we have specified the filepath to the assets folder along with the name of the files using the path module." }, { "code": null, "e": 33473, "s": 32278, "text": "saveType: String This parameter cannot be empty. It specifies the type of save operations that needs to be performed on the BrowserWindow Instance. It can take in any one of the following values.HTMLOnly: This value of the saveType property saves only the HTML file of the current BrowserWindow Instance without any associated files.HTMLComplete: This value of the saveType property saves the complete webpage of the current BrowserWindow Instance including the HTML file and the associated JavaScript and CSS files respectively at the specified filepath. This value creates a new folder page_files within the specified filepath. This folder contains the additional CSS and JS files of the saved webpage.MHTML: This value of the saveType property saves the HTML file of the BrowserWindow Instance as MHTML. It stands for MIME HTML and it is a MIME encapsulation of the aggregate HTML document. It is a web page format which is used to combine the HTML code and its resources (such as images, audio, video files, etc) that are represented by external hyperlinks in the code, into a single HTML file. The contents of the MHTML file are encoded using using the MIME content type multipart/related." }, { "code": null, "e": 33612, "s": 33473, "text": "HTMLOnly: This value of the saveType property saves only the HTML file of the current BrowserWindow Instance without any associated files." }, { "code": null, "e": 33984, "s": 33612, "text": "HTMLComplete: This value of the saveType property saves the complete webpage of the current BrowserWindow Instance including the HTML file and the associated JavaScript and CSS files respectively at the specified filepath. This value creates a new folder page_files within the specified filepath. This folder contains the additional CSS and JS files of the saved webpage." }, { "code": null, "e": 34475, "s": 33984, "text": "MHTML: This value of the saveType property saves the HTML file of the BrowserWindow Instance as MHTML. It stands for MIME HTML and it is a MIME encapsulation of the aggregate HTML document. It is a web page format which is used to combine the HTML code and its resources (such as images, audio, video files, etc) that are represented by external hyperlinks in the code, into a single HTML file. The contents of the MHTML file are encoded using using the MIME content type multipart/related." }, { "code": null, "e": 35129, "s": 34475, "text": "The did-finish-load Instance Event belongs to the webContents Property. It is emitted when the navigation of the webpage (specified by the window.loadURL() Instance method) is done and the page is completely loaded. This happens when the spinner of the page has stopped spinning, and the onload event has been dispatched. In our code, we have used this Instance event to wait for the GeeksForGeeks.org website to completely load into our BrowserWindow Instance before we can save the HTML file onto our System.To get the current BrowserWindow Instance in the Renderer Process, we can use some of the Static Methods provided by the BrowserWindow object. " }, { "code": null, "e": 35368, "s": 35129, "text": "BrowserWindow.getAllWindows(): This method returns an Array of active/opened BrowserWindow Instances. In this application, we have only one active BrowserWindow Instance and it can be directly referred from the Array as shown in the code." }, { "code": null, "e": 35690, "s": 35368, "text": "BrowserWindow.getFocusedWindow(): This method returns the BrowserWindow Instance which is focused in the Application. If no current BrowserWindow Instance is found, it returns null. In this application, we only have one active BrowserWindow Instance and it can be directly referred using this method as shown in the code." }, { "code": null, "e": 35835, "s": 35690, "text": "Output: Saving the current BrowserWindow Instance by specifying win.webContents.savePage(filepathlocal, ‘MHTML’), Generated MHTML Output file. " }, { "code": null, "e": 35852, "s": 35835, "text": "khushboogoyal499" }, { "code": null, "e": 35863, "s": 35852, "text": "ElectronJS" }, { "code": null, "e": 35867, "s": 35863, "text": "CSS" }, { "code": null, "e": 35872, "s": 35867, "text": "HTML" }, { "code": null, "e": 35883, "s": 35872, "text": "JavaScript" }, { "code": null, "e": 35891, "s": 35883, "text": "Node.js" }, { "code": null, "e": 35908, "s": 35891, "text": "Web Technologies" }, { "code": null, "e": 35913, "s": 35908, "text": "HTML" }, { "code": null, "e": 36011, "s": 35913, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36048, "s": 36011, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 36087, "s": 36048, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 36116, "s": 36087, "text": "Form validation using jQuery" }, { "code": null, "e": 36158, "s": 36116, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 36193, "s": 36158, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 36253, "s": 36193, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 36306, "s": 36253, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 36367, "s": 36306, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 36391, "s": 36367, "text": "REST API (Introduction)" } ]
What is the meaning of invalid literal for int() with base = ' '? - GeeksforGeeks
20 Aug, 2020 ValueError is encountered when we pass an inappropriate argument type. Here, we are talking about the ValueError caused by passing an incorrect argument to the int() function. When we pass a string representation of a float or any string representation other than that of int, it gives a ValueError. Example 1 : ValueError with base 10. # ValueError caused by conversion of # String representation of float to intint('23.5') Output : ValueError: invalid literal for int() with base 10: '23.5' One can think that while executing the above code, the decimal part ‘.5’ should be truncated and the code should give output as 23 only. But the point to be noted is that the int( ) function uses the decimal number system as its base for conversion ie. base = 10 is the default value for conversion. And in the decimal number system, we have numbers from 0 to 9 excluding the decimal (.) and other characters(alphabets and special chars). Therefore, int() with base = 10 can only convert a string representation of int and not floats or chars. We can first convert the string representation of float into float using float() function and then convert it into an integer using int(). print(int(float('23.5'))) Output : 23 Example 2 : Passing alphabets in int(). int('abc') Output : invalid literal for int() with base 10: 'abc' The chars a, b, c, d, e, and f are present in the base =16 system and therefore only these chars along with digits 0 to 9 can be converted from their string representation to integer in hexadecimal form. We have to pass an parameter base with value 16. print(int('abc', base = 16)) Output : 2748 python-string Program Output Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Output of Java Program | Set 11 Output of C++ programs | Set 34 (File Handling) Output of Java program | Set 28 Output of Java Programs | Set 12 Output of Java Programs | Set 48 (Static keyword) 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": 25587, "s": 25559, "text": "\n20 Aug, 2020" }, { "code": null, "e": 25887, "s": 25587, "text": "ValueError is encountered when we pass an inappropriate argument type. Here, we are talking about the ValueError caused by passing an incorrect argument to the int() function. When we pass a string representation of a float or any string representation other than that of int, it gives a ValueError." }, { "code": null, "e": 25924, "s": 25887, "text": "Example 1 : ValueError with base 10." }, { "code": "# ValueError caused by conversion of # String representation of float to intint('23.5')", "e": 26012, "s": 25924, "text": null }, { "code": null, "e": 26021, "s": 26012, "text": "Output :" }, { "code": null, "e": 26080, "s": 26021, "text": "ValueError: invalid literal for int() with base 10: '23.5'" }, { "code": null, "e": 26624, "s": 26080, "text": "One can think that while executing the above code, the decimal part ‘.5’ should be truncated and the code should give output as 23 only. But the point to be noted is that the int( ) function uses the decimal number system as its base for conversion ie. base = 10 is the default value for conversion. And in the decimal number system, we have numbers from 0 to 9 excluding the decimal (.) and other characters(alphabets and special chars). Therefore, int() with base = 10 can only convert a string representation of int and not floats or chars." }, { "code": null, "e": 26763, "s": 26624, "text": "We can first convert the string representation of float into float using float() function and then convert it into an integer using int()." }, { "code": "print(int(float('23.5')))", "e": 26789, "s": 26763, "text": null }, { "code": null, "e": 26798, "s": 26789, "text": "Output :" }, { "code": null, "e": 26801, "s": 26798, "text": "23" }, { "code": null, "e": 26841, "s": 26801, "text": "Example 2 : Passing alphabets in int()." }, { "code": "int('abc')", "e": 26852, "s": 26841, "text": null }, { "code": null, "e": 26861, "s": 26852, "text": "Output :" }, { "code": null, "e": 26907, "s": 26861, "text": "invalid literal for int() with base 10: 'abc'" }, { "code": null, "e": 27160, "s": 26907, "text": "The chars a, b, c, d, e, and f are present in the base =16 system and therefore only these chars along with digits 0 to 9 can be converted from their string representation to integer in hexadecimal form. We have to pass an parameter base with value 16." }, { "code": "print(int('abc', base = 16))", "e": 27189, "s": 27160, "text": null }, { "code": null, "e": 27198, "s": 27189, "text": "Output :" }, { "code": null, "e": 27203, "s": 27198, "text": "2748" }, { "code": null, "e": 27217, "s": 27203, "text": "python-string" }, { "code": null, "e": 27232, "s": 27217, "text": "Program Output" }, { "code": null, "e": 27239, "s": 27232, "text": "Python" }, { "code": null, "e": 27337, "s": 27239, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27369, "s": 27337, "text": "Output of Java Program | Set 11" }, { "code": null, "e": 27417, "s": 27369, "text": "Output of C++ programs | Set 34 (File Handling)" }, { "code": null, "e": 27449, "s": 27417, "text": "Output of Java program | Set 28" }, { "code": null, "e": 27482, "s": 27449, "text": "Output of Java Programs | Set 12" }, { "code": null, "e": 27532, "s": 27482, "text": "Output of Java Programs | Set 48 (Static keyword)" }, { "code": null, "e": 27560, "s": 27532, "text": "Read JSON file using Python" }, { "code": null, "e": 27610, "s": 27560, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 27632, "s": 27610, "text": "Python map() function" } ]
Python Program to Find and Print Address of Variable - GeeksforGeeks
31 Aug, 2021 In this article, we are going to see how to find and print the address of the Python variable. It can be done in these ways: Using id() function Using addressof() function Using hex() function We can get an address using id() function, id() function gives the address of the particular object. Syntax: id(object) where, object is the data variables. Here we are going to find the address of the list, variable, tuple and dictionary. Python3 # get id of lista = [1, 2, 3, 4, 5]print(id(a)) # get id of a variablea = 12print(id(a)) # get id of tuplea = (1, 2, 3, 4, 5)print(id(a)) # get id of a dictionarya = {'a' : 1, 'b' : 2}print(id(a)) Output: 140234866534752 94264748411744 140234904267376 140234866093264 we can also get memory addresses using these functions, ctypes is a foreign function library for Python. It provides C-compatible data types and allows calling functions in DLLs or shared libraries. Syntax:addressof(c_int(object)) where object is the data variables Python3 # import addressof,# c_int modules from ctypes modulefrom ctypes import c_int, addressof # get memory address of variablea = 44print(addressof(c_int(a))) Output: 140234866278064 Here we will call the hex(address) function, to convert the memory address to hexadecimal representation. Syntax: hex(id(object)) where, hex() is the memory hexadecimal representation to the address id is used to get the memory of the object object is the data Python3 # get id of list in hexadecimal representationa = [1, 2, 3, 4, 5]print(hex(id(a))) # get id of a variable in hexadecimal representationa = 12print(hex(id(a))) # get id of tuple in hexadecimal representationa = (1, 2, 3, 4, 5)print(hex(id(a))) # get id of a dictionary in hexadecimal representationa = {'a': 1,'b' : 2}print(hex(id(a))) Output: 0x7fba9b0ae8c0 0x5572da858b60 0x7fba9f3c4a10 0x7fba9b05b8c0 Picked python-basics Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25562, "s": 25534, "text": "\n31 Aug, 2021" }, { "code": null, "e": 25658, "s": 25562, "text": "In this article, we are going to see how to find and print the address of the Python variable. " }, { "code": null, "e": 25688, "s": 25658, "text": "It can be done in these ways:" }, { "code": null, "e": 25708, "s": 25688, "text": "Using id() function" }, { "code": null, "e": 25735, "s": 25708, "text": "Using addressof() function" }, { "code": null, "e": 25756, "s": 25735, "text": "Using hex() function" }, { "code": null, "e": 25857, "s": 25756, "text": "We can get an address using id() function, id() function gives the address of the particular object." }, { "code": null, "e": 25876, "s": 25857, "text": "Syntax: id(object)" }, { "code": null, "e": 25913, "s": 25876, "text": "where, object is the data variables." }, { "code": null, "e": 25996, "s": 25913, "text": "Here we are going to find the address of the list, variable, tuple and dictionary." }, { "code": null, "e": 26004, "s": 25996, "text": "Python3" }, { "code": "# get id of lista = [1, 2, 3, 4, 5]print(id(a)) # get id of a variablea = 12print(id(a)) # get id of tuplea = (1, 2, 3, 4, 5)print(id(a)) # get id of a dictionarya = {'a' : 1, 'b' : 2}print(id(a))", "e": 26204, "s": 26004, "text": null }, { "code": null, "e": 26212, "s": 26204, "text": "Output:" }, { "code": null, "e": 26275, "s": 26212, "text": "140234866534752\n94264748411744\n140234904267376\n140234866093264" }, { "code": null, "e": 26474, "s": 26275, "text": "we can also get memory addresses using these functions, ctypes is a foreign function library for Python. It provides C-compatible data types and allows calling functions in DLLs or shared libraries." }, { "code": null, "e": 26506, "s": 26474, "text": "Syntax:addressof(c_int(object))" }, { "code": null, "e": 26541, "s": 26506, "text": "where object is the data variables" }, { "code": null, "e": 26549, "s": 26541, "text": "Python3" }, { "code": "# import addressof,# c_int modules from ctypes modulefrom ctypes import c_int, addressof # get memory address of variablea = 44print(addressof(c_int(a)))", "e": 26704, "s": 26549, "text": null }, { "code": null, "e": 26712, "s": 26704, "text": "Output:" }, { "code": null, "e": 26728, "s": 26712, "text": "140234866278064" }, { "code": null, "e": 26834, "s": 26728, "text": "Here we will call the hex(address) function, to convert the memory address to hexadecimal representation." }, { "code": null, "e": 26858, "s": 26834, "text": "Syntax: hex(id(object))" }, { "code": null, "e": 26865, "s": 26858, "text": "where," }, { "code": null, "e": 26927, "s": 26865, "text": "hex() is the memory hexadecimal representation to the address" }, { "code": null, "e": 26970, "s": 26927, "text": "id is used to get the memory of the object" }, { "code": null, "e": 26989, "s": 26970, "text": "object is the data" }, { "code": null, "e": 26997, "s": 26989, "text": "Python3" }, { "code": "# get id of list in hexadecimal representationa = [1, 2, 3, 4, 5]print(hex(id(a))) # get id of a variable in hexadecimal representationa = 12print(hex(id(a))) # get id of tuple in hexadecimal representationa = (1, 2, 3, 4, 5)print(hex(id(a))) # get id of a dictionary in hexadecimal representationa = {'a': 1,'b' : 2}print(hex(id(a)))", "e": 27335, "s": 26997, "text": null }, { "code": null, "e": 27343, "s": 27335, "text": "Output:" }, { "code": null, "e": 27403, "s": 27343, "text": "0x7fba9b0ae8c0\n0x5572da858b60\n0x7fba9f3c4a10\n0x7fba9b05b8c0" }, { "code": null, "e": 27410, "s": 27403, "text": "Picked" }, { "code": null, "e": 27424, "s": 27410, "text": "python-basics" }, { "code": null, "e": 27431, "s": 27424, "text": "Python" }, { "code": null, "e": 27529, "s": 27431, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27561, "s": 27529, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27603, "s": 27561, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27645, "s": 27603, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27672, "s": 27645, "text": "Python Classes and Objects" }, { "code": null, "e": 27728, "s": 27672, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27750, "s": 27728, "text": "Defaultdict in Python" }, { "code": null, "e": 27789, "s": 27750, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27820, "s": 27789, "text": "Python | os.path.join() method" }, { "code": null, "e": 27849, "s": 27820, "text": "Create a directory in Python" } ]
Count number of bits to be flipped to convert A to B - GeeksforGeeks
07 Sep, 2021 Given two numbers ‘a’ and b’. Write a program to count number of bits needed to be flipped to convert ‘a’ to ‘b’. Example : Input : a = 10, b = 20 Output : 4 Binary representation of a is 00001010 Binary representation of b is 00010100 We need to flip highlighted four bits in a to make it b. Input : a = 7, b = 10 Output : 3 Binary representation of a is 00000111 Binary representation of b is 00001010 We need to flip highlighted three bits in a to make it b. 1. Calculate XOR of A and B. a_xor_b = A ^ B 2. Count the set bits in the above calculated XOR result. countSetBits(a_xor_b) XOR of two number will have set bits only at those places where A differs from B. C++ Java Python3 C# PHP Javascript // Count number of bits to be flipped// to convert A into B#include <iostream>using namespace std; // Function that count set bitsint countSetBits(int n){ int count = 0; while (n > 0) { count++; n &= (n-1); } return count;} // Function that return count of// flipped numberint FlippedCount(int a, int b){ // Return count of set bits in // a XOR b return countSetBits(a^b);} // Driver codeint main(){ int a = 10; int b = 20; cout << FlippedCount(a, b)<<endl; return 0;} // Count number of bits to be flipped// to convert A into Bimport java.util.*; class Count { // Function that count set bits public static int countSetBits(int n) { int count = 0; while (n != 0) { count++; n &=(n-1); } return count; } // Function that return count of // flipped number public static int FlippedCount(int a, int b) { // Return count of set bits in // a XOR b return countSetBits(a ^ b); } // Driver code public static void main(String[] args) { int a = 10; int b = 20; System.out.print(FlippedCount(a, b)); }} // This code is contributed by rishabh_jain # Count number of bits to be flipped# to convert A into B # Function that count set bitsdef countSetBits( n ): count = 0 while n: count += 1 n &= (n-1) return count # Function that return count of# flipped numberdef FlippedCount(a , b): # Return count of set bits in # a XOR b return countSetBits(a^b) # Driver codea = 10b = 20print(FlippedCount(a, b)) # This code is contributed by "Sharad_Bhardwaj". // Count number of bits to be// flipped to convert A into Busing System; class Count { // Function that count set bits public static int countSetBits(int n) { int count = 0; while (n != 0) { count++; n &= (n-1); } return count; } // Function that return // count of flipped number public static int FlippedCount(int a, int b) { // Return count of set // bits in a XOR b return countSetBits(a ^ b); } // Driver code public static void Main() { int a = 10; int b = 20; Console.WriteLine(FlippedCount(a, b)); }} // This code is contributed by vt_m. <?php// Count number of bits to be// flipped to convert A into B // Function that count set bitsfunction countSetBits($n){ $count = 0; while($n) { $count += 1; $n &= (n-1); } return $count;} // Function that return// count of flipped numberfunction FlippedCount($a, $b){ // Return count of set // bits in a XOR b return countSetBits($a ^ $b);} // Driver code$a = 10;$b = 20;echo FlippedCount($a, $b); // This code is contributed by mits?> <script>// Count number of bits to be flipped// to convert A into Bclass Count { // Function that count set bits function countSetBits(n) { var count = 0; while (n != 0) { count++; n &= (n - 1); } return count; } // Function that return count of // flipped number function FlippedCount(a , b) { // Return count of set bits in // a XOR b return countSetBits(a ^ b); } // Driver code var a = 10; var b = 20; document.write(FlippedCount(a, b)); // This code is contributed by shikhasingrajput</script> 4 C++ Java Python3 C# Javascript // C++ program#include <iostream>using namespace std; int countFlips(int a, int b){ // initially flips is equal to 0 int flips = 0; // & each bits of a && b with 1 // and store them if t1 and t2 // if t1 != t2 then we will flip that bit while(a > 0 || b > 0){ int t1 = (a&1); int t2 = (b&1); if(t1!=t2){ flips++; } // right shifting a and b a>>=1; b>>=1; } return flips;} int main () { int a = 10; int b = 20; cout <<countFlips(a, b);} // this code is contributed by shivanisinghss2110 /*package whatever //do not write package name here */ // CONTRIBUTED BY PRAVEEN VISHWAKARMA import java.io.*; class GFG { public static int countFlips(int a, int b){ // initially flips is equal to 0 int flips = 0; // & each bits of a && b with 1 // and store them if t1 and t2 // if t1 != t2 then we will flip that bit while(a>0 || b>0){ int t1 = (a&1); int t2 = (b&1); if(t1!=t2){ flips++; } // right shifting a and b a>>>=1; b>>>=1; } return flips; } public static void main (String[] args) { int a = 10; int b = 20; System.out.println(countFlips(a, b)); } } def countFlips(a, b): # initially flips is equal to 0 flips = 0 # & each bits of a && b with 1 # and store them if t1 and t2 # if t1 != t2 then we will flip that bit while(a > 0 or b > 0): t1 = (a & 1) t2 = (b & 1) if(t1 != t2): flips += 1 # right shifting a and b a>>=1 b>>=1 return flips a = 10b = 20print(countFlips(a, b)) # This code is contributed by shivanisinghss2110 /*package whatever //do not write package name here */using System; class GFG { public static int countFlips(int a, int b) { // initially flips is equal to 0 int flips = 0; // & each bits of a && b with 1 // and store them if t1 and t2 // if t1 != t2 then we will flip that bit while(a > 0 || b > 0){ int t1 = (a&1); int t2 = (b&1); if(t1 != t2){ flips++; } // right shifting a and b a>>=1; b>>=1; } return flips; } // Driver code public static void Main (String[] args) { int a = 10; int b = 20; Console.Write(countFlips(a, b)); } } // This code is contributed by shivanisinghss2110 <script>/*package whatever //do not write package name here */ function countFlips(a, b){ // initially flips is equal to 0 var flips = 0; // & each bits of a && b with 1 // and store them if t1 and t2 // if t1 != t2 then we will flip that bit while(a>0 || b>0){ var t1 = (a&1); var t2 = (b&1); if(t1!=t2){ flips++; } // right shifting a and b a>>>=1; b>>>=1; } return flips; } var a = 10; var b = 20; document.write(countFlips(a, b)); // This code is contributed by shivanisinghss2110</script> 4 Thanks to Sahil Rajput for providing above implementation. YouTubeGeeksforGeeks507K subscribersCount number of bits to be flipped to convert A to B | 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 / 2:49•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=WVgYaucD1S4" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> To get the set bit count please see this post: Count set bits in an integerIf you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Mithun Kumar shaik asra shikhasingrajput praveenvishwakarma11063 shivanisinghss2110 Amazon Bitwise-XOR Qualcomm Samsung Bit Magic Amazon Samsung Qualcomm Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Cyclic Redundancy Check and Modulo-2 Division Add two numbers without using arithmetic operators Bits manipulation (Important tactics) Bit Fields in C Find the element that appears once Set, Clear and Toggle a given bit of a number in C C++ bitset and its application Divide two integers without using multiplication, division and mod operator 1's and 2's complement of a Binary Number Check whether K-th bit is set or not
[ { "code": null, "e": 26545, "s": 26517, "text": "\n07 Sep, 2021" }, { "code": null, "e": 26671, "s": 26545, "text": "Given two numbers ‘a’ and b’. Write a program to count number of bits needed to be flipped to convert ‘a’ to ‘b’. Example : " }, { "code": null, "e": 27010, "s": 26671, "text": "Input : a = 10, b = 20\nOutput : 4\nBinary representation of a is 00001010\nBinary representation of b is 00010100\nWe need to flip highlighted four bits in a\nto make it b.\n\nInput : a = 7, b = 10\nOutput : 3\nBinary representation of a is 00000111\nBinary representation of b is 00001010\nWe need to flip highlighted three bits in a\nto make it b." }, { "code": null, "e": 27171, "s": 27014, "text": " 1. Calculate XOR of A and B. \n a_xor_b = A ^ B\n 2. Count the set bits in the above \n calculated XOR result.\n countSetBits(a_xor_b)" }, { "code": null, "e": 27255, "s": 27171, "text": "XOR of two number will have set bits only at those places where A differs from B. " }, { "code": null, "e": 27259, "s": 27255, "text": "C++" }, { "code": null, "e": 27264, "s": 27259, "text": "Java" }, { "code": null, "e": 27272, "s": 27264, "text": "Python3" }, { "code": null, "e": 27275, "s": 27272, "text": "C#" }, { "code": null, "e": 27279, "s": 27275, "text": "PHP" }, { "code": null, "e": 27290, "s": 27279, "text": "Javascript" }, { "code": "// Count number of bits to be flipped// to convert A into B#include <iostream>using namespace std; // Function that count set bitsint countSetBits(int n){ int count = 0; while (n > 0) { count++; n &= (n-1); } return count;} // Function that return count of// flipped numberint FlippedCount(int a, int b){ // Return count of set bits in // a XOR b return countSetBits(a^b);} // Driver codeint main(){ int a = 10; int b = 20; cout << FlippedCount(a, b)<<endl; return 0;}", "e": 27809, "s": 27290, "text": null }, { "code": "// Count number of bits to be flipped// to convert A into Bimport java.util.*; class Count { // Function that count set bits public static int countSetBits(int n) { int count = 0; while (n != 0) { count++; n &=(n-1); } return count; } // Function that return count of // flipped number public static int FlippedCount(int a, int b) { // Return count of set bits in // a XOR b return countSetBits(a ^ b); } // Driver code public static void main(String[] args) { int a = 10; int b = 20; System.out.print(FlippedCount(a, b)); }} // This code is contributed by rishabh_jain", "e": 28521, "s": 27809, "text": null }, { "code": "# Count number of bits to be flipped# to convert A into B # Function that count set bitsdef countSetBits( n ): count = 0 while n: count += 1 n &= (n-1) return count # Function that return count of# flipped numberdef FlippedCount(a , b): # Return count of set bits in # a XOR b return countSetBits(a^b) # Driver codea = 10b = 20print(FlippedCount(a, b)) # This code is contributed by \"Sharad_Bhardwaj\".", "e": 28960, "s": 28521, "text": null }, { "code": "// Count number of bits to be// flipped to convert A into Busing System; class Count { // Function that count set bits public static int countSetBits(int n) { int count = 0; while (n != 0) { count++; n &= (n-1); } return count; } // Function that return // count of flipped number public static int FlippedCount(int a, int b) { // Return count of set // bits in a XOR b return countSetBits(a ^ b); } // Driver code public static void Main() { int a = 10; int b = 20; Console.WriteLine(FlippedCount(a, b)); }} // This code is contributed by vt_m.", "e": 29640, "s": 28960, "text": null }, { "code": "<?php// Count number of bits to be// flipped to convert A into B // Function that count set bitsfunction countSetBits($n){ $count = 0; while($n) { $count += 1; $n &= (n-1); } return $count;} // Function that return// count of flipped numberfunction FlippedCount($a, $b){ // Return count of set // bits in a XOR b return countSetBits($a ^ $b);} // Driver code$a = 10;$b = 20;echo FlippedCount($a, $b); // This code is contributed by mits?>", "e": 30121, "s": 29640, "text": null }, { "code": "<script>// Count number of bits to be flipped// to convert A into Bclass Count { // Function that count set bits function countSetBits(n) { var count = 0; while (n != 0) { count++; n &= (n - 1); } return count; } // Function that return count of // flipped number function FlippedCount(a , b) { // Return count of set bits in // a XOR b return countSetBits(a ^ b); } // Driver code var a = 10; var b = 20; document.write(FlippedCount(a, b)); // This code is contributed by shikhasingrajput</script>", "e": 30739, "s": 30121, "text": null }, { "code": null, "e": 30741, "s": 30739, "text": "4" }, { "code": null, "e": 30745, "s": 30741, "text": "C++" }, { "code": null, "e": 30750, "s": 30745, "text": "Java" }, { "code": null, "e": 30758, "s": 30750, "text": "Python3" }, { "code": null, "e": 30761, "s": 30758, "text": "C#" }, { "code": null, "e": 30772, "s": 30761, "text": "Javascript" }, { "code": "// C++ program#include <iostream>using namespace std; int countFlips(int a, int b){ // initially flips is equal to 0 int flips = 0; // & each bits of a && b with 1 // and store them if t1 and t2 // if t1 != t2 then we will flip that bit while(a > 0 || b > 0){ int t1 = (a&1); int t2 = (b&1); if(t1!=t2){ flips++; } // right shifting a and b a>>=1; b>>=1; } return flips;} int main () { int a = 10; int b = 20; cout <<countFlips(a, b);} // this code is contributed by shivanisinghss2110", "e": 31301, "s": 30772, "text": null }, { "code": "/*package whatever //do not write package name here */ // CONTRIBUTED BY PRAVEEN VISHWAKARMA import java.io.*; class GFG { public static int countFlips(int a, int b){ // initially flips is equal to 0 int flips = 0; // & each bits of a && b with 1 // and store them if t1 and t2 // if t1 != t2 then we will flip that bit while(a>0 || b>0){ int t1 = (a&1); int t2 = (b&1); if(t1!=t2){ flips++; } // right shifting a and b a>>>=1; b>>>=1; } return flips; } public static void main (String[] args) { int a = 10; int b = 20; System.out.println(countFlips(a, b)); } }", "e": 32131, "s": 31301, "text": null }, { "code": "def countFlips(a, b): # initially flips is equal to 0 flips = 0 # & each bits of a && b with 1 # and store them if t1 and t2 # if t1 != t2 then we will flip that bit while(a > 0 or b > 0): t1 = (a & 1) t2 = (b & 1) if(t1 != t2): flips += 1 # right shifting a and b a>>=1 b>>=1 return flips a = 10b = 20print(countFlips(a, b)) # This code is contributed by shivanisinghss2110", "e": 32612, "s": 32131, "text": null }, { "code": "/*package whatever //do not write package name here */using System; class GFG { public static int countFlips(int a, int b) { // initially flips is equal to 0 int flips = 0; // & each bits of a && b with 1 // and store them if t1 and t2 // if t1 != t2 then we will flip that bit while(a > 0 || b > 0){ int t1 = (a&1); int t2 = (b&1); if(t1 != t2){ flips++; } // right shifting a and b a>>=1; b>>=1; } return flips; } // Driver code public static void Main (String[] args) { int a = 10; int b = 20; Console.Write(countFlips(a, b)); } } // This code is contributed by shivanisinghss2110", "e": 33475, "s": 32612, "text": null }, { "code": "<script>/*package whatever //do not write package name here */ function countFlips(a, b){ // initially flips is equal to 0 var flips = 0; // & each bits of a && b with 1 // and store them if t1 and t2 // if t1 != t2 then we will flip that bit while(a>0 || b>0){ var t1 = (a&1); var t2 = (b&1); if(t1!=t2){ flips++; } // right shifting a and b a>>>=1; b>>>=1; } return flips; } var a = 10; var b = 20; document.write(countFlips(a, b)); // This code is contributed by shivanisinghss2110</script>", "e": 34219, "s": 33475, "text": null }, { "code": null, "e": 34221, "s": 34219, "text": "4" }, { "code": null, "e": 34281, "s": 34221, "text": "Thanks to Sahil Rajput for providing above implementation. " }, { "code": null, "e": 35132, "s": 34281, "text": "YouTubeGeeksforGeeks507K subscribersCount number of bits to be flipped to convert A to B | 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 / 2:49•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=WVgYaucD1S4\" 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": 35583, "s": 35132, "text": "To get the set bit count please see this post: Count set bits in an integerIf you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 35596, "s": 35583, "text": "Mithun Kumar" }, { "code": null, "e": 35607, "s": 35596, "text": "shaik asra" }, { "code": null, "e": 35624, "s": 35607, "text": "shikhasingrajput" }, { "code": null, "e": 35648, "s": 35624, "text": "praveenvishwakarma11063" }, { "code": null, "e": 35667, "s": 35648, "text": "shivanisinghss2110" }, { "code": null, "e": 35674, "s": 35667, "text": "Amazon" }, { "code": null, "e": 35686, "s": 35674, "text": "Bitwise-XOR" }, { "code": null, "e": 35695, "s": 35686, "text": "Qualcomm" }, { "code": null, "e": 35703, "s": 35695, "text": "Samsung" }, { "code": null, "e": 35713, "s": 35703, "text": "Bit Magic" }, { "code": null, "e": 35720, "s": 35713, "text": "Amazon" }, { "code": null, "e": 35728, "s": 35720, "text": "Samsung" }, { "code": null, "e": 35737, "s": 35728, "text": "Qualcomm" }, { "code": null, "e": 35747, "s": 35737, "text": "Bit Magic" }, { "code": null, "e": 35845, "s": 35747, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35891, "s": 35845, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 35942, "s": 35891, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 35980, "s": 35942, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 35996, "s": 35980, "text": "Bit Fields in C" }, { "code": null, "e": 36031, "s": 35996, "text": "Find the element that appears once" }, { "code": null, "e": 36082, "s": 36031, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 36113, "s": 36082, "text": "C++ bitset and its application" }, { "code": null, "e": 36189, "s": 36113, "text": "Divide two integers without using multiplication, division and mod operator" }, { "code": null, "e": 36231, "s": 36189, "text": "1's and 2's complement of a Binary Number" } ]
ListMap in Scala - GeeksforGeeks
04 Aug, 2021 Immutable maps Implemented by using a list-based data structure. The Scala List class holds a sequenced, linear list of items. We must import scala.collection.mutable.ListMap for ListMap. ListMap collection used only for a small number of elements.Syntax: var listMapName = ListMap("k1"->"v1", "k2"->"v2", "k3"->"v3", ...) Here, k is key and v is value. Creating an ListMap: In below code we can see a ListMap is created with values. Scala // Scala program to create or print ListMapimport scala.collection.immutable.ListMap // Creating objectobject Geeks{ // Main method def main(args: Array[String]) { // Creating ListMap with values var listMap = ListMap("C"->"Csharp", "S"->"Scala", "J"->"Java") // Printing ListMap println(listMap) }} Output: Map(C -> Csharp, S -> Scala, J -> Java) Adding and accessing elements : A ListMap is created, add elements and access elements also performed. Scala // Scala program to Adding and Accessing Elements ListMapimport scala.collection.mutable.ListMap // Creating objectobject Geeks{ // Main method def main(args: Array[String]) { // Creating ListMap var listMap = ListMap("C"->"Csharp", "S"->"Scala", "J"->"Java") // Iterating elements listMap.foreach { case (key, value) => println (key + " -> " + value) } // Accessing value by using key println(listMap("S")) // Adding element var ListMap2 = listMap + ("P"->"Perl") ListMap2.foreach { case (key, value) => println (key + " -> " + value) } }} Output: J -> Java C -> Csharp S -> Scala Scala P -> Perl C -> Csharp J -> Java S -> Scala Removing an element from ListMap : A ListMap is created than removing an element is performed using – sign. Below is the example to removing an element from ListMap. Scala // Scala program to removing Element from ListMapimport scala.collection.mutable.ListMap // Creating objectobject Geeks{ // Main method def main(args: Array[String]) { // Creating ListMap var listMap = ListMap("C"->"Csharp", "S"->"Scala", "J"->"Java") // Iterating elements listMap.foreach { case (key, value) => println (key + " -> " + value) } // Removing an element listMap -= "C" println("After Removing") listMap.foreach { case (key, value) => println (key + " -> " + value) } }} Output: J -> Java C -> Csharp S -> Scala After Removing J -> Java S -> Scala Creating an empty ListMap: An empty ListMap is created either by calling its constructor or using ListMap.empty method. Scala // Scala program to Create an empty ListMapimport scala.collection.mutable.ListMap // Creating objectobject Geeks{ // Main method def main(args: Array[String]) { // Creating an empty list map by calling constructor var ListMap1 = new ListMap() // Creating an empty list map by using .empty method var ListMap2 = ListMap.empty // Printing empty ListMap println(emptyListMap1) println(emptyListMap2) }} Output: Map() Map() surinderdawra388 scala-collection Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Type Casting in Scala Class and Object in Scala Scala Lists Scala Tutorial – Learn Scala with Step By Step Guide Operators in Scala Inheritance in Scala Scala Constructors Scala | Arrays Scala String substring() method with example Lambda Expression in Scala
[ { "code": null, "e": 25213, "s": 25185, "text": "\n04 Aug, 2021" }, { "code": null, "e": 25471, "s": 25213, "text": "Immutable maps Implemented by using a list-based data structure. The Scala List class holds a sequenced, linear list of items. We must import scala.collection.mutable.ListMap for ListMap. ListMap collection used only for a small number of elements.Syntax: " }, { "code": null, "e": 25539, "s": 25471, "text": "var listMapName = ListMap(\"k1\"->\"v1\", \"k2\"->\"v2\", \"k3\"->\"v3\", ...) " }, { "code": null, "e": 25571, "s": 25539, "text": "Here, k is key and v is value. " }, { "code": null, "e": 25651, "s": 25571, "text": "Creating an ListMap: In below code we can see a ListMap is created with values." }, { "code": null, "e": 25657, "s": 25651, "text": "Scala" }, { "code": "// Scala program to create or print ListMapimport scala.collection.immutable.ListMap // Creating objectobject Geeks{ // Main method def main(args: Array[String]) { // Creating ListMap with values var listMap = ListMap(\"C\"->\"Csharp\", \"S\"->\"Scala\", \"J\"->\"Java\") // Printing ListMap println(listMap) }}", "e": 26007, "s": 25657, "text": null }, { "code": null, "e": 26017, "s": 26007, "text": "Output: " }, { "code": null, "e": 26057, "s": 26017, "text": "Map(C -> Csharp, S -> Scala, J -> Java)" }, { "code": null, "e": 26161, "s": 26057, "text": " Adding and accessing elements : A ListMap is created, add elements and access elements also performed." }, { "code": null, "e": 26167, "s": 26161, "text": "Scala" }, { "code": "// Scala program to Adding and Accessing Elements ListMapimport scala.collection.mutable.ListMap // Creating objectobject Geeks{ // Main method def main(args: Array[String]) { // Creating ListMap var listMap = ListMap(\"C\"->\"Csharp\", \"S\"->\"Scala\", \"J\"->\"Java\") // Iterating elements listMap.foreach { case (key, value) => println (key + \" -> \" + value) } // Accessing value by using key println(listMap(\"S\")) // Adding element var ListMap2 = listMap + (\"P\"->\"Perl\") ListMap2.foreach { case (key, value) => println (key + \" -> \" + value) } }}", "e": 26869, "s": 26167, "text": null }, { "code": null, "e": 26879, "s": 26869, "text": "Output: " }, { "code": null, "e": 26961, "s": 26879, "text": "J -> Java\nC -> Csharp\nS -> Scala\nScala\nP -> Perl\nC -> Csharp\nJ -> Java\nS -> Scala" }, { "code": null, "e": 27130, "s": 26961, "text": " Removing an element from ListMap : A ListMap is created than removing an element is performed using – sign. Below is the example to removing an element from ListMap. " }, { "code": null, "e": 27136, "s": 27130, "text": "Scala" }, { "code": "// Scala program to removing Element from ListMapimport scala.collection.mutable.ListMap // Creating objectobject Geeks{ // Main method def main(args: Array[String]) { // Creating ListMap var listMap = ListMap(\"C\"->\"Csharp\", \"S\"->\"Scala\", \"J\"->\"Java\") // Iterating elements listMap.foreach { case (key, value) => println (key + \" -> \" + value) } // Removing an element listMap -= \"C\" println(\"After Removing\") listMap.foreach { case (key, value) => println (key + \" -> \" + value) } }}", "e": 27771, "s": 27136, "text": null }, { "code": null, "e": 27781, "s": 27771, "text": "Output: " }, { "code": null, "e": 27850, "s": 27781, "text": "J -> Java\nC -> Csharp\nS -> Scala\nAfter Removing\nJ -> Java\nS -> Scala" }, { "code": null, "e": 27972, "s": 27850, "text": " Creating an empty ListMap: An empty ListMap is created either by calling its constructor or using ListMap.empty method." }, { "code": null, "e": 27978, "s": 27972, "text": "Scala" }, { "code": "// Scala program to Create an empty ListMapimport scala.collection.mutable.ListMap // Creating objectobject Geeks{ // Main method def main(args: Array[String]) { // Creating an empty list map by calling constructor var ListMap1 = new ListMap() // Creating an empty list map by using .empty method var ListMap2 = ListMap.empty // Printing empty ListMap println(emptyListMap1) println(emptyListMap2) }}", "e": 28463, "s": 27978, "text": null }, { "code": null, "e": 28473, "s": 28463, "text": "Output: " }, { "code": null, "e": 28485, "s": 28473, "text": "Map()\nMap()" }, { "code": null, "e": 28504, "s": 28487, "text": "surinderdawra388" }, { "code": null, "e": 28521, "s": 28504, "text": "scala-collection" }, { "code": null, "e": 28527, "s": 28521, "text": "Scala" }, { "code": null, "e": 28625, "s": 28527, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28647, "s": 28625, "text": "Type Casting in Scala" }, { "code": null, "e": 28673, "s": 28647, "text": "Class and Object in Scala" }, { "code": null, "e": 28685, "s": 28673, "text": "Scala Lists" }, { "code": null, "e": 28738, "s": 28685, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 28757, "s": 28738, "text": "Operators in Scala" }, { "code": null, "e": 28778, "s": 28757, "text": "Inheritance in Scala" }, { "code": null, "e": 28797, "s": 28778, "text": "Scala Constructors" }, { "code": null, "e": 28812, "s": 28797, "text": "Scala | Arrays" }, { "code": null, "e": 28857, "s": 28812, "text": "Scala String substring() method with example" } ]
Collectors collectingAndThen() method in Java with Examples - GeeksforGeeks
08 Jan, 2019 The collectingAndThen(Collector downstream, Function finisher) method of class collectors in Java, which adopts Collector so that we can perform an additional finishing transformation. Syntax : public static <T, A, R, RR> Collector <T, A, RR> collectingAndThen(Collector <T, A, R> downstream, Function <R, RR> finisher) Where, T : The type of the input elements A :Intermediate accumulation type of the downstream collector R :Result type of the downstream collector RR :Result type of the resulting collector T : The type of the input elements A :Intermediate accumulation type of the downstream collector R :Result type of the downstream collector RR :Result type of the resulting collector Parameters:This method accepts two parameters which are listed below downstream: It is an instance of a collector, i.e we can use any collector can here. finisher: It is an instance of a function which is to be applied to the final result of the downstream collector.Returns: Returns a collector which performs the action of the downstream collector, followed by an additional finishing step, with the help of finisher function.Below are examples to illustrate collectingAndThen() the method.Example 1: To create an immutable list// Write Java code here// Collectors collectingAndThen() method import java.util.Collections;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream; public class GFG { public static void main(String[] args) { // Create an Immutable List List<String> lt = Stream .of("GEEKS", "For", "GEEKS") .collect(Collectors .collectingAndThen( Collectors.toList(), Collections::<String> unmodifiableList)); System.out.println(lt); }}Output:[GEEKS, For, GEEKS] Example 2: To create an immuitable set.// Write Java code hereimport java.util.Collections;import java.util.List;import java.util.Set;import java.util.stream.Collectors;import java.util.stream.Stream; public class GFG { public static void main(String[] args) { // Create an Immutable Set Set<String> st = Stream .of("GEEKS", "FOR", "GEEKS") .collect( Collectors .collectingAndThen(Collectors.toSet(), Collections::<String> unmodifiableSet)); System.out.println(st); }}Output:[GEEKS, FOR] Example 2: To create an immutable mapimport java.util.*; public class GFG { public static void main(String[] args) { // Create an Immutable Map Map<String, String> mp = Stream .of(new String[][] { { "1", "Geeks" }, { "2", "For" }, { "3", "Geeks" } }) .collect( Collectors .collectingAndThen( Collectors.toMap(p -> p[0], p -> p[1]), Collections::<String, String> unmodifiableMap)); System.out.println(mp); }}Output:{1=Geeks, 2=For, 3=Geeks} Note:This method is most commonly used for creating immutable collections.My Personal Notes arrow_drop_upSave Returns: Returns a collector which performs the action of the downstream collector, followed by an additional finishing step, with the help of finisher function. Below are examples to illustrate collectingAndThen() the method. Example 1: To create an immutable list // Write Java code here// Collectors collectingAndThen() method import java.util.Collections;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream; public class GFG { public static void main(String[] args) { // Create an Immutable List List<String> lt = Stream .of("GEEKS", "For", "GEEKS") .collect(Collectors .collectingAndThen( Collectors.toList(), Collections::<String> unmodifiableList)); System.out.println(lt); }} [GEEKS, For, GEEKS] Example 2: To create an immuitable set. // Write Java code hereimport java.util.Collections;import java.util.List;import java.util.Set;import java.util.stream.Collectors;import java.util.stream.Stream; public class GFG { public static void main(String[] args) { // Create an Immutable Set Set<String> st = Stream .of("GEEKS", "FOR", "GEEKS") .collect( Collectors .collectingAndThen(Collectors.toSet(), Collections::<String> unmodifiableSet)); System.out.println(st); }} [GEEKS, FOR] Example 2: To create an immutable map import java.util.*; public class GFG { public static void main(String[] args) { // Create an Immutable Map Map<String, String> mp = Stream .of(new String[][] { { "1", "Geeks" }, { "2", "For" }, { "3", "Geeks" } }) .collect( Collectors .collectingAndThen( Collectors.toMap(p -> p[0], p -> p[1]), Collections::<String, String> unmodifiableMap)); System.out.println(mp); }} {1=Geeks, 2=For, 3=Geeks} Note:This method is most commonly used for creating immutable collections. Java - util package Java-Collectors Java-Functions Java-Stream-Collectors Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java Set in Java
[ { "code": null, "e": 25563, "s": 25535, "text": "\n08 Jan, 2019" }, { "code": null, "e": 25748, "s": 25563, "text": "The collectingAndThen(Collector downstream, Function finisher) method of class collectors in Java, which adopts Collector so that we can perform an additional finishing transformation." }, { "code": null, "e": 25757, "s": 25748, "text": "Syntax :" }, { "code": null, "e": 26195, "s": 25757, "text": "public static <T, A, R, RR> \n Collector <T, A, RR> \n collectingAndThen(Collector <T, A, R> downstream, \n Function <R, RR> finisher)\n \n\nWhere,\n T : The type of the input elements\n A :Intermediate accumulation type of the downstream collector\n R :Result type of the downstream collector\n RR :Result type of the resulting collector\n" }, { "code": null, "e": 26235, "s": 26195, "text": "T : The type of the input elements\n " }, { "code": null, "e": 26302, "s": 26235, "text": "A :Intermediate accumulation type of the downstream collector\n " }, { "code": null, "e": 26350, "s": 26302, "text": "R :Result type of the downstream collector\n " }, { "code": null, "e": 26394, "s": 26350, "text": "RR :Result type of the resulting collector\n" }, { "code": null, "e": 26463, "s": 26394, "text": "Parameters:This method accepts two parameters which are listed below" }, { "code": null, "e": 26548, "s": 26463, "text": "downstream: It is an instance of a collector, i.e we can use any collector can here." }, { "code": null, "e": 29107, "s": 26548, "text": "finisher: It is an instance of a function which is to be applied to the final result of the downstream collector.Returns: Returns a collector which performs the action of the downstream collector, followed by an additional finishing step, with the help of finisher function.Below are examples to illustrate collectingAndThen() the method.Example 1: To create an immutable list// Write Java code here// Collectors collectingAndThen() method import java.util.Collections;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream; public class GFG { public static void main(String[] args) { // Create an Immutable List List<String> lt = Stream .of(\"GEEKS\", \"For\", \"GEEKS\") .collect(Collectors .collectingAndThen( Collectors.toList(), Collections::<String> unmodifiableList)); System.out.println(lt); }}Output:[GEEKS, For, GEEKS]\nExample 2: To create an immuitable set.// Write Java code hereimport java.util.Collections;import java.util.List;import java.util.Set;import java.util.stream.Collectors;import java.util.stream.Stream; public class GFG { public static void main(String[] args) { // Create an Immutable Set Set<String> st = Stream .of(\"GEEKS\", \"FOR\", \"GEEKS\") .collect( Collectors .collectingAndThen(Collectors.toSet(), Collections::<String> unmodifiableSet)); System.out.println(st); }}Output:[GEEKS, FOR]\nExample 2: To create an immutable mapimport java.util.*; public class GFG { public static void main(String[] args) { // Create an Immutable Map Map<String, String> mp = Stream .of(new String[][] { { \"1\", \"Geeks\" }, { \"2\", \"For\" }, { \"3\", \"Geeks\" } }) .collect( Collectors .collectingAndThen( Collectors.toMap(p -> p[0], p -> p[1]), Collections::<String, String> unmodifiableMap)); System.out.println(mp); }}Output:{1=Geeks, 2=For, 3=Geeks}\nNote:This method is most commonly used for creating immutable collections.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 29269, "s": 29107, "text": "Returns: Returns a collector which performs the action of the downstream collector, followed by an additional finishing step, with the help of finisher function." }, { "code": null, "e": 29334, "s": 29269, "text": "Below are examples to illustrate collectingAndThen() the method." }, { "code": null, "e": 29373, "s": 29334, "text": "Example 1: To create an immutable list" }, { "code": "// Write Java code here// Collectors collectingAndThen() method import java.util.Collections;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream; public class GFG { public static void main(String[] args) { // Create an Immutable List List<String> lt = Stream .of(\"GEEKS\", \"For\", \"GEEKS\") .collect(Collectors .collectingAndThen( Collectors.toList(), Collections::<String> unmodifiableList)); System.out.println(lt); }}", "e": 30002, "s": 29373, "text": null }, { "code": null, "e": 30023, "s": 30002, "text": "[GEEKS, For, GEEKS]\n" }, { "code": null, "e": 30063, "s": 30023, "text": "Example 2: To create an immuitable set." }, { "code": "// Write Java code hereimport java.util.Collections;import java.util.List;import java.util.Set;import java.util.stream.Collectors;import java.util.stream.Stream; public class GFG { public static void main(String[] args) { // Create an Immutable Set Set<String> st = Stream .of(\"GEEKS\", \"FOR\", \"GEEKS\") .collect( Collectors .collectingAndThen(Collectors.toSet(), Collections::<String> unmodifiableSet)); System.out.println(st); }}", "e": 30707, "s": 30063, "text": null }, { "code": null, "e": 30721, "s": 30707, "text": "[GEEKS, FOR]\n" }, { "code": null, "e": 30759, "s": 30721, "text": "Example 2: To create an immutable map" }, { "code": "import java.util.*; public class GFG { public static void main(String[] args) { // Create an Immutable Map Map<String, String> mp = Stream .of(new String[][] { { \"1\", \"Geeks\" }, { \"2\", \"For\" }, { \"3\", \"Geeks\" } }) .collect( Collectors .collectingAndThen( Collectors.toMap(p -> p[0], p -> p[1]), Collections::<String, String> unmodifiableMap)); System.out.println(mp); }}", "e": 31406, "s": 30759, "text": null }, { "code": null, "e": 31433, "s": 31406, "text": "{1=Geeks, 2=For, 3=Geeks}\n" }, { "code": null, "e": 31508, "s": 31433, "text": "Note:This method is most commonly used for creating immutable collections." }, { "code": null, "e": 31528, "s": 31508, "text": "Java - util package" }, { "code": null, "e": 31544, "s": 31528, "text": "Java-Collectors" }, { "code": null, "e": 31559, "s": 31544, "text": "Java-Functions" }, { "code": null, "e": 31582, "s": 31559, "text": "Java-Stream-Collectors" }, { "code": null, "e": 31587, "s": 31582, "text": "Java" }, { "code": null, "e": 31592, "s": 31587, "text": "Java" }, { "code": null, "e": 31690, "s": 31592, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31741, "s": 31690, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 31771, "s": 31741, "text": "HashMap in Java with Examples" }, { "code": null, "e": 31790, "s": 31771, "text": "Interfaces in Java" }, { "code": null, "e": 31821, "s": 31790, "text": "How to iterate any Map in Java" }, { "code": null, "e": 31839, "s": 31821, "text": "ArrayList in Java" }, { "code": null, "e": 31871, "s": 31839, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 31891, "s": 31871, "text": "Stack Class in Java" }, { "code": null, "e": 31923, "s": 31891, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 31947, "s": 31923, "text": "Singleton Class in Java" } ]
Iterate through list of dictionaries in Python - GeeksforGeeks
22 Nov, 2021 In this article, we will learn how to iterate through a list of dictionaries. List of dictionaries in use: [{‘Python’: ‘Machine Learning’, ‘R’: ‘Machine learning’}, {‘Python’: ‘Web development’, ‘Java Script’: ‘Web Development’, ‘HTML’: ‘Web Development’}, {‘C++’: ‘Game Development’, ‘Python’: ‘Game Development’}, {‘Java’: ‘App Development’, ‘Kotlin’: ‘App Development’}] This is a direct method, where list elements are extracted using just the index. Syntax: list[index] Example: Python3 # Create a list of dictionarieslanguages = [ { "Python": "Machine Learning", "R": "Machine learning", }, { "Python": "Web development", "Java Script": "Web Development", "HTML": "Web Development" }, { "C++": "Game Development", "Python": "Game Development" }, { "Java": "App Development", "Kotlin": "App Development" }] print(languages[0])print(languages[1])print(languages[2])print(languages[3]) Output: {‘Python’: ‘Machine Learning’, ‘R’: ‘Machine learning’} {‘Python’: ‘Web development’, ‘Java Script’: ‘Web Development’, ‘HTML’: ‘Web Development’} {‘C++’: ‘Game Development’, ‘Python’: ‘Game Development’} {‘Java’: ‘App Development’, ‘Kotlin’: ‘App Development’} After using indexing to particular dictionaries, now we can treat each item of the list as a dictionary, Example: Extracting values from a particular dictionary Python3 # Create a list of dictionarieslanguages = [ { "Python": "Machine Learning", "R": "Machine learning", }, { "Python": "Web development", "Java Script": "Web Development", "HTML": "Web Development" }, { "C++": "Game Development", "Python": "Game Development" }, { "Java": "App Development", "Kotlin": "App Development" }] for key, val in languages[0].items(): print("{} : {}".format(key, val)) Output: Python : Machine Learning R : Machine learning After iterating to a list the keys from the dictionary can further be extracted using the keys() function. Example: Extracting key values Python3 # Create a list of dictionarieslanguages = [ { "Python": "Machine Learning", "R": "Machine learning", }, { "Python": "Web development", "Java Script": "Web Development", "HTML": "Web Development" }, { "C++": "Game Development", "Python": "Game Development" }, { "Java": "App Development", "Kotlin": "App Development" }] # iterate over the listfor i in languages: # now i is a dict, now we see the keys # of the dict for key in i.keys(): # print every key of each dict print(key) print("-------------") Output: Python R ————- Python Java Script HTML ————- C++ Python ————- Java Kotlin ————- The list is simply iterated using list comprehension and the dictionaries are printed. Example: Extracting keys using list comprehension Python3 # Create a list of dictionarieslanguages = [ { "Python" : "Machine Learning", "R" : "Machine learning", }, { "Python" : "Web development", "Java Script" : "Web Development", "HTML" : "Web Development" }, { "C++" : "Game Development", "Python" : "Game Development" }, { "Java" : "App Development", "Kotlin" : "App Development" }] # here we are printing the keys of the dictionary# by using list comprehension and each key will be# printed in a new line due to the presence of " sep = "\n" ".# It will add a new line character to our output. print(*[key for i in languages for key in i.keys()], sep = "\n") Output: Python R Python Java Script HTML C++ Python Java Kotlin as5853535 Picked Python List-of-Dict python-dict Python python-dict Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n22 Nov, 2021" }, { "code": null, "e": 25616, "s": 25537, "text": "In this article, we will learn how to iterate through a list of dictionaries. " }, { "code": null, "e": 25645, "s": 25616, "text": "List of dictionaries in use:" }, { "code": null, "e": 25704, "s": 25645, "text": "[{‘Python’: ‘Machine Learning’, ‘R’: ‘Machine learning’}, " }, { "code": null, "e": 25797, "s": 25704, "text": "{‘Python’: ‘Web development’, ‘Java Script’: ‘Web Development’, ‘HTML’: ‘Web Development’}, " }, { "code": null, "e": 25914, "s": 25797, "text": "{‘C++’: ‘Game Development’, ‘Python’: ‘Game Development’}, {‘Java’: ‘App Development’, ‘Kotlin’: ‘App Development’}]" }, { "code": null, "e": 25995, "s": 25914, "text": "This is a direct method, where list elements are extracted using just the index." }, { "code": null, "e": 26003, "s": 25995, "text": "Syntax:" }, { "code": null, "e": 26015, "s": 26003, "text": "list[index]" }, { "code": null, "e": 26024, "s": 26015, "text": "Example:" }, { "code": null, "e": 26032, "s": 26024, "text": "Python3" }, { "code": "# Create a list of dictionarieslanguages = [ { \"Python\": \"Machine Learning\", \"R\": \"Machine learning\", }, { \"Python\": \"Web development\", \"Java Script\": \"Web Development\", \"HTML\": \"Web Development\" }, { \"C++\": \"Game Development\", \"Python\": \"Game Development\" }, { \"Java\": \"App Development\", \"Kotlin\": \"App Development\" }] print(languages[0])print(languages[1])print(languages[2])print(languages[3])", "e": 26517, "s": 26032, "text": null }, { "code": null, "e": 26525, "s": 26517, "text": "Output:" }, { "code": null, "e": 26581, "s": 26525, "text": "{‘Python’: ‘Machine Learning’, ‘R’: ‘Machine learning’}" }, { "code": null, "e": 26672, "s": 26581, "text": "{‘Python’: ‘Web development’, ‘Java Script’: ‘Web Development’, ‘HTML’: ‘Web Development’}" }, { "code": null, "e": 26730, "s": 26672, "text": "{‘C++’: ‘Game Development’, ‘Python’: ‘Game Development’}" }, { "code": null, "e": 26787, "s": 26730, "text": "{‘Java’: ‘App Development’, ‘Kotlin’: ‘App Development’}" }, { "code": null, "e": 26892, "s": 26787, "text": "After using indexing to particular dictionaries, now we can treat each item of the list as a dictionary," }, { "code": null, "e": 26948, "s": 26892, "text": "Example: Extracting values from a particular dictionary" }, { "code": null, "e": 26956, "s": 26948, "text": "Python3" }, { "code": "# Create a list of dictionarieslanguages = [ { \"Python\": \"Machine Learning\", \"R\": \"Machine learning\", }, { \"Python\": \"Web development\", \"Java Script\": \"Web Development\", \"HTML\": \"Web Development\" }, { \"C++\": \"Game Development\", \"Python\": \"Game Development\" }, { \"Java\": \"App Development\", \"Kotlin\": \"App Development\" }] for key, val in languages[0].items(): print(\"{} : {}\".format(key, val))", "e": 27438, "s": 26956, "text": null }, { "code": null, "e": 27446, "s": 27438, "text": "Output:" }, { "code": null, "e": 27472, "s": 27446, "text": "Python : Machine Learning" }, { "code": null, "e": 27493, "s": 27472, "text": "R : Machine learning" }, { "code": null, "e": 27600, "s": 27493, "text": "After iterating to a list the keys from the dictionary can further be extracted using the keys() function." }, { "code": null, "e": 27631, "s": 27600, "text": "Example: Extracting key values" }, { "code": null, "e": 27639, "s": 27631, "text": "Python3" }, { "code": "# Create a list of dictionarieslanguages = [ { \"Python\": \"Machine Learning\", \"R\": \"Machine learning\", }, { \"Python\": \"Web development\", \"Java Script\": \"Web Development\", \"HTML\": \"Web Development\" }, { \"C++\": \"Game Development\", \"Python\": \"Game Development\" }, { \"Java\": \"App Development\", \"Kotlin\": \"App Development\" }] # iterate over the listfor i in languages: # now i is a dict, now we see the keys # of the dict for key in i.keys(): # print every key of each dict print(key) print(\"-------------\")", "e": 28265, "s": 27639, "text": null }, { "code": null, "e": 28273, "s": 28265, "text": "Output:" }, { "code": null, "e": 28280, "s": 28273, "text": "Python" }, { "code": null, "e": 28282, "s": 28280, "text": "R" }, { "code": null, "e": 28288, "s": 28282, "text": "————-" }, { "code": null, "e": 28295, "s": 28288, "text": "Python" }, { "code": null, "e": 28307, "s": 28295, "text": "Java Script" }, { "code": null, "e": 28312, "s": 28307, "text": "HTML" }, { "code": null, "e": 28318, "s": 28312, "text": "————-" }, { "code": null, "e": 28322, "s": 28318, "text": "C++" }, { "code": null, "e": 28329, "s": 28322, "text": "Python" }, { "code": null, "e": 28335, "s": 28329, "text": "————-" }, { "code": null, "e": 28340, "s": 28335, "text": "Java" }, { "code": null, "e": 28347, "s": 28340, "text": "Kotlin" }, { "code": null, "e": 28353, "s": 28347, "text": "————-" }, { "code": null, "e": 28440, "s": 28353, "text": "The list is simply iterated using list comprehension and the dictionaries are printed." }, { "code": null, "e": 28490, "s": 28440, "text": "Example: Extracting keys using list comprehension" }, { "code": null, "e": 28498, "s": 28490, "text": "Python3" }, { "code": "# Create a list of dictionarieslanguages = [ { \"Python\" : \"Machine Learning\", \"R\" : \"Machine learning\", }, { \"Python\" : \"Web development\", \"Java Script\" : \"Web Development\", \"HTML\" : \"Web Development\" }, { \"C++\" : \"Game Development\", \"Python\" : \"Game Development\" }, { \"Java\" : \"App Development\", \"Kotlin\" : \"App Development\" }] # here we are printing the keys of the dictionary# by using list comprehension and each key will be# printed in a new line due to the presence of \" sep = \"\\n\" \".# It will add a new line character to our output. print(*[key for i in languages for key in i.keys()], sep = \"\\n\")", "e": 29190, "s": 28498, "text": null }, { "code": null, "e": 29198, "s": 29190, "text": "Output:" }, { "code": null, "e": 29205, "s": 29198, "text": "Python" }, { "code": null, "e": 29207, "s": 29205, "text": "R" }, { "code": null, "e": 29214, "s": 29207, "text": "Python" }, { "code": null, "e": 29226, "s": 29214, "text": "Java Script" }, { "code": null, "e": 29231, "s": 29226, "text": "HTML" }, { "code": null, "e": 29235, "s": 29231, "text": "C++" }, { "code": null, "e": 29242, "s": 29235, "text": "Python" }, { "code": null, "e": 29247, "s": 29242, "text": "Java" }, { "code": null, "e": 29254, "s": 29247, "text": "Kotlin" }, { "code": null, "e": 29264, "s": 29254, "text": "as5853535" }, { "code": null, "e": 29271, "s": 29264, "text": "Picked" }, { "code": null, "e": 29291, "s": 29271, "text": "Python List-of-Dict" }, { "code": null, "e": 29303, "s": 29291, "text": "python-dict" }, { "code": null, "e": 29310, "s": 29303, "text": "Python" }, { "code": null, "e": 29322, "s": 29310, "text": "python-dict" }, { "code": null, "e": 29420, "s": 29322, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29452, "s": 29420, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29494, "s": 29452, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29536, "s": 29494, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29592, "s": 29536, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29619, "s": 29592, "text": "Python Classes and Objects" }, { "code": null, "e": 29650, "s": 29619, "text": "Python | os.path.join() method" }, { "code": null, "e": 29689, "s": 29650, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29718, "s": 29689, "text": "Create a directory in Python" }, { "code": null, "e": 29740, "s": 29718, "text": "Defaultdict in Python" } ]
Count number of pairs (A <= N, B <= N) such that gcd (A , B) is B - GeeksforGeeks
09 Mar, 2021 Given a number n. We need find the number of ordered pairs of a and b such gcd(a, b) is b itselfExamples : Input : n = 2 Output : 3 (1, 1) (2, 2) and (2, 1) Input : n = 3 Output : 5 (1, 1) (2, 2) (3, 3) (2, 1) and (3, 1) Naive approach : gcd(a, b) = b means b is a factor of a. So total number of pairs will be equal to sum of divisors for each a = 1 to n. Please refer find all divisors of a natural number for implementation.Efficient approach : gcd(a, b) = b means that a is a multiple of b. So total number of pairs will be sum of number of multiples of each b (where b varies from 1 to n) which are less than or equal to n. For a number i, number of multiples of i is less than or equal to floor(n/i). So what we need to do is just sum the floor(n/i) for each i = 1 to n and print it. But more optimizations can be done. floor(n/i) can have atmost 2*sqrt(n) values for i >= sqrt(n). floor(n/i) can vary from 1 to sqrt(n) and similarly for i = 1 to sqrt(n) floor(n/i) can have values from 1 to sqrt(n). So total of 2*sqrt(n) distinct values let floor(n/i) = k k <= n/i < k + 1 n/k+1 < i <= n/k floor(n/k+1) < i <= floor(n/k) Thus for given k the largest value of i for which the floor(n/i) = k is floor(n/k) and all the set of i for which the floor(n/i) = k are consecutive CPP Java Python3 C# PHP Javascript // C++ implementation of counting pairs// such that gcd (a, b) = b#include <bits/stdc++.h>using namespace std; // returns number of valid pairsint CountPairs(int n){ // initialize k int k = n; // loop till imin <= n int imin = 1; // Initialize result int ans = 0; while (imin <= n) { // max i with given k floor(n/k) int imax = n / k; // adding k*(number of i with // floor(n/i) = k to ans ans += k * (imax - imin + 1); // set imin = imax + 1 and k = n/imin imin = imax + 1; k = n / imin; } return ans;} // Driver functionint main(){ cout << CountPairs(1) << endl; cout << CountPairs(2) << endl; cout << CountPairs(3) << endl; return 0;} // Java implementation of counting pairs// such that gcd (a, b) = bclass GFG { // returns number of valid pairs static int CountPairs(int n) { // initialize k int k = n; // loop till imin <= n int imin = 1; // Initialize result int ans = 0; while (imin <= n) { // max i with given k floor(n/k) int imax = n / k; // adding k*(number of i with // floor(n/i) = k to ans ans += k * (imax - imin + 1); // set imin = imax + 1 // and k = n/imin imin = imax + 1; k = n / imin; } return ans; } // Driver code public static void main(String[] args) { System.out.println(CountPairs(1)); System.out.println(CountPairs(2)); System.out.println(CountPairs(3)); }} // This code is contributed by Anant Agarwal. # Python implementation of counting# pairs such that gcd (a, b) = b # returns number of valid pairsdef CountPairs(n): # initialize k k = n # loop till imin <= n imin = 1 # Initialize result ans = 0 while(imin <= n): # max i with given k floor(n / k) imax = n / k # adding k*(number of i with # floor(n / i) = k to ans ans += k * (imax - imin + 1) # set imin = imax + 1 and # k = n / imin imin = imax + 1 k = n / imin return ans # Driver codeprint(CountPairs(1))print(CountPairs(2))print(CountPairs(3)) # This code is contributed by Anant Agarwal. // C# implementation of counting// pairs such that gcd (a, b) = busing System; class GFG { // returns number of valid pairs static int CountPairs(int n) { // initialize k int k = n; // loop till imin <= n int imin = 1; // Initialize result int ans = 0; while (imin <= n) { // max i with given // k floor(n / k) int imax = n / k; // adding k * (number of i // with floor(n / i) = k // to ans ans += k * (imax - imin + 1); // set imin = imax + 1 // and k = n / imin imin = imax + 1; k = n / imin; } return ans; } // Driver code public static void Main(String []args) { Console.WriteLine(CountPairs(1)); Console.WriteLine(CountPairs(2)); Console.WriteLine(CountPairs(3)); }} // This code is contributed by vt_m. <?php// PHP implementation of counting// pairs such that gcd (a, b) = b // returns number of valid pairsfunction CountPairs($n){ // initialize k $k = $n; // loop till imin <= n $imin = 1; // Initialize result $ans = 0; while ($imin <= $n) { // max i with given k floor(n/k) $imax = $n / $k; // adding k*(number of i with // floor(n/i) = k to ans $ans += $k * ($imax - $imin + 1); // set imin = imax + 1 // and k = n/imin $imin = $imax + 1; $k = (int)($n / $imin); } return $ans;} // Driver Codeecho(CountPairs(1) . "\n");echo(CountPairs(2) . "\n");echo(CountPairs(3) . "\n"); // This code is contributed by Ajit.?> <script> // Javascript implementation of counting pairs// such that gcd (a, b) = b // returns number of valid pairsfunction CountPairs(n){ // initialize k let k = n; // loop till imin <= n let imin = 1; // Initialize result let ans = 0; while (imin <= n) { // max i with given k floor(n/k) let imax = Math.floor(n / k); // adding k*(number of i with // floor(n/i) = k to ans ans += k * (imax - imin + 1); // set imin = imax + 1 and k = n/imin imin = imax + 1; k = Math.floor(n / imin); } return ans;} // Driver function document.write(CountPairs(1) + "<br>"); document.write(CountPairs(2) + "<br>"); document.write(CountPairs(3) + "<br>"); // This is code is contributed by Mayank Tyagi </script> Output : 1 3 5 This article is contributed by Ayush Jha. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m jit_t mayanktyagi1709 GCD-LCM number-theory Mathematical number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program for factorial of a number Print all possible combinations of r elements in a given array of size n Program for Decimal to Binary Conversion The Knight's tour problem | Backtracking-1 Operators in C / C++ Find minimum number of coins that make a given value Program to find sum of elements in a given array
[ { "code": null, "e": 26231, "s": 26203, "text": "\n09 Mar, 2021" }, { "code": null, "e": 26340, "s": 26231, "text": "Given a number n. We need find the number of ordered pairs of a and b such gcd(a, b) is b itselfExamples : " }, { "code": null, "e": 26456, "s": 26340, "text": "Input : n = 2\nOutput : 3\n(1, 1) (2, 2) and (2, 1) \n\nInput : n = 3\nOutput : 5\n(1, 1) (2, 2) (3, 3) (2, 1) and (3, 1)" }, { "code": null, "e": 27284, "s": 26458, "text": "Naive approach : gcd(a, b) = b means b is a factor of a. So total number of pairs will be equal to sum of divisors for each a = 1 to n. Please refer find all divisors of a natural number for implementation.Efficient approach : gcd(a, b) = b means that a is a multiple of b. So total number of pairs will be sum of number of multiples of each b (where b varies from 1 to n) which are less than or equal to n. For a number i, number of multiples of i is less than or equal to floor(n/i). So what we need to do is just sum the floor(n/i) for each i = 1 to n and print it. But more optimizations can be done. floor(n/i) can have atmost 2*sqrt(n) values for i >= sqrt(n). floor(n/i) can vary from 1 to sqrt(n) and similarly for i = 1 to sqrt(n) floor(n/i) can have values from 1 to sqrt(n). So total of 2*sqrt(n) distinct values " }, { "code": null, "e": 27519, "s": 27284, "text": "let floor(n/i) = k\nk <= n/i < k + 1\nn/k+1 < i <= n/k\nfloor(n/k+1) < i <= floor(n/k)\nThus for given k the largest value of i for \nwhich the floor(n/i) = k is floor(n/k)\nand all the set of i for which the \nfloor(n/i) = k are consecutive" }, { "code": null, "e": 27525, "s": 27521, "text": "CPP" }, { "code": null, "e": 27530, "s": 27525, "text": "Java" }, { "code": null, "e": 27538, "s": 27530, "text": "Python3" }, { "code": null, "e": 27541, "s": 27538, "text": "C#" }, { "code": null, "e": 27545, "s": 27541, "text": "PHP" }, { "code": null, "e": 27556, "s": 27545, "text": "Javascript" }, { "code": "// C++ implementation of counting pairs// such that gcd (a, b) = b#include <bits/stdc++.h>using namespace std; // returns number of valid pairsint CountPairs(int n){ // initialize k int k = n; // loop till imin <= n int imin = 1; // Initialize result int ans = 0; while (imin <= n) { // max i with given k floor(n/k) int imax = n / k; // adding k*(number of i with // floor(n/i) = k to ans ans += k * (imax - imin + 1); // set imin = imax + 1 and k = n/imin imin = imax + 1; k = n / imin; } return ans;} // Driver functionint main(){ cout << CountPairs(1) << endl; cout << CountPairs(2) << endl; cout << CountPairs(3) << endl; return 0;}", "e": 28296, "s": 27556, "text": null }, { "code": "// Java implementation of counting pairs// such that gcd (a, b) = bclass GFG { // returns number of valid pairs static int CountPairs(int n) { // initialize k int k = n; // loop till imin <= n int imin = 1; // Initialize result int ans = 0; while (imin <= n) { // max i with given k floor(n/k) int imax = n / k; // adding k*(number of i with // floor(n/i) = k to ans ans += k * (imax - imin + 1); // set imin = imax + 1 // and k = n/imin imin = imax + 1; k = n / imin; } return ans; } // Driver code public static void main(String[] args) { System.out.println(CountPairs(1)); System.out.println(CountPairs(2)); System.out.println(CountPairs(3)); }} // This code is contributed by Anant Agarwal.", "e": 29254, "s": 28296, "text": null }, { "code": "# Python implementation of counting# pairs such that gcd (a, b) = b # returns number of valid pairsdef CountPairs(n): # initialize k k = n # loop till imin <= n imin = 1 # Initialize result ans = 0 while(imin <= n): # max i with given k floor(n / k) imax = n / k # adding k*(number of i with # floor(n / i) = k to ans ans += k * (imax - imin + 1) # set imin = imax + 1 and # k = n / imin imin = imax + 1 k = n / imin return ans # Driver codeprint(CountPairs(1))print(CountPairs(2))print(CountPairs(3)) # This code is contributed by Anant Agarwal.", "e": 29904, "s": 29254, "text": null }, { "code": "// C# implementation of counting// pairs such that gcd (a, b) = busing System; class GFG { // returns number of valid pairs static int CountPairs(int n) { // initialize k int k = n; // loop till imin <= n int imin = 1; // Initialize result int ans = 0; while (imin <= n) { // max i with given // k floor(n / k) int imax = n / k; // adding k * (number of i // with floor(n / i) = k // to ans ans += k * (imax - imin + 1); // set imin = imax + 1 // and k = n / imin imin = imax + 1; k = n / imin; } return ans; } // Driver code public static void Main(String []args) { Console.WriteLine(CountPairs(1)); Console.WriteLine(CountPairs(2)); Console.WriteLine(CountPairs(3)); }} // This code is contributed by vt_m.", "e": 30905, "s": 29904, "text": null }, { "code": "<?php// PHP implementation of counting// pairs such that gcd (a, b) = b // returns number of valid pairsfunction CountPairs($n){ // initialize k $k = $n; // loop till imin <= n $imin = 1; // Initialize result $ans = 0; while ($imin <= $n) { // max i with given k floor(n/k) $imax = $n / $k; // adding k*(number of i with // floor(n/i) = k to ans $ans += $k * ($imax - $imin + 1); // set imin = imax + 1 // and k = n/imin $imin = $imax + 1; $k = (int)($n / $imin); } return $ans;} // Driver Codeecho(CountPairs(1) . \"\\n\");echo(CountPairs(2) . \"\\n\");echo(CountPairs(3) . \"\\n\"); // This code is contributed by Ajit.?>", "e": 31621, "s": 30905, "text": null }, { "code": "<script> // Javascript implementation of counting pairs// such that gcd (a, b) = b // returns number of valid pairsfunction CountPairs(n){ // initialize k let k = n; // loop till imin <= n let imin = 1; // Initialize result let ans = 0; while (imin <= n) { // max i with given k floor(n/k) let imax = Math.floor(n / k); // adding k*(number of i with // floor(n/i) = k to ans ans += k * (imax - imin + 1); // set imin = imax + 1 and k = n/imin imin = imax + 1; k = Math.floor(n / imin); } return ans;} // Driver function document.write(CountPairs(1) + \"<br>\"); document.write(CountPairs(2) + \"<br>\"); document.write(CountPairs(3) + \"<br>\"); // This is code is contributed by Mayank Tyagi </script>", "e": 32418, "s": 31621, "text": null }, { "code": null, "e": 32428, "s": 32418, "text": "Output : " }, { "code": null, "e": 32434, "s": 32428, "text": "1\n3\n5" }, { "code": null, "e": 32856, "s": 32434, "text": "This article is contributed by Ayush Jha. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 32861, "s": 32856, "text": "vt_m" }, { "code": null, "e": 32867, "s": 32861, "text": "jit_t" }, { "code": null, "e": 32883, "s": 32867, "text": "mayanktyagi1709" }, { "code": null, "e": 32891, "s": 32883, "text": "GCD-LCM" }, { "code": null, "e": 32905, "s": 32891, "text": "number-theory" }, { "code": null, "e": 32918, "s": 32905, "text": "Mathematical" }, { "code": null, "e": 32932, "s": 32918, "text": "number-theory" }, { "code": null, "e": 32945, "s": 32932, "text": "Mathematical" }, { "code": null, "e": 33043, "s": 32945, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33067, "s": 33043, "text": "Merge two sorted arrays" }, { "code": null, "e": 33110, "s": 33067, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 33124, "s": 33110, "text": "Prime Numbers" }, { "code": null, "e": 33158, "s": 33124, "text": "Program for factorial of a number" }, { "code": null, "e": 33231, "s": 33158, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 33272, "s": 33231, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 33315, "s": 33272, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 33336, "s": 33315, "text": "Operators in C / C++" }, { "code": null, "e": 33389, "s": 33336, "text": "Find minimum number of coins that make a given value" } ]
How to create a matrix with random values in R? - GeeksforGeeks
16 May, 2021 In this article, we will discuss hw to create a matrix with random values in the R programming language. The functions which are used to generate the random values are: rnorm() runif() rexp() rpois() rbinom() sample() We will use all these functions one by one to create the matrix with random values. Method 1: Using rnorm() rnorm() function basically creates the random values according to the normal distribution. Syntax: rnorm(n, mean, sd) So, we give 25 as an argument in the rnorm() function, after that put those values in the matrix function with the row number and create the matrix. R # matrix create with the help# of matrix function random values# generated with the help of rnorm()m<-matrix(rnorm(25) , nrow = 5) # print the matrixprint(m) Output: Method 2: Using runif() function runif() function basically creates the random values according to the uniform distribution. So, we give 25 as an argument in the runif() function. Syntax: runif(n, min, max) Parameters:n: represents number of observationsmin, max: represents lower and upper limits of the distribution Code: R # matrix create with the help # of matrix function random values # generated with the help of runif()m <- matrix( ruif(25), nrow = 5) # print the matrixprint(m) Output: Method 3: Using rexp() function rexp() function basically creates the random values according to the exponential distribution. So, we give 25 as an argument in the rexp() function. Syntax: rexp(N, rate ) Code: R # matrix create with the help # of matrix function random values# generated with the help of runif()m <- matrix( runif(25), nrow = 5) # print the matrixprint(m) Output: Method 4: Using rpois() function In this example, we will try to create the random values using the rpois(). rpois() function basically creates the random values according to the Poisson distribution x ~ P(lambda). So, we give 25 and 5 as an argument in the rpois() function. Syntax: rpois(N, lambda) Parameters:N: Sample Sizelambda: Average number of events per interval Code: R # matrix create with the help # of matrix function random values # generated with the help of rpois()m <- matrix(rpois( 25, 5), nrow = 5) # print the matrixprint(m) Output: Method 5: Using rbinom() function In this example, we will try to create the random values using the rbinom(). rbinom() function basically creates the random values of a given probability. rbinom(n, N, p) Where n is the number of observations, N is the total number of trials, p is the probability of success. So, we give 25, 5, and .6 as an argument in the rbinom() function. Code: R # matrix create with the help# of matrix function random values# generated with the help of rbinom()m <- matrix(rbinom( 25, 5, .6), nrow = 5) # print the matrixprint(m) Output: Method 6: Using sample() function In this example, we will try to create random values using the sample(). sample() function basically creates the random values of given elements. Syntax:sample(x, size, replace) Parameters:x: indicates either vector or a positive integer or data framesize: indicates size of sample to be takenreplace: indicates logical value. If TRUE, sample may have more than one same value So, we give 1:20 and 100 as an argument in the sample() function. Code: R # matrix create with the help# of matrix function random values# generated with the help of sample()m <- matrix(sample( 1 : 20, 100, replace = TRUE), ncol = 10) # print the matrixprint(m) Output: Picked R Matrix-Programs R-Matrix R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Convert Matrix to Dataframe in R
[ { "code": null, "e": 26487, "s": 26459, "text": "\n16 May, 2021" }, { "code": null, "e": 26592, "s": 26487, "text": "In this article, we will discuss hw to create a matrix with random values in the R programming language." }, { "code": null, "e": 26656, "s": 26592, "text": "The functions which are used to generate the random values are:" }, { "code": null, "e": 26664, "s": 26656, "text": "rnorm()" }, { "code": null, "e": 26672, "s": 26664, "text": "runif()" }, { "code": null, "e": 26679, "s": 26672, "text": "rexp()" }, { "code": null, "e": 26687, "s": 26679, "text": "rpois()" }, { "code": null, "e": 26696, "s": 26687, "text": "rbinom()" }, { "code": null, "e": 26705, "s": 26696, "text": "sample()" }, { "code": null, "e": 26789, "s": 26705, "text": "We will use all these functions one by one to create the matrix with random values." }, { "code": null, "e": 26813, "s": 26789, "text": "Method 1: Using rnorm()" }, { "code": null, "e": 26905, "s": 26813, "text": "rnorm() function basically creates the random values according to the normal distribution. " }, { "code": null, "e": 26932, "s": 26905, "text": "Syntax: rnorm(n, mean, sd)" }, { "code": null, "e": 27081, "s": 26932, "text": "So, we give 25 as an argument in the rnorm() function, after that put those values in the matrix function with the row number and create the matrix." }, { "code": null, "e": 27083, "s": 27081, "text": "R" }, { "code": "# matrix create with the help# of matrix function random values# generated with the help of rnorm()m<-matrix(rnorm(25) , nrow = 5) # print the matrixprint(m)", "e": 27242, "s": 27083, "text": null }, { "code": null, "e": 27250, "s": 27242, "text": "Output:" }, { "code": null, "e": 27283, "s": 27250, "text": "Method 2: Using runif() function" }, { "code": null, "e": 27430, "s": 27283, "text": "runif() function basically creates the random values according to the uniform distribution. So, we give 25 as an argument in the runif() function." }, { "code": null, "e": 27457, "s": 27430, "text": "Syntax: runif(n, min, max)" }, { "code": null, "e": 27568, "s": 27457, "text": "Parameters:n: represents number of observationsmin, max: represents lower and upper limits of the distribution" }, { "code": null, "e": 27574, "s": 27568, "text": "Code:" }, { "code": null, "e": 27576, "s": 27574, "text": "R" }, { "code": "# matrix create with the help # of matrix function random values # generated with the help of runif()m <- matrix( ruif(25), nrow = 5) # print the matrixprint(m)", "e": 27738, "s": 27576, "text": null }, { "code": null, "e": 27746, "s": 27738, "text": "Output:" }, { "code": null, "e": 27778, "s": 27746, "text": "Method 3: Using rexp() function" }, { "code": null, "e": 27927, "s": 27778, "text": "rexp() function basically creates the random values according to the exponential distribution. So, we give 25 as an argument in the rexp() function." }, { "code": null, "e": 27950, "s": 27927, "text": "Syntax: rexp(N, rate )" }, { "code": null, "e": 27956, "s": 27950, "text": "Code:" }, { "code": null, "e": 27958, "s": 27956, "text": "R" }, { "code": "# matrix create with the help # of matrix function random values# generated with the help of runif()m <- matrix( runif(25), nrow = 5) # print the matrixprint(m)", "e": 28120, "s": 27958, "text": null }, { "code": null, "e": 28128, "s": 28120, "text": "Output:" }, { "code": null, "e": 28161, "s": 28128, "text": "Method 4: Using rpois() function" }, { "code": null, "e": 28405, "s": 28161, "text": " In this example, we will try to create the random values using the rpois(). rpois() function basically creates the random values according to the Poisson distribution x ~ P(lambda). So, we give 25 and 5 as an argument in the rpois() function." }, { "code": null, "e": 28430, "s": 28405, "text": "Syntax: rpois(N, lambda)" }, { "code": null, "e": 28501, "s": 28430, "text": "Parameters:N: Sample Sizelambda: Average number of events per interval" }, { "code": null, "e": 28507, "s": 28501, "text": "Code:" }, { "code": null, "e": 28509, "s": 28507, "text": "R" }, { "code": "# matrix create with the help # of matrix function random values # generated with the help of rpois()m <- matrix(rpois( 25, 5), nrow = 5) # print the matrixprint(m)", "e": 28675, "s": 28509, "text": null }, { "code": null, "e": 28683, "s": 28675, "text": "Output:" }, { "code": null, "e": 28717, "s": 28683, "text": "Method 5: Using rbinom() function" }, { "code": null, "e": 28873, "s": 28717, "text": "In this example, we will try to create the random values using the rbinom(). rbinom() function basically creates the random values of a given probability. " }, { "code": null, "e": 28889, "s": 28873, "text": "rbinom(n, N, p)" }, { "code": null, "e": 29061, "s": 28889, "text": "Where n is the number of observations, N is the total number of trials, p is the probability of success. So, we give 25, 5, and .6 as an argument in the rbinom() function." }, { "code": null, "e": 29067, "s": 29061, "text": "Code:" }, { "code": null, "e": 29069, "s": 29067, "text": "R" }, { "code": "# matrix create with the help# of matrix function random values# generated with the help of rbinom()m <- matrix(rbinom( 25, 5, .6), nrow = 5) # print the matrixprint(m)", "e": 29239, "s": 29069, "text": null }, { "code": null, "e": 29247, "s": 29239, "text": "Output:" }, { "code": null, "e": 29281, "s": 29247, "text": "Method 6: Using sample() function" }, { "code": null, "e": 29427, "s": 29281, "text": "In this example, we will try to create random values using the sample(). sample() function basically creates the random values of given elements." }, { "code": null, "e": 29459, "s": 29427, "text": "Syntax:sample(x, size, replace)" }, { "code": null, "e": 29658, "s": 29459, "text": "Parameters:x: indicates either vector or a positive integer or data framesize: indicates size of sample to be takenreplace: indicates logical value. If TRUE, sample may have more than one same value" }, { "code": null, "e": 29724, "s": 29658, "text": "So, we give 1:20 and 100 as an argument in the sample() function." }, { "code": null, "e": 29730, "s": 29724, "text": "Code:" }, { "code": null, "e": 29732, "s": 29730, "text": "R" }, { "code": "# matrix create with the help# of matrix function random values# generated with the help of sample()m <- matrix(sample( 1 : 20, 100, replace = TRUE), ncol = 10) # print the matrixprint(m)", "e": 29922, "s": 29732, "text": null }, { "code": null, "e": 29930, "s": 29922, "text": "Output:" }, { "code": null, "e": 29937, "s": 29930, "text": "Picked" }, { "code": null, "e": 29955, "s": 29937, "text": "R Matrix-Programs" }, { "code": null, "e": 29964, "s": 29955, "text": "R-Matrix" }, { "code": null, "e": 29975, "s": 29964, "text": "R Language" }, { "code": null, "e": 29986, "s": 29975, "text": "R Programs" }, { "code": null, "e": 30084, "s": 29986, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30136, "s": 30084, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 30171, "s": 30136, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 30209, "s": 30171, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 30267, "s": 30209, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30310, "s": 30267, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 30368, "s": 30310, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30411, "s": 30368, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 30460, "s": 30411, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 30510, "s": 30460, "text": "How to filter R dataframe by multiple conditions?" } ]
Python | Extract length of longest string in list - GeeksforGeeks
29 Nov, 2019 Sometimes, while working with a lot of data, we can have a problem in which we need to extract the maximum length of all the strings in list. This kind of problem can have application in many domains. Let’s discuss certain ways in which this task can be performed. Method #1 : Using max() + generator expressionThe combination of above functionalities can be used to perform this task. In this, we extract all the list lengths using generator expression and return maximum of them using max(). # Python3 code to demonstrate working of# Extracting length of longest string in list# using max() + generator expression # initialize list test_list = ['gfg', 'is', 'best'] # printing original list print("The original list : " + str(test_list)) # Extracting length of longest string in list# using max() + generator expressionres = max(len(ele) for ele in test_list) # printing resultprint("Length of maximum string is : " + str(res)) The original list : ['gfg', 'is', 'best'] Length of maximum string is : 4 Method #2 : Using len() + key argument + max()The combination of above functions can be used to perform this task. In this, we extract the maximum length using len() and max(). It is faster than above method as it performs more task built in rather than overhead by generator expression. # Python3 code to demonstrate working of# Extracting length of longest string in list# using len() + key argument + max() # initialize list test_list = ['gfg', 'is', 'best'] # printing original list print("The original list : " + str(test_list)) # Extracting length of longest string in list# using len() + key argument + max()res = len(max(test_list, key = len)) # printing resultprint("Length of maximum string is : " + str(res)) The original list : ['gfg', 'is', 'best'] Length of maximum string is : 4 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() Defaultdict in Python Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python? Python | Convert string dictionary to dictionary
[ { "code": null, "e": 26069, "s": 26041, "text": "\n29 Nov, 2019" }, { "code": null, "e": 26334, "s": 26069, "text": "Sometimes, while working with a lot of data, we can have a problem in which we need to extract the maximum length of all the strings in list. This kind of problem can have application in many domains. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 26563, "s": 26334, "text": "Method #1 : Using max() + generator expressionThe combination of above functionalities can be used to perform this task. In this, we extract all the list lengths using generator expression and return maximum of them using max()." }, { "code": "# Python3 code to demonstrate working of# Extracting length of longest string in list# using max() + generator expression # initialize list test_list = ['gfg', 'is', 'best'] # printing original list print(\"The original list : \" + str(test_list)) # Extracting length of longest string in list# using max() + generator expressionres = max(len(ele) for ele in test_list) # printing resultprint(\"Length of maximum string is : \" + str(res))", "e": 27003, "s": 26563, "text": null }, { "code": null, "e": 27078, "s": 27003, "text": "The original list : ['gfg', 'is', 'best']\nLength of maximum string is : 4\n" }, { "code": null, "e": 27368, "s": 27080, "text": "Method #2 : Using len() + key argument + max()The combination of above functions can be used to perform this task. In this, we extract the maximum length using len() and max(). It is faster than above method as it performs more task built in rather than overhead by generator expression." }, { "code": "# Python3 code to demonstrate working of# Extracting length of longest string in list# using len() + key argument + max() # initialize list test_list = ['gfg', 'is', 'best'] # printing original list print(\"The original list : \" + str(test_list)) # Extracting length of longest string in list# using len() + key argument + max()res = len(max(test_list, key = len)) # printing resultprint(\"Length of maximum string is : \" + str(res))", "e": 27804, "s": 27368, "text": null }, { "code": null, "e": 27879, "s": 27804, "text": "The original list : ['gfg', 'is', 'best']\nLength of maximum string is : 4\n" }, { "code": null, "e": 27900, "s": 27879, "text": "Python list-programs" }, { "code": null, "e": 27907, "s": 27900, "text": "Python" }, { "code": null, "e": 27923, "s": 27907, "text": "Python Programs" }, { "code": null, "e": 28021, "s": 27923, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28039, "s": 28021, "text": "Python Dictionary" }, { "code": null, "e": 28071, "s": 28039, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28093, "s": 28071, "text": "Enumerate() in Python" }, { "code": null, "e": 28135, "s": 28093, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28161, "s": 28135, "text": "Python String | replace()" }, { "code": null, "e": 28183, "s": 28161, "text": "Defaultdict in Python" }, { "code": null, "e": 28229, "s": 28183, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28267, "s": 28229, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 28307, "s": 28267, "text": "How to print without newline in Python?" } ]
H2 Database - Alter
ALTER is a command used to change the table structure by adding different clauses to the alter command. Based on the scenario, we need to add respective clause to the alter command. In this chapter, we will discuss various scenarios of alter command. Alter Table Add is a command used to add a new column to a table along with the respective data type. This command commits the transaction in this connection. Following is the generic syntax of the Alter Table Add command. ALTER TABLE [ IF EXISTS ] tableName ADD [ COLUMN ] { [ IF NOT EXISTS ] columnDefinition [ { BEFORE | AFTER } columnName ] | ( { columnDefinition } [,...] ) } In this example, we will add a new column start_date to the table tutorials_tbl. The datatype for start_date is Date. Following is the query to add a new column. ALTER TABLE tutorials_tbl ADD start_date DATE; The above query produces the following output. (6) rows effected Alter table add constraint is a command used to add different constraints to the table such as primary key, foreign key, not null, etc. The required indexes are automatically created if they don’t exist yet. It is not possible to disable checking for unique constraint. This command commits an open transaction in this connection. Following is the generic syntax of the Alter table add constraint command. ALTER TABLE [ IF EXISTS ] tableName ADD constraint [ CHECK | NOCHECK ] In this example, let us add a primary key constraint (tutorials_tbl_pk) to the column id of the table tutorials_tbl, using the following query. ALTER TABLE tutorials_tbl ADD CONSTRAINT tutorials_tbl_pk PRIMARYKEY(id); The above query produces the following output. (6) row (s) effected This command is used to rename the constraint name of a particular relation table. This command commits an open transaction in this connection. Following is the generic syntax of the Alter Table Rename Constraint command. ALTER TABLE [ IF EXISTS ] tableName RENAME oldConstraintName TO newConstraintName While using this syntax, make sure that the old constraint name should exist with the respective column. In this example, we will change the primary key constraint name of the table tutorials_tbl from tutorials_tbl_pk to tutorials_tbl_pk_constraint. Following is the query to do so. ALTER TABLE tutorials_tbl RENAME CONSTRAINT tutorials_tbl_pk TO tutorials_tbl_pk_constraint; The above query produces the following output. (1) row (s) effected This command is used to change the structure and properties of the column of a particular table. Changing the properties means changing the datatype of a column, rename a column, change the identity value, or change the selectivity. Following is the generic syntax of the Alter Table Alter Column command. ALTER TABLE [ IF EXISTS ] tableName ALTER COLUMN columnName { { dataType [ DEFAULT expression ] [ [ NOT ] NULL ] [ AUTO_INCREMENT | IDENTITY ] } | { RENAME TO name } | { RESTART WITH long } | { SELECTIVITY int } | { SET DEFAULT expression } | { SET NULL } | { SET NOT NULL } } In the above syntax − RESTART − command changes the next value of an auto increment column. RESTART − command changes the next value of an auto increment column. SELECTIVITY − command sets the selectivity (1-100) for a column. Based on the selectivity value we can image the value of the column. SELECTIVITY − command sets the selectivity (1-100) for a column. Based on the selectivity value we can image the value of the column. SET DEFAULT − changes the default value of a column. SET DEFAULT − changes the default value of a column. SET NULL − sets the column to allow NULL. SET NULL − sets the column to allow NULL. SET NOT NULL − sets the column to allow NOT NULL. SET NOT NULL − sets the column to allow NOT NULL. In this example, we will rename the column of the table tutorials_tbl from Title to Tutorial_Title using the following query. ALTER TABLE tutorials_tbl ALTER COLUMN title RENAME TO tutorial_title; The above query produces the following output. (0) row(s) effected In a similar way, we can perform different scenarios with the ALTER command. 14 Lectures 1 hours Mahesh Kumar 100 Lectures 9.5 hours Hari Om Singh 108 Lectures 8 hours Pavan Lalwani 10 Lectures 1 hours Deepti Trivedi 20 Lectures 2 hours Deepti Trivedi 14 Lectures 1 hours Deepti Trivedi Print Add Notes Bookmark this page
[ { "code": null, "e": 2358, "s": 2107, "text": "ALTER is a command used to change the table structure by adding different clauses to the alter command. Based on the scenario, we need to add respective clause to the alter command. In this chapter, we will discuss various scenarios of alter command." }, { "code": null, "e": 2517, "s": 2358, "text": "Alter Table Add is a command used to add a new column to a table along with the respective data type. This command commits the transaction in this connection." }, { "code": null, "e": 2581, "s": 2517, "text": "Following is the generic syntax of the Alter Table Add command." }, { "code": null, "e": 2745, "s": 2581, "text": "ALTER TABLE [ IF EXISTS ] tableName ADD [ COLUMN ] \n{ [ IF NOT EXISTS ] columnDefinition [ { BEFORE | AFTER } columnName ] \n | ( { columnDefinition } [,...] ) }\n" }, { "code": null, "e": 2907, "s": 2745, "text": "In this example, we will add a new column start_date to the table tutorials_tbl. The datatype for start_date is Date. Following is the query to add a new column." }, { "code": null, "e": 2954, "s": 2907, "text": "ALTER TABLE tutorials_tbl ADD start_date DATE;" }, { "code": null, "e": 3001, "s": 2954, "text": "The above query produces the following output." }, { "code": null, "e": 3021, "s": 3001, "text": "(6) rows effected \n" }, { "code": null, "e": 3157, "s": 3021, "text": "Alter table add constraint is a command used to add different constraints to the table such as primary key, foreign key, not null, etc." }, { "code": null, "e": 3352, "s": 3157, "text": "The required indexes are automatically created if they don’t exist yet. It is not possible to disable checking for unique constraint. This command commits an open transaction in this connection." }, { "code": null, "e": 3427, "s": 3352, "text": "Following is the generic syntax of the Alter table add constraint command." }, { "code": null, "e": 3500, "s": 3427, "text": "ALTER TABLE [ IF EXISTS ] tableName ADD constraint [ CHECK | NOCHECK ] \n" }, { "code": null, "e": 3644, "s": 3500, "text": "In this example, let us add a primary key constraint (tutorials_tbl_pk) to the column id of the table tutorials_tbl, using the following query." }, { "code": null, "e": 3719, "s": 3644, "text": "ALTER TABLE tutorials_tbl ADD CONSTRAINT tutorials_tbl_pk PRIMARYKEY(id); " }, { "code": null, "e": 3766, "s": 3719, "text": "The above query produces the following output." }, { "code": null, "e": 3788, "s": 3766, "text": "(6) row (s) effected\n" }, { "code": null, "e": 3932, "s": 3788, "text": "This command is used to rename the constraint name of a particular relation table. This command commits an open transaction in this connection." }, { "code": null, "e": 4010, "s": 3932, "text": "Following is the generic syntax of the Alter Table Rename Constraint command." }, { "code": null, "e": 4093, "s": 4010, "text": "ALTER TABLE [ IF EXISTS ] tableName RENAME oldConstraintName TO newConstraintName\n" }, { "code": null, "e": 4198, "s": 4093, "text": "While using this syntax, make sure that the old constraint name should exist with the respective column." }, { "code": null, "e": 4376, "s": 4198, "text": "In this example, we will change the primary key constraint name of the table tutorials_tbl from tutorials_tbl_pk to tutorials_tbl_pk_constraint. Following is the query to do so." }, { "code": null, "e": 4470, "s": 4376, "text": "ALTER TABLE tutorials_tbl RENAME CONSTRAINT \ntutorials_tbl_pk TO tutorials_tbl_pk_constraint;" }, { "code": null, "e": 4517, "s": 4470, "text": "The above query produces the following output." }, { "code": null, "e": 4540, "s": 4517, "text": "(1) row (s) effected \n" }, { "code": null, "e": 4773, "s": 4540, "text": "This command is used to change the structure and properties of the column of a particular table. Changing the properties means changing the datatype of a column, rename a column, change the identity value, or change the selectivity." }, { "code": null, "e": 4846, "s": 4773, "text": "Following is the generic syntax of the Alter Table Alter Column command." }, { "code": null, "e": 5132, "s": 4846, "text": "ALTER TABLE [ IF EXISTS ] tableName ALTER COLUMN columnName \n{ { dataType [ DEFAULT expression ] [ [ NOT ] NULL ] [ AUTO_INCREMENT | IDENTITY ] } \n| { RENAME TO name } \n| { RESTART WITH long } \n| { SELECTIVITY int } \n| { SET DEFAULT expression } \n| { SET NULL } \n| { SET NOT NULL } } \n" }, { "code": null, "e": 5154, "s": 5132, "text": "In the above syntax −" }, { "code": null, "e": 5224, "s": 5154, "text": "RESTART − command changes the next value of an auto increment column." }, { "code": null, "e": 5294, "s": 5224, "text": "RESTART − command changes the next value of an auto increment column." }, { "code": null, "e": 5428, "s": 5294, "text": "SELECTIVITY − command sets the selectivity (1-100) for a column. Based on the selectivity value we can image the value of the column." }, { "code": null, "e": 5562, "s": 5428, "text": "SELECTIVITY − command sets the selectivity (1-100) for a column. Based on the selectivity value we can image the value of the column." }, { "code": null, "e": 5615, "s": 5562, "text": "SET DEFAULT − changes the default value of a column." }, { "code": null, "e": 5668, "s": 5615, "text": "SET DEFAULT − changes the default value of a column." }, { "code": null, "e": 5710, "s": 5668, "text": "SET NULL − sets the column to allow NULL." }, { "code": null, "e": 5752, "s": 5710, "text": "SET NULL − sets the column to allow NULL." }, { "code": null, "e": 5802, "s": 5752, "text": "SET NOT NULL − sets the column to allow NOT NULL." }, { "code": null, "e": 5852, "s": 5802, "text": "SET NOT NULL − sets the column to allow NOT NULL." }, { "code": null, "e": 5978, "s": 5852, "text": "In this example, we will rename the column of the table tutorials_tbl from Title to Tutorial_Title using the following query." }, { "code": null, "e": 6051, "s": 5978, "text": "ALTER TABLE tutorials_tbl ALTER COLUMN title RENAME TO tutorial_title; \n" }, { "code": null, "e": 6098, "s": 6051, "text": "The above query produces the following output." }, { "code": null, "e": 6120, "s": 6098, "text": "(0) row(s) effected \n" }, { "code": null, "e": 6197, "s": 6120, "text": "In a similar way, we can perform different scenarios with the ALTER command." }, { "code": null, "e": 6230, "s": 6197, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 6244, "s": 6230, "text": " Mahesh Kumar" }, { "code": null, "e": 6280, "s": 6244, "text": "\n 100 Lectures \n 9.5 hours \n" }, { "code": null, "e": 6295, "s": 6280, "text": " Hari Om Singh" }, { "code": null, "e": 6329, "s": 6295, "text": "\n 108 Lectures \n 8 hours \n" }, { "code": null, "e": 6344, "s": 6329, "text": " Pavan Lalwani" }, { "code": null, "e": 6377, "s": 6344, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 6393, "s": 6377, "text": " Deepti Trivedi" }, { "code": null, "e": 6426, "s": 6393, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 6442, "s": 6426, "text": " Deepti Trivedi" }, { "code": null, "e": 6475, "s": 6442, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 6491, "s": 6475, "text": " Deepti Trivedi" }, { "code": null, "e": 6498, "s": 6491, "text": " Print" }, { "code": null, "e": 6509, "s": 6498, "text": " Add Notes" } ]
Convert Decimal to the equivalent 64-bit unsigned integer in C#
To convert the value of the specified Decimal to the equivalent 64-bit unsigned integer, the code is as follows − Live Demo using System; public class Demo { public static void Main() { Decimal val = 99.29m; Console.WriteLine("Decimal value = "+val); ulong res = Decimal.ToUInt64(val); Console.WriteLine("64-bit unsigned integer = "+res); } } This will produce the following output − Decimal value = 99.29 64-bit unsigned integer = 99 Let us see another example − Live Demo using System; public class Demo { public static void Main(){ Decimal val = 0.001m; Console.WriteLine("Decimal value = "+val); ulong res = Decimal.ToUInt64(val); Console.WriteLine("64-bit unsigned integer = "+res); } } This will produce the following output − Decimal value = 0.001 64-bit unsigned integer = 0
[ { "code": null, "e": 1176, "s": 1062, "text": "To convert the value of the specified Decimal to the equivalent 64-bit unsigned integer, the code is as follows −" }, { "code": null, "e": 1187, "s": 1176, "text": " Live Demo" }, { "code": null, "e": 1436, "s": 1187, "text": "using System;\npublic class Demo {\n public static void Main() {\n Decimal val = 99.29m;\n Console.WriteLine(\"Decimal value = \"+val);\n ulong res = Decimal.ToUInt64(val);\n Console.WriteLine(\"64-bit unsigned integer = \"+res);\n }\n}" }, { "code": null, "e": 1477, "s": 1436, "text": "This will produce the following output −" }, { "code": null, "e": 1528, "s": 1477, "text": "Decimal value = 99.29\n64-bit unsigned integer = 99" }, { "code": null, "e": 1557, "s": 1528, "text": "Let us see another example −" }, { "code": null, "e": 1568, "s": 1557, "text": " Live Demo" }, { "code": null, "e": 1816, "s": 1568, "text": "using System;\npublic class Demo {\n public static void Main(){\n Decimal val = 0.001m;\n Console.WriteLine(\"Decimal value = \"+val);\n ulong res = Decimal.ToUInt64(val);\n Console.WriteLine(\"64-bit unsigned integer = \"+res);\n }\n}" }, { "code": null, "e": 1857, "s": 1816, "text": "This will produce the following output −" }, { "code": null, "e": 1907, "s": 1857, "text": "Decimal value = 0.001\n64-bit unsigned integer = 0" } ]
What is Bitwise XOR Operator (^) in JavaScript?
It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR means that either operand one is true or operand two is true, but not both. You can try to run the following code to learn how to work with Bitwise XOR Operator Live Demo <html> <body> <script> <!-- var a = 2; // Bit presentation 10 var b = 3; // Bit presentation 11 document.write("(a ^ b) => "); result = (a ^ b); document.write(result); </script> </body> </html>
[ { "code": null, "e": 1234, "s": 1062, "text": "It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR means that either operand one is true or operand two is true, but not both." }, { "code": null, "e": 1319, "s": 1234, "text": "You can try to run the following code to learn how to work with Bitwise XOR Operator" }, { "code": null, "e": 1329, "s": 1319, "text": "Live Demo" }, { "code": null, "e": 1599, "s": 1329, "text": "<html>\n <body>\n <script>\n <!--\n var a = 2; // Bit presentation 10\n var b = 3; // Bit presentation 11\n document.write(\"(a ^ b) => \");\n result = (a ^ b);\n document.write(result);\n </script>\n </body>\n</html>" } ]
How to Build Amazing AI Use Cases under 10 Mins using GPT-3? | by Sharan Kumar Ravindran | Towards Data Science
Do you think that building an NLP based AI application such as a chatbot or a Translator requires a lot of data science skills and would take a lot of time? It is not always true, this article will help you better understand. I am going to show how to use GPT-3 to build some amazing NLP based AI applications with minimal development effort. Before getting into the build let’s first understand what GPT-3 is and what are all the features of GPT-3 that make it so special. GPT-3 is Generative Pre-trained Transformer 3, it is a language model trained on a vast number of datasets from the internet and developed by a company called OpenAI. GPT-3 is being offered via API, currently, the API is in a controlled beta and there is a waitlist for one to gain access to this amazing API. Below are some reasons why the GPT-3 model has been most talked about for GPT-3 model consists of 175 billion parameters, the previous version, GPT-2 model had only 1.5 billion parameters. Parameters are weights in a neural network model that transforms the inputs to output It is a generative model which means that it has the ability to generate a long sequence of words that is coherent as an output This state-of-the-art language model can respond to almost any question passed on to it and that too in a more humane way Billions of words, text, and code snippets used in model training hence make it capable of auto code in a wide range of programming languages Its Multilingual text processing help to work on languages other than English as well The best part is GPT-3 model can perform a specific task, such as being a translator or a chatbot or code builder without any customization or any special tuning, all it needs is a few training examples To learn more about the technical details of this amazing model check out here. Here in this article, I am going to show you how this amazing API can be used to solve different NLP based AI use-cases. To build the use-cases covered in this article, you need to have access to the GPT-3 beta API. It is currently available only on an invite, you can apply for access using the below link. It will take you to a form where a couple of questions will be asked about your organization and the project you are planning to implement. To interface with the GPT-3 API, I am going to use a script from the following gpt3-sandbox repository. The script I am using from this repository is gpt.py available at the API folder that enables me to access the GPT-3 API hence making it possible to show different use-cases that can be solved. The scripts used in this article can be found here Here we are not going to pass any training examples but just directly access the API and use it as a chatbot. In the below example, I am importing the required packages as well as the script we have downloaded from the “gpt3-sandbox” repository. We will be passing three arguments to the model they are, Engine — There are four options for us to choose from, they are Davinci, ADA, Babbage, and Curie. We will be using Davinci as it is the most powerful engine trained using 175 billion parameters Temperature — This is usually between the range 0 and 1, it is used to control the randomness of the generated output. A value of 0 makes the model deterministic that is, the output will be the same every time we execute whereas on the other hand with 1 there will be high randomness in the output generated. max_tokens — maximum completion length In the below script the question that needs to be asked is passed on to the variable “prompt1” and then passed to the model using the submit_request function. The result is stored in the ‘output1’ variable as shown below, import json import openai from gpt import GPT from gpt import Example import config # Reading the API key from a file service_key = config.api_key openai.api_key = service_key # Application 1 - Directly use as chatbot Use-case gpt1 = GPT(engine="davinci", temperature=0.2, max_tokens=100) # Input to the Model prompt1 = "How to learn data science?" output1 = gpt1.submit_request(prompt1) # Model Output output1.choices[0].text '\nI think the best way to learn data science is to do data science.\n\nI’ve been doing data science for a few years now, and I’ve learned a lot from doing it. I’ve learned a lot from reading books and blogs, but I’ve learned the most from doing it.\n\nI’ve learned a lot from doing data science, and I’ve learned a lot from reading books and blogs.\n\nI' In the above example, as you see the model can come up with a really good response for the question asked with no tweaking or tuning. Since here we are not providing any training examples the model output need not always be a response it could come up with a similar set of questions or with content related to the input passed. The performance can be improved by supplying some training examples In the below example we are going to see the implementation of text to equation conversion with very minimal training which is not possible with other pre-trained models. In the below example the temperature value has been increased to bring some randomness to the response and we are also passing some predefined examples to the model as a training dataset. With just 5 examples we could train the model to convert the text to an equation. After training the model with the known examples we pass the following as input “x squared plus 2 times ” and the model converts it into an equation. # Application 2 - LaTex Use-case - Text to Equation gpt2 = GPT(engine="davinci", temperature=0.5, max_tokens=100) # Examples to train as LaTex Application gpt2.add_example(Example('Two plus two equals four', '2 + 2 = 4')) gpt2.add_example(Example('The integral from zero to infinity', '\\int_0^{\\infty}')) gpt2.add_example(Example('The gradient of x squared plus two times x with respect to x', '\\nabla_x x^2 + 2x')) gpt2.add_example(Example('The log of two times x', '\\log{2x}')) gpt2.add_example(Example('x squared plus y squared plus equals z squared', 'x^2 + y^2 = z^2')) # Input to the model prompt2 = "x squared plus 2 times x" output2 = gpt2.submit_request(prompt2) # Model Output output2.choices[0].text 'output: x^2 + 2x\n\n' Like above use-case with a few examples, we could train the model to behave like a translator. Below is the code for the translator module where we train the model to translate the text in English to French with just three examples. # Application 3 - Translator Use-case gpt3 = GPT(engine="davinci", temperature=0.5, max_tokens=100) # Examples to train as a English to French translator gpt3.add_example(Example('What is your name?', 'quel est votre nom?')) gpt3.add_example(Example('What are you doing?', 'Que faites-vous?')) gpt3.add_example(Example('How are you?', 'Comment allez-vous?')) # Input to the model prompt3 = "where are you?" output3 = gpt3.submit_request(prompt3) # Model output output3.choices[0].text 'output: Où êtes-vous?\n\n' This ability of the model to perform a specific task like “foreign language translator” or “text to equation converter” with very minimal development effort makes it very special. Below is a tutorial video where I provide a walk-through of the use-case implementation. To learn more about interesting applications built using GPT3 check this page here. I am a Data Science professional with over 10 years of experience and I have authored 2 books in data science. I write data science-related content intending to make it simple and accessible. Follow me up at Medium. I have a YouTube channel as well where I teach and talk about various data science concepts. If interested, subscribe to my channel below.
[ { "code": null, "e": 646, "s": 172, "text": "Do you think that building an NLP based AI application such as a chatbot or a Translator requires a lot of data science skills and would take a lot of time? It is not always true, this article will help you better understand. I am going to show how to use GPT-3 to build some amazing NLP based AI applications with minimal development effort. Before getting into the build let’s first understand what GPT-3 is and what are all the features of GPT-3 that make it so special." }, { "code": null, "e": 956, "s": 646, "text": "GPT-3 is Generative Pre-trained Transformer 3, it is a language model trained on a vast number of datasets from the internet and developed by a company called OpenAI. GPT-3 is being offered via API, currently, the API is in a controlled beta and there is a waitlist for one to gain access to this amazing API." }, { "code": null, "e": 1030, "s": 956, "text": "Below are some reasons why the GPT-3 model has been most talked about for" }, { "code": null, "e": 1231, "s": 1030, "text": "GPT-3 model consists of 175 billion parameters, the previous version, GPT-2 model had only 1.5 billion parameters. Parameters are weights in a neural network model that transforms the inputs to output" }, { "code": null, "e": 1359, "s": 1231, "text": "It is a generative model which means that it has the ability to generate a long sequence of words that is coherent as an output" }, { "code": null, "e": 1481, "s": 1359, "text": "This state-of-the-art language model can respond to almost any question passed on to it and that too in a more humane way" }, { "code": null, "e": 1623, "s": 1481, "text": "Billions of words, text, and code snippets used in model training hence make it capable of auto code in a wide range of programming languages" }, { "code": null, "e": 1709, "s": 1623, "text": "Its Multilingual text processing help to work on languages other than English as well" }, { "code": null, "e": 1912, "s": 1709, "text": "The best part is GPT-3 model can perform a specific task, such as being a translator or a chatbot or code builder without any customization or any special tuning, all it needs is a few training examples" }, { "code": null, "e": 2113, "s": 1912, "text": "To learn more about the technical details of this amazing model check out here. Here in this article, I am going to show you how this amazing API can be used to solve different NLP based AI use-cases." }, { "code": null, "e": 2440, "s": 2113, "text": "To build the use-cases covered in this article, you need to have access to the GPT-3 beta API. It is currently available only on an invite, you can apply for access using the below link. It will take you to a form where a couple of questions will be asked about your organization and the project you are planning to implement." }, { "code": null, "e": 2789, "s": 2440, "text": "To interface with the GPT-3 API, I am going to use a script from the following gpt3-sandbox repository. The script I am using from this repository is gpt.py available at the API folder that enables me to access the GPT-3 API hence making it possible to show different use-cases that can be solved. The scripts used in this article can be found here" }, { "code": null, "e": 2899, "s": 2789, "text": "Here we are not going to pass any training examples but just directly access the API and use it as a chatbot." }, { "code": null, "e": 3093, "s": 2899, "text": "In the below example, I am importing the required packages as well as the script we have downloaded from the “gpt3-sandbox” repository. We will be passing three arguments to the model they are," }, { "code": null, "e": 3287, "s": 3093, "text": "Engine — There are four options for us to choose from, they are Davinci, ADA, Babbage, and Curie. We will be using Davinci as it is the most powerful engine trained using 175 billion parameters" }, { "code": null, "e": 3596, "s": 3287, "text": "Temperature — This is usually between the range 0 and 1, it is used to control the randomness of the generated output. A value of 0 makes the model deterministic that is, the output will be the same every time we execute whereas on the other hand with 1 there will be high randomness in the output generated." }, { "code": null, "e": 3635, "s": 3596, "text": "max_tokens — maximum completion length" }, { "code": null, "e": 3857, "s": 3635, "text": "In the below script the question that needs to be asked is passed on to the variable “prompt1” and then passed to the model using the submit_request function. The result is stored in the ‘output1’ variable as shown below," }, { "code": null, "e": 3945, "s": 3857, "text": "import json\nimport openai\n\nfrom gpt import GPT\nfrom gpt import Example\n\nimport config \n" }, { "code": null, "e": 4038, "s": 3945, "text": "# Reading the API key from a file\nservice_key = config.api_key\nopenai.api_key = service_key\n" }, { "code": null, "e": 4290, "s": 4038, "text": "# Application 1 - Directly use as chatbot Use-case\ngpt1 = GPT(engine=\"davinci\", temperature=0.2, max_tokens=100)\n# Input to the Model\nprompt1 = \"How to learn data science?\"\noutput1 = gpt1.submit_request(prompt1)\n# Model Output\noutput1.choices[0].text\n" }, { "code": null, "e": 4646, "s": 4290, "text": "'\\nI think the best way to learn data science is to do data science.\\n\\nI’ve been doing data science for a few years now, and I’ve learned a lot from doing it. I’ve learned a lot from reading books and blogs, but I’ve learned the most from doing it.\\n\\nI’ve learned a lot from doing data science, and I’ve learned a lot from reading books and blogs.\\n\\nI'" }, { "code": null, "e": 5043, "s": 4646, "text": "In the above example, as you see the model can come up with a really good response for the question asked with no tweaking or tuning. Since here we are not providing any training examples the model output need not always be a response it could come up with a similar set of questions or with content related to the input passed. The performance can be improved by supplying some training examples" }, { "code": null, "e": 5214, "s": 5043, "text": "In the below example we are going to see the implementation of text to equation conversion with very minimal training which is not possible with other pre-trained models." }, { "code": null, "e": 5634, "s": 5214, "text": "In the below example the temperature value has been increased to bring some randomness to the response and we are also passing some predefined examples to the model as a training dataset. With just 5 examples we could train the model to convert the text to an equation. After training the model with the known examples we pass the following as input “x squared plus 2 times ” and the model converts it into an equation." }, { "code": null, "e": 6214, "s": 5634, "text": "# Application 2 - LaTex Use-case - Text to Equation\ngpt2 = GPT(engine=\"davinci\", temperature=0.5, max_tokens=100)\n# Examples to train as LaTex Application\ngpt2.add_example(Example('Two plus two equals four', '2 + 2 = 4'))\ngpt2.add_example(Example('The integral from zero to infinity', '\\\\int_0^{\\\\infty}'))\ngpt2.add_example(Example('The gradient of x squared plus two times x with respect to x', '\\\\nabla_x x^2 + 2x'))\ngpt2.add_example(Example('The log of two times x', '\\\\log{2x}'))\ngpt2.add_example(Example('x squared plus y squared plus equals z squared', 'x^2 + y^2 = z^2'))\n" }, { "code": null, "e": 6351, "s": 6214, "text": "# Input to the model\nprompt2 = \"x squared plus 2 times x\"\noutput2 = gpt2.submit_request(prompt2)\n# Model Output\noutput2.choices[0].text\n" }, { "code": null, "e": 6374, "s": 6351, "text": "'output: x^2 + 2x\\n\\n'" }, { "code": null, "e": 6610, "s": 6377, "text": "Like above use-case with a few examples, we could train the model to behave like a translator. Below is the code for the translator module where we train the model to translate the text in English to French with just three examples." }, { "code": null, "e": 6970, "s": 6610, "text": "# Application 3 - Translator Use-case\ngpt3 = GPT(engine=\"davinci\", temperature=0.5, max_tokens=100)\n# Examples to train as a English to French translator\ngpt3.add_example(Example('What is your name?', 'quel est votre nom?'))\ngpt3.add_example(Example('What are you doing?', 'Que faites-vous?'))\ngpt3.add_example(Example('How are you?', 'Comment allez-vous?'))\n" }, { "code": null, "e": 7097, "s": 6970, "text": "# Input to the model\nprompt3 = \"where are you?\"\noutput3 = gpt3.submit_request(prompt3)\n# Model output\noutput3.choices[0].text\n" }, { "code": null, "e": 7127, "s": 7097, "text": "'output: Où êtes-vous?\\n\\n'" }, { "code": null, "e": 7310, "s": 7130, "text": "This ability of the model to perform a specific task like “foreign language translator” or “text to equation converter” with very minimal development effort makes it very special." }, { "code": null, "e": 7399, "s": 7310, "text": "Below is a tutorial video where I provide a walk-through of the use-case implementation." }, { "code": null, "e": 7483, "s": 7399, "text": "To learn more about interesting applications built using GPT3 check this page here." } ]
BigQuery: 3 simple ways to Audit and Monitor your Database. | by David Martins | Towards Data Science
Google BigQuery is a managed, highly scalable, serverless data warehouse, capable of querying terabytes of data in seconds. It‘s a great tool, easily accessible for Data Analysts & Scientists. Because GCP made it fully managed, you don’t have to overthink about database administration. For years, I’ve been working with old-fashioned enterprise-grade databases (Oracle, SAP / Sybase,..). We needed Database administrators in the team, to manage the database “health”. But when it comes to a fully managed BigQuery database, used primarily by Data Analysts and Data Scientists, it’s a classic pitfall to have nobody taking over that role. So, here are 5 simple ways to start monitoring your BigQuery DB right away! Metadata are data that provides information about other data. — Wikipedia When it comes to relational databases, metadata provides information about the database themselves: schema, tables, columns, or any other information about database elements and usage. GCP and BigQuery provide a few convenient ways to monitor your database through metadata. I won't go much into detail regarding BigQuery’s Metadata, since you can refer to this great article by Skye Tran. But let’s have an overview. INFORMATION_SCHEMA is a series of views that provide information about tables, views, datasets, and more. You can accessINFORMATION_SCHEMA.TABLES, INFORMATION_SCHEMA.VIEWS, INFORMATION_SCHEMA.COLUMNS , and a few others. Example: Get insights about the tables in a schema -- Returns metadata for tables in a single dataset.SELECT * FROM `bigquery-public-data.census_bureau_international`.INFORMATION_SCHEMA.TABLES; Example: Show your datasets sorted by creation date SELECT * FROM myProject.INFORMATION_SCHEMA.SCHEMATAORDER BY creation_time; B. __TABLES__ Each dataset has its own hidden metadata table, named __TABLES__.That one is very useful! That’s a convenient way to get info like “When were your tables last updated?” or “What’s the size of your tables?”. Example: When were your dataset’s tables last updated? SELECT table_id, # creation_time and last_modified_time to a timestamp TIMESTAMP_MILLIS(creation_time) AS creation_time, TIMESTAMP_MILLIS(last_modified_time) AS last_modified_time, row_count,# convert size in MB ROUND(size_bytes/(1024*1024),2) as size_mb,# Convert type from numerical to description CASE WHEN type = 1 THEN 'table' WHEN type = 2 THEN 'view' ELSE NULL END AS type FROM `bigquery-public-data.census_bureau_international`.__TABLES__ ORDER BY last_modified_time ASC Now, you want to have more control over what happens in your database: When were your tables last accessed? How much does a user “cost”? What tables are the most heavily used? Even if the information is not available through BigQuery’s Metadata, you can answer those questions by exporting Cloud Logging to BigQuery. Step1: Create a new BigQuery dataset to store the logs Since you want to receive your logs in BigQuery and analyze them with SQL, it’s better to organize your database by creating a new dataset. Choose a convenient name, such as logs or monitoring. Step 2: Create a Cloud Logging Sink Sinks allow you to route your logs or filtered subsets of your logs, to a selected destination. You can create it using the gcloud CLI or Google Cloud’s UI. Let’s use the second method.NB: A sink doesn’t get backfilled with events from before it was created. Go to Google Cloud Logging, and select Logs Router. Click on Create Sink. Give it a name. Chose BigQuery dataset as a destination and use your newly created dataset.I recommend checking the “Use partitioned tables” option: I might improve performances and will make your dataset more readable. Finally, you might want to use a filter to include only relevant logs.To export all records for the core BigQuery operations, use the filter:protoPayload.metadata."@type"="type.googleapis.com/google.cloud.audit.BigQueryAuditMetadata" Step3: Query your logs from BigQuery You will soon have your logs flowing to your dataset, into 3 tables: cloudaudit_googleapis_com_data_access cloudaudit_googleapis_com_activity cloudaudit_googleapis_com_system_event cloudaudit_googleapis_com_data_access is by far the most useful table to monitor your database. Let’s dive into it! Analyzing access might be of great help. Now that we have the “access history” logs available in cloudaudit_googleapis_com_data_access , let’s run some queries! Example: When were your tables last accessed? SELECT# Dataset nameREGEXP_EXTRACT(protopayload_auditlog.resourceName, '^projects/[^/]+/datasets/([^/]+)/tables') AS dataset,# Table nameSPLIT(REGEXP_EXTRACT(protopayload_auditlog.resourceName, '^projects/[^/]+/datasets/[^/]+/tables/(.*)$'), '$')[OFFSET(0)] AS table,# Last access dateMAX(timestamp) as last_accessed_at,# Was it a Read or Write operation ?CASE WHEN JSON_EXTRACT(protopayload_auditlog.metadataJson, "$.tableDataRead") IS NOT NULL THEN 'Read' WHEN JSON_EXTRACT(protopayload_auditlog.metadataJson, "$.tableDataChange") IS NOT NULL THEN 'Change'END method,# Optionally: display the user who executed the operation#protopayload_auditlog.authenticationInfo.principalEmailFROM logs.cloudaudit_googleapis_com_data_accessWHERE JSON_EXTRACT(protopayload_auditlog.metadataJson, "$.tableDataRead") IS NOT NULL OR JSON_EXTRACT(protopayload_auditlog.metadataJson, "$.tableDataChange") IS NOT NULLGROUP BY dataset, table, method# Optionally: Select a specific dataset#HAVING dataset = 'public'ORDER BY last_accessed_at desc Example: How much does your database cost per day/hour/month?This convenient request comes straight from the documentation. SELECT# Adapt the period of time according to your needsTIMESTAMP_TRUNC(TIMESTAMP(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, "$.jobChange.job.jobStats.endTime")), DAY) AS period,FORMAT('%9.2f',5.0 * (SUM(CAST(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, "$.jobChange.job.jobStats.queryStats.totalBilledBytes") AS INT64))/POWER(2, 40))) AS Estimated_USD_CostFROM logs.cloudaudit_googleapis_com_data_accessWHEREJSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, "$.jobChange.job.jobConfig.type") = "QUERY"GROUP BY periodORDER BY period DESC Example: How much does your database cost per user per month?Similar to the previous request, let’s break down the cost per user per month! SELECT# Adapt the period of time according to your needsTIMESTAMP_TRUNC(TIMESTAMP(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, "$.jobChange.job.jobStats.endTime")), MONTH) AS period,# Userprotopayload_auditlog.authenticationInfo.principalEmail as principal,FORMAT('%9.2f',5.0 * (SUM(CAST(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, "$.jobChange.job.jobStats.queryStats.totalBilledBytes") AS INT64))/POWER(2, 40))) AS Estimated_USD_CostFROM logs.cloudaudit_googleapis_com_data_accessWHEREJSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, "$.jobChange.job.jobConfig.type") = "QUERY"GROUP BY period, principalORDER BY period, principal DESC You can find more examples of requests in the documentation. Feel free to create your own! Since cloudaudit_googleapis_com_data_access can get confusing, BigQuery provides a helper view over this table through the BigQuery utils project. If you followed along with this article, you won’t need to recreate a log sink. Simply jump to steps 3 and 4 of the Prerequisites, execute the .sql script, and you’re all set! Through INFORMATION_SCHEMA, __TABLES__, and Cloud Logging in BigQuery, you now have 3 easy ways to audit and monitor your database. Because you don’t want to rewrite all those queries every time you want to check on your database health, it’s a good practice to create views based on your most-used analysis. You can also create alerts based on certain thresholds, but that’s a story for another day!
[ { "code": null, "e": 459, "s": 172, "text": "Google BigQuery is a managed, highly scalable, serverless data warehouse, capable of querying terabytes of data in seconds. It‘s a great tool, easily accessible for Data Analysts & Scientists. Because GCP made it fully managed, you don’t have to overthink about database administration." }, { "code": null, "e": 641, "s": 459, "text": "For years, I’ve been working with old-fashioned enterprise-grade databases (Oracle, SAP / Sybase,..). We needed Database administrators in the team, to manage the database “health”." }, { "code": null, "e": 811, "s": 641, "text": "But when it comes to a fully managed BigQuery database, used primarily by Data Analysts and Data Scientists, it’s a classic pitfall to have nobody taking over that role." }, { "code": null, "e": 887, "s": 811, "text": "So, here are 5 simple ways to start monitoring your BigQuery DB right away!" }, { "code": null, "e": 962, "s": 887, "text": "Metadata are data that provides information about other data. — Wikipedia" }, { "code": null, "e": 1147, "s": 962, "text": "When it comes to relational databases, metadata provides information about the database themselves: schema, tables, columns, or any other information about database elements and usage." }, { "code": null, "e": 1237, "s": 1147, "text": "GCP and BigQuery provide a few convenient ways to monitor your database through metadata." }, { "code": null, "e": 1380, "s": 1237, "text": "I won't go much into detail regarding BigQuery’s Metadata, since you can refer to this great article by Skye Tran. But let’s have an overview." }, { "code": null, "e": 1600, "s": 1380, "text": "INFORMATION_SCHEMA is a series of views that provide information about tables, views, datasets, and more. You can accessINFORMATION_SCHEMA.TABLES, INFORMATION_SCHEMA.VIEWS, INFORMATION_SCHEMA.COLUMNS , and a few others." }, { "code": null, "e": 1651, "s": 1600, "text": "Example: Get insights about the tables in a schema" }, { "code": null, "e": 1794, "s": 1651, "text": "-- Returns metadata for tables in a single dataset.SELECT * FROM `bigquery-public-data.census_bureau_international`.INFORMATION_SCHEMA.TABLES;" }, { "code": null, "e": 1846, "s": 1794, "text": "Example: Show your datasets sorted by creation date" }, { "code": null, "e": 1921, "s": 1846, "text": "SELECT * FROM myProject.INFORMATION_SCHEMA.SCHEMATAORDER BY creation_time;" }, { "code": null, "e": 1935, "s": 1921, "text": "B. __TABLES__" }, { "code": null, "e": 2142, "s": 1935, "text": "Each dataset has its own hidden metadata table, named __TABLES__.That one is very useful! That’s a convenient way to get info like “When were your tables last updated?” or “What’s the size of your tables?”." }, { "code": null, "e": 2197, "s": 2142, "text": "Example: When were your dataset’s tables last updated?" }, { "code": null, "e": 2697, "s": 2197, "text": "SELECT table_id, # creation_time and last_modified_time to a timestamp TIMESTAMP_MILLIS(creation_time) AS creation_time, TIMESTAMP_MILLIS(last_modified_time) AS last_modified_time, row_count,# convert size in MB ROUND(size_bytes/(1024*1024),2) as size_mb,# Convert type from numerical to description CASE WHEN type = 1 THEN 'table' WHEN type = 2 THEN 'view' ELSE NULL END AS type FROM `bigquery-public-data.census_bureau_international`.__TABLES__ ORDER BY last_modified_time ASC" }, { "code": null, "e": 2873, "s": 2697, "text": "Now, you want to have more control over what happens in your database: When were your tables last accessed? How much does a user “cost”? What tables are the most heavily used?" }, { "code": null, "e": 3014, "s": 2873, "text": "Even if the information is not available through BigQuery’s Metadata, you can answer those questions by exporting Cloud Logging to BigQuery." }, { "code": null, "e": 3069, "s": 3014, "text": "Step1: Create a new BigQuery dataset to store the logs" }, { "code": null, "e": 3263, "s": 3069, "text": "Since you want to receive your logs in BigQuery and analyze them with SQL, it’s better to organize your database by creating a new dataset. Choose a convenient name, such as logs or monitoring." }, { "code": null, "e": 3299, "s": 3263, "text": "Step 2: Create a Cloud Logging Sink" }, { "code": null, "e": 3558, "s": 3299, "text": "Sinks allow you to route your logs or filtered subsets of your logs, to a selected destination. You can create it using the gcloud CLI or Google Cloud’s UI. Let’s use the second method.NB: A sink doesn’t get backfilled with events from before it was created." }, { "code": null, "e": 3610, "s": 3558, "text": "Go to Google Cloud Logging, and select Logs Router." }, { "code": null, "e": 3648, "s": 3610, "text": "Click on Create Sink. Give it a name." }, { "code": null, "e": 3852, "s": 3648, "text": "Chose BigQuery dataset as a destination and use your newly created dataset.I recommend checking the “Use partitioned tables” option: I might improve performances and will make your dataset more readable." }, { "code": null, "e": 4086, "s": 3852, "text": "Finally, you might want to use a filter to include only relevant logs.To export all records for the core BigQuery operations, use the filter:protoPayload.metadata.\"@type\"=\"type.googleapis.com/google.cloud.audit.BigQueryAuditMetadata\"" }, { "code": null, "e": 4123, "s": 4086, "text": "Step3: Query your logs from BigQuery" }, { "code": null, "e": 4192, "s": 4123, "text": "You will soon have your logs flowing to your dataset, into 3 tables:" }, { "code": null, "e": 4230, "s": 4192, "text": "cloudaudit_googleapis_com_data_access" }, { "code": null, "e": 4265, "s": 4230, "text": "cloudaudit_googleapis_com_activity" }, { "code": null, "e": 4304, "s": 4265, "text": "cloudaudit_googleapis_com_system_event" }, { "code": null, "e": 4420, "s": 4304, "text": "cloudaudit_googleapis_com_data_access is by far the most useful table to monitor your database. Let’s dive into it!" }, { "code": null, "e": 4581, "s": 4420, "text": "Analyzing access might be of great help. Now that we have the “access history” logs available in cloudaudit_googleapis_com_data_access , let’s run some queries!" }, { "code": null, "e": 4627, "s": 4581, "text": "Example: When were your tables last accessed?" }, { "code": null, "e": 5661, "s": 4627, "text": "SELECT# Dataset nameREGEXP_EXTRACT(protopayload_auditlog.resourceName, '^projects/[^/]+/datasets/([^/]+)/tables') AS dataset,# Table nameSPLIT(REGEXP_EXTRACT(protopayload_auditlog.resourceName, '^projects/[^/]+/datasets/[^/]+/tables/(.*)$'), '$')[OFFSET(0)] AS table,# Last access dateMAX(timestamp) as last_accessed_at,# Was it a Read or Write operation ?CASE WHEN JSON_EXTRACT(protopayload_auditlog.metadataJson, \"$.tableDataRead\") IS NOT NULL THEN 'Read' WHEN JSON_EXTRACT(protopayload_auditlog.metadataJson, \"$.tableDataChange\") IS NOT NULL THEN 'Change'END method,# Optionally: display the user who executed the operation#protopayload_auditlog.authenticationInfo.principalEmailFROM logs.cloudaudit_googleapis_com_data_accessWHERE JSON_EXTRACT(protopayload_auditlog.metadataJson, \"$.tableDataRead\") IS NOT NULL OR JSON_EXTRACT(protopayload_auditlog.metadataJson, \"$.tableDataChange\") IS NOT NULLGROUP BY dataset, table, method# Optionally: Select a specific dataset#HAVING dataset = 'public'ORDER BY last_accessed_at desc" }, { "code": null, "e": 5785, "s": 5661, "text": "Example: How much does your database cost per day/hour/month?This convenient request comes straight from the documentation." }, { "code": null, "e": 6353, "s": 5785, "text": "SELECT# Adapt the period of time according to your needsTIMESTAMP_TRUNC(TIMESTAMP(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, \"$.jobChange.job.jobStats.endTime\")), DAY) AS period,FORMAT('%9.2f',5.0 * (SUM(CAST(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, \"$.jobChange.job.jobStats.queryStats.totalBilledBytes\") AS INT64))/POWER(2, 40))) AS Estimated_USD_CostFROM logs.cloudaudit_googleapis_com_data_accessWHEREJSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, \"$.jobChange.job.jobConfig.type\") = \"QUERY\"GROUP BY periodORDER BY period DESC" }, { "code": null, "e": 6493, "s": 6353, "text": "Example: How much does your database cost per user per month?Similar to the previous request, let’s break down the cost per user per month!" }, { "code": null, "e": 7160, "s": 6493, "text": "SELECT# Adapt the period of time according to your needsTIMESTAMP_TRUNC(TIMESTAMP(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, \"$.jobChange.job.jobStats.endTime\")), MONTH) AS period,# Userprotopayload_auditlog.authenticationInfo.principalEmail as principal,FORMAT('%9.2f',5.0 * (SUM(CAST(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, \"$.jobChange.job.jobStats.queryStats.totalBilledBytes\") AS INT64))/POWER(2, 40))) AS Estimated_USD_CostFROM logs.cloudaudit_googleapis_com_data_accessWHEREJSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, \"$.jobChange.job.jobConfig.type\") = \"QUERY\"GROUP BY period, principalORDER BY period, principal DESC" }, { "code": null, "e": 7251, "s": 7160, "text": "You can find more examples of requests in the documentation. Feel free to create your own!" }, { "code": null, "e": 7398, "s": 7251, "text": "Since cloudaudit_googleapis_com_data_access can get confusing, BigQuery provides a helper view over this table through the BigQuery utils project." }, { "code": null, "e": 7574, "s": 7398, "text": "If you followed along with this article, you won’t need to recreate a log sink. Simply jump to steps 3 and 4 of the Prerequisites, execute the .sql script, and you’re all set!" }, { "code": null, "e": 7706, "s": 7574, "text": "Through INFORMATION_SCHEMA, __TABLES__, and Cloud Logging in BigQuery, you now have 3 easy ways to audit and monitor your database." } ]
How to Create a Text File Using the Command Line in Linux - GeeksforGeeks
17 Jun, 2021 There are a couple of quick ways to create a text file from the Linux Command Line or Terminal. Some of them have been explained in the following article. This is the most standard command to quickly create an empty text file. The command is quite simple to type and makes it quite easier to create several text files at once. The commands are as follows: touch filename.txt As simple as that, just type the word touch followed by the name of the file you like to give it, and Voila! you have created an empty text file inside of a terminal. You can add the file names of the file you would like to create at once with space in between each filename. The command below creates three empty files at once using the touch command and you can create as many files as you like. touch file1.txt file2.txt file3.txt touch command touch command for creating multiple files It is also quite easy to understand the command to create a text file in the terminal with the minimum effort. This works really very well for creating a single text file quickly, but for creating several text files at once it becomes a bit tedious. The command is simply using the standard redirect symbol (>) spacebar followed by the file name. > filename.txt If you want to create several text files at once, then you can add the redirect symbol after the previous filename and chain the command repeatedly to create multiple empty files. > file.txt > file2.txt > file3.txt The above command creates three empty text files. The redirect symbol is quite time-saving if you just want to create a single text file. It gets quite longer than the touch command to create multiple empty text files. Using the redirect symbol for creating files. Now, this method is also quite simple and easy to use. Simply type in CAT with two redirect symbols (>>) and the file name( It is not mandatory to use >> symbols, a user can also use > symbol, but if the user types a pre-existing file by mistake, the existing content in the text file will be overwritten using a single > symbol). This method is a kind of combination of touch and the redirect symbol commands. This method is a bit quirky, so you only prefer using the above two commands if you want to create an empty never edited file. If you want to create and type in the text file straight away, by far this is quite a brilliant method. This will save you time to open up an editor and the command is also quite easy. The below command creates an empty yet edited file as it prompts the user to create a text file and type in the file at the same time. So, if you do not want to edit the file, simply press CTRL+C and it will simply exit and create an empty file. cat >> file.txt But, if you would like to add some text to the file, you can type in after this, like this: cat >> new.txt This is some text in the file from command line. To stop editing and saving in the file, simply type CTRL+C, it will create, save and exit the file. So, this method is quite a time-saving method if you want to edit the text file very quickly. The following command will append the text to the pre-existing file. On the other hand, if you use a single redirect symbol(>) it will overwrite the content of the file, so you only prefer using double redirect symbols for safety reasons. Using cat command to create the file. Using cat command to create and write a file. This is also similar to cat command, but it is very flexible comparatively. The following command is usually used for printing text on the terminal, but we can also use it to write to a file or make an empty file. The echo command is used along with the double redirect symbols (single > will also work) followed by the filename. echo >> filename.txt If you want to create multiple files at a time, you can chain up the command as in previous methods. echo >> file1.txt >> file2.txt >> file3.txt We can also add functionality to the echo command to quickly create and write to the text file just like cat command. echo -e ‘This will be the text in the file \n this is the new line’ >> file.txt The above command can be highly customizable as it uses the properties of the echo command to make it quite versatile to write the text in the file, but using a new line character every time can be annoying as well. using the echo command to create files. Using echo command to create and write to a file. Similar to the echo command, we have the printf command as well. The print command does the same thing as the echo command but in a C style rather than shell-style editing. printf "" >> filename.txt printf "" >> file1.txt >> file2.txt >> file3.txt printf “This is some text here \n The second line \n The third line” >> file.txt The print command does some pretty C-like things, such as the newline character and the variable names can be used as well, but that is not for a simple text file. But still, the printf command can be useful in a lot of cases to edit files on the go. Using printf command to create files. Using printf to create and write to files. This is the most time-consuming method and not the fastest, yet the method can be useful for Linux beginners. If you want to heavily edit a text file, you can use command-line text-editors such as Vim, nano, and there are other options as well. But most people use nano as it is simple to use and quick to go. Vim can also be used but most beginners find it difficult to use, so we’ll stick with nano for this example. nano filename.txt vim filename.txt We are now in the nano editor(or vim). You can type in the stuff you require and simply type CTRL+S to save and CTRL+X to exit. In Vim it is a bit different. We won’t make a vim guide here, so you can check out the ‘Nano text editor in Linux‘ or ‘Getting started with vim‘ article from geeks for geeks. Using Nano to create and write files. So that wraps up the methods for quickly creating a text file or writing to the file. Each method can be used differently depending on the situation and the case used. Not every method will be the fastest, yet these were some of the fastest ways to create a Text File Using the Command Line in Linux. Linux-file-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Thread functions in C/C++ Array Basics in Shell Scripting | Set 1 scp command in Linux with Examples chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program mv command in Linux with examples SED command in Linux | Set 2 Basic Operators in Shell Scripting Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 24428, "s": 24397, "text": " \n17 Jun, 2021\n" }, { "code": null, "e": 24583, "s": 24428, "text": "There are a couple of quick ways to create a text file from the Linux Command Line or Terminal. Some of them have been explained in the following article." }, { "code": null, "e": 24784, "s": 24583, "text": "This is the most standard command to quickly create an empty text file. The command is quite simple to type and makes it quite easier to create several text files at once. The commands are as follows:" }, { "code": null, "e": 24803, "s": 24784, "text": "touch filename.txt" }, { "code": null, "e": 25201, "s": 24803, "text": "As simple as that, just type the word touch followed by the name of the file you like to give it, and Voila! you have created an empty text file inside of a terminal. You can add the file names of the file you would like to create at once with space in between each filename. The command below creates three empty files at once using the touch command and you can create as many files as you like." }, { "code": null, "e": 25238, "s": 25201, "text": "touch file1.txt file2.txt file3.txt " }, { "code": null, "e": 25252, "s": 25238, "text": "touch command" }, { "code": null, "e": 25294, "s": 25252, "text": "touch command for creating multiple files" }, { "code": null, "e": 25642, "s": 25294, "text": "It is also quite easy to understand the command to create a text file in the terminal with the minimum effort. This works really very well for creating a single text file quickly, but for creating several text files at once it becomes a bit tedious. The command is simply using the standard redirect symbol (>) spacebar followed by the file name. " }, { "code": null, "e": 25658, "s": 25642, "text": "> filename.txt " }, { "code": null, "e": 25838, "s": 25658, "text": "If you want to create several text files at once, then you can add the redirect symbol after the previous filename and chain the command repeatedly to create multiple empty files." }, { "code": null, "e": 25873, "s": 25838, "text": "> file.txt > file2.txt > file3.txt" }, { "code": null, "e": 26092, "s": 25873, "text": "The above command creates three empty text files. The redirect symbol is quite time-saving if you just want to create a single text file. It gets quite longer than the touch command to create multiple empty text files." }, { "code": null, "e": 26138, "s": 26092, "text": "Using the redirect symbol for creating files." }, { "code": null, "e": 26863, "s": 26138, "text": "Now, this method is also quite simple and easy to use. Simply type in CAT with two redirect symbols (>>) and the file name( It is not mandatory to use >> symbols, a user can also use > symbol, but if the user types a pre-existing file by mistake, the existing content in the text file will be overwritten using a single > symbol). This method is a kind of combination of touch and the redirect symbol commands. This method is a bit quirky, so you only prefer using the above two commands if you want to create an empty never edited file. If you want to create and type in the text file straight away, by far this is quite a brilliant method. This will save you time to open up an editor and the command is also quite easy. " }, { "code": null, "e": 27109, "s": 26863, "text": "The below command creates an empty yet edited file as it prompts the user to create a text file and type in the file at the same time. So, if you do not want to edit the file, simply press CTRL+C and it will simply exit and create an empty file." }, { "code": null, "e": 27125, "s": 27109, "text": "cat >> file.txt" }, { "code": null, "e": 27217, "s": 27125, "text": "But, if you would like to add some text to the file, you can type in after this, like this:" }, { "code": null, "e": 27281, "s": 27217, "text": "cat >> new.txt\nThis is some text in the file from command line." }, { "code": null, "e": 27714, "s": 27281, "text": "To stop editing and saving in the file, simply type CTRL+C, it will create, save and exit the file. So, this method is quite a time-saving method if you want to edit the text file very quickly. The following command will append the text to the pre-existing file. On the other hand, if you use a single redirect symbol(>) it will overwrite the content of the file, so you only prefer using double redirect symbols for safety reasons." }, { "code": null, "e": 27752, "s": 27714, "text": "Using cat command to create the file." }, { "code": null, "e": 27798, "s": 27752, "text": "Using cat command to create and write a file." }, { "code": null, "e": 28129, "s": 27798, "text": "This is also similar to cat command, but it is very flexible comparatively. The following command is usually used for printing text on the terminal, but we can also use it to write to a file or make an empty file. The echo command is used along with the double redirect symbols (single > will also work) followed by the filename. " }, { "code": null, "e": 28150, "s": 28129, "text": "echo >> filename.txt" }, { "code": null, "e": 28251, "s": 28150, "text": "If you want to create multiple files at a time, you can chain up the command as in previous methods." }, { "code": null, "e": 28295, "s": 28251, "text": "echo >> file1.txt >> file2.txt >> file3.txt" }, { "code": null, "e": 28414, "s": 28295, "text": "We can also add functionality to the echo command to quickly create and write to the text file just like cat command." }, { "code": null, "e": 28495, "s": 28414, "text": "echo -e ‘This will be the text in the file \\n this is the new line’ >> file.txt " }, { "code": null, "e": 28712, "s": 28495, "text": "The above command can be highly customizable as it uses the properties of the echo command to make it quite versatile to write the text in the file, but using a new line character every time can be annoying as well. " }, { "code": null, "e": 28752, "s": 28712, "text": "using the echo command to create files." }, { "code": null, "e": 28802, "s": 28752, "text": "Using echo command to create and write to a file." }, { "code": null, "e": 28975, "s": 28802, "text": "Similar to the echo command, we have the printf command as well. The print command does the same thing as the echo command but in a C style rather than shell-style editing." }, { "code": null, "e": 29001, "s": 28975, "text": "printf \"\" >> filename.txt" }, { "code": null, "e": 29050, "s": 29001, "text": "printf \"\" >> file1.txt >> file2.txt >> file3.txt" }, { "code": null, "e": 29131, "s": 29050, "text": "printf “This is some text here \\n The second line \\n The third line” >> file.txt" }, { "code": null, "e": 29382, "s": 29131, "text": "The print command does some pretty C-like things, such as the newline character and the variable names can be used as well, but that is not for a simple text file. But still, the printf command can be useful in a lot of cases to edit files on the go." }, { "code": null, "e": 29420, "s": 29382, "text": "Using printf command to create files." }, { "code": null, "e": 29463, "s": 29420, "text": "Using printf to create and write to files." }, { "code": null, "e": 29882, "s": 29463, "text": "This is the most time-consuming method and not the fastest, yet the method can be useful for Linux beginners. If you want to heavily edit a text file, you can use command-line text-editors such as Vim, nano, and there are other options as well. But most people use nano as it is simple to use and quick to go. Vim can also be used but most beginners find it difficult to use, so we’ll stick with nano for this example." }, { "code": null, "e": 29900, "s": 29882, "text": "nano filename.txt" }, { "code": null, "e": 29917, "s": 29900, "text": "vim filename.txt" }, { "code": null, "e": 30220, "s": 29917, "text": "We are now in the nano editor(or vim). You can type in the stuff you require and simply type CTRL+S to save and CTRL+X to exit. In Vim it is a bit different. We won’t make a vim guide here, so you can check out the ‘Nano text editor in Linux‘ or ‘Getting started with vim‘ article from geeks for geeks." }, { "code": null, "e": 30258, "s": 30220, "text": "Using Nano to create and write files." }, { "code": null, "e": 30559, "s": 30258, "text": "So that wraps up the methods for quickly creating a text file or writing to the file. Each method can be used differently depending on the situation and the case used. Not every method will be the fastest, yet these were some of the fastest ways to create a Text File Using the Command Line in Linux." }, { "code": null, "e": 30581, "s": 30559, "text": "\nLinux-file-commands\n" }, { "code": null, "e": 30590, "s": 30581, "text": "\nPicked\n" }, { "code": null, "e": 30603, "s": 30590, "text": "\nLinux-Unix\n" }, { "code": null, "e": 30808, "s": 30603, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 30834, "s": 30808, "text": "Thread functions in C/C++" }, { "code": null, "e": 30874, "s": 30834, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 30909, "s": 30874, "text": "scp command in Linux with Examples" }, { "code": null, "e": 30946, "s": 30909, "text": "chown command in Linux with Examples" }, { "code": null, "e": 30983, "s": 30946, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 31025, "s": 30983, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 31059, "s": 31025, "text": "mv command in Linux with examples" }, { "code": null, "e": 31088, "s": 31059, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 31123, "s": 31088, "text": "Basic Operators in Shell Scripting" } ]
How to convert Unix timestamp to time in JavaScript? - GeeksforGeeks
18 Jul, 2019 UNIX timestamps can be converted to time using 2 approaches: Method 1: Using the toUTCString() method:As JavaScript works in milliseconds, it is necessary to convert the time into milliseconds by multiplying it by 1000 before converting it. This value is then given to the Date() function to create a new Date object. The toUTCString() method is used to represent the Date object as a string the UTC time format. The time from this date string can be found by extracting from the 11th to last to the 4th to the last character of the string. This is extracted using the slice() function. This string is the time representation of the UNIX timestamp. Syntax: dateObj = new Date(unixTimestamp * 1000);utcString = dateObj.toUTCString();time = utcString.slice(-11, -4); Example: <!DOCTYPE html><html> <head> <title> How to convert Unix timestamp to time in JavaScript? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to convert Unix timestamp to time in JavaScript? </b> <p> UNIX Timestamp is: 10637282 </p> <p>Time is: <span class="output"> </span> </p> <button onclick="convertTimestamptoTime()"> Get time from timestamp </button> <script type="text/javascript"> function convertTimestamptoTime() { unixTimestamp = 10637282; // convert to milliseconds and // then create a new Date object dateObj = new Date(unixTimestamp * 1000); utcString = dateObj.toUTCString(); time = utcString.slice(-11, -4); document.querySelector( '.output').textContent = time; } </script></body> </html> Output: Before clicking the button: After clicking the button: Method 2: Getting individual hours, minutes and secondsAs JavaScript works in milliseconds, it is necessary to convert the time into milliseconds by multiplying it by 1000 before converting it. This value is then given to the Date() function to create a new Date object. Each part of the time is extracted from the Date object. The hour’s value in UTC is extracted from the date using the getUTCHours() method. The minute’s value in UTC is extracted from the date using the getUTCMinutes() method. The second’s value in UTC is extracted from the date using the getUTCSeconds() method. The final formatted date is created by converting each of these values to a string using the toString() method and then padding them with an extra ‘0’, if the value is a single-digit by using the padStart() method. The individual parts are then joined together with a colon(:) as the separator. This string is the time representation of the UNIX timestamp. Syntax: dateObj = new Date(unixTimestamp * 1000); // Get hours from the timestamphours = dateObj.getUTCHours(); // Get minutes part from the timestampminutes = dateObj.getUTCMinutes(); // Get seconds part from the timestampseconds = dateObj.getUTCSeconds(); formattedTime = hours.toString().padStart(2, '0') + ':' + minutes.toString().padStart(2, '0') + ':' + seconds.toString().padStart(2, '0'); Example: <!DOCTYPE html><html> <head> <title> How to convert Unix timestamp to time in JavaScript? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to convert Unix timestamp to time in JavaScript? </b> <p>UNIX Timestamp is: 10637282</p> <p>Time is: <span class="output"> </span> </p> <button onclick="convertTimestamptoTime()"> Get time from timestamp </button> <script type="text/javascript"> function convertTimestamptoTime() { unixTimestamp = 10637282; // convert to milliseconds // and then create a new Date object dateObj = new Date(unixTimestamp * 1000); // Get hours from the timestamp hours = dateObj.getUTCHours(); // Get minutes part from the timestamp minutes = dateObj.getUTCMinutes(); // Get seconds part from the timestamp seconds = dateObj.getUTCSeconds(); formattedTime = hours.toString().padStart(2, '0') + ':' + minutes.toString().padStart(2, '0') + ':' + seconds.toString().padStart(2, '0'); document.querySelector('.output').textContent = formattedTime; } </script></body> </html> Output: Before clicking the button: After clicking the button: JavaScript-Misc Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React Difference between var, let and const keywords in JavaScript How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24720, "s": 24692, "text": "\n18 Jul, 2019" }, { "code": null, "e": 24781, "s": 24720, "text": "UNIX timestamps can be converted to time using 2 approaches:" }, { "code": null, "e": 25038, "s": 24781, "text": "Method 1: Using the toUTCString() method:As JavaScript works in milliseconds, it is necessary to convert the time into milliseconds by multiplying it by 1000 before converting it. This value is then given to the Date() function to create a new Date object." }, { "code": null, "e": 25369, "s": 25038, "text": "The toUTCString() method is used to represent the Date object as a string the UTC time format. The time from this date string can be found by extracting from the 11th to last to the 4th to the last character of the string. This is extracted using the slice() function. This string is the time representation of the UNIX timestamp." }, { "code": null, "e": 25377, "s": 25369, "text": "Syntax:" }, { "code": "dateObj = new Date(unixTimestamp * 1000);utcString = dateObj.toUTCString();time = utcString.slice(-11, -4);", "e": 25485, "s": 25377, "text": null }, { "code": null, "e": 25494, "s": 25485, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to convert Unix timestamp to time in JavaScript? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to convert Unix timestamp to time in JavaScript? </b> <p> UNIX Timestamp is: 10637282 </p> <p>Time is: <span class=\"output\"> </span> </p> <button onclick=\"convertTimestamptoTime()\"> Get time from timestamp </button> <script type=\"text/javascript\"> function convertTimestamptoTime() { unixTimestamp = 10637282; // convert to milliseconds and // then create a new Date object dateObj = new Date(unixTimestamp * 1000); utcString = dateObj.toUTCString(); time = utcString.slice(-11, -4); document.querySelector( '.output').textContent = time; } </script></body> </html>", "e": 26414, "s": 25494, "text": null }, { "code": null, "e": 26422, "s": 26414, "text": "Output:" }, { "code": null, "e": 26450, "s": 26422, "text": "Before clicking the button:" }, { "code": null, "e": 26477, "s": 26450, "text": "After clicking the button:" }, { "code": null, "e": 26748, "s": 26477, "text": "Method 2: Getting individual hours, minutes and secondsAs JavaScript works in milliseconds, it is necessary to convert the time into milliseconds by multiplying it by 1000 before converting it. This value is then given to the Date() function to create a new Date object." }, { "code": null, "e": 27062, "s": 26748, "text": "Each part of the time is extracted from the Date object. The hour’s value in UTC is extracted from the date using the getUTCHours() method. The minute’s value in UTC is extracted from the date using the getUTCMinutes() method. The second’s value in UTC is extracted from the date using the getUTCSeconds() method." }, { "code": null, "e": 27419, "s": 27062, "text": "The final formatted date is created by converting each of these values to a string using the toString() method and then padding them with an extra ‘0’, if the value is a single-digit by using the padStart() method. The individual parts are then joined together with a colon(:) as the separator. This string is the time representation of the UNIX timestamp." }, { "code": null, "e": 27427, "s": 27419, "text": "Syntax:" }, { "code": "dateObj = new Date(unixTimestamp * 1000); // Get hours from the timestamphours = dateObj.getUTCHours(); // Get minutes part from the timestampminutes = dateObj.getUTCMinutes(); // Get seconds part from the timestampseconds = dateObj.getUTCSeconds(); formattedTime = hours.toString().padStart(2, '0') + ':' + minutes.toString().padStart(2, '0') + ':' + seconds.toString().padStart(2, '0');", "e": 27848, "s": 27427, "text": null }, { "code": null, "e": 27857, "s": 27848, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to convert Unix timestamp to time in JavaScript? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to convert Unix timestamp to time in JavaScript? </b> <p>UNIX Timestamp is: 10637282</p> <p>Time is: <span class=\"output\"> </span> </p> <button onclick=\"convertTimestamptoTime()\"> Get time from timestamp </button> <script type=\"text/javascript\"> function convertTimestamptoTime() { unixTimestamp = 10637282; // convert to milliseconds // and then create a new Date object dateObj = new Date(unixTimestamp * 1000); // Get hours from the timestamp hours = dateObj.getUTCHours(); // Get minutes part from the timestamp minutes = dateObj.getUTCMinutes(); // Get seconds part from the timestamp seconds = dateObj.getUTCSeconds(); formattedTime = hours.toString().padStart(2, '0') + ':' + minutes.toString().padStart(2, '0') + ':' + seconds.toString().padStart(2, '0'); document.querySelector('.output').textContent = formattedTime; } </script></body> </html>", "e": 29136, "s": 27857, "text": null }, { "code": null, "e": 29144, "s": 29136, "text": "Output:" }, { "code": null, "e": 29172, "s": 29144, "text": "Before clicking the button:" }, { "code": null, "e": 29199, "s": 29172, "text": "After clicking the button:" }, { "code": null, "e": 29215, "s": 29199, "text": "JavaScript-Misc" }, { "code": null, "e": 29222, "s": 29215, "text": "Picked" }, { "code": null, "e": 29233, "s": 29222, "text": "JavaScript" }, { "code": null, "e": 29250, "s": 29233, "text": "Web Technologies" }, { "code": null, "e": 29348, "s": 29250, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29357, "s": 29348, "text": "Comments" }, { "code": null, "e": 29370, "s": 29357, "text": "Old Comments" }, { "code": null, "e": 29415, "s": 29370, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29487, "s": 29415, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29548, "s": 29487, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29600, "s": 29548, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 29646, "s": 29600, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 29688, "s": 29646, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 29721, "s": 29688, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29783, "s": 29721, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29826, "s": 29783, "text": "How to fetch data from an API in ReactJS ?" } ]
Console Class in C#
14 Mar, 2019 A console is an operating system window through which a user can communicate with the operating system or we can say a console is an application in which we can give text as an input from the keyboard and get the text as an output from the computer end. The command prompt is an example of a console in the windows and which accept MS-DOS commands. The console contains two attributes named as screen buffer and a console window.In C#, the Console class is used to represent the standard input, output, and error streams for the console applications. You are not allowed to inherit Console class. This class is defined under System namespace. This class does not contain any constructor. Instead of the constructor, this class provides different types of properties and methods to perform operations. Example: // C# program to illustrate how to get// Background and Foreground color// of the consoleusing System; public class GFG { static public void Main() { // Get the Background and foreground // color of Console Using BackgroundColor // and ForegroundColor property of Console Console.WriteLine("Background color :{0}", Console.BackgroundColor); Console.WriteLine("Foreground color : {0}", Console.ForegroundColor); }} Background color : Black Foreground color : Black Example: // C# program to illustrate the concept// of WriteLine(String) method in consoleusing System; public class GFG { static public void Main() { // WriteLine(String) method is used // to display the string Console.WriteLine("Welcome to GeeksforGeeks"); Console.WriteLine("This is a tutorial of Console Class"); }} Welcome to GeeksforGeeks This is a tutorial of Console Class Reference: https://docs.microsoft.com/en-us/dotnet/api/system.console?view=netframework-4.7.2#definition CSharp-Console-Class C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Mar, 2019" }, { "code": null, "e": 829, "s": 28, "text": "A console is an operating system window through which a user can communicate with the operating system or we can say a console is an application in which we can give text as an input from the keyboard and get the text as an output from the computer end. The command prompt is an example of a console in the windows and which accept MS-DOS commands. The console contains two attributes named as screen buffer and a console window.In C#, the Console class is used to represent the standard input, output, and error streams for the console applications. You are not allowed to inherit Console class. This class is defined under System namespace. This class does not contain any constructor. Instead of the constructor, this class provides different types of properties and methods to perform operations." }, { "code": null, "e": 838, "s": 829, "text": "Example:" }, { "code": "// C# program to illustrate how to get// Background and Foreground color// of the consoleusing System; public class GFG { static public void Main() { // Get the Background and foreground // color of Console Using BackgroundColor // and ForegroundColor property of Console Console.WriteLine(\"Background color :{0}\", Console.BackgroundColor); Console.WriteLine(\"Foreground color : {0}\", Console.ForegroundColor); }}", "e": 1352, "s": 838, "text": null }, { "code": null, "e": 1403, "s": 1352, "text": "Background color : Black\nForeground color : Black\n" }, { "code": null, "e": 1412, "s": 1403, "text": "Example:" }, { "code": "// C# program to illustrate the concept// of WriteLine(String) method in consoleusing System; public class GFG { static public void Main() { // WriteLine(String) method is used // to display the string Console.WriteLine(\"Welcome to GeeksforGeeks\"); Console.WriteLine(\"This is a tutorial of Console Class\"); }}", "e": 1765, "s": 1412, "text": null }, { "code": null, "e": 1827, "s": 1765, "text": "Welcome to GeeksforGeeks\nThis is a tutorial of Console Class\n" }, { "code": null, "e": 1838, "s": 1827, "text": "Reference:" }, { "code": null, "e": 1932, "s": 1838, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.console?view=netframework-4.7.2#definition" }, { "code": null, "e": 1953, "s": 1932, "text": "CSharp-Console-Class" }, { "code": null, "e": 1956, "s": 1953, "text": "C#" } ]
Flutter – Concept of Key in Widgets
28 Jul, 2021 In this article, we will study Keys and when and where to use them. So you may ask what are keys? Well, Keys are the ones to preserve state when widgets move around the widget tree. It is used to preserve the user scroll location or keeping state when modifying a collection. Key’s aren’t needed if the entire widget subtree is stateless. Now let us study when to use the keys. As we know that we use keys to preserve states when widgets move around the widget subtree. So, basically, keys are not needed in a stateless widget but would be needed in a Stateful widget. To explain the keys we will create a basic application in which on tapping the button the boxes will swap the colors. The values of the colors would be stored using the keys. The following code is of the application created without the use of keys. Here in this code, we have created the application using the stateless widget. A class PositionedTiles is created here. The comment you are seeing in this code is for the unique color generate to generate the colors for the boxes randomly. On tapping the button the swapTiles function gets activated then the swapping takes place. The onTap button is the smiley face at the bottom. Dart import 'package:flutter/material.dart';import 'dart:math'; void main() => runApp(new MaterialApp(home: PositionedTiles())); class PositionedTiles extends StatefulWidget{ @override State<StatefulWidget> createState() => PositionedTilesState();} class PositionedTilesState extends State<PositionedTiles>{ late List<Widget> tiles; @override void initState(){ super.initState(); tiles = [ StatelessColorfulTile(), StatelessColorfulTile(), ]; } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("GEEKSFORGEEKS"), backgroundColor: Colors.green, ) , body: SafeArea(child: Row(children: tiles)), floatingActionButton: FloatingActionButton( child: Icon(Icons.sentiment_very_satisfied), onPressed: swapTiles), ); } swapTiles(){ setState(() { tiles.insert(1, tiles.removeAt(0)); }); }} class StatelessColorfulTile extends StatelessWidget { Color myColor = UniqueColorGenerator.getColor(); @override Widget build(BuildContext context) { return Container( color: myColor, child: Padding(padding: EdgeInsets.all(70.0))); }} //this code snippet tells you how UniqueColorGenerator worksclass UniqueColorGenerator { static List colorOptions = [ Colors.blue, Colors.red, Colors.green, Colors.yellow, Colors.purple, Colors.orange, Colors.indigo, Colors.amber, Colors.black, ]; static Random random = new Random(); static Color getColor() { if (colorOptions.length > 0) { return colorOptions.removeAt(random.nextInt(colorOptions.length)); } else { return Color.fromARGB(random.nextInt(256), random.nextInt(256), random.nextInt(256), random.nextInt(256)); } }} Output: Stateless Widget Tree Here you can see that the colors are changing but when we would change it to the Stateful widget the code will work correctly but nothing will be shown on the application. But as we use the keys here in the Stateful widget the application will work fine. The following code shown below is direct with the keys. Here in this code, you can see we have used the keys feature here, because of which the application is working fine. The rest of the code is the same, only the Key feature is newly added here. Dart import 'package:flutter/material.dart';import 'dart:math'; void main() => runApp(new MaterialApp(home: PositionedTiles())); class PositionedTiles extends StatefulWidget{ @override State<StatefulWidget> createState() => PositionedTilesState();} class PositionedTilesState extends State<PositionedTiles>{ late List<Widget> tiles; @override void initState(){ super.initState(); tiles = [ StatefulColorfulTile(key: UniqueKey()), StatefulColorfulTile(key: UniqueKey()), ]; } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("GEEKSFORGEEKS"), backgroundColor: Colors.green, ) , body: SafeArea(child: Row(children: tiles)), floatingActionButton: FloatingActionButton( child: Icon(Icons.sentiment_very_satisfied), onPressed: swapTiles), ); } swapTiles(){ setState(() { tiles.insert(1, tiles.removeAt(0)); }); }} class StatefulColorfulTile extends StatefulWidget { StatefulColorfulTile({required Key key}) : super(key: key); @override State<StatefulWidget> createState() => StatefulColorfulTileState();}class StatefulColorfulTileState extends State<StatefulColorfulTile> { late Color myColor; @override void initState() { super.initState(); myColor = UniqueColorGenerator.getColor(); } @override Widget build(BuildContext context) { return Container( color: myColor, child: Padding( padding: EdgeInsets.all(70.0), )); }} class UniqueColorGenerator { static List colorOptions = [ Colors.blue, Colors.red, Colors.green, Colors.yellow, Colors.purple, Colors.orange, Colors.indigo, Colors.amber, Colors.black, ]; static Random random = new Random(); static Color getColor() { if (colorOptions.length > 0) { return colorOptions.removeAt(random.nextInt(colorOptions.length)); } else { return Color.fromARGB(random.nextInt(256), random.nextInt(256), random.nextInt(256), random.nextInt(256)); } }} Output: Stateful Widget Tree Now it is clear from the above example where to add them. The answer is simple, if you have to use the Stateful widget then you have to use the Keys else no need to use them. Now there are many types of Keys in flutter. All of them have been discussed below: Value Key: The value key is used when it has to be assigned to something constant and extraordinary. For example, in the To-Do List the text entered is the value. Object Key: The Object key is used when any single field such as name or birthday, they maybe the same of more than two people but would be unique for each person or each data combination. Unique Key: The unique key is used when there are many widgets with the same incentive then we must use define each widget as a unique widget. We used it in our code also because we didn’t know what random color would be assigned to it until the widgets were assembled. Global key: The use of Global key is that it contains the data which can be accessed by other widgets present in the code. In case you don’t want to share it with other widgets then you must use the Global Key<From State> that holds a form of state and won’t allow other widgets to access the data stored in it. So, in conclusion, we can say that keys are a very good feature in flutter. It only works with the Stateful widget and the purpose to use it to store the value of the current state when modifying the collection. Flutter-widgets Picked Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jul, 2021" }, { "code": null, "e": 407, "s": 28, "text": "In this article, we will study Keys and when and where to use them. So you may ask what are keys? Well, Keys are the ones to preserve state when widgets move around the widget tree. It is used to preserve the user scroll location or keeping state when modifying a collection. Key’s aren’t needed if the entire widget subtree is stateless. Now let us study when to use the keys." }, { "code": null, "e": 598, "s": 407, "text": "As we know that we use keys to preserve states when widgets move around the widget subtree. So, basically, keys are not needed in a stateless widget but would be needed in a Stateful widget." }, { "code": null, "e": 848, "s": 598, "text": "To explain the keys we will create a basic application in which on tapping the button the boxes will swap the colors. The values of the colors would be stored using the keys. The following code is of the application created without the use of keys." }, { "code": null, "e": 1230, "s": 848, "text": "Here in this code, we have created the application using the stateless widget. A class PositionedTiles is created here. The comment you are seeing in this code is for the unique color generate to generate the colors for the boxes randomly. On tapping the button the swapTiles function gets activated then the swapping takes place. The onTap button is the smiley face at the bottom." }, { "code": null, "e": 1235, "s": 1230, "text": "Dart" }, { "code": "import 'package:flutter/material.dart';import 'dart:math'; void main() => runApp(new MaterialApp(home: PositionedTiles())); class PositionedTiles extends StatefulWidget{ @override State<StatefulWidget> createState() => PositionedTilesState();} class PositionedTilesState extends State<PositionedTiles>{ late List<Widget> tiles; @override void initState(){ super.initState(); tiles = [ StatelessColorfulTile(), StatelessColorfulTile(), ]; } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(\"GEEKSFORGEEKS\"), backgroundColor: Colors.green, ) , body: SafeArea(child: Row(children: tiles)), floatingActionButton: FloatingActionButton( child: Icon(Icons.sentiment_very_satisfied), onPressed: swapTiles), ); } swapTiles(){ setState(() { tiles.insert(1, tiles.removeAt(0)); }); }} class StatelessColorfulTile extends StatelessWidget { Color myColor = UniqueColorGenerator.getColor(); @override Widget build(BuildContext context) { return Container( color: myColor, child: Padding(padding: EdgeInsets.all(70.0))); }} //this code snippet tells you how UniqueColorGenerator worksclass UniqueColorGenerator { static List colorOptions = [ Colors.blue, Colors.red, Colors.green, Colors.yellow, Colors.purple, Colors.orange, Colors.indigo, Colors.amber, Colors.black, ]; static Random random = new Random(); static Color getColor() { if (colorOptions.length > 0) { return colorOptions.removeAt(random.nextInt(colorOptions.length)); } else { return Color.fromARGB(random.nextInt(256), random.nextInt(256), random.nextInt(256), random.nextInt(256)); } }}", "e": 2990, "s": 1235, "text": null }, { "code": null, "e": 2998, "s": 2990, "text": "Output:" }, { "code": null, "e": 3020, "s": 2998, "text": "Stateless Widget Tree" }, { "code": null, "e": 3332, "s": 3020, "text": "Here you can see that the colors are changing but when we would change it to the Stateful widget the code will work correctly but nothing will be shown on the application. But as we use the keys here in the Stateful widget the application will work fine. The following code shown below is direct with the keys. " }, { "code": null, "e": 3525, "s": 3332, "text": "Here in this code, you can see we have used the keys feature here, because of which the application is working fine. The rest of the code is the same, only the Key feature is newly added here." }, { "code": null, "e": 3530, "s": 3525, "text": "Dart" }, { "code": "import 'package:flutter/material.dart';import 'dart:math'; void main() => runApp(new MaterialApp(home: PositionedTiles())); class PositionedTiles extends StatefulWidget{ @override State<StatefulWidget> createState() => PositionedTilesState();} class PositionedTilesState extends State<PositionedTiles>{ late List<Widget> tiles; @override void initState(){ super.initState(); tiles = [ StatefulColorfulTile(key: UniqueKey()), StatefulColorfulTile(key: UniqueKey()), ]; } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(\"GEEKSFORGEEKS\"), backgroundColor: Colors.green, ) , body: SafeArea(child: Row(children: tiles)), floatingActionButton: FloatingActionButton( child: Icon(Icons.sentiment_very_satisfied), onPressed: swapTiles), ); } swapTiles(){ setState(() { tiles.insert(1, tiles.removeAt(0)); }); }} class StatefulColorfulTile extends StatefulWidget { StatefulColorfulTile({required Key key}) : super(key: key); @override State<StatefulWidget> createState() => StatefulColorfulTileState();}class StatefulColorfulTileState extends State<StatefulColorfulTile> { late Color myColor; @override void initState() { super.initState(); myColor = UniqueColorGenerator.getColor(); } @override Widget build(BuildContext context) { return Container( color: myColor, child: Padding( padding: EdgeInsets.all(70.0), )); }} class UniqueColorGenerator { static List colorOptions = [ Colors.blue, Colors.red, Colors.green, Colors.yellow, Colors.purple, Colors.orange, Colors.indigo, Colors.amber, Colors.black, ]; static Random random = new Random(); static Color getColor() { if (colorOptions.length > 0) { return colorOptions.removeAt(random.nextInt(colorOptions.length)); } else { return Color.fromARGB(random.nextInt(256), random.nextInt(256), random.nextInt(256), random.nextInt(256)); } }}", "e": 5567, "s": 3530, "text": null }, { "code": null, "e": 5575, "s": 5567, "text": "Output:" }, { "code": null, "e": 5596, "s": 5575, "text": "Stateful Widget Tree" }, { "code": null, "e": 5772, "s": 5596, "text": "Now it is clear from the above example where to add them. The answer is simple, if you have to use the Stateful widget then you have to use the Keys else no need to use them. " }, { "code": null, "e": 5856, "s": 5772, "text": "Now there are many types of Keys in flutter. All of them have been discussed below:" }, { "code": null, "e": 6021, "s": 5856, "text": "Value Key: The value key is used when it has to be assigned to something constant and extraordinary. For example, in the To-Do List the text entered is the value." }, { "code": null, "e": 6210, "s": 6021, "text": "Object Key: The Object key is used when any single field such as name or birthday, they maybe the same of more than two people but would be unique for each person or each data combination." }, { "code": null, "e": 6480, "s": 6210, "text": "Unique Key: The unique key is used when there are many widgets with the same incentive then we must use define each widget as a unique widget. We used it in our code also because we didn’t know what random color would be assigned to it until the widgets were assembled." }, { "code": null, "e": 6793, "s": 6480, "text": "Global key: The use of Global key is that it contains the data which can be accessed by other widgets present in the code. In case you don’t want to share it with other widgets then you must use the Global Key<From State> that holds a form of state and won’t allow other widgets to access the data stored in it." }, { "code": null, "e": 7005, "s": 6793, "text": "So, in conclusion, we can say that keys are a very good feature in flutter. It only works with the Stateful widget and the purpose to use it to store the value of the current state when modifying the collection." }, { "code": null, "e": 7021, "s": 7005, "text": "Flutter-widgets" }, { "code": null, "e": 7028, "s": 7021, "text": "Picked" }, { "code": null, "e": 7033, "s": 7028, "text": "Dart" }, { "code": null, "e": 7041, "s": 7033, "text": "Flutter" } ]
Stack firstElement() method in Java with Example
24 Dec, 2018 The Java.util.Stack.firstElement() method in Java is used to retrieve or fetch the first element of the Stack. It returns the element present at the 0th index of the Stack Syntax: Stack.firstElement() Parameters: The method does not take any parameter. Return Value: The method returns the first element present in the Stack. Below programs illustrate the Java.util.Stack.firstElement() method: Program 1: // Java code to illustrate firstElement()import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<String> stack = new Stack<String>(); // Use add() method to add elements into the Stack stack.add("Welcome"); stack.add("To"); stack.add("Geeks"); stack.add("4"); stack.add("Geeks"); // Displaying the Stack System.out.println("Stack: " + stack); // Displaying the first element System.out.println("The first element is: " + stack.firstElement()); }} Stack: [Welcome, To, Geeks, 4, Geeks] The first element is: Welcome Program 2: // Java code to illustrate firstElement()import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<Integer> stack = new Stack<Integer>(); // Use add() method to add elements into the Stack stack.add(10); stack.add(15); stack.add(30); stack.add(20); stack.add(5); // Displaying the Stack System.out.println("Stack: " + stack); // Displaying the first element System.out.println("The first element is: " + stack.firstElement()); }} Stack: [10, 15, 30, 20, 5] The first element is: 10 Java - util package Java-Collections Java-Functions Java-Stack Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Dec, 2018" }, { "code": null, "e": 200, "s": 28, "text": "The Java.util.Stack.firstElement() method in Java is used to retrieve or fetch the first element of the Stack. It returns the element present at the 0th index of the Stack" }, { "code": null, "e": 208, "s": 200, "text": "Syntax:" }, { "code": null, "e": 229, "s": 208, "text": "Stack.firstElement()" }, { "code": null, "e": 281, "s": 229, "text": "Parameters: The method does not take any parameter." }, { "code": null, "e": 354, "s": 281, "text": "Return Value: The method returns the first element present in the Stack." }, { "code": null, "e": 423, "s": 354, "text": "Below programs illustrate the Java.util.Stack.firstElement() method:" }, { "code": null, "e": 434, "s": 423, "text": "Program 1:" }, { "code": "// Java code to illustrate firstElement()import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<String> stack = new Stack<String>(); // Use add() method to add elements into the Stack stack.add(\"Welcome\"); stack.add(\"To\"); stack.add(\"Geeks\"); stack.add(\"4\"); stack.add(\"Geeks\"); // Displaying the Stack System.out.println(\"Stack: \" + stack); // Displaying the first element System.out.println(\"The first element is: \" + stack.firstElement()); }}", "e": 1070, "s": 434, "text": null }, { "code": null, "e": 1139, "s": 1070, "text": "Stack: [Welcome, To, Geeks, 4, Geeks]\nThe first element is: Welcome\n" }, { "code": null, "e": 1150, "s": 1139, "text": "Program 2:" }, { "code": "// Java code to illustrate firstElement()import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<Integer> stack = new Stack<Integer>(); // Use add() method to add elements into the Stack stack.add(10); stack.add(15); stack.add(30); stack.add(20); stack.add(5); // Displaying the Stack System.out.println(\"Stack: \" + stack); // Displaying the first element System.out.println(\"The first element is: \" + stack.firstElement()); }}", "e": 1767, "s": 1150, "text": null }, { "code": null, "e": 1820, "s": 1767, "text": "Stack: [10, 15, 30, 20, 5]\nThe first element is: 10\n" }, { "code": null, "e": 1840, "s": 1820, "text": "Java - util package" }, { "code": null, "e": 1857, "s": 1840, "text": "Java-Collections" }, { "code": null, "e": 1872, "s": 1857, "text": "Java-Functions" }, { "code": null, "e": 1883, "s": 1872, "text": "Java-Stack" }, { "code": null, "e": 1888, "s": 1883, "text": "Java" }, { "code": null, "e": 1893, "s": 1888, "text": "Java" }, { "code": null, "e": 1910, "s": 1893, "text": "Java-Collections" } ]
Material Design Components Progress Indicator in Android
27 Sep, 2021 Material Design Components (MDC Android) offers designers and developers a way to implement Material Design in their Android applications. Developed by a core team of engineers and UX designers at Google, these components enable a reliable development workflow to build beautiful and functional Android applications. Material design in Android is one of the key features that attracts and engages the customer towards the application. This is a special type of design, which is guided by Google. So in this article, it has been demonstrated how to use Progress Indicators, their types, and anatomy. Create an empty activity project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Add Required Dependency Include google material design components dependency in the build.gradle file. After adding the dependencies don’t forget to click on the “Sync Now” button present at the top right corner. implementation ‘com.google.android.material:material:1.4.0’ Note that while syncing your project you need to be connected to the network and make sure that you are adding the dependency to the app-level Gradle file as shown below. Progress indicators are used in android to inform the user about ongoing processes, for example, loading applications, network calls, downloading or uploading files. These communicate the app’s state and inform the user whether they can navigate away from the current session of the app. There are majorly two types of Progress Indicators one is a linear indicator and another is a circular indicator. Have a look at the following image to get the difference. These progress indicators may be Determinate or Indeterminate. Determinate indicators inform the user about the definite process, these should be only used when the process rate can be detected. Indeterminate indicators inform the user about the indefinite process means the current process is can take an indefinite time to complete. The Linear Progress indicator Consists of two major components: Track: The component which is of fixed width, which sets boundaries for the indicator to travel along. Indicator: The component which animates along the track. Working with the activity_main.xml file The main layout of the application consists of two progress indicators. One is a Linear progress indicator and another is a Circular progress indicator. Note that the indeterminate attribute in each of them to be true, otherwise it will not animate when the app is run on an emulator. To implement the same invoke the following code inside the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <com.google.android.material.progressindicator.LinearProgressIndicator android:id="@+id/linearProgressIndicator" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="32dp" android:indeterminate="true" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <com.google.android.material.progressindicator.CircularProgressIndicator android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="32dp" android:indeterminate="true" app:layout_constraintEnd_toEndOf="@+id/linearProgressIndicator" app:layout_constraintStart_toStartOf="@+id/linearProgressIndicator" app:layout_constraintTop_toBottomOf="@+id/linearProgressIndicator" /> </androidx.constraintlayout.widget.ConstraintLayout> Output: Customizing Linear progress indicator: To change the track thickness, track color, and indicator color the attributes are: app:trackThickness=”colorValue” app:trackColor=”colorValue” app:indicatorColor=”colorValue” Following is an example: XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <com.google.android.material.progressindicator.LinearProgressIndicator android:id="@+id/linearProgressIndicator" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="32dp" android:indeterminate="true" app:indicatorColor="@color/green_500" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:trackColor="@color/purple_500" app:trackThickness="8dp" /> </androidx.constraintlayout.widget.ConstraintLayout> Output: Increasing the size of the track thickness, track color, and indicator size for circular progress indicator: To change the track color, indicator color, track thickness, and indicator size the attributes are: app:trackThickness=”colorValue” app:trackColor=”colorValue” app:indicatorColor=”colorValue” app:indicatorSize=”valueInDp” Following is an example: XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <com.google.android.material.progressindicator.CircularProgressIndicator android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="32dp" android:indeterminate="true" app:indicatorColor="@color/green_500" app:indicatorSize="64dp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:trackColor="@color/purple_500" app:trackThickness="8dp" /> </androidx.constraintlayout.widget.ConstraintLayout> Output: Some common attributes of linear and circular indicators are: Element Attribute Related Methods setTrackThickness getTrackThickness setIndicatorColor getIndicatorColor setTrackColor getTrackColor setTrackCornerRadius getTrackCornerRadius setShowAnimationBehavior getShowAnimationBehavior setHideAnimationBehavior getHideAnimationBehavior Specific Attributes for Linear progress indicator: These attributes are specific for Linear Progress indicators. Element Attribute Related Methods setIndeterminateAnimationType getIndeterminateAnimationType setIndicatorDirection getIndicatorDirection Specific Attributes for Circular progress indicator: These attributes are specific for Circular Progress indicators. Element Attribute Related Methods setIndicatorSize getIndicatorSize setIndicatorInset getIndicatorInset setIndicatorDirection getIndicatorDirection Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Sep, 2021" }, { "code": null, "e": 627, "s": 28, "text": "Material Design Components (MDC Android) offers designers and developers a way to implement Material Design in their Android applications. Developed by a core team of engineers and UX designers at Google, these components enable a reliable development workflow to build beautiful and functional Android applications. Material design in Android is one of the key features that attracts and engages the customer towards the application. This is a special type of design, which is guided by Google. So in this article, it has been demonstrated how to use Progress Indicators, their types, and anatomy." }, { "code": null, "e": 660, "s": 627, "text": "Create an empty activity project" }, { "code": null, "e": 771, "s": 660, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio." }, { "code": null, "e": 795, "s": 771, "text": "Add Required Dependency" }, { "code": null, "e": 984, "s": 795, "text": "Include google material design components dependency in the build.gradle file. After adding the dependencies don’t forget to click on the “Sync Now” button present at the top right corner." }, { "code": null, "e": 1044, "s": 984, "text": "implementation ‘com.google.android.material:material:1.4.0’" }, { "code": null, "e": 1215, "s": 1044, "text": "Note that while syncing your project you need to be connected to the network and make sure that you are adding the dependency to the app-level Gradle file as shown below." }, { "code": null, "e": 1503, "s": 1215, "text": "Progress indicators are used in android to inform the user about ongoing processes, for example, loading applications, network calls, downloading or uploading files. These communicate the app’s state and inform the user whether they can navigate away from the current session of the app." }, { "code": null, "e": 1739, "s": 1503, "text": "There are majorly two types of Progress Indicators one is a linear indicator and another is a circular indicator. Have a look at the following image to get the difference. These progress indicators may be Determinate or Indeterminate. " }, { "code": null, "e": 1871, "s": 1739, "text": "Determinate indicators inform the user about the definite process, these should be only used when the process rate can be detected." }, { "code": null, "e": 2011, "s": 1871, "text": "Indeterminate indicators inform the user about the indefinite process means the current process is can take an indefinite time to complete." }, { "code": null, "e": 2075, "s": 2011, "text": "The Linear Progress indicator Consists of two major components:" }, { "code": null, "e": 2178, "s": 2075, "text": "Track: The component which is of fixed width, which sets boundaries for the indicator to travel along." }, { "code": null, "e": 2235, "s": 2178, "text": "Indicator: The component which animates along the track." }, { "code": null, "e": 2275, "s": 2235, "text": "Working with the activity_main.xml file" }, { "code": null, "e": 2643, "s": 2275, "text": "The main layout of the application consists of two progress indicators. One is a Linear progress indicator and another is a Circular progress indicator. Note that the indeterminate attribute in each of them to be true, otherwise it will not animate when the app is run on an emulator. To implement the same invoke the following code inside the activity_main.xml file." }, { "code": null, "e": 2647, "s": 2643, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <com.google.android.material.progressindicator.LinearProgressIndicator android:id=\"@+id/linearProgressIndicator\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"32dp\" android:indeterminate=\"true\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <com.google.android.material.progressindicator.CircularProgressIndicator android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"32dp\" android:indeterminate=\"true\" app:layout_constraintEnd_toEndOf=\"@+id/linearProgressIndicator\" app:layout_constraintStart_toStartOf=\"@+id/linearProgressIndicator\" app:layout_constraintTop_toBottomOf=\"@+id/linearProgressIndicator\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 3974, "s": 2647, "text": null }, { "code": null, "e": 3982, "s": 3974, "text": "Output:" }, { "code": null, "e": 4021, "s": 3982, "text": "Customizing Linear progress indicator:" }, { "code": null, "e": 4105, "s": 4021, "text": "To change the track thickness, track color, and indicator color the attributes are:" }, { "code": null, "e": 4137, "s": 4105, "text": "app:trackThickness=”colorValue”" }, { "code": null, "e": 4165, "s": 4137, "text": "app:trackColor=”colorValue”" }, { "code": null, "e": 4197, "s": 4165, "text": "app:indicatorColor=”colorValue”" }, { "code": null, "e": 4222, "s": 4197, "text": "Following is an example:" }, { "code": null, "e": 4226, "s": 4222, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <com.google.android.material.progressindicator.LinearProgressIndicator android:id=\"@+id/linearProgressIndicator\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"32dp\" android:indeterminate=\"true\" app:indicatorColor=\"@color/green_500\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:trackColor=\"@color/purple_500\" app:trackThickness=\"8dp\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 5209, "s": 4226, "text": null }, { "code": null, "e": 5217, "s": 5209, "text": "Output:" }, { "code": null, "e": 5326, "s": 5217, "text": "Increasing the size of the track thickness, track color, and indicator size for circular progress indicator:" }, { "code": null, "e": 5426, "s": 5326, "text": "To change the track color, indicator color, track thickness, and indicator size the attributes are:" }, { "code": null, "e": 5458, "s": 5426, "text": "app:trackThickness=”colorValue”" }, { "code": null, "e": 5486, "s": 5458, "text": "app:trackColor=”colorValue”" }, { "code": null, "e": 5518, "s": 5486, "text": "app:indicatorColor=”colorValue”" }, { "code": null, "e": 5548, "s": 5518, "text": "app:indicatorSize=”valueInDp”" }, { "code": null, "e": 5573, "s": 5548, "text": "Following is an example:" }, { "code": null, "e": 5577, "s": 5573, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <com.google.android.material.progressindicator.CircularProgressIndicator android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"32dp\" android:indeterminate=\"true\" app:indicatorColor=\"@color/green_500\" app:indicatorSize=\"64dp\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:trackColor=\"@color/purple_500\" app:trackThickness=\"8dp\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 6544, "s": 5577, "text": null }, { "code": null, "e": 6552, "s": 6544, "text": "Output:" }, { "code": null, "e": 6614, "s": 6552, "text": "Some common attributes of linear and circular indicators are:" }, { "code": null, "e": 6622, "s": 6614, "text": "Element" }, { "code": null, "e": 6632, "s": 6622, "text": "Attribute" }, { "code": null, "e": 6648, "s": 6632, "text": "Related Methods" }, { "code": null, "e": 6666, "s": 6648, "text": "setTrackThickness" }, { "code": null, "e": 6684, "s": 6666, "text": "getTrackThickness" }, { "code": null, "e": 6702, "s": 6684, "text": "setIndicatorColor" }, { "code": null, "e": 6720, "s": 6702, "text": "getIndicatorColor" }, { "code": null, "e": 6734, "s": 6720, "text": "setTrackColor" }, { "code": null, "e": 6748, "s": 6734, "text": "getTrackColor" }, { "code": null, "e": 6769, "s": 6748, "text": "setTrackCornerRadius" }, { "code": null, "e": 6790, "s": 6769, "text": "getTrackCornerRadius" }, { "code": null, "e": 6815, "s": 6790, "text": "setShowAnimationBehavior" }, { "code": null, "e": 6840, "s": 6815, "text": "getShowAnimationBehavior" }, { "code": null, "e": 6865, "s": 6840, "text": "setHideAnimationBehavior" }, { "code": null, "e": 6890, "s": 6865, "text": "getHideAnimationBehavior" }, { "code": null, "e": 6941, "s": 6890, "text": "Specific Attributes for Linear progress indicator:" }, { "code": null, "e": 7003, "s": 6941, "text": "These attributes are specific for Linear Progress indicators." }, { "code": null, "e": 7012, "s": 7003, "text": "Element " }, { "code": null, "e": 7022, "s": 7012, "text": "Attribute" }, { "code": null, "e": 7038, "s": 7022, "text": "Related Methods" }, { "code": null, "e": 7068, "s": 7038, "text": "setIndeterminateAnimationType" }, { "code": null, "e": 7098, "s": 7068, "text": "getIndeterminateAnimationType" }, { "code": null, "e": 7120, "s": 7098, "text": "setIndicatorDirection" }, { "code": null, "e": 7142, "s": 7120, "text": "getIndicatorDirection" }, { "code": null, "e": 7195, "s": 7142, "text": "Specific Attributes for Circular progress indicator:" }, { "code": null, "e": 7259, "s": 7195, "text": "These attributes are specific for Circular Progress indicators." }, { "code": null, "e": 7267, "s": 7259, "text": "Element" }, { "code": null, "e": 7277, "s": 7267, "text": "Attribute" }, { "code": null, "e": 7293, "s": 7277, "text": "Related Methods" }, { "code": null, "e": 7310, "s": 7293, "text": "setIndicatorSize" }, { "code": null, "e": 7327, "s": 7310, "text": "getIndicatorSize" }, { "code": null, "e": 7345, "s": 7327, "text": "setIndicatorInset" }, { "code": null, "e": 7363, "s": 7345, "text": "getIndicatorInset" }, { "code": null, "e": 7385, "s": 7363, "text": "setIndicatorDirection" }, { "code": null, "e": 7407, "s": 7385, "text": "getIndicatorDirection" }, { "code": null, "e": 7415, "s": 7407, "text": "Android" }, { "code": null, "e": 7422, "s": 7415, "text": "Kotlin" }, { "code": null, "e": 7430, "s": 7422, "text": "Android" } ]
What is Has-A-Relation in Java?
19 Jan, 2021 Association is the relation between two separate classes which establishes through their Objects. Composition and Aggregation are the two forms of association. In Java, a Has-A relationship is otherwise called composition. It is additionally utilized for code reusability in Java. In Java, a Has-A relationship essentially implies that an example of one class has a reference to an occasion of another class or another occurrence of a similar class. For instance, a vehicle has a motor, a canine has a tail, etc. In Java, there is no such watchword that executes a Has-A relationship. Yet, we generally utilize new catchphrases to actualize a Has-A relationship in Java. Has-a is a special form of Association where: It represents the Has-A relationship. It is a unidirectional association i.e. a one-way relationship. For example, here above as shown pulsar motorcycle has an engine but vice-versa is not possible and thus unidirectional in nature. In Aggregation, both the entries can survive individually which means ending one entity will not affect the other entity. Illustration: This shows that class Pulsar Has-a an engine. By having a different class for the engine, we don’t need to put the whole code that has a place with speed inside the Van class, which makes it conceivable to reuse the Speed class in numerous applications. In an Object-Oriented element, the clients don’t have to make a big deal about which article is accomplishing the genuine work. To accomplish this, the Van class conceals the execution subtleties from the clients of the Van class. Thus, essentially what happens is the clients would ask the Van class to do a specific activity and the Van class will either accomplish the work without help from anyone else or request that another class play out the activity. Implementation: Here is the implementation of the same which is as follows: Car class has a couple of instance variable and few methodsMaserati is a type of car that extends the Car class that shows Maserati is a Car. Maserati also uses an Engine’s method, stop, using composition. So it shows that a Maserati has an Engine.The Engine class has the two methods start() and stop() that are used by the Maserati class. Car class has a couple of instance variable and few methods Maserati is a type of car that extends the Car class that shows Maserati is a Car. Maserati also uses an Engine’s method, stop, using composition. So it shows that a Maserati has an Engine. The Engine class has the two methods start() and stop() that are used by the Maserati class. Example: Java // Java Program to Illustrate has-a relation // Class1// Parent classpublic class Car { // Instance members of class Car private String color; private int maxSpeed; // Main driver method public static void main(String[] args) { // Creating an object of Car class Car nano = new Car(); // Assigning car object color nano.setColor("RED"); // Assigning car object speed nano.setMaxSpeed(329); // Calling carInfo() over object of Car class nano.carInfo(); // Creating an object of Maserati class Maserati quattroporte = new Maserati(); // Calling MaseratiStartDemo() over // object of Maserati class quattroporte.MaseratiStartDemo(); } // Methods implementation // Method 1 // To set the maximum speed of car public void setMaxSpeed(int maxSpeed) { // This keyword refers to current object itself this.maxSpeed = maxSpeed; } // Method 2 // To set the color of car public void setColor(String color) { // This keyword refers to current object this.color = color; } // Method 3 // To display car information public void carInfo() { // Print the car information - color and speed System.out.println("Car Color= " + color + " Max Speed= " + maxSpeed); }} // Class2// Child class// Helper classclass Maserati extends Car { // Method in which it is shown // what happened with the engine of Puslar public void MaseratiStartDemo() { // Creating an object of Engine type // using stop() method // Here, MaseratiEngine is name of an object Engine MaseratiEngine = new Engine(); MaseratiEngine.start(); MaseratiEngine.stop(); }} // Class 3// Helper classclass Engine { // Method 1 // To start a engine public void start() { // Print statement when engine starts System.out.println("Started:"); } // Method 2 // To stop a engine public void stop() { // Print statement when engine stops System.out.println("Stopped:"); }} Car Color= RED Max Speed= 150 Started: Stopped: java-inheritance Java-Object Oriented Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Jan, 2021" }, { "code": null, "e": 723, "s": 52, "text": "Association is the relation between two separate classes which establishes through their Objects. Composition and Aggregation are the two forms of association. In Java, a Has-A relationship is otherwise called composition. It is additionally utilized for code reusability in Java. In Java, a Has-A relationship essentially implies that an example of one class has a reference to an occasion of another class or another occurrence of a similar class. For instance, a vehicle has a motor, a canine has a tail, etc. In Java, there is no such watchword that executes a Has-A relationship. Yet, we generally utilize new catchphrases to actualize a Has-A relationship in Java." }, { "code": null, "e": 769, "s": 723, "text": "Has-a is a special form of Association where:" }, { "code": null, "e": 807, "s": 769, "text": "It represents the Has-A relationship." }, { "code": null, "e": 1002, "s": 807, "text": "It is a unidirectional association i.e. a one-way relationship. For example, here above as shown pulsar motorcycle has an engine but vice-versa is not possible and thus unidirectional in nature." }, { "code": null, "e": 1124, "s": 1002, "text": "In Aggregation, both the entries can survive individually which means ending one entity will not affect the other entity." }, { "code": null, "e": 1138, "s": 1124, "text": "Illustration:" }, { "code": null, "e": 1394, "s": 1138, "text": "This shows that class Pulsar Has-a an engine. By having a different class for the engine, we don’t need to put the whole code that has a place with speed inside the Van class, which makes it conceivable to reuse the Speed class in numerous applications. " }, { "code": null, "e": 1854, "s": 1394, "text": "In an Object-Oriented element, the clients don’t have to make a big deal about which article is accomplishing the genuine work. To accomplish this, the Van class conceals the execution subtleties from the clients of the Van class. Thus, essentially what happens is the clients would ask the Van class to do a specific activity and the Van class will either accomplish the work without help from anyone else or request that another class play out the activity." }, { "code": null, "e": 1931, "s": 1854, "text": "Implementation: Here is the implementation of the same which is as follows: " }, { "code": null, "e": 2272, "s": 1931, "text": "Car class has a couple of instance variable and few methodsMaserati is a type of car that extends the Car class that shows Maserati is a Car. Maserati also uses an Engine’s method, stop, using composition. So it shows that a Maserati has an Engine.The Engine class has the two methods start() and stop() that are used by the Maserati class." }, { "code": null, "e": 2332, "s": 2272, "text": "Car class has a couple of instance variable and few methods" }, { "code": null, "e": 2522, "s": 2332, "text": "Maserati is a type of car that extends the Car class that shows Maserati is a Car. Maserati also uses an Engine’s method, stop, using composition. So it shows that a Maserati has an Engine." }, { "code": null, "e": 2615, "s": 2522, "text": "The Engine class has the two methods start() and stop() that are used by the Maserati class." }, { "code": null, "e": 2624, "s": 2615, "text": "Example:" }, { "code": null, "e": 2629, "s": 2624, "text": "Java" }, { "code": "// Java Program to Illustrate has-a relation // Class1// Parent classpublic class Car { // Instance members of class Car private String color; private int maxSpeed; // Main driver method public static void main(String[] args) { // Creating an object of Car class Car nano = new Car(); // Assigning car object color nano.setColor(\"RED\"); // Assigning car object speed nano.setMaxSpeed(329); // Calling carInfo() over object of Car class nano.carInfo(); // Creating an object of Maserati class Maserati quattroporte = new Maserati(); // Calling MaseratiStartDemo() over // object of Maserati class quattroporte.MaseratiStartDemo(); } // Methods implementation // Method 1 // To set the maximum speed of car public void setMaxSpeed(int maxSpeed) { // This keyword refers to current object itself this.maxSpeed = maxSpeed; } // Method 2 // To set the color of car public void setColor(String color) { // This keyword refers to current object this.color = color; } // Method 3 // To display car information public void carInfo() { // Print the car information - color and speed System.out.println(\"Car Color= \" + color + \" Max Speed= \" + maxSpeed); }} // Class2// Child class// Helper classclass Maserati extends Car { // Method in which it is shown // what happened with the engine of Puslar public void MaseratiStartDemo() { // Creating an object of Engine type // using stop() method // Here, MaseratiEngine is name of an object Engine MaseratiEngine = new Engine(); MaseratiEngine.start(); MaseratiEngine.stop(); }} // Class 3// Helper classclass Engine { // Method 1 // To start a engine public void start() { // Print statement when engine starts System.out.println(\"Started:\"); } // Method 2 // To stop a engine public void stop() { // Print statement when engine stops System.out.println(\"Stopped:\"); }}", "e": 4810, "s": 2629, "text": null }, { "code": null, "e": 4858, "s": 4810, "text": "Car Color= RED Max Speed= 150\nStarted:\nStopped:" }, { "code": null, "e": 4875, "s": 4858, "text": "java-inheritance" }, { "code": null, "e": 4896, "s": 4875, "text": "Java-Object Oriented" }, { "code": null, "e": 4901, "s": 4896, "text": "Java" }, { "code": null, "e": 4906, "s": 4901, "text": "Java" } ]
MoviePy – Resizing Video File
29 Dec, 2021 In this article, we will see how we can resize video file clips in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Resizing video files means. Image/frame interpolation occurs when you resize or distort your frame of video from one-pixel grid to another. Video resizing is necessary when we need to increase or decrease the total number of pixels, whereas remapping can occur when you are correcting for lens distortion or rotating a video. In order to do this we will use resize method with the VideoFileClip object Syntax : clip.resize(n) Argument : It takes float value i.e multiplier Return : It returns VideoFileClip object Below is the implementation Python3 # Import everything needed to edit video clipsfrom moviepy.editor import * # loading video dsa gfg intro video# and getting only first 5 secondsclip1 = VideoFileClip("dsa_geek.webm").subclip(0, 5) # getting width and height of clip 1w1 = clip1.wh1 = clip1.h print("Width x Height of clip 1 : ", end = " ")print(str(w1) + " x ", str(h1)) print("---------------------------------------") # resizing video downsize 50 %clip2 = clip1.resize(0.5) # getting width and height of clip 1w2 = clip2.wh2 = clip2.h print("Width x Height of clip 2 : ", end = " ")print(str(w2) + " x ", str(h2)) print("---------------------------------------") # showing final clipclip2.ipython_display(width = 480) Output : Width x Height of clip 1 : 854 x 480 --------------------------------------- Width x Height of clip 2 : 427 x 240 --------------------------------------- Moviepy - Building video __temp__.mp4. Moviepy - Writing video __temp__.mp4 Moviepy - Done ! Moviepy - video ready __temp__.mp4 Another example Python3 # Import everything needed to edit video clipsfrom moviepy.editor import * # loading video gfgclip = VideoFileClip("geeks.mp4") # getting subclipclip1 = clip.subclip(0, 7) # getting width and height of clip 1w1 = clip1.wh1 = clip1.h print("Width x Height of clip 1 : ", end = " ")print(str(w1) + " x ", str(h1)) print("---------------------------------------") # resizing video downsize 50 %clip2 = clip1.resize(0.5) # getting width and height of clip 1w2 = clip2.wh2 = clip2.h print("Width x Height of clip 2 : ", end = " ")print(str(w2) + " x ", str(h2)) print("---------------------------------------") # showing final clipclip2.ipython_display() Output : Width x Height of clip 1 : 656 x 404 --------------------------------------- Width x Height of clip 2 : 328 x 202 --------------------------------------- Moviepy - Building video __temp__.mp4. MoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3 MoviePy - Done. Moviepy - Writing video __temp__.mp4 Moviepy - Done ! Moviepy - video ready __temp__.mp4 sagarkarn9 Python-MoviePy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n29 Dec, 2021" }, { "code": null, "e": 561, "s": 53, "text": "In this article, we will see how we can resize video file clips in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Resizing video files means. Image/frame interpolation occurs when you resize or distort your frame of video from one-pixel grid to another. Video resizing is necessary when we need to increase or decrease the total number of pixels, whereas remapping can occur when you are correcting for lens distortion or rotating a video." }, { "code": null, "e": 637, "s": 561, "text": "In order to do this we will use resize method with the VideoFileClip object" }, { "code": null, "e": 661, "s": 637, "text": "Syntax : clip.resize(n)" }, { "code": null, "e": 709, "s": 661, "text": "Argument : It takes float value i.e multiplier " }, { "code": null, "e": 752, "s": 709, "text": "Return : It returns VideoFileClip object " }, { "code": null, "e": 782, "s": 752, "text": "Below is the implementation " }, { "code": null, "e": 790, "s": 782, "text": "Python3" }, { "code": "# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video dsa gfg intro video# and getting only first 5 secondsclip1 = VideoFileClip(\"dsa_geek.webm\").subclip(0, 5) # getting width and height of clip 1w1 = clip1.wh1 = clip1.h print(\"Width x Height of clip 1 : \", end = \" \")print(str(w1) + \" x \", str(h1)) print(\"---------------------------------------\") # resizing video downsize 50 %clip2 = clip1.resize(0.5) # getting width and height of clip 1w2 = clip2.wh2 = clip2.h print(\"Width x Height of clip 2 : \", end = \" \")print(str(w2) + \" x \", str(h2)) print(\"---------------------------------------\") # showing final clipclip2.ipython_display(width = 480)", "e": 1476, "s": 790, "text": null }, { "code": null, "e": 1486, "s": 1476, "text": "Output : " }, { "code": null, "e": 1775, "s": 1486, "text": "Width x Height of clip 1 : 854 x 480\n---------------------------------------\nWidth x Height of clip 2 : 427 x 240\n---------------------------------------\nMoviepy - Building video __temp__.mp4.\nMoviepy - Writing video __temp__.mp4\n\n\nMoviepy - Done !\nMoviepy - video ready __temp__.mp4 " }, { "code": null, "e": 1793, "s": 1775, "text": "Another example " }, { "code": null, "e": 1801, "s": 1793, "text": "Python3" }, { "code": "# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video gfgclip = VideoFileClip(\"geeks.mp4\") # getting subclipclip1 = clip.subclip(0, 7) # getting width and height of clip 1w1 = clip1.wh1 = clip1.h print(\"Width x Height of clip 1 : \", end = \" \")print(str(w1) + \" x \", str(h1)) print(\"---------------------------------------\") # resizing video downsize 50 %clip2 = clip1.resize(0.5) # getting width and height of clip 1w2 = clip2.wh2 = clip2.h print(\"Width x Height of clip 2 : \", end = \" \")print(str(w2) + \" x \", str(h2)) print(\"---------------------------------------\") # showing final clipclip2.ipython_display()", "e": 2451, "s": 1801, "text": null }, { "code": null, "e": 2461, "s": 2451, "text": "Output : " }, { "code": null, "e": 2822, "s": 2461, "text": "Width x Height of clip 1 : 656 x 404\n---------------------------------------\nWidth x Height of clip 2 : 328 x 202\n---------------------------------------\nMoviepy - Building video __temp__.mp4.\nMoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3\n\nMoviePy - Done.\nMoviepy - Writing video __temp__.mp4\n\n\nMoviepy - Done !\nMoviepy - video ready __temp__.mp4" }, { "code": null, "e": 2833, "s": 2822, "text": "sagarkarn9" }, { "code": null, "e": 2848, "s": 2833, "text": "Python-MoviePy" }, { "code": null, "e": 2855, "s": 2848, "text": "Python" } ]
ML | Dummy classifiers using sklearn
28 Nov, 2019 A dummy classifier is a type of classifier which does not generate any insight about the data and classifies the given data using only simple rules. The classifier’s behavior is completely independent of the training data as the trends in the training data are completely ignored and instead uses one of the strategies to predict the class label.It is used only as a simple baseline for the other classifiers i.e. any other classifier is expected to perform better on the given dataset. It is especially useful for datasets where are sure of a class imbalance. It is based on the philosophy that any analytic approach for a classification problem should be better than a random guessing approach. Below are a few strategies used by the dummy classifier to predict a class label – Most Frequent: The classifier always predicts the most frequent class label in the training data.Stratified: It generates predictions by respecting the class distribution of the training data. It is different from the “most frequent” strategy as it instead associates a probability with each data point of being the most frequent class label.Uniform: It generates predictions uniformly at random.Constant: The classifier always predicts a constant label and is primarily used when classifying non-majority class labels. Most Frequent: The classifier always predicts the most frequent class label in the training data. Stratified: It generates predictions by respecting the class distribution of the training data. It is different from the “most frequent” strategy as it instead associates a probability with each data point of being the most frequent class label. Uniform: It generates predictions uniformly at random. Constant: The classifier always predicts a constant label and is primarily used when classifying non-majority class labels. Now, let’s see the implementation of dummy classifiers using the sklearn library – Step 1: Importing the required Libraries import numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.neighbors import KNeighborsClassifierimport matplotlib.pyplot as plt import seaborn as sns Step 2: Reading the Dataset cd C:\Users\Dev\Desktop\Kaggle\Breast_Cancer# Changing the read file location to the location of the filedf = pd.read_csv('data.csv') y = df['diagnosis']X = df.drop('diagnosis', axis = 1)X = X.drop('Unnamed: 32', axis = 1)X = X.drop('id', axis = 1)# Separating the dependent and independent variable X_train, X_test, y_train, y_test = train_test_split( X, y, test_size = 0.3, random_state = 0)# Splitting the data into training and testing data Step 3: Training the dummy model strategies = ['most_frequent', 'stratified', 'uniform', 'constant'] test_scores = []for s in strategies: if s =='constant': dclf = DummyClassifier(strategy = s, random_state = 0, constant ='M') else: dclf = DummyClassifier(strategy = s, random_state = 0) dclf.fit(X_train, y_train) score = dclf.score(X_test, y_test) test_scores.append(score) Step 4: Analyzing our results ax = sns.stripplot(strategies, test_scores);ax.set(xlabel ='Strategy', ylabel ='Test Score')plt.show() Step 5: Training the KNN model clf = KNeighborsClassifier(n_neighbors = 5)clf.fit(X_train, y_train)print(clf.score(X_test, y_test)) On comparing the scores of the KNN classifier with the dummy classifier, we come to the conclusion that the KNN classifier is, in fact, a good classifier for the given data. AlindGupta shubham_singh Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Monte Carlo Tree Search (MCTS) Introduction to Recurrent Neural Network Markov Decision Process Getting started with Machine Learning ML | Underfitting and Overfitting Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas How to get column names in Pandas dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Nov, 2019" }, { "code": null, "e": 725, "s": 28, "text": "A dummy classifier is a type of classifier which does not generate any insight about the data and classifies the given data using only simple rules. The classifier’s behavior is completely independent of the training data as the trends in the training data are completely ignored and instead uses one of the strategies to predict the class label.It is used only as a simple baseline for the other classifiers i.e. any other classifier is expected to perform better on the given dataset. It is especially useful for datasets where are sure of a class imbalance. It is based on the philosophy that any analytic approach for a classification problem should be better than a random guessing approach." }, { "code": null, "e": 808, "s": 725, "text": "Below are a few strategies used by the dummy classifier to predict a class label –" }, { "code": null, "e": 1328, "s": 808, "text": "Most Frequent: The classifier always predicts the most frequent class label in the training data.Stratified: It generates predictions by respecting the class distribution of the training data. It is different from the “most frequent” strategy as it instead associates a probability with each data point of being the most frequent class label.Uniform: It generates predictions uniformly at random.Constant: The classifier always predicts a constant label and is primarily used when classifying non-majority class labels." }, { "code": null, "e": 1426, "s": 1328, "text": "Most Frequent: The classifier always predicts the most frequent class label in the training data." }, { "code": null, "e": 1672, "s": 1426, "text": "Stratified: It generates predictions by respecting the class distribution of the training data. It is different from the “most frequent” strategy as it instead associates a probability with each data point of being the most frequent class label." }, { "code": null, "e": 1727, "s": 1672, "text": "Uniform: It generates predictions uniformly at random." }, { "code": null, "e": 1851, "s": 1727, "text": "Constant: The classifier always predicts a constant label and is primarily used when classifying non-majority class labels." }, { "code": null, "e": 1934, "s": 1851, "text": "Now, let’s see the implementation of dummy classifiers using the sklearn library –" }, { "code": null, "e": 1975, "s": 1934, "text": "Step 1: Importing the required Libraries" }, { "code": "import numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.neighbors import KNeighborsClassifierimport matplotlib.pyplot as plt import seaborn as sns", "e": 2168, "s": 1975, "text": null }, { "code": null, "e": 2197, "s": 2168, "text": " Step 2: Reading the Dataset" }, { "code": "cd C:\\Users\\Dev\\Desktop\\Kaggle\\Breast_Cancer# Changing the read file location to the location of the filedf = pd.read_csv('data.csv') y = df['diagnosis']X = df.drop('diagnosis', axis = 1)X = X.drop('Unnamed: 32', axis = 1)X = X.drop('id', axis = 1)# Separating the dependent and independent variable X_train, X_test, y_train, y_test = train_test_split( X, y, test_size = 0.3, random_state = 0)# Splitting the data into training and testing data", "e": 2655, "s": 2197, "text": null }, { "code": null, "e": 2689, "s": 2655, "text": " Step 3: Training the dummy model" }, { "code": "strategies = ['most_frequent', 'stratified', 'uniform', 'constant'] test_scores = []for s in strategies: if s =='constant': dclf = DummyClassifier(strategy = s, random_state = 0, constant ='M') else: dclf = DummyClassifier(strategy = s, random_state = 0) dclf.fit(X_train, y_train) score = dclf.score(X_test, y_test) test_scores.append(score)", "e": 3062, "s": 2689, "text": null }, { "code": null, "e": 3093, "s": 3062, "text": " Step 4: Analyzing our results" }, { "code": "ax = sns.stripplot(strategies, test_scores);ax.set(xlabel ='Strategy', ylabel ='Test Score')plt.show()", "e": 3196, "s": 3093, "text": null }, { "code": null, "e": 3228, "s": 3196, "text": " Step 5: Training the KNN model" }, { "code": "clf = KNeighborsClassifier(n_neighbors = 5)clf.fit(X_train, y_train)print(clf.score(X_test, y_test))", "e": 3329, "s": 3228, "text": null }, { "code": null, "e": 3503, "s": 3329, "text": "On comparing the scores of the KNN classifier with the dummy classifier, we come to the conclusion that the KNN classifier is, in fact, a good classifier for the given data." }, { "code": null, "e": 3514, "s": 3503, "text": "AlindGupta" }, { "code": null, "e": 3528, "s": 3514, "text": "shubham_singh" }, { "code": null, "e": 3545, "s": 3528, "text": "Machine Learning" }, { "code": null, "e": 3552, "s": 3545, "text": "Python" }, { "code": null, "e": 3569, "s": 3552, "text": "Machine Learning" }, { "code": null, "e": 3667, "s": 3569, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3703, "s": 3667, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 3744, "s": 3703, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 3768, "s": 3744, "text": "Markov Decision Process" }, { "code": null, "e": 3806, "s": 3768, "text": "Getting started with Machine Learning" }, { "code": null, "e": 3840, "s": 3806, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 3868, "s": 3840, "text": "Read JSON file using Python" }, { "code": null, "e": 3890, "s": 3868, "text": "Python map() function" }, { "code": null, "e": 3940, "s": 3890, "text": "Adding new column to existing DataFrame in Pandas" } ]
How to make a placeholder for a ‘select’ box?
04 Jan, 2022 There is no placeholder attribute in ‘select’ tag but it can make the placeholder for a ‘select’ box. There are many ways to create the placeholder for a ‘select’ box. Example 1: html <!DOCTYPE html><html> <head> <title>make placeholder</title> <style> body { border:black; justify-content: center; text-align: center; } div { max-width: 18em; } h1 { color:green; } select { margin-left:130px; } </style> </head> <body> <h1>GeeksforGeeks<h1> <div include="form-input-select()"> <select required> <option value="">Example Placeholder</option> <!-- Available Options --> <option value="1">GeeksforGeeks</option> <option value="2">w3skul</option> <option value="3">tuitorial point</option> <option value="4">CodeComunity</option> <option value="5">Coders</option> </select> </div> </body></html> Example 2: Using JavaScript to create placeholder in select box. html <!DOCTYPE html><html> <head> <script type="text/javascript"> function populate(s, s1) { var s = document.getElementById(s); var s1 = document.getElementById(s1); s1.innerHTML = ""; if(s.value == "Database") { var arr = ["|Select","mysql|MySQL","oracle|Oracle"]; } for(var option in arr) { var pair = arr[option].split("|"); var new_op = document.createElement("option"); new_op.value = pair[0]; new_op.innerHTML = pair[1]; s1.options.add(new_op); } } </script> <style> body { text-align:center; } h1 { color:green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>Choose Subject:</h2> <select id = "slct" name = "slct" onchange = "populate(this.id, 'slct1')"> <option value="">Select</option> <option value="Database">Database</option> <option value="Java">Java</option> <option value="Python">Python</option> </select> <h2>Choose topics:</h2> <select id = "slct1" name = "slct1"></select> </body></html> sumitgumber28 Picked Technical Scripter 2018 CSS HTML Technical Scripter Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Jan, 2022" }, { "code": null, "e": 222, "s": 54, "text": "There is no placeholder attribute in ‘select’ tag but it can make the placeholder for a ‘select’ box. There are many ways to create the placeholder for a ‘select’ box." }, { "code": null, "e": 233, "s": 222, "text": "Example 1:" }, { "code": null, "e": 238, "s": 233, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>make placeholder</title> <style> body { border:black; justify-content: center; text-align: center; } div { max-width: 18em; } h1 { color:green; } select { margin-left:130px; } </style> </head> <body> <h1>GeeksforGeeks<h1> <div include=\"form-input-select()\"> <select required> <option value=\"\">Example Placeholder</option> <!-- Available Options --> <option value=\"1\">GeeksforGeeks</option> <option value=\"2\">w3skul</option> <option value=\"3\">tuitorial point</option> <option value=\"4\">CodeComunity</option> <option value=\"5\">Coders</option> </select> </div> </body></html> ", "e": 1249, "s": 238, "text": null }, { "code": null, "e": 1314, "s": 1249, "text": "Example 2: Using JavaScript to create placeholder in select box." }, { "code": null, "e": 1319, "s": 1314, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <script type=\"text/javascript\"> function populate(s, s1) { var s = document.getElementById(s); var s1 = document.getElementById(s1); s1.innerHTML = \"\"; if(s.value == \"Database\") { var arr = [\"|Select\",\"mysql|MySQL\",\"oracle|Oracle\"]; } for(var option in arr) { var pair = arr[option].split(\"|\"); var new_op = document.createElement(\"option\"); new_op.value = pair[0]; new_op.innerHTML = pair[1]; s1.options.add(new_op); } } </script> <style> body { text-align:center; } h1 { color:green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>Choose Subject:</h2> <select id = \"slct\" name = \"slct\" onchange = \"populate(this.id, 'slct1')\"> <option value=\"\">Select</option> <option value=\"Database\">Database</option> <option value=\"Java\">Java</option> <option value=\"Python\">Python</option> </select> <h2>Choose topics:</h2> <select id = \"slct1\" name = \"slct1\"></select> </body></html> ", "e": 2720, "s": 1319, "text": null }, { "code": null, "e": 2734, "s": 2720, "text": "sumitgumber28" }, { "code": null, "e": 2741, "s": 2734, "text": "Picked" }, { "code": null, "e": 2765, "s": 2741, "text": "Technical Scripter 2018" }, { "code": null, "e": 2769, "s": 2765, "text": "CSS" }, { "code": null, "e": 2774, "s": 2769, "text": "HTML" }, { "code": null, "e": 2793, "s": 2774, "text": "Technical Scripter" }, { "code": null, "e": 2810, "s": 2793, "text": "Web Technologies" }, { "code": null, "e": 2815, "s": 2810, "text": "HTML" } ]
How to get HTML content of an iFrame using JavaScript ?
05 Jun, 2020 The <iframe> tag specifies an inline frame. It allows us to load a separate HTML file into an existing document. Code snippet: function getIframeContent(frameId) { var frameObj = document.getElementById(frameId); var frameContent = frameObj. contentWindow.document.body.innerHTML; alert("frame content : " + frameContent); } Some of the definitions are given below: getIframeContent(frameId): It is used to get the object reference of an iframe. contentWindow: It is a property which returns the window object of the iframe. contentWindow.document: It returns the document object of iframe window. contentWindow.document.body.innerHTML: It returns the HTML content of iframe body. Example: The following example demonstrates to include separate HTML file into existing document. <!DOCTYPE html><html> <head> <title> How to get HTML content of an iFrame using javascript? </title></head> <body> <iframe id="frameID" src= "ContentOfFrame.html"> </iframe> <a href="#" onclick= "getIframeContent('frameID');"> Get the content of Iframe </a> <script> function getIframeContent(frameID) { var frameObj = document.getElementById(frameID); var frameContent = frameObj .contentWindow.document.body.innerHTML; alert("frame content : " + frameContent); } </script></body> </html> ContentOfFrame.html The following example demonstrates the HTML code content of file “ContentOfFrame.html” <!DOCTYPE html><html> <body> GeeksForGeeks: A Computer Science Portal For Geeks (It is loaded inside the iframe)</body> </html> Output: Before clicking the link: After clicking the link: HTML-Misc JavaScript-Misc Picked HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Jun, 2020" }, { "code": null, "e": 167, "s": 54, "text": "The <iframe> tag specifies an inline frame. It allows us to load a separate HTML file into an existing document." }, { "code": null, "e": 181, "s": 167, "text": "Code snippet:" }, { "code": null, "e": 419, "s": 181, "text": "function getIframeContent(frameId) {\n var frameObj = \n document.getElementById(frameId);\n\n var frameContent = frameObj.\n contentWindow.document.body.innerHTML;\n \n alert(\"frame content : \" + frameContent);\n}\n" }, { "code": null, "e": 460, "s": 419, "text": "Some of the definitions are given below:" }, { "code": null, "e": 540, "s": 460, "text": "getIframeContent(frameId): It is used to get the object reference of an iframe." }, { "code": null, "e": 619, "s": 540, "text": "contentWindow: It is a property which returns the window object of the iframe." }, { "code": null, "e": 692, "s": 619, "text": "contentWindow.document: It returns the document object of iframe window." }, { "code": null, "e": 775, "s": 692, "text": "contentWindow.document.body.innerHTML: It returns the HTML content of iframe body." }, { "code": null, "e": 873, "s": 775, "text": "Example: The following example demonstrates to include separate HTML file into existing document." }, { "code": "<!DOCTYPE html><html> <head> <title> How to get HTML content of an iFrame using javascript? </title></head> <body> <iframe id=\"frameID\" src= \"ContentOfFrame.html\"> </iframe> <a href=\"#\" onclick= \"getIframeContent('frameID');\"> Get the content of Iframe </a> <script> function getIframeContent(frameID) { var frameObj = document.getElementById(frameID); var frameContent = frameObj .contentWindow.document.body.innerHTML; alert(\"frame content : \" + frameContent); } </script></body> </html>", "e": 1510, "s": 873, "text": null }, { "code": null, "e": 1617, "s": 1510, "text": "ContentOfFrame.html The following example demonstrates the HTML code content of file “ContentOfFrame.html”" }, { "code": "<!DOCTYPE html><html> <body> GeeksForGeeks: A Computer Science Portal For Geeks (It is loaded inside the iframe)</body> </html>", "e": 1761, "s": 1617, "text": null }, { "code": null, "e": 1769, "s": 1761, "text": "Output:" }, { "code": null, "e": 1795, "s": 1769, "text": "Before clicking the link:" }, { "code": null, "e": 1820, "s": 1795, "text": "After clicking the link:" }, { "code": null, "e": 1830, "s": 1820, "text": "HTML-Misc" }, { "code": null, "e": 1846, "s": 1830, "text": "JavaScript-Misc" }, { "code": null, "e": 1853, "s": 1846, "text": "Picked" }, { "code": null, "e": 1858, "s": 1853, "text": "HTML" }, { "code": null, "e": 1869, "s": 1858, "text": "JavaScript" }, { "code": null, "e": 1886, "s": 1869, "text": "Web Technologies" }, { "code": null, "e": 1913, "s": 1886, "text": "Web technologies Questions" }, { "code": null, "e": 1918, "s": 1913, "text": "HTML" } ]
How to remove all leading zeros in a string in PHP ?
20 Sep, 2019 Given a number in string format and the task is to remove all leading zeros from the given string in PHP. Examples: Input : str = 00006665555 Output : 6665555 Input : str = 00775505 Output : 775505 Method 1: Using ltrim() function: The ltrim() function is used to remove whitespaces or other characters (if specified) from the left side of a string. Syntax: ltrim( "string", "character which to be remove from the left side of string"); Program: <?php // Store the number string with// leading zeros into variable$str = "00775505"; // Passing the string as first// argument and the character// to be removed as second// parameter$str = ltrim($str, "0"); // Display the resultecho $str; ?> 775505 Method 2: First convert the given string into number typecast the string to int which will automatically remove all the leading zeros and then again typecast it to string to make it string again. Program: <?php // Store the number string with// leading zeros into variable$str = "00775505"; // First typecast to int and // then to string$str = (string)((int)($str)); // Display the resultecho $str; ?> 775505 Picked PHP PHP Programs Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Sep, 2019" }, { "code": null, "e": 134, "s": 28, "text": "Given a number in string format and the task is to remove all leading zeros from the given string in PHP." }, { "code": null, "e": 144, "s": 134, "text": "Examples:" }, { "code": null, "e": 228, "s": 144, "text": "Input : str = 00006665555\nOutput : 6665555\n\nInput : str = 00775505\nOutput : 775505\n" }, { "code": null, "e": 380, "s": 228, "text": "Method 1: Using ltrim() function: The ltrim() function is used to remove whitespaces or other characters (if specified) from the left side of a string." }, { "code": null, "e": 388, "s": 380, "text": "Syntax:" }, { "code": null, "e": 467, "s": 388, "text": "ltrim( \"string\", \"character which to be remove from the left side of string\");" }, { "code": null, "e": 476, "s": 467, "text": "Program:" }, { "code": "<?php // Store the number string with// leading zeros into variable$str = \"00775505\"; // Passing the string as first// argument and the character// to be removed as second// parameter$str = ltrim($str, \"0\"); // Display the resultecho $str; ?>", "e": 732, "s": 476, "text": null }, { "code": null, "e": 740, "s": 732, "text": "775505\n" }, { "code": null, "e": 936, "s": 740, "text": "Method 2: First convert the given string into number typecast the string to int which will automatically remove all the leading zeros and then again typecast it to string to make it string again." }, { "code": null, "e": 945, "s": 936, "text": "Program:" }, { "code": "<?php // Store the number string with// leading zeros into variable$str = \"00775505\"; // First typecast to int and // then to string$str = (string)((int)($str)); // Display the resultecho $str; ?>", "e": 1154, "s": 945, "text": null }, { "code": null, "e": 1162, "s": 1154, "text": "775505\n" }, { "code": null, "e": 1169, "s": 1162, "text": "Picked" }, { "code": null, "e": 1173, "s": 1169, "text": "PHP" }, { "code": null, "e": 1186, "s": 1173, "text": "PHP Programs" }, { "code": null, "e": 1203, "s": 1186, "text": "Web Technologies" }, { "code": null, "e": 1230, "s": 1203, "text": "Web technologies Questions" }, { "code": null, "e": 1234, "s": 1230, "text": "PHP" } ]
Trapping Rain Water
06 Jul, 2022 Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. Examples: 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. Input: arr[] = {2, 0, 2} Output: 2 Explanation: The structure is like below We can trap 2 units of water in the middle gap. Input: arr[] = {3, 0, 2, 0, 4} Output: 7 Explanation: Structure is like below We can trap "3 units" of water between 3 and 2, "1 unit" on top of bar 2 and "3 units" between 2 and 4. See below diagram also. Input: arr[] = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] Output: 6 Explanation: The structure is like below Trap "1 unit" between first 1 and 2, "4 units" between first 2 and 3 and "1 unit" between second last 1 and last 2 Basic Insight: An element of the array can store water if there are higher bars on the left and right. The amount of water to be stored in every element can be found by finding the heights of bars on the left and right sides. The idea is to compute the amount of water that can be stored in every element of the array. Example:Consider the array {3, 0, 2, 0, 4}, three units of water can be stored in two indexes 1 and 3, and one unit of water at index 2. For Array[] = {3, 0, 2, 0, 4} Water stored = 0 + 3 + 1 + 3 + 0 = 7 Method 1: This is a simple solution to the above problem. Approach: The idea is to traverse every array element and find the highest bars on the left and right sides. Take the smaller of two heights. The difference between the smaller height and the height of the current element is the amount of water that can be stored in this array element. Algorithm: Traverse the array from start to end.For every element, traverse the array from start to that index and find the maximum height (a) and traverse the array from the current index to end, and find the maximum height (b).The amount of water that will be stored in this column is min(a,b) – array[i], add this value to the total amount of water storedPrint the total amount of water stored. Traverse the array from start to end.For every element, traverse the array from start to that index and find the maximum height (a) and traverse the array from the current index to end, and find the maximum height (b).The amount of water that will be stored in this column is min(a,b) – array[i], add this value to the total amount of water storedPrint the total amount of water stored. Traverse the array from start to end. For every element, traverse the array from start to that index and find the maximum height (a) and traverse the array from the current index to end, and find the maximum height (b). The amount of water that will be stored in this column is min(a,b) – array[i], add this value to the total amount of water stored Print the total amount of water stored. Implementation: C++ C Java Python3 C# Javascript // C++ implementation of the approach#include<bits/stdc++.h> using namespace std; // Function to return the maximum// water that can be storedint maxWater(int arr[], int n) { // To store the maximum water // that can be stored int res = 0; // For every element of the array for (int i = 1; i < n-1; i++) { // Find the maximum element on its left int left = arr[i]; for (int j=0; j<i; j++) left = max(left, arr[j]); // Find the maximum element on its right int right = arr[i]; for (int j=i+1; j<n; j++) right = max(right, arr[j]); // Update the maximum water res = res + (min(left, right) - arr[i]); } return res; } // Driver codeint main() { int arr[] = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << maxWater(arr, n); return 0; } // Implementation in C of the above approach // Importing the required header files#include <stdio.h> // Creating MACRO for finding the maximum number #define max(x, y) (((x) > (y)) ? (x) : (y)) // Creating MACRO for finding the minimum number #define min(x, y) (((x) < (y)) ? (x) : (y)) // Function to return the maximum // water that can be storedint maxWater(int arr[], int n){ // To store the maximum water int res = 0; // For every element of the array for (int i = 0; i < n; i++) { // Find the maximum element on its left int left = arr[i]; for (int j = 0; j < i; j++) { left = max(left, arr[j]); } // Find the maximum element on its left int right = arr[i]; for (int j = i + 1; j < n; j++) { right = max(right, arr[j]); } // Update the result (maximum water) res = res + (min(left, right) - arr[i]); } // return the maximum water return res;} // Driver codeint main(){ int arr[] = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; int n = sizeof(arr) / sizeof(arr[0]); printf("%d", maxWater(arr, n)); return 0;} // This code is contributed by amnindersingh1414. // Java implementation of the approachclass GFG{ // Function to return the maximum// water that can be storedpublic static int maxWater(int[] arr, int n) { // To store the maximum water // that can be stored int res = 0; // For every element of the array // except first and last element for(int i = 1; i < n - 1; i++) { // Find maximum element on its left int left = arr[i]; for(int j = 0; j < i; j++) { left = Math.max(left, arr[j]); } // Find maximum element on its right int right = arr[i]; for(int j = i + 1; j < n; j++) { right = Math.max(right, arr[j]); } // Update maximum water value res += Math.min(left, right) - arr[i]; } return res;} // Driver codepublic static void main(String[] args){ int[] arr = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; int n = arr.length; System.out.print(maxWater(arr,n));}} // This code is contributed by Debidutta Rath # Python3 implementation of the approach # Function to return the maximum # water that can be stored def maxWater(arr, n) : # To store the maximum water # that can be stored res = 0; # For every element of the array for i in range(1, n - 1) : # Find the maximum element on its left left = arr[i]; for j in range(i) : left = max(left, arr[j]); # Find the maximum element on its right right = arr[i]; for j in range(i + 1 , n) : right = max(right, arr[j]); # Update the maximum water res = res + (min(left, right) - arr[i]); return res; # Driver code if __name__ == "__main__" : arr = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]; n = len(arr); print(maxWater(arr, n)); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System; class GFG{ // Function to return the maximum// water that can be storedpublic static int maxWater(int[] arr, int n) { // To store the maximum water // that can be stored int res = 0; // For every element of the array // except first and last element for(int i = 1; i < n - 1; i++) { // Find maximum element on its left int left = arr[i]; for(int j = 0; j < i; j++) { left = Math.Max(left, arr[j]); } // Find maximum element on its right int right = arr[i]; for(int j = i + 1; j < n; j++) { right = Math.Max(right, arr[j]); } // Update maximum water value res += Math.Min(left, right) - arr[i]; } return res;} // Driver codepublic static void Main(String[] args){ int[] arr = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; int n = arr.Length; Console.Write(maxWater(arr,n));}} // This code is contributed by shivanisinghss2110 <script> // Javascript implementation of the approach // Function to return the maximum // water that can be stored function maxWater(arr, n) { // To store the maximum water // that can be stored let res = 0; // For every element of the array // except first and last element for(let i = 1; i < n - 1; i++) { // Find maximum element on its left let left = arr[i]; for(let j = 0; j < i; j++) { left = Math.max(left, arr[j]); } // Find maximum element on its right let right = arr[i]; for(let j = i + 1; j < n; j++) { right = Math.max(right, arr[j]); } // Update maximum water value res += Math.min(left, right) - arr[i]; } return res; } let arr = [ 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 ]; let n = arr.length; document.write(maxWater(arr,n)); </script> 6 Complexity Analysis: Time Complexity: O(n2). There are two nested loops traversing the array, So the time Complexity is O(n2).Space Complexity: O(1). No extra space is required. Time Complexity: O(n2). There are two nested loops traversing the array, So the time Complexity is O(n2). Space Complexity: O(1). No extra space is required. Method 2: This is an efficient solution to the above problem. Approach: In the previous solution, to find the highest bar on the left and right, array traversal is needed, which reduces the efficiency of the solution. To make this efficient, one must pre-compute the highest bar on the left and right of every bar in linear time. Then use these pre-computed values to find the amount of water in every array element. Algorithm: Create two arrays left and right of size n. create a variable max_ = INT_MIN.Run one loop from start to end. In each iteration update max_ as max_ = max(max_, arr[i]) and also assign left[i] = max_Update max_ = INT_MIN.Run another loop from end to start. In each iteration update max_ as max_ = max(max_, arr[i]) and also assign right[i] = max_Traverse the array from start to end.The amount of water that will be stored in this column is min(a,b) – array[i],(where a = left[i] and b = right[i]) add this value to total amount of water storedPrint the total amount of water stored. Create two arrays left and right of size n. create a variable max_ = INT_MIN.Run one loop from start to end. In each iteration update max_ as max_ = max(max_, arr[i]) and also assign left[i] = max_Update max_ = INT_MIN.Run another loop from end to start. In each iteration update max_ as max_ = max(max_, arr[i]) and also assign right[i] = max_Traverse the array from start to end.The amount of water that will be stored in this column is min(a,b) – array[i],(where a = left[i] and b = right[i]) add this value to total amount of water storedPrint the total amount of water stored. Create two arrays left and right of size n. create a variable max_ = INT_MIN. Run one loop from start to end. In each iteration update max_ as max_ = max(max_, arr[i]) and also assign left[i] = max_ Update max_ = INT_MIN. Run another loop from end to start. In each iteration update max_ as max_ = max(max_, arr[i]) and also assign right[i] = max_ Traverse the array from start to end. The amount of water that will be stored in this column is min(a,b) – array[i],(where a = left[i] and b = right[i]) add this value to total amount of water stored Print the total amount of water stored. Implementation: C++ C Java Python3 C# PHP Javascript // C++ program to find maximum amount of water that can// be trapped within given set of bars.#include <bits/stdc++.h>using namespace std; int findWater(int arr[], int n){ // left[i] contains height of tallest bar to the // left of i'th bar including itself int left[n]; // Right [i] contains height of tallest bar to // the right of ith bar including itself int right[n]; // Initialize result int water = 0; // Fill left array left[0] = arr[0]; for (int i = 1; i < n; i++) left[i] = max(left[i - 1], arr[i]); // Fill right array right[n - 1] = arr[n - 1]; for (int i = n - 2; i >= 0; i--) right[i] = max(right[i + 1], arr[i]); // Calculate the accumulated water element by element // consider the amount of water on i'th bar, the // amount of water accumulated on this particular // bar will be equal to min(left[i], right[i]) - arr[i] . for (int i = 1; i < n-1; i++) { int var=min(left[i-1],right[i+1]); if(var > arr[i]) { water += var - arr[i]; } } return water;} // Driver programint main(){ int arr[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Maximum water that can be accumulated is " << findWater(arr, n); return 0;} // Implementation in C of the above approach // Importing the required header files#include <stdio.h> // Creating MACRO for finding the maximum number #define max(x, y) (((x) > (y)) ? (x) : (y)) // Creating MACRO for finding the minimum number #define min(x, y) (((x) < (y)) ? (x) : (y)) // Function to return the maximum // water that can be storedint findWater(int arr[], int n){ // left[i] contains height of tallest bar to the // left of i'th bar including itself int left[n]; // Right [i] contains height of tallest bar to the // right of ith bar including itself int right[n]; // Initialize result int water = 0; // Fill left array left[0] = arr[0]; for (int i = 1; i < n; i++) { left[i] = max(left[i-1], arr[i]); } // Fill right array right[n-1] = arr[n-1]; for (int i = n-2; i >= 0; i--) { right[i] = max(right[i+1], arr[i]); } // Calculate the accumulated water element by element // consider the amount of water on i'th bar, the // amount of water accumulated on this particular // bar will be equal to min(left[i], right[i]) - arr[i] . for (int i = 1; i < n-1; i++){ int var = min(left[i-1], right[i+1]); if (var > arr[i]) { water += var - arr[i]; } } return water;} // Driver programint main(){ int arr[] = {0,1,0,2,1,0,1,3,2,1,2,1}; int n = sizeof(arr)/sizeof(arr[0]); printf("Maximum water that can be accumulated is %d", findWater(arr, n)); return 0;} // This code is contributed by amnindersingh1414. // Java program to find maximum amount of water that can// be trapped within given set of bars. class Test { static int arr[] = new int[] { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; // Method for maximum amount of water static int findWater(int n) { // left[i] contains height of tallest bar to the // left of i'th bar including itself int left[] = new int[n]; // Right [i] contains height of tallest bar to // the right of ith bar including itself int right[] = new int[n]; // Initialize result int water = 0; // Fill left array left[0] = arr[0]; for (int i = 1; i < n; i++) left[i] = Math.max(left[i - 1], arr[i]); // Fill right array right[n - 1] = arr[n - 1]; for (int i = n - 2; i >= 0; i--) right[i] = Math.max(right[i + 1], arr[i]); // Calculate the accumulated water element by element // consider the amount of water on i'th bar, the // amount of water accumulated on this particular // bar will be equal to min(left[i], right[i]) - arr[i] . for (int i = 0; i < n; i++) water += Math.min(left[i], right[i]) - arr[i]; return water; } // Driver method to test the above function public static void main(String[] args) { System.out.println("Maximum water that can be accumulated is " + findWater(arr.length)); }} # Python program to find maximum amount of water that can# be trapped within given set of bars. def findWater(arr, n): # left[i] contains height of tallest bar to the # left of i'th bar including itself left = [0]*n # Right [i] contains height of tallest bar to # the right of ith bar including itself right = [0]*n # Initialize result water = 0 # Fill left array left[0] = arr[0] for i in range( 1, n): left[i] = max(left[i-1], arr[i]) # Fill right array right[n-1] = arr[n-1] for i in range(n-2, -1, -1): right[i] = max(right[i + 1], arr[i]); # Calculate the accumulated water element by element # consider the amount of water on i'th bar, the # amount of water accumulated on this particular # bar will be equal to min(left[i], right[i]) - arr[i] . for i in range(0, n): water += min(left[i], right[i]) - arr[i] return water # Driver program arr = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]n = len(arr)print("Maximum water that can be accumulated is", findWater(arr, n)) # This code is contributed by# Smitha Dinesh Semwal // C# program to find maximum amount of water that can// be trapped within given set of bars.using System; class Test { static int[] arr = new int[] { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; // Method for maximum amount of water static int findWater(int n) { // left[i] contains height of tallest bar to the // left of i'th bar including itself int[] left = new int[n]; // Right [i] contains height of tallest bar to // the right of ith bar including itself int[] right = new int[n]; // Initialize result int water = 0; // Fill left array left[0] = arr[0]; for (int i = 1; i < n; i++) left[i] = Math.Max(left[i - 1], arr[i]); // Fill right array right[n - 1] = arr[n - 1]; for (int i = n - 2; i >= 0; i--) right[i] = Math.Max(right[i + 1], arr[i]); // Calculate the accumulated water element by element // consider the amount of water on i'th bar, the // amount of water accumulated on this particular // bar will be equal to min(left[i], right[i]) - arr[i] . for (int i = 0; i < n; i++) water += Math.Min(left[i], right[i]) - arr[i]; return water; } // Driver method to test the above function public static void Main() { Console.WriteLine("Maximum water that can be accumulated is " + findWater(arr.Length)); }} // This code is contributed by vt_m. <?php// PHP program to find maximum// amount of water that can// be trapped within given set of bars. function findWater($arr, $n){ // left[i] contains height of // tallest bar to the // left of i'th bar including // itself // Right [i] contains height // of tallest bar to the right // of ith bar including itself // $right[$n]; // Initialize result $water = 0; // Fill left array $left[0] = $arr[0]; for ($i = 1; $i < $n; $i++) $left[$i] = max($left[$i - 1], $arr[$i]); // Fill right array $right[$n - 1] = $arr[$n - 1]; for ($i = $n - 2; $i >= 0; $i--) $right[$i] = max($right[$i + 1], $arr[$i]); // Calculate the accumulated // water element by element // consider the amount of // water on i'th bar, the // amount of water accumulated // on this particular // bar will be equal to min(left[i], // right[i]) - arr[i] . for ($i = 0; $i < $n; $i++) $water += min($left[$i], $right[$i]) - $arr[$i]; return $water;} // Driver program $arr = array(0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1); $n = sizeof($arr); echo "Maximum water that can be accumulated is ", findWater($arr, $n); // This code is contributed by ajit?> <script>// Javascript program to find maximum amount of water that can// be trapped within given set of bars. let arr = [ 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 ]; // Method for maximum amount of water function findWater(n) { // left[i] contains height of tallest bar to the // left of i'th bar including itself let left = new Array(n); // Right [i] contains height of tallest bar to // the right of ith bar including itself let right = new Array(n); // Initialize result let water = 0; // Fill left array left[0] = arr[0]; for (let i = 1; i < n; i++) left[i] = Math.max(left[i - 1], arr[i]); // Fill right array right[n - 1] = arr[n - 1]; for (let i = n - 2; i >= 0; i--) right[i] = Math.max(right[i + 1], arr[i]); // Calculate the accumulated water element by element // consider the amount of water on i'th bar, the // amount of water accumulated on this particular // bar will be equal to min(left[i], right[i]) - arr[i] . for (let i = 0; i < n; i++) water += Math.min(left[i], right[i]) - arr[i]; return water; } // Driver method to test the above function document.write("Maximum water that can be accumulated is " + findWater(arr.length)); // This code is contributed by unknown2108</script> Maximum water that can be accumulated is 6 Complexity Analysis: Time Complexity: O(n). Only one traversal of the array is needed, So time Complexity is O(n).Space Complexity: O(n). Two extra arrays are needed, each of size n. Time Complexity: O(n). Only one traversal of the array is needed, So time Complexity is O(n). Space Complexity: O(n). Two extra arrays are needed, each of size n. Space Optimization for the above Solution: Instead of maintaining two arrays of size n for storing the left and a right max of each element, maintain two variables to store the maximum till that point. Since water trapped at any element = min(max_left, max_right) – arr[i]. Calculate water trapped on smaller elements out of A[lo] and A[hi] first, and move the pointers till lo doesn’t cross hi. Implementation: C++ Java Python3 C# PHP Javascript C // C++ program to find maximum amount of water that can// be trapped within given set of bars.// Space Complexity : O(1) #include <iostream>using namespace std; int findWater(int arr[], int n){ // initialize output int result = 0; // maximum element on left and right int left_max = 0, right_max = 0; // indices to traverse the array int lo = 0, hi = n - 1; while (lo <= hi) { if (arr[lo] < arr[hi]) { if (arr[lo] > left_max) // update max in left left_max = arr[lo]; else // water on curr element = max - curr result += left_max - arr[lo]; lo++; } else { if (arr[hi] > right_max) // update right maximum right_max = arr[hi]; else result += right_max - arr[hi]; hi--; } } return result;} int main(){ int arr[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Maximum water that can be accumulated is " << findWater(arr, n);} // This code is contributed by Aditi Sharma // JAVA Code For Trapping Rain Waterimport java.util.*; class GFG { static int findWater(int arr[], int n) { // initialize output int result = 0; // maximum element on left and right int left_max = 0, right_max = 0; // indices to traverse the array int lo = 0, hi = n - 1; while (lo <= hi) { if (arr[lo] < arr[hi]) { if (arr[lo] > left_max) // update max in left left_max = arr[lo]; else // water on curr element = // max - curr result += left_max - arr[lo]; lo++; } else { if (arr[hi] > right_max) // update right maximum right_max = arr[hi]; else result += right_max - arr[hi]; hi--; } } return result; } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; int n = arr.length; System.out.println("Maximum water that " + "can be accumulated is " + findWater(arr, n)); }}// This code is contributed by Arnav Kr. Mandal. # Python program to find# maximum amount of water that can# be trapped within given set of bars.# Space Complexity : O(1) def findWater(arr, n): # initialize output result = 0 # maximum element on left and right left_max = 0 right_max = 0 # indices to traverse the array lo = 0 hi = n-1 while(lo <= hi): if(arr[lo] < arr[hi]): if(arr[lo] > left_max): # update max in left left_max = arr[lo] else: # water on curr element = max - curr result += left_max - arr[lo] lo+= 1 else: if(arr[hi] > right_max): # update right maximum right_max = arr[hi] else: result += right_max - arr[hi] hi-= 1 return result # Driver program arr = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]n = len(arr) print("Maximum water that can be accumulated is ", findWater(arr, n)) # This code is contributed# by Anant Agarwal. // C# Code For Trapping Rain Waterusing System; class GFG { static int findWater(int[] arr, int n) { // initialize output int result = 0; // maximum element on left and right int left_max = 0, right_max = 0; // indices to traverse the array int lo = 0, hi = n - 1; while (lo <= hi) { if (arr[lo] < arr[hi]) { if (arr[lo] > left_max) // update max in left left_max = arr[lo]; else // water on curr element = // max - curr result += left_max - arr[lo]; lo++; } else { if (arr[hi] > right_max) // update right maximum right_max = arr[hi]; else result += right_max - arr[hi]; hi--; } } return result; } // Driver program public static void Main() { int[] arr = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; int result = Trap.findWater(arr, arr.length); System.out.print(" Total trapping water: " + result); }} // This code is contributed by vt_m. <?php// PHP program to find maximum amount// of water that can be trapped within // given set of bars. // Method to find maximum amount// of water that can be trapped within // given set of bars.function findWater($arr, $n){ // initialize output $result = 0; // maximum element on // left and right $left_max = 0; $right_max = 0; // indices to traverse // the array $lo = 0; $hi = $n - 1; while($lo <= $hi) { if($arr[$lo] < $arr[$hi]) { if($arr[$lo] > $left_max) // update max in left $left_max = $arr[$lo]; else // water on curr // element = max - curr $result += $left_max - $arr[$lo]; $lo++; } else { if($arr[$hi] > $right_max) // update right maximum $right_max = $arr[$hi]; else $result += $right_max - $arr[$hi]; $hi--; } } return $result;} // Driver Code $arr = array(0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1); $n = count($arr); echo "Maximum water that can be accumulated is ", findWater($arr, $n); // This code is contributed by anuj_67.?> <script>// JAVASCRIPT Code For Trapping Rain Water function findWater(arr,n){ // initialize output let result = 0; // maximum element on left and right let left_max = 0, right_max = 0; // indices to traverse the array let lo = 0, hi = n - 1; while (lo <= hi) { if (arr[lo] < arr[hi]) { if (arr[lo] > left_max) // update max in left left_max = arr[lo]; else // water on curr element = // max - curr result += left_max - arr[lo]; lo++; } else { if (arr[hi] > right_max) // update right maximum right_max = arr[hi]; else result += right_max - arr[hi]; hi--; } } return result;} /* Driver program to test above function */let arr=[0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1];let n = arr.length;document.write("Maximum water that " + "can be accumulated is " + findWater(arr, n)); // This code is contributed by ab2127</script> // Implementation in C of the above approach // Importing the required header files#include <stdio.h> // Creating MACRO for finding the maximum number #define max(x, y) (((x) > (y)) ? (x) : (y)) // Creating MACRO for finding the minimum number #define min(x, y) (((x) < (y)) ? (x) : (y)) // Function to return the maximum // water that can be storedint findWater(int arr[], int n){ // initialize output int result = 0; //maximum element on left and right int left_max = 0, right_max = 0; // indices to traverse the array int lo = 0, hi = n-1; while (lo <= hi){ if (arr[lo] < arr[hi]){ if(arr[lo] > left_max){ // update left max left_max = arr[lo];} else // water on curr element = max - curr {result += left_max - arr[lo];} lo++; } else{ if(arr[hi] > right_max){ // update right max right_max = arr[hi]; } else // water on curr element = max - curr {result += right_max - arr[hi];} hi--; } } return result;} // Driver codeint main(){ int arr[] = {0,1,0,2,1,0,1,3,2,1,2,1}; int n = sizeof(arr)/sizeof(arr[0]); printf("Maximum water that can be accumulated is %d", findWater(arr, n)); return 0;} Maximum water that can be accumulated is 6 Complexity Analysis: Time Complexity: O(n). Only one traversal of the array is needed.Auxiliary Space: O(1). As no extra space is required. Time Complexity: O(n). Only one traversal of the array is needed. Auxiliary Space: O(1). As no extra space is required. Thanks to Gaurav Ahirwar and Aditi Sharma for the above solution. Method 3: Here another efficient solution has been shown. Approach: The concept here is that if there is a larger wall to the right, then the water can be retained with a height equal to the smaller wall on the left. If there are no larger walls to the right, then start from the left. There must be a larger wall to the left now. Let’s take an example of the heights are {....,3, 2, 1, 4,....}, So here 3 and 4 are boundaries the heights 2 and 1 are submerged and cannot act as boundaries. So at any point or index knowing the previous boundary is sufficient if there is a higher or equal length boundary in the remaining part of the array. If not, then traverse the array backward and now must be a larger wall to the left. Algorithm: Loop from index 0 to the end of the given array.If a wall greater than or equal to the previous wall is encountered, then make note of the index of that wall in a var called prev_index.Keep adding the previous wall’s height minus the current (ith) wall to the variable water.Have a temporary variable that stores the same value as water.If no wall greater than or equal to the previous wall is found, then quit.If prev_index < size of the input array, then subtract the temp variable from water, and loop from the end of the input array to prev_index. Find a wall greater than or equal to the previous wall (in this case, the last wall from backward). Loop from index 0 to the end of the given array. If a wall greater than or equal to the previous wall is encountered, then make note of the index of that wall in a var called prev_index. Keep adding the previous wall’s height minus the current (ith) wall to the variable water. Have a temporary variable that stores the same value as water. If no wall greater than or equal to the previous wall is found, then quit. If prev_index < size of the input array, then subtract the temp variable from water, and loop from the end of the input array to prev_index. Find a wall greater than or equal to the previous wall (in this case, the last wall from backward). Implementation: C++ Java Python3 C# Javascript C // C++ implementation of the approach#include<iostream>using namespace std; // Function to return the maximum// water that can be storedint maxWater(int arr[], int n){ int size = n - 1; // Let the first element be stored as // previous, we shall loop from index 1 int prev = arr[0]; // To store previous wall's index int prev_index = 0; int water = 0; // To store the water until a larger wall // is found, if there are no larger walls // then delete temp value from water int temp = 0; for(int i = 1; i <= size; i++) { // If the current wall is taller than // the previous wall then make current // wall as the previous wall and its // index as previous wall's index // for the subsequent loops if (arr[i] >= prev) { prev = arr[i]; prev_index = i; // Because larger or same // height wall is found temp = 0; } else { // Since current wall is shorter than // the previous, we subtract previous // wall's height from the current wall's // height and add it to the water water += prev - arr[i]; // Store the same value in temp as well // If we dont find any larger wall then // we will subtract temp from water temp += prev - arr[i]; } } // If the last wall was larger than or equal // to the previous wall then prev_index would // be equal to size of the array (last element) // If we didn't find a wall greater than or equal // to the previous wall from the left then // prev_index must be less than the index // of the last element if(prev_index < size) { // Temp would've stored the water collected // from previous largest wall till the end // of array if no larger wall was found then // it has excess water and remove that // from water variable water -= temp; // We start from the end of the array, // so previous should be assigned to // the last element prev = arr[size]; // Loop from the end of array up to the // previous index which would contain // the largest wall from the left for(int i = size; i >= prev_index; i--) { // Right end wall will be definitely // smaller than the 'previous index' wall if(arr[i] >= prev) { prev = arr[i]; } else { water += prev - arr[i]; } } } // Return the maximum water return water;} // Driver Codeint main(){ int arr[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxWater(arr, n); return 0;} // This code is contributed by Debidutta Rath // Java implementation of the approachclass GFG { // Function to return the maximum // water that can be stored public static int maxWater(int arr[], int n) { int size = n - 1; // Let the first element be stored as // previous, we shall loop from index 1 int prev = arr[0]; // To store previous wall's index int prev_index = 0; int water = 0; // To store the water until a larger wall // is found, if there are no larger walls // then delete temp value from water int temp = 0; for (int i = 1; i <= size; i++) { // If the current wall is taller than // the previous wall then make current // wall as the previous wall and its // index as previous wall's index // for the subsequent loops if (arr[i] >= prev) { prev = arr[i]; prev_index = i; // Because larger or same height wall is found temp = 0; } else { // Since current wall is shorter than // the previous, we subtract previous // wall's height from the current wall's // height and add it to the water water += prev - arr[i]; // Store the same value in temp as well // If we dont find any larger wall then // we will subtract temp from water temp += prev - arr[i]; } } // If the last wall was larger than or equal // to the previous wall then prev_index would // be equal to size of the array (last element) // If we didn't find a wall greater than or equal // to the previous wall from the left then // prev_index must be less than the index // of the last element if (prev_index < size) { // Temp would've stored the water collected // from previous largest wall till the end // of array if no larger wall was found then // it has excess water and remove that // from 'water' var water -= temp; // We start from the end of the array, so previous // should be assigned to the last element prev = arr[size]; // Loop from the end of array up to the 'previous index' // which would contain the "largest wall from the left" for (int i = size; i >= prev_index; i--) { // Right end wall will be definitely smaller // than the 'previous index' wall if (arr[i] >= prev) { prev = arr[i]; } else { water += prev - arr[i]; } } } // Return the maximum water return water; } // Driver code public static void main(String[] args) { int arr[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; int n = arr.length; System.out.print(maxWater(arr, n)); }} # Python3 implementation of the approach # Function to return the maximum# water that can be storeddef maxWater(arr, n): size = n - 1 # Let the first element be stored as # previous, we shall loop from index 1 prev = arr[0] # To store previous wall's index prev_index = 0 water = 0 # To store the water until a larger wall # is found, if there are no larger walls # then delete temp value from water temp = 0 for i in range(1, size + 1): # If the current wall is taller than # the previous wall then make current # wall as the previous wall and its # index as previous wall's index # for the subsequent loops if (arr[i] >= prev): prev = arr[i] prev_index = i # Because larger or same height wall is found temp = 0 else: # Since current wall is shorter than # the previous, we subtract previous # wall's height from the current wall's # height and add it to the water water += prev - arr[i] # Store the same value in temp as well # If we dont find any larger wall then # we will subtract temp from water temp += prev - arr[i] # If the last wall was larger than or equal # to the previous wall then prev_index would # be equal to size of the array (last element) # If we didn't find a wall greater than or equal # to the previous wall from the left then # prev_index must be less than the index # of the last element if (prev_index < size): # Temp would've stored the water collected # from previous largest wall till the end # of array if no larger wall was found then # it has excess water and remove that # from 'water' var water -= temp # We start from the end of the array, so previous # should be assigned to the last element prev = arr[size] # Loop from the end of array up to the 'previous index' # which would contain the "largest wall from the left" for i in range(size, prev_index - 1, -1): # Right end wall will be definitely smaller # than the 'previous index' wall if (arr[i] >= prev): prev = arr[i] else: water += prev - arr[i] # Return the maximum water return water # Driver codearr = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]n = len(arr)print(maxWater(arr, n)) # This code is contributed by Mohit Kumar // C# implementation of the approachusing System;class GFG{ // Function to return the maximum // water that can be stored static int maxWater(int[] arr, int n) { int size = n - 1; // Let the first element be stored as // previous, we shall loop from index 1 int prev = arr[0]; // To store previous wall's index int prev_index = 0; int water = 0; // To store the water until a larger wall // is found, if there are no larger walls // then delete temp value from water int temp = 0; for(int i = 1; i <= size; i++) { // If the current wall is taller than // the previous wall then make current // wall as the previous wall and its // index as previous wall's index // for the subsequent loops if (arr[i] >= prev) { prev = arr[i]; prev_index = i; // Because larger or same // height wall is found temp = 0; } else { // Since current wall is shorter than // the previous, we subtract previous // wall's height from the current wall's // height and add it to the water water += prev - arr[i]; // Store the same value in temp as well // If we dont find any larger wall then // we will subtract temp from water temp += prev - arr[i]; } } // If the last wall was larger than or equal // to the previous wall then prev_index would // be equal to size of the array (last element) // If we didn't find a wall greater than or equal // to the previous wall from the left then // prev_index must be less than the index // of the last element if(prev_index < size) { // Temp would've stored the water collected // from previous largest wall till the end // of array if no larger wall was found then // it has excess water and remove that // from water variable water -= temp; // We start from the end of the array, // so previous should be assigned to // the last element prev = arr[size]; // Loop from the end of array up to the // previous index which would contain // the largest wall from the left for(int i = size; i >= prev_index; i--) { // Right end wall will be definitely // smaller than the 'previous index' wall if(arr[i] >= prev) { prev = arr[i]; } else { water += prev - arr[i]; } } } // Return the maximum water return water; } // Driver code static void Main() { int[] arr = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; int n = arr.Length; Console.WriteLine(maxWater(arr, n)); }} // This code is contributed by divyesh072019 <script> // JavaScript implementation of the approach // Function to return the maximum // water that can be stored function maxWater(arr,n) { let size = n - 1; // Let the first element be stored as // previous, we shall loop from index 1 let prev = arr[0]; // To store previous wall's index let prev_index = 0; let water = 0; // To store the water until a larger wall // is found, if there are no larger walls // then delete temp value from water let temp = 0; for (let i = 1; i <= size; i++) { // If the current wall is taller than // the previous wall then make current // wall as the previous wall and its // index as previous wall's index // for the subsequent loops if (arr[i] >= prev) { prev = arr[i]; prev_index = i; // Because larger or same height wall is found temp = 0; } else { // Since current wall is shorter than // the previous, we subtract previous // wall's height from the current wall's // height and add it to the water water += prev - arr[i]; // Store the same value in temp as well // If we dont find any larger wall then // we will subtract temp from water temp += prev - arr[i]; } } // If the last wall was larger than or equal // to the previous wall then prev_index would // be equal to size of the array (last element) // If we didn't find a wall greater than or equal // to the previous wall from the left then // prev_index must be less than the index // of the last element if (prev_index < size) { // Temp would've stored the water collected // from previous largest wall till the end // of array if no larger wall was found then // it has excess water and remove that // from 'water' var water -= temp; // We start from the end of the array, so previous // should be assigned to the last element prev = arr[size]; // Loop from the end of array up to the 'previous index' // which would contain the "largest wall from the left" for (let i = size; i >= prev_index; i--) { // Right end wall will be definitely smaller // than the 'previous index' wall if (arr[i] >= prev) { prev = arr[i]; } else { water += prev - arr[i]; } } } // Return the maximum water return water; } // Driver code let arr=[ 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]; let n = arr.length; document.write(maxWater(arr, n)); // This code is contributed by patel2127 </script> // Implementation in C of the above approach // Importing the required header files#include <stdio.h> // Creating MACRO for finding the maximum number #define max(x, y)(((x) > (y)) ? (x) : (y)) // Creating MACRO for finding the minimum number #define min(x, y)(((x) < (y)) ? (x) : (y)) // Function to return the maximum // water that can be storedint maxWater(int arr[], int n) { int size = n - 1; // Let the first element be stored as // previous, we shall loop from index 1 int prev = arr[0]; // To store previous wall's index int prev_index = 0; int water = 0; // To store the water until a larger wall // is found, if there are no larger walls // then delete temp value from water int temp = 0; for (int i = 1; i <= size; i++) { // If the current wall is taller than // the previous wall then make current // wall as the previous wall and its // index as previous wall's index // for the subsequent loops if (arr[i] >= prev) { prev = arr[i]; prev_index = i; // Because larger or same // height wall is found temp = 0; } else { // Since current wall is shorter than // the previous, we subtract previous // wall's height from the current wall's // height and add it to the water water += prev - arr[i]; // Store the same value in temp as well // If we dont find any larger wall then // we will subtract temp from water temp += prev - arr[i]; } } // If the last wall was larger than or equal // to the previous wall then prev_index would // be equal to size of the array (last element) // If we didn't find a wall greater than or equal // to the previous wall from the left then // prev_index must be less than the index // of the last element if (prev_index < size) { // Temp would've stored the water collected // from previous largest wall till the end // of array if no larger wall was found then // it has excess water and remove that // from water variable water -= temp; // We start from the end of the array, // so previous should be assigned to // the last element prev = arr[size]; // Loop from the end of array up to the // previous index which would contain // the largest wall from the left for (int i = size; i >= prev_index; i--) { // Right end wall will be definitely // smaller than the 'previous index' wall if (arr[i] >= prev) { prev = arr[i]; } else { water += prev - arr[i]; } } } // Return the maximum water return water;} // driver code int main() { int arr[] = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; int n = sizeof(arr) / sizeof(arr[0]); printf("%d", maxWater(arr, n)); return 0;} 6 Complexity Analysis: Time Complexity: O(n). As only one traversal of the array is needed.Auxiliary Space: O(1). As no extra space is required. Time Complexity: O(n). As only one traversal of the array is needed. Auxiliary Space: O(1). As no extra space is required. Method 4 (Using Stack): We can use a Stack to track the bars that are bounded by the longer left and right bars. This can be done using only one iteration using stacks. Approach: 1. Loop through the indices of the bar array. 2. For each bar, we can do the following: While the Stack is not empty and the current bar has a height greater than the top bar of the stack, Store the index of the top bar in pop_height and pop it from the Stack. Find the distance between the left bar(current top) of the popped bar and the current bar. Find the minimum height between the top bar and the current bar. The maximum water that can be trapped in distance * min_height. The water trapped, including the popped bar, is (distance * min_height) – height[pop_height]. Add that to the fans. 3. Final answer will the ans. C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h> using namespace std; // Function to return the maximum// water that can be storedint maxWater(int height[], int n){ // Stores the indices of the bars stack <int> st; // Stores the final result int ans = 0; // Loop through the each bar for(int i = 0; i < n; i++) { // Remove bars from the stack // until the condition holds while ((!st.empty()) && (height[st.top()] < height[i])) { // Store the height of the top // and pop it. int pop_height = height[st.top()]; st.pop(); // If the stack does not have any // bars or the popped bar // has no left boundary if (st.empty()) break; // Get the distance between the // left and right boundary of // popped bar int distance = i - st.top() - 1; // Calculate the min. height int min_height = min(height[st.top()], height[i]) - pop_height; ans += distance * min_height; } // If the stack is either empty or // height of the current bar is less than // or equal to the top bar of stack st.push(i); } return ans;} // Driver codeint main() { int arr[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxWater(arr, n); return 0;} // The code is contributed by Soumitri Chattopadhyay import java.util.*;import java.io.*; // Java implementation of the approachclass GFG { // Function to return the maximum // water that can be stored public static int maxWater(int[] height) { // Stores the indices of the bars Stack<Integer> stack = new Stack<>(); // size of the array int n = height.length; // Stores the final result int ans = 0; // Loop through the each bar for (int i = 0; i < n; i++) { // Remove bars from the stack // until the condition holds while ((!stack.isEmpty()) && (height[stack.peek()] < height[i])) { // store the height of the top // and pop it. int pop_height = height[stack.peek()]; stack.pop(); // If the stack does not have any // bars or the popped bar // has no left boundary if (stack.isEmpty()) break; // Get the distance between the // left and right boundary of // popped bar int distance = i - stack.peek() - 1; // Calculate the min. height int min_height = Math.min(height[stack.peek()], height[i]) - pop_height; ans += distance * min_height; } // If the stack is either empty or // height of the current bar is less than // or equal to the top bar of stack stack.push(i); } return ans; } // Driver code public static void main(String[] args) { int arr[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; System.out.print(maxWater(arr)); }} # Python implementation of the approach # Function to return the maximum# water that can be storeddef maxWater(height): # Stores the indices of the bars stack = [] # size of the array n = len(height) # Stores the final result ans = 0 # Loop through the each bar for i in range(n): # Remove bars from the stack # until the condition holds while(len(stack) != 0 and (height[stack[-1]] < height[i]) ): # store the height of the top # and pop it. pop_height = height[stack[-1]] stack.pop() # If the stack does not have any # bars or the popped bar # has no left boundary if(len(stack) == 0): break # Get the distance between the # left and right boundary of # popped bar distance = i - stack[-1] - 1 # Calculate the min. height min_height = min(height[stack[-1]],height[i])-pop_height ans += distance * min_height # If the stack is either empty or # height of the current bar is less than # or equal to the top bar of stack stack.append(i) return ans # Driver codearr=[ 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]print(maxWater(arr)) # This code is contributed by rag2127 using System;using System.Collections;using System.Collections.Generic; // C# implementation of the approachclass GFG { // Function to return the maximum // water that can be stored public static int maxWater(int[] height) { // Stores the indices of the bars Stack stack = new Stack(); // size of the array int n = height.Length; // Stores the final result int ans = 0; // Loop through the each bar for (int i = 0; i < n; i++) { // Remove bars from the stack // until the condition holds while ((stack.Count!=0) && (height[(int)stack.Peek()] < height[i])) { // store the height of the top // and pop it. int pop_height = height[(int)stack.Peek()]; stack.Pop(); // If the stack does not have any // bars or the popped bar // has no left boundary if (stack.Count == 0) break; // Get the distance between the // left and right boundary of // popped bar int distance = i - (int)stack.Peek() - 1; // Calculate the min. height int min_height = Math.Min(height[(int)stack.Peek()], height[i]) - pop_height; ans += distance * min_height; } // If the stack is either empty or // height of the current bar is less than // or equal to the top bar of stack stack.Push(i); } return ans; } // Driver code public static void Main() { int []arr = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; Console.Write(maxWater(arr)); }} // This code is contributed by pratham76. <script> // Python implementation of the approach // Function to return the maximum// water that can be storedfunction maxWater(height){ // Stores the indices of the bars let stack = [] // size of the array let n = height.length // Stores the final result let ans = 0 // Loop through the each bar for(let i=0;i<n;i++){ // Remove bars from the stack // until the condition holds while(stack.length != 0 && (height[stack[stack.length-1]] < height[i]) ){ // store the height of the top // and pop it. let pop_height = height[stack.pop()] // If the stack does not have any // bars or the popped bar // has no left boundary if(stack.length == 0) break // Get the distance between the // left and right boundary of // popped bar let distance = i - stack[stack.length - 1] - 1 // Calculate the min. height let min_height =Math.min(height[stack[stack.length - 1]],height[i])-pop_height ans += distance * min_height } // If the stack is either empty or // height of the current bar is less than // or equal to the top bar of stack stack.push(i) } return ans} // Driver codelet arr = [ 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]document.write(maxWater(arr)) // This code is contributed by shinjanpatra </script> 6 Time Complexity: O(n)Auxiliary Space: O(n) Method 5 (Two Pointer Approach) Approach: At every index, The amount of rainwater stored is the difference between the current index height and a minimum of left max height and right max-height Algorithm :Take two pointers l and r. Initialize l to the starting index 0 and r to the last index n-1Since l is the first element, left_max would be 0, and right max for r would be 0While l <= r, iterate the array. We have two possible conditionsCondition1 : left_max <= right maxConsider Element at index lSince we have traversed all elements to the left of l, left_max is known For the right max of l, We can say that the right max would always be >= current r_max hereSo, min(left_max,right_max) would always equal to left_max in this caseIncrement lCondition2 : left_max > right maxConsider Element at index rSince we have traversed all elements to the right of r, right_max is knownFor the left max of l, We can say that the left max would always be >= current l_max hereSo, min(left_max,right_max) would always equal to right_max in this caseDecrement r Take two pointers l and r. Initialize l to the starting index 0 and r to the last index n-1 Since l is the first element, left_max would be 0, and right max for r would be 0 While l <= r, iterate the array. We have two possible conditions Condition1 : left_max <= right maxConsider Element at index lSince we have traversed all elements to the left of l, left_max is known For the right max of l, We can say that the right max would always be >= current r_max hereSo, min(left_max,right_max) would always equal to left_max in this caseIncrement l Consider Element at index l Since we have traversed all elements to the left of l, left_max is known For the right max of l, We can say that the right max would always be >= current r_max here So, min(left_max,right_max) would always equal to left_max in this case Increment l Condition2 : left_max > right maxConsider Element at index rSince we have traversed all elements to the right of r, right_max is knownFor the left max of l, We can say that the left max would always be >= current l_max hereSo, min(left_max,right_max) would always equal to right_max in this caseDecrement r Consider Element at index r Since we have traversed all elements to the right of r, right_max is known For the left max of l, We can say that the left max would always be >= current l_max here So, min(left_max,right_max) would always equal to right_max in this case Decrement r Implementation: C++ Java Python3 C# Javascript C // C++ implementation of the approach#include <iostream>using namespace std; int maxWater(int arr[], int n){ // indices to traverse the array int left = 0; int right = n-1; // To store Left max and right max // for two pointers left and right int l_max = 0; int r_max = 0; // To store the total amount // of rain water trapped int result = 0; while (left <= right) { // We need check for minimum of left // and right max for each element if(r_max <= l_max) { // Add the difference between // current value and right max at index r result += max(0, r_max-arr[right]); // Update right max r_max = max(r_max, arr[right]); // Update right pointer right -= 1; } else { // Add the difference between // current value and left max at index l result += max(0, l_max-arr[left]); // Update left max l_max = max(l_max, arr[left]); // Update left pointer left += 1; } } return result;} // Driver codeint main() { int arr[] = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << maxWater(arr, n) << endl; return 0;} // This code is contributed by avanitrachhadiya2155 // Java implementation of the approachimport java.util.*; class GFG { static int maxWater(int[] arr, int n) { // indices to traverse the array int left = 0; int right = n - 1; // To store Left max and right max // for two pointers left and right int l_max = 0; int r_max = 0; // To store the total amount // of rain water trapped int result = 0; while (left <= right) { // We need check for minimum of left // and right max for each element if(r_max <= l_max) { // Add the difference between // current value and right max at index r result += Math.max(0, r_max-arr[right]); // Update right max r_max = Math.max(r_max, arr[right]); // Update right pointer right -= 1; } else { // Add the difference between // current value and left max at index l result += Math.max(0, l_max-arr[left]); // Update left max l_max = Math.max(l_max, arr[left]); // Update left pointer left += 1; } } return result; } // Driver code public static void main(String []args) { int[] arr = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; int n = arr.length; System.out.print(maxWater(arr, n)); }} // This code is contributed by rutvik_56. # Python3 implementation of the approach # Function to return the maximum# water that can be stored def maxWater(arr, n): # indices to traverse the array left = 0 right = n-1 # To store Left max and right max # for two pointers left and right l_max = 0 r_max = 0 # To store the total amount # of rain water trapped result = 0 while (left <= right): # We need check for minimum of left # and right max for each element if r_max <= l_max: # Add the difference between #current value and right max at index r result += max(0, r_max-arr[right]) # Update right max r_max = max(r_max, arr[right]) # Update right pointer right -= 1 else: # Add the difference between # current value and left max at index l result += max(0, l_max-arr[left]) # Update left max l_max = max(l_max, arr[left]) # Update left pointer left += 1 return result # Driver codearr = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]n = len(arr)print(maxWater(arr, n)) # This code is contributed by Nikhil Chatragadda // C# implementation of the approachusing System;class GFG { static int maxWater(int[] arr, int n) { // indices to traverse the array int left = 0; int right = n-1; // To store Left max and right max // for two pointers left and right int l_max = 0; int r_max = 0; // To store the total amount // of rain water trapped int result = 0; while (left <= right) { // We need check for minimum of left // and right max for each element if(r_max <= l_max) { // Add the difference between // current value and right max at index r result += Math.Max(0, r_max-arr[right]); // Update right max r_max = Math.Max(r_max, arr[right]); // Update right pointer right -= 1; } else { // Add the difference between // current value and left max at index l result += Math.Max(0, l_max-arr[left]); // Update left max l_max = Math.Max(l_max, arr[left]); // Update left pointer left += 1; } } return result; } // Driver code static void Main() { int[] arr = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; int n = arr.Length; Console.WriteLine(maxWater(arr, n)); }} // This code is contributed by divyeshrabadiya07. <script> // Javascript implementation of the approachfunction maxWater(arr, n){ // indices to traverse the array let left = 0; let right = n - 1; // To store Left max and right max // for two pointers left and right let l_max = 0; let r_max = 0; // To store the total amount // of rain water trapped let result = 0; while (left <= right) { // We need check for minimum of left // and right max for each element if(r_max <= l_max) { // Add the difference between // current value and right max at index r result += Math.max(0, r_max - arr[right]); // Update right max r_max = Math.max(r_max, arr[right]); // Update right pointer right -= 1; } else { // Add the difference between // current value and left max at index l result += Math.max(0, l_max - arr[left]); // Update left max l_max = Math.max(l_max, arr[left]); // Update left pointer left += 1; } } return result;} // Driver code let arr = [ 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 ];let n = arr.length; document.write(maxWater(arr, n)); // This code is contributed by suresh07 </script> // Implementation in C of the above approach // Importing the required header files#include <stdio.h> // Creating MACRO for finding the maximum number #define max(x, y)(((x) > (y)) ? (x) : (y)) // Creating MACRO for finding the minimum number #define min(x, y)(((x) < (y)) ? (x) : (y)) // Function to return the maximum int maxWater(int arr[], int n){ // indices to traverse the array int left = 0; int right = n-1; // To store Left max and right max // for two pointers left and right int l_max = 0; int r_max = 0; // To store the total amount // of rain water trapped int result = 0; while (left <= right) { // We need check for minimum of left // and right max for each element if(r_max <= l_max) { // Add the difference between // current value and right max at index r result += max(0, r_max-arr[right]); // Update right max r_max = max(r_max, arr[right]); // Update right pointer right -= 1; } else { // Add the difference between // current value and left max at index l result += max(0, l_max-arr[left]); // Update left max l_max = max(l_max, arr[left]); // Update left pointer left += 1; } } return result;} // driver code int main() { int arr[] = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; int n = sizeof(arr) / sizeof(arr[0]); printf("%d", maxWater(arr, n)); return 0;} 6 Time Complexity: O(n)Auxiliary Space: O(1) Method 6 (horizontal scan method) Approach If max_height is the height of the tallest block, then it will be the maximum possible height for any trapped rainwater. And if we traverse each row from left to right for each row from bottom to max_height, we can count the number of blocks that will contain water. AlgorithmFind the total number of blocks, i.e., sum of the heights array, num_blocksfind the maximum height, max_heightstore total water in a variable, total = 0keep two pointers, left = 0 and right = n -1, we will use them laterfor each row i from 0 to max_height, do the followingScan heights array from left to right, if height > i (current row), this will be the boundary of one of the sections of trapped water, let us store these indexes.Let the boundary indexes be boundary = [i1, i2, i3 ...]The water stored in current row between i1 and i2 = i2 – i1 – 1, between i2 and i3 = i3 – i2 – 1 and so on.Total water stored in current row = (i2 – i1 – 1) + (i3 – i2 – 1) + ... (in – in-1 -1) = in – i1 – (k – 1), where k in number of blocks in this rowif we find i1 and in i.e., first and last boundary index of each row, we don’t need to scan the whole array. We will not find k, since it is a number of blocks in current row, it will accumulate and it will add up to total number of blocks, which we have found already, and the 1 will accumulate for each row, i.e., it will become max_heightfind i1 by traversing from left towards right till you find h where h > i (current row), similarly, find in by traversing from right towards left.Set left = i1 and right = in and add in – i1 to totalsubtract num_blocks – max_height from total, which was accumulatedtotal will be the quantity of trapped water Find the total number of blocks, i.e., sum of the heights array, num_blocks find the maximum height, max_height store total water in a variable, total = 0 keep two pointers, left = 0 and right = n -1, we will use them later for each row i from 0 to max_height, do the followingScan heights array from left to right, if height > i (current row), this will be the boundary of one of the sections of trapped water, let us store these indexes.Let the boundary indexes be boundary = [i1, i2, i3 ...]The water stored in current row between i1 and i2 = i2 – i1 – 1, between i2 and i3 = i3 – i2 – 1 and so on.Total water stored in current row = (i2 – i1 – 1) + (i3 – i2 – 1) + ... (in – in-1 -1) = in – i1 – (k – 1), where k in number of blocks in this rowif we find i1 and in i.e., first and last boundary index of each row, we don’t need to scan the whole array. We will not find k, since it is a number of blocks in current row, it will accumulate and it will add up to total number of blocks, which we have found already, and the 1 will accumulate for each row, i.e., it will become max_heightfind i1 by traversing from left towards right till you find h where h > i (current row), similarly, find in by traversing from right towards left.Set left = i1 and right = in and add in – i1 to total Scan heights array from left to right, if height > i (current row), this will be the boundary of one of the sections of trapped water, let us store these indexes. Let the boundary indexes be boundary = [i1, i2, i3 ...] The water stored in current row between i1 and i2 = i2 – i1 – 1, between i2 and i3 = i3 – i2 – 1 and so on. Total water stored in current row = (i2 – i1 – 1) + (i3 – i2 – 1) + ... (in – in-1 -1) = in – i1 – (k – 1), where k in number of blocks in this row if we find i1 and in i.e., first and last boundary index of each row, we don’t need to scan the whole array. We will not find k, since it is a number of blocks in current row, it will accumulate and it will add up to total number of blocks, which we have found already, and the 1 will accumulate for each row, i.e., it will become max_height find i1 by traversing from left towards right till you find h where h > i (current row), similarly, find in by traversing from right towards left. Set left = i1 and right = in and add in – i1 to total subtract num_blocks – max_height from total, which was accumulated total will be the quantity of trapped water Implementation C++ Java Python Javascript // C++ program to implement the approach#include <bits/stdc++.h>using namespace std; int trappedWater(vector<int>&heights){ int num_blocks = 0; int n = 0; int max_height = INT_MIN; // Find total blocks, max height and length of array for(auto height : heights){ num_blocks += height; n += 1; max_height = max(max_height, height); } // Total water, left pointer and right pointer initialized to 0 and n - 1 int total = 0; int left = 0; int right = n - 1; for(int i = 0; i < max_height; i++) { // Find leftmost point greater than current row (i) while(heights[left] <= i) left += 1; // Find rightmost point greater than current row (i) while(heights[right] <= i) right -= 1; // water in this row = right - left - (k - 1), where k - 1 accumulates total += right - left; } // k - 1 accumulates to num_blocks - max_height, // subtract it to get actual answer total -= (num_blocks - max_height); return total;} // Driver codeint main(){ vector<int> heights = {0,1,0,2,1,0,1,3,2,1,2,1}; cout << trappedWater(heights) << endl; return 0; } // This code is contributed by shinjanpatra //Java program to determine how much amount of water can an elevation//map store given in the form of an array of height of n points import java.io.*; class GFG { public static int trappedWater(int arr[]){ int n = arr.length; //to store the number of blocks int num_blocks=0; //to store the sum of all the heights int max_height = Integer.MIN_VALUE; //to store the maximum height in the array //compute the sum of all heights and the //maximum height given in the array for(int i=0;i<n;i++){ max_height=Math.max(max_height,arr[i]); num_blocks+=arr[i]; } //to store the answer and initialise //the left and right pointers int total=0,left=0,right=n-1; for(int i=0;i<max_height;i++){ //Compute the leftmost point greater than current row (i) while(arr[left]<=i){ left++; } //Compute the rightmost point greater than current row (i) while(arr[right]<=i){ right--; } //water in this row = right - left - (k - 1), where k - 1 accumulates total+=right-left; } //k - 1 accumulates to num_blocks - max_height. // Hence, subtract it to get actual answer total-=num_blocks-max_height; return total; } //Driver Code public static void main (String[] args) { int arr[] = {0,1,0,2,1,0,1,3,2,1,2,1}; //sample array to test System.out.println(trappedWater(arr)); //function call }} //this code is contributed by shruti456rawal def trappedWater(heights): num_blocks = 0 n = 0 max_height = float('-inf') # Find total blocks, max height and length of array for height in heights: num_blocks += height n += 1 max_height = max(max_height, height) # Total water, left pointer and right pointer initialized to 0 and n - 1 total = 0 left = 0 right = n - 1 for i in range(max_height): # Find leftmost point greater than current row (i) while heights[left] <= i: left += 1 # Find rightmost point greater than current row (i) while heights[right] <= i: right -= 1 # water in this row = right - left - (k - 1), where k - 1 accumulates total += right - left # k - 1 accumulates to num_blocks - max_height, subtract it to get actual answer total -= (num_blocks - max_height) return total if __name__ == "__main__": heights = [0,1,0,2,1,0,1,3,2,1,2,1] print(trappedWater(heights)) <script> function trappedWater(heights){ let num_blocks = 0 let n = 0 let max_height =Number.MIN_VALUE // Find total blocks, max height and length of array for(let height of heights){ num_blocks += height n += 1 max_height = Math.max(max_height, height) } // Total water, left pointer and right pointer initialized to 0 and n - 1 let total = 0 let left = 0 let right = n - 1 for(let i=0;i<max_height;i++){ // Find leftmost point greater than current row (i) while(heights[left] <= i) left += 1 // Find rightmost point greater than current row (i) while(heights[right] <= i) right -= 1 // water in this row = right - left - (k - 1), where k - 1 accumulates total += right - left } // k - 1 accumulates to num_blocks - max_height, subtract it to get actual answer total -= (num_blocks - max_height) return total} // driver codelet heights = [0,1,0,2,1,0,1,3,2,1,2,1]document.write(trappedWater(heights)) // This code is contributed by shinjanpatra </script> 6 Time Complexity: O(max_height * k) where k is total change in left and right pointers per row, k < nSpace Complexity: O(1) Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t vt_m sakhidamaulik Ashwin Subu ankthon mohit kumar 29 andrew1234 AmiyaRanjanRout Ganeshchowdharysadanala chatterjee0soumitri parascoding shivanisinghss2110 nikhil ch divyesh072019 divyeshrabadiya07 rutvik_56 pratham76 avanitrachhadiya2155 rag2127 azmuth kumarishaan01 suresh07 decode2207 unknown2108 SubhrodipMohanta ab2127 patel2127 singhashwani2002 theabbie simranarora5sos arorakashish0911 surinderdawra388 amnindersingh1414 shinjanpatra shruti456rawal parthshar48 Accolite Adobe Amazon D-E-Shaw MakeMyTrip Microsoft Payu Arrays Accolite Amazon Microsoft D-E-Shaw MakeMyTrip Payu Adobe Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 203, "s": 52, "text": "Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining." }, { "code": null, "e": 215, "s": 203, "text": "Examples: " }, { "code": null, "e": 224, "s": 215, "text": "Chapters" }, { "code": null, "e": 251, "s": 224, "text": "descriptions off, selected" }, { "code": null, "e": 301, "s": 251, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 324, "s": 301, "text": "captions off, selected" }, { "code": null, "e": 332, "s": 324, "text": "English" }, { "code": null, "e": 356, "s": 332, "text": "This is a modal window." }, { "code": null, "e": 425, "s": 356, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 447, "s": 425, "text": "End of dialog window." }, { "code": null, "e": 525, "s": 447, "text": "Input: arr[] = {2, 0, 2}\nOutput: 2\nExplanation:\nThe structure is like below" }, { "code": null, "e": 654, "s": 525, "text": "We can trap 2 units of water in the middle gap.\n\nInput: arr[] = {3, 0, 2, 0, 4}\nOutput: 7\nExplanation:\nStructure is like below" }, { "code": null, "e": 889, "s": 654, "text": "We can trap \"3 units\" of water between 3 and 2,\n\"1 unit\" on top of bar 2 and \"3 units\" between 2 \nand 4. See below diagram also.\n\nInput: arr[] = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]\nOutput: 6\n\nExplanation:\nThe structure is like below" }, { "code": null, "e": 1004, "s": 889, "text": "Trap \"1 unit\" between first 1 and 2, \"4 units\" between\nfirst 2 and 3 and \"1 unit\" between second last 1 and last 2" }, { "code": null, "e": 1324, "s": 1004, "text": "Basic Insight: An element of the array can store water if there are higher bars on the left and right. The amount of water to be stored in every element can be found by finding the heights of bars on the left and right sides. The idea is to compute the amount of water that can be stored in every element of the array. " }, { "code": null, "e": 1461, "s": 1324, "text": "Example:Consider the array {3, 0, 2, 0, 4}, three units of water can be stored in two indexes 1 and 3, and one unit of water at index 2." }, { "code": null, "e": 1530, "s": 1461, "text": "For Array[] = {3, 0, 2, 0, 4} Water stored = 0 + 3 + 1 + 3 + 0 = 7 " }, { "code": null, "e": 1588, "s": 1530, "text": "Method 1: This is a simple solution to the above problem." }, { "code": null, "e": 1875, "s": 1588, "text": "Approach: The idea is to traverse every array element and find the highest bars on the left and right sides. Take the smaller of two heights. The difference between the smaller height and the height of the current element is the amount of water that can be stored in this array element." }, { "code": null, "e": 2273, "s": 1875, "text": "Algorithm: Traverse the array from start to end.For every element, traverse the array from start to that index and find the maximum height (a) and traverse the array from the current index to end, and find the maximum height (b).The amount of water that will be stored in this column is min(a,b) – array[i], add this value to the total amount of water storedPrint the total amount of water stored." }, { "code": null, "e": 2660, "s": 2273, "text": "Traverse the array from start to end.For every element, traverse the array from start to that index and find the maximum height (a) and traverse the array from the current index to end, and find the maximum height (b).The amount of water that will be stored in this column is min(a,b) – array[i], add this value to the total amount of water storedPrint the total amount of water stored." }, { "code": null, "e": 2698, "s": 2660, "text": "Traverse the array from start to end." }, { "code": null, "e": 2880, "s": 2698, "text": "For every element, traverse the array from start to that index and find the maximum height (a) and traverse the array from the current index to end, and find the maximum height (b)." }, { "code": null, "e": 3010, "s": 2880, "text": "The amount of water that will be stored in this column is min(a,b) – array[i], add this value to the total amount of water stored" }, { "code": null, "e": 3050, "s": 3010, "text": "Print the total amount of water stored." }, { "code": null, "e": 3066, "s": 3050, "text": "Implementation:" }, { "code": null, "e": 3070, "s": 3066, "text": "C++" }, { "code": null, "e": 3072, "s": 3070, "text": "C" }, { "code": null, "e": 3077, "s": 3072, "text": "Java" }, { "code": null, "e": 3085, "s": 3077, "text": "Python3" }, { "code": null, "e": 3088, "s": 3085, "text": "C#" }, { "code": null, "e": 3099, "s": 3088, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include<bits/stdc++.h> using namespace std; // Function to return the maximum// water that can be storedint maxWater(int arr[], int n) { // To store the maximum water // that can be stored int res = 0; // For every element of the array for (int i = 1; i < n-1; i++) { // Find the maximum element on its left int left = arr[i]; for (int j=0; j<i; j++) left = max(left, arr[j]); // Find the maximum element on its right int right = arr[i]; for (int j=i+1; j<n; j++) right = max(right, arr[j]); // Update the maximum water res = res + (min(left, right) - arr[i]); } return res; } // Driver codeint main() { int arr[] = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << maxWater(arr, n); return 0; }", "e": 4047, "s": 3099, "text": null }, { "code": "// Implementation in C of the above approach // Importing the required header files#include <stdio.h> // Creating MACRO for finding the maximum number #define max(x, y) (((x) > (y)) ? (x) : (y)) // Creating MACRO for finding the minimum number #define min(x, y) (((x) < (y)) ? (x) : (y)) // Function to return the maximum // water that can be storedint maxWater(int arr[], int n){ // To store the maximum water int res = 0; // For every element of the array for (int i = 0; i < n; i++) { // Find the maximum element on its left int left = arr[i]; for (int j = 0; j < i; j++) { left = max(left, arr[j]); } // Find the maximum element on its left int right = arr[i]; for (int j = i + 1; j < n; j++) { right = max(right, arr[j]); } // Update the result (maximum water) res = res + (min(left, right) - arr[i]); } // return the maximum water return res;} // Driver codeint main(){ int arr[] = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; int n = sizeof(arr) / sizeof(arr[0]); printf(\"%d\", maxWater(arr, n)); return 0;} // This code is contributed by amnindersingh1414.", "e": 5174, "s": 4047, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function to return the maximum// water that can be storedpublic static int maxWater(int[] arr, int n) { // To store the maximum water // that can be stored int res = 0; // For every element of the array // except first and last element for(int i = 1; i < n - 1; i++) { // Find maximum element on its left int left = arr[i]; for(int j = 0; j < i; j++) { left = Math.max(left, arr[j]); } // Find maximum element on its right int right = arr[i]; for(int j = i + 1; j < n; j++) { right = Math.max(right, arr[j]); } // Update maximum water value res += Math.min(left, right) - arr[i]; } return res;} // Driver codepublic static void main(String[] args){ int[] arr = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; int n = arr.length; System.out.print(maxWater(arr,n));}} // This code is contributed by Debidutta Rath", "e": 6217, "s": 5174, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the maximum # water that can be stored def maxWater(arr, n) : # To store the maximum water # that can be stored res = 0; # For every element of the array for i in range(1, n - 1) : # Find the maximum element on its left left = arr[i]; for j in range(i) : left = max(left, arr[j]); # Find the maximum element on its right right = arr[i]; for j in range(i + 1 , n) : right = max(right, arr[j]); # Update the maximum water res = res + (min(left, right) - arr[i]); return res; # Driver code if __name__ == \"__main__\" : arr = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]; n = len(arr); print(maxWater(arr, n)); # This code is contributed by AnkitRai01", "e": 7125, "s": 6217, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the maximum// water that can be storedpublic static int maxWater(int[] arr, int n) { // To store the maximum water // that can be stored int res = 0; // For every element of the array // except first and last element for(int i = 1; i < n - 1; i++) { // Find maximum element on its left int left = arr[i]; for(int j = 0; j < i; j++) { left = Math.Max(left, arr[j]); } // Find maximum element on its right int right = arr[i]; for(int j = i + 1; j < n; j++) { right = Math.Max(right, arr[j]); } // Update maximum water value res += Math.Min(left, right) - arr[i]; } return res;} // Driver codepublic static void Main(String[] args){ int[] arr = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; int n = arr.Length; Console.Write(maxWater(arr,n));}} // This code is contributed by shivanisinghss2110", "e": 8181, "s": 7125, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the maximum // water that can be stored function maxWater(arr, n) { // To store the maximum water // that can be stored let res = 0; // For every element of the array // except first and last element for(let i = 1; i < n - 1; i++) { // Find maximum element on its left let left = arr[i]; for(let j = 0; j < i; j++) { left = Math.max(left, arr[j]); } // Find maximum element on its right let right = arr[i]; for(let j = i + 1; j < n; j++) { right = Math.max(right, arr[j]); } // Update maximum water value res += Math.min(left, right) - arr[i]; } return res; } let arr = [ 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 ]; let n = arr.length; document.write(maxWater(arr,n)); </script>", "e": 9229, "s": 8181, "text": null }, { "code": null, "e": 9231, "s": 9229, "text": "6" }, { "code": null, "e": 9409, "s": 9231, "text": "Complexity Analysis: Time Complexity: O(n2). There are two nested loops traversing the array, So the time Complexity is O(n2).Space Complexity: O(1). No extra space is required." }, { "code": null, "e": 9515, "s": 9409, "text": "Time Complexity: O(n2). There are two nested loops traversing the array, So the time Complexity is O(n2)." }, { "code": null, "e": 9567, "s": 9515, "text": "Space Complexity: O(1). No extra space is required." }, { "code": null, "e": 9629, "s": 9567, "text": "Method 2: This is an efficient solution to the above problem." }, { "code": null, "e": 9984, "s": 9629, "text": "Approach: In the previous solution, to find the highest bar on the left and right, array traversal is needed, which reduces the efficiency of the solution. To make this efficient, one must pre-compute the highest bar on the left and right of every bar in linear time. Then use these pre-computed values to find the amount of water in every array element." }, { "code": null, "e": 10577, "s": 9984, "text": "Algorithm: Create two arrays left and right of size n. create a variable max_ = INT_MIN.Run one loop from start to end. In each iteration update max_ as max_ = max(max_, arr[i]) and also assign left[i] = max_Update max_ = INT_MIN.Run another loop from end to start. In each iteration update max_ as max_ = max(max_, arr[i]) and also assign right[i] = max_Traverse the array from start to end.The amount of water that will be stored in this column is min(a,b) – array[i],(where a = left[i] and b = right[i]) add this value to total amount of water storedPrint the total amount of water stored." }, { "code": null, "e": 11159, "s": 10577, "text": "Create two arrays left and right of size n. create a variable max_ = INT_MIN.Run one loop from start to end. In each iteration update max_ as max_ = max(max_, arr[i]) and also assign left[i] = max_Update max_ = INT_MIN.Run another loop from end to start. In each iteration update max_ as max_ = max(max_, arr[i]) and also assign right[i] = max_Traverse the array from start to end.The amount of water that will be stored in this column is min(a,b) – array[i],(where a = left[i] and b = right[i]) add this value to total amount of water storedPrint the total amount of water stored." }, { "code": null, "e": 11237, "s": 11159, "text": "Create two arrays left and right of size n. create a variable max_ = INT_MIN." }, { "code": null, "e": 11358, "s": 11237, "text": "Run one loop from start to end. In each iteration update max_ as max_ = max(max_, arr[i]) and also assign left[i] = max_" }, { "code": null, "e": 11381, "s": 11358, "text": "Update max_ = INT_MIN." }, { "code": null, "e": 11507, "s": 11381, "text": "Run another loop from end to start. In each iteration update max_ as max_ = max(max_, arr[i]) and also assign right[i] = max_" }, { "code": null, "e": 11545, "s": 11507, "text": "Traverse the array from start to end." }, { "code": null, "e": 11707, "s": 11545, "text": "The amount of water that will be stored in this column is min(a,b) – array[i],(where a = left[i] and b = right[i]) add this value to total amount of water stored" }, { "code": null, "e": 11747, "s": 11707, "text": "Print the total amount of water stored." }, { "code": null, "e": 11763, "s": 11747, "text": "Implementation:" }, { "code": null, "e": 11767, "s": 11763, "text": "C++" }, { "code": null, "e": 11769, "s": 11767, "text": "C" }, { "code": null, "e": 11774, "s": 11769, "text": "Java" }, { "code": null, "e": 11782, "s": 11774, "text": "Python3" }, { "code": null, "e": 11785, "s": 11782, "text": "C#" }, { "code": null, "e": 11789, "s": 11785, "text": "PHP" }, { "code": null, "e": 11800, "s": 11789, "text": "Javascript" }, { "code": "// C++ program to find maximum amount of water that can// be trapped within given set of bars.#include <bits/stdc++.h>using namespace std; int findWater(int arr[], int n){ // left[i] contains height of tallest bar to the // left of i'th bar including itself int left[n]; // Right [i] contains height of tallest bar to // the right of ith bar including itself int right[n]; // Initialize result int water = 0; // Fill left array left[0] = arr[0]; for (int i = 1; i < n; i++) left[i] = max(left[i - 1], arr[i]); // Fill right array right[n - 1] = arr[n - 1]; for (int i = n - 2; i >= 0; i--) right[i] = max(right[i + 1], arr[i]); // Calculate the accumulated water element by element // consider the amount of water on i'th bar, the // amount of water accumulated on this particular // bar will be equal to min(left[i], right[i]) - arr[i] . for (int i = 1; i < n-1; i++) { int var=min(left[i-1],right[i+1]); if(var > arr[i]) { water += var - arr[i]; } } return water;} // Driver programint main(){ int arr[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Maximum water that can be accumulated is \" << findWater(arr, n); return 0;}", "e": 13121, "s": 11800, "text": null }, { "code": "// Implementation in C of the above approach // Importing the required header files#include <stdio.h> // Creating MACRO for finding the maximum number #define max(x, y) (((x) > (y)) ? (x) : (y)) // Creating MACRO for finding the minimum number #define min(x, y) (((x) < (y)) ? (x) : (y)) // Function to return the maximum // water that can be storedint findWater(int arr[], int n){ // left[i] contains height of tallest bar to the // left of i'th bar including itself int left[n]; // Right [i] contains height of tallest bar to the // right of ith bar including itself int right[n]; // Initialize result int water = 0; // Fill left array left[0] = arr[0]; for (int i = 1; i < n; i++) { left[i] = max(left[i-1], arr[i]); } // Fill right array right[n-1] = arr[n-1]; for (int i = n-2; i >= 0; i--) { right[i] = max(right[i+1], arr[i]); } // Calculate the accumulated water element by element // consider the amount of water on i'th bar, the // amount of water accumulated on this particular // bar will be equal to min(left[i], right[i]) - arr[i] . for (int i = 1; i < n-1; i++){ int var = min(left[i-1], right[i+1]); if (var > arr[i]) { water += var - arr[i]; } } return water;} // Driver programint main(){ int arr[] = {0,1,0,2,1,0,1,3,2,1,2,1}; int n = sizeof(arr)/sizeof(arr[0]); printf(\"Maximum water that can be accumulated is %d\", findWater(arr, n)); return 0;} // This code is contributed by amnindersingh1414.", "e": 14734, "s": 13121, "text": null }, { "code": "// Java program to find maximum amount of water that can// be trapped within given set of bars. class Test { static int arr[] = new int[] { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; // Method for maximum amount of water static int findWater(int n) { // left[i] contains height of tallest bar to the // left of i'th bar including itself int left[] = new int[n]; // Right [i] contains height of tallest bar to // the right of ith bar including itself int right[] = new int[n]; // Initialize result int water = 0; // Fill left array left[0] = arr[0]; for (int i = 1; i < n; i++) left[i] = Math.max(left[i - 1], arr[i]); // Fill right array right[n - 1] = arr[n - 1]; for (int i = n - 2; i >= 0; i--) right[i] = Math.max(right[i + 1], arr[i]); // Calculate the accumulated water element by element // consider the amount of water on i'th bar, the // amount of water accumulated on this particular // bar will be equal to min(left[i], right[i]) - arr[i] . for (int i = 0; i < n; i++) water += Math.min(left[i], right[i]) - arr[i]; return water; } // Driver method to test the above function public static void main(String[] args) { System.out.println(\"Maximum water that can be accumulated is \" + findWater(arr.length)); }}", "e": 16175, "s": 14734, "text": null }, { "code": "# Python program to find maximum amount of water that can# be trapped within given set of bars. def findWater(arr, n): # left[i] contains height of tallest bar to the # left of i'th bar including itself left = [0]*n # Right [i] contains height of tallest bar to # the right of ith bar including itself right = [0]*n # Initialize result water = 0 # Fill left array left[0] = arr[0] for i in range( 1, n): left[i] = max(left[i-1], arr[i]) # Fill right array right[n-1] = arr[n-1] for i in range(n-2, -1, -1): right[i] = max(right[i + 1], arr[i]); # Calculate the accumulated water element by element # consider the amount of water on i'th bar, the # amount of water accumulated on this particular # bar will be equal to min(left[i], right[i]) - arr[i] . for i in range(0, n): water += min(left[i], right[i]) - arr[i] return water # Driver program arr = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]n = len(arr)print(\"Maximum water that can be accumulated is\", findWater(arr, n)) # This code is contributed by# Smitha Dinesh Semwal", "e": 17296, "s": 16175, "text": null }, { "code": "// C# program to find maximum amount of water that can// be trapped within given set of bars.using System; class Test { static int[] arr = new int[] { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; // Method for maximum amount of water static int findWater(int n) { // left[i] contains height of tallest bar to the // left of i'th bar including itself int[] left = new int[n]; // Right [i] contains height of tallest bar to // the right of ith bar including itself int[] right = new int[n]; // Initialize result int water = 0; // Fill left array left[0] = arr[0]; for (int i = 1; i < n; i++) left[i] = Math.Max(left[i - 1], arr[i]); // Fill right array right[n - 1] = arr[n - 1]; for (int i = n - 2; i >= 0; i--) right[i] = Math.Max(right[i + 1], arr[i]); // Calculate the accumulated water element by element // consider the amount of water on i'th bar, the // amount of water accumulated on this particular // bar will be equal to min(left[i], right[i]) - arr[i] . for (int i = 0; i < n; i++) water += Math.Min(left[i], right[i]) - arr[i]; return water; } // Driver method to test the above function public static void Main() { Console.WriteLine(\"Maximum water that can be accumulated is \" + findWater(arr.Length)); }} // This code is contributed by vt_m.", "e": 18772, "s": 17296, "text": null }, { "code": "<?php// PHP program to find maximum// amount of water that can// be trapped within given set of bars. function findWater($arr, $n){ // left[i] contains height of // tallest bar to the // left of i'th bar including // itself // Right [i] contains height // of tallest bar to the right // of ith bar including itself // $right[$n]; // Initialize result $water = 0; // Fill left array $left[0] = $arr[0]; for ($i = 1; $i < $n; $i++) $left[$i] = max($left[$i - 1], $arr[$i]); // Fill right array $right[$n - 1] = $arr[$n - 1]; for ($i = $n - 2; $i >= 0; $i--) $right[$i] = max($right[$i + 1], $arr[$i]); // Calculate the accumulated // water element by element // consider the amount of // water on i'th bar, the // amount of water accumulated // on this particular // bar will be equal to min(left[i], // right[i]) - arr[i] . for ($i = 0; $i < $n; $i++) $water += min($left[$i], $right[$i]) - $arr[$i]; return $water;} // Driver program $arr = array(0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1); $n = sizeof($arr); echo \"Maximum water that can be accumulated is \", findWater($arr, $n); // This code is contributed by ajit?>", "e": 20100, "s": 18772, "text": null }, { "code": "<script>// Javascript program to find maximum amount of water that can// be trapped within given set of bars. let arr = [ 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 ]; // Method for maximum amount of water function findWater(n) { // left[i] contains height of tallest bar to the // left of i'th bar including itself let left = new Array(n); // Right [i] contains height of tallest bar to // the right of ith bar including itself let right = new Array(n); // Initialize result let water = 0; // Fill left array left[0] = arr[0]; for (let i = 1; i < n; i++) left[i] = Math.max(left[i - 1], arr[i]); // Fill right array right[n - 1] = arr[n - 1]; for (let i = n - 2; i >= 0; i--) right[i] = Math.max(right[i + 1], arr[i]); // Calculate the accumulated water element by element // consider the amount of water on i'th bar, the // amount of water accumulated on this particular // bar will be equal to min(left[i], right[i]) - arr[i] . for (let i = 0; i < n; i++) water += Math.min(left[i], right[i]) - arr[i]; return water; } // Driver method to test the above function document.write(\"Maximum water that can be accumulated is \" + findWater(arr.length)); // This code is contributed by unknown2108</script>", "e": 21536, "s": 20100, "text": null }, { "code": null, "e": 21579, "s": 21536, "text": "Maximum water that can be accumulated is 6" }, { "code": null, "e": 21762, "s": 21579, "text": "Complexity Analysis: Time Complexity: O(n). Only one traversal of the array is needed, So time Complexity is O(n).Space Complexity: O(n). Two extra arrays are needed, each of size n." }, { "code": null, "e": 21856, "s": 21762, "text": "Time Complexity: O(n). Only one traversal of the array is needed, So time Complexity is O(n)." }, { "code": null, "e": 21925, "s": 21856, "text": "Space Complexity: O(n). Two extra arrays are needed, each of size n." }, { "code": null, "e": 21969, "s": 21925, "text": "Space Optimization for the above Solution: " }, { "code": null, "e": 22322, "s": 21969, "text": "Instead of maintaining two arrays of size n for storing the left and a right max of each element, maintain two variables to store the maximum till that point. Since water trapped at any element = min(max_left, max_right) – arr[i]. Calculate water trapped on smaller elements out of A[lo] and A[hi] first, and move the pointers till lo doesn’t cross hi." }, { "code": null, "e": 22338, "s": 22322, "text": "Implementation:" }, { "code": null, "e": 22342, "s": 22338, "text": "C++" }, { "code": null, "e": 22347, "s": 22342, "text": "Java" }, { "code": null, "e": 22355, "s": 22347, "text": "Python3" }, { "code": null, "e": 22358, "s": 22355, "text": "C#" }, { "code": null, "e": 22362, "s": 22358, "text": "PHP" }, { "code": null, "e": 22373, "s": 22362, "text": "Javascript" }, { "code": null, "e": 22375, "s": 22373, "text": "C" }, { "code": "// C++ program to find maximum amount of water that can// be trapped within given set of bars.// Space Complexity : O(1) #include <iostream>using namespace std; int findWater(int arr[], int n){ // initialize output int result = 0; // maximum element on left and right int left_max = 0, right_max = 0; // indices to traverse the array int lo = 0, hi = n - 1; while (lo <= hi) { if (arr[lo] < arr[hi]) { if (arr[lo] > left_max) // update max in left left_max = arr[lo]; else // water on curr element = max - curr result += left_max - arr[lo]; lo++; } else { if (arr[hi] > right_max) // update right maximum right_max = arr[hi]; else result += right_max - arr[hi]; hi--; } } return result;} int main(){ int arr[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Maximum water that can be accumulated is \" << findWater(arr, n);} // This code is contributed by Aditi Sharma", "e": 23539, "s": 22375, "text": null }, { "code": "// JAVA Code For Trapping Rain Waterimport java.util.*; class GFG { static int findWater(int arr[], int n) { // initialize output int result = 0; // maximum element on left and right int left_max = 0, right_max = 0; // indices to traverse the array int lo = 0, hi = n - 1; while (lo <= hi) { if (arr[lo] < arr[hi]) { if (arr[lo] > left_max) // update max in left left_max = arr[lo]; else // water on curr element = // max - curr result += left_max - arr[lo]; lo++; } else { if (arr[hi] > right_max) // update right maximum right_max = arr[hi]; else result += right_max - arr[hi]; hi--; } } return result; } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; int n = arr.length; System.out.println(\"Maximum water that \" + \"can be accumulated is \" + findWater(arr, n)); }}// This code is contributed by Arnav Kr. Mandal.", "e": 24931, "s": 23539, "text": null }, { "code": "# Python program to find# maximum amount of water that can# be trapped within given set of bars.# Space Complexity : O(1) def findWater(arr, n): # initialize output result = 0 # maximum element on left and right left_max = 0 right_max = 0 # indices to traverse the array lo = 0 hi = n-1 while(lo <= hi): if(arr[lo] < arr[hi]): if(arr[lo] > left_max): # update max in left left_max = arr[lo] else: # water on curr element = max - curr result += left_max - arr[lo] lo+= 1 else: if(arr[hi] > right_max): # update right maximum right_max = arr[hi] else: result += right_max - arr[hi] hi-= 1 return result # Driver program arr = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]n = len(arr) print(\"Maximum water that can be accumulated is \", findWater(arr, n)) # This code is contributed# by Anant Agarwal.", "e": 26022, "s": 24931, "text": null }, { "code": "// C# Code For Trapping Rain Waterusing System; class GFG { static int findWater(int[] arr, int n) { // initialize output int result = 0; // maximum element on left and right int left_max = 0, right_max = 0; // indices to traverse the array int lo = 0, hi = n - 1; while (lo <= hi) { if (arr[lo] < arr[hi]) { if (arr[lo] > left_max) // update max in left left_max = arr[lo]; else // water on curr element = // max - curr result += left_max - arr[lo]; lo++; } else { if (arr[hi] > right_max) // update right maximum right_max = arr[hi]; else result += right_max - arr[hi]; hi--; } } return result; } // Driver program public static void Main() { int[] arr = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; int result = Trap.findWater(arr, arr.length); System.out.print(\" Total trapping water: \" + result); }} // This code is contributed by vt_m.", "e": 27293, "s": 26022, "text": null }, { "code": "<?php// PHP program to find maximum amount// of water that can be trapped within // given set of bars. // Method to find maximum amount// of water that can be trapped within // given set of bars.function findWater($arr, $n){ // initialize output $result = 0; // maximum element on // left and right $left_max = 0; $right_max = 0; // indices to traverse // the array $lo = 0; $hi = $n - 1; while($lo <= $hi) { if($arr[$lo] < $arr[$hi]) { if($arr[$lo] > $left_max) // update max in left $left_max = $arr[$lo]; else // water on curr // element = max - curr $result += $left_max - $arr[$lo]; $lo++; } else { if($arr[$hi] > $right_max) // update right maximum $right_max = $arr[$hi]; else $result += $right_max - $arr[$hi]; $hi--; } } return $result;} // Driver Code $arr = array(0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1); $n = count($arr); echo \"Maximum water that can be accumulated is \", findWater($arr, $n); // This code is contributed by anuj_67.?>", "e": 28636, "s": 27293, "text": null }, { "code": "<script>// JAVASCRIPT Code For Trapping Rain Water function findWater(arr,n){ // initialize output let result = 0; // maximum element on left and right let left_max = 0, right_max = 0; // indices to traverse the array let lo = 0, hi = n - 1; while (lo <= hi) { if (arr[lo] < arr[hi]) { if (arr[lo] > left_max) // update max in left left_max = arr[lo]; else // water on curr element = // max - curr result += left_max - arr[lo]; lo++; } else { if (arr[hi] > right_max) // update right maximum right_max = arr[hi]; else result += right_max - arr[hi]; hi--; } } return result;} /* Driver program to test above function */let arr=[0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1];let n = arr.length;document.write(\"Maximum water that \" + \"can be accumulated is \" + findWater(arr, n)); // This code is contributed by ab2127</script>", "e": 29905, "s": 28636, "text": null }, { "code": "// Implementation in C of the above approach // Importing the required header files#include <stdio.h> // Creating MACRO for finding the maximum number #define max(x, y) (((x) > (y)) ? (x) : (y)) // Creating MACRO for finding the minimum number #define min(x, y) (((x) < (y)) ? (x) : (y)) // Function to return the maximum // water that can be storedint findWater(int arr[], int n){ // initialize output int result = 0; //maximum element on left and right int left_max = 0, right_max = 0; // indices to traverse the array int lo = 0, hi = n-1; while (lo <= hi){ if (arr[lo] < arr[hi]){ if(arr[lo] > left_max){ // update left max left_max = arr[lo];} else // water on curr element = max - curr {result += left_max - arr[lo];} lo++; } else{ if(arr[hi] > right_max){ // update right max right_max = arr[hi]; } else // water on curr element = max - curr {result += right_max - arr[hi];} hi--; } } return result;} // Driver codeint main(){ int arr[] = {0,1,0,2,1,0,1,3,2,1,2,1}; int n = sizeof(arr)/sizeof(arr[0]); printf(\"Maximum water that can be accumulated is %d\", findWater(arr, n)); return 0;}", "e": 31303, "s": 29905, "text": null }, { "code": null, "e": 31346, "s": 31303, "text": "Maximum water that can be accumulated is 6" }, { "code": null, "e": 31486, "s": 31346, "text": "Complexity Analysis: Time Complexity: O(n). Only one traversal of the array is needed.Auxiliary Space: O(1). As no extra space is required." }, { "code": null, "e": 31552, "s": 31486, "text": "Time Complexity: O(n). Only one traversal of the array is needed." }, { "code": null, "e": 31606, "s": 31552, "text": "Auxiliary Space: O(1). As no extra space is required." }, { "code": null, "e": 31674, "s": 31606, "text": "Thanks to Gaurav Ahirwar and Aditi Sharma for the above solution. " }, { "code": null, "e": 31732, "s": 31674, "text": "Method 3: Here another efficient solution has been shown." }, { "code": null, "e": 32402, "s": 31732, "text": "Approach: The concept here is that if there is a larger wall to the right, then the water can be retained with a height equal to the smaller wall on the left. If there are no larger walls to the right, then start from the left. There must be a larger wall to the left now. Let’s take an example of the heights are {....,3, 2, 1, 4,....}, So here 3 and 4 are boundaries the heights 2 and 1 are submerged and cannot act as boundaries. So at any point or index knowing the previous boundary is sufficient if there is a higher or equal length boundary in the remaining part of the array. If not, then traverse the array backward and now must be a larger wall to the left. " }, { "code": null, "e": 33065, "s": 32402, "text": "Algorithm: Loop from index 0 to the end of the given array.If a wall greater than or equal to the previous wall is encountered, then make note of the index of that wall in a var called prev_index.Keep adding the previous wall’s height minus the current (ith) wall to the variable water.Have a temporary variable that stores the same value as water.If no wall greater than or equal to the previous wall is found, then quit.If prev_index < size of the input array, then subtract the temp variable from water, and loop from the end of the input array to prev_index. Find a wall greater than or equal to the previous wall (in this case, the last wall from backward)." }, { "code": null, "e": 33114, "s": 33065, "text": "Loop from index 0 to the end of the given array." }, { "code": null, "e": 33252, "s": 33114, "text": "If a wall greater than or equal to the previous wall is encountered, then make note of the index of that wall in a var called prev_index." }, { "code": null, "e": 33343, "s": 33252, "text": "Keep adding the previous wall’s height minus the current (ith) wall to the variable water." }, { "code": null, "e": 33406, "s": 33343, "text": "Have a temporary variable that stores the same value as water." }, { "code": null, "e": 33481, "s": 33406, "text": "If no wall greater than or equal to the previous wall is found, then quit." }, { "code": null, "e": 33722, "s": 33481, "text": "If prev_index < size of the input array, then subtract the temp variable from water, and loop from the end of the input array to prev_index. Find a wall greater than or equal to the previous wall (in this case, the last wall from backward)." }, { "code": null, "e": 33738, "s": 33722, "text": "Implementation:" }, { "code": null, "e": 33742, "s": 33738, "text": "C++" }, { "code": null, "e": 33747, "s": 33742, "text": "Java" }, { "code": null, "e": 33755, "s": 33747, "text": "Python3" }, { "code": null, "e": 33758, "s": 33755, "text": "C#" }, { "code": null, "e": 33769, "s": 33758, "text": "Javascript" }, { "code": null, "e": 33771, "s": 33769, "text": "C" }, { "code": "// C++ implementation of the approach#include<iostream>using namespace std; // Function to return the maximum// water that can be storedint maxWater(int arr[], int n){ int size = n - 1; // Let the first element be stored as // previous, we shall loop from index 1 int prev = arr[0]; // To store previous wall's index int prev_index = 0; int water = 0; // To store the water until a larger wall // is found, if there are no larger walls // then delete temp value from water int temp = 0; for(int i = 1; i <= size; i++) { // If the current wall is taller than // the previous wall then make current // wall as the previous wall and its // index as previous wall's index // for the subsequent loops if (arr[i] >= prev) { prev = arr[i]; prev_index = i; // Because larger or same // height wall is found temp = 0; } else { // Since current wall is shorter than // the previous, we subtract previous // wall's height from the current wall's // height and add it to the water water += prev - arr[i]; // Store the same value in temp as well // If we dont find any larger wall then // we will subtract temp from water temp += prev - arr[i]; } } // If the last wall was larger than or equal // to the previous wall then prev_index would // be equal to size of the array (last element) // If we didn't find a wall greater than or equal // to the previous wall from the left then // prev_index must be less than the index // of the last element if(prev_index < size) { // Temp would've stored the water collected // from previous largest wall till the end // of array if no larger wall was found then // it has excess water and remove that // from water variable water -= temp; // We start from the end of the array, // so previous should be assigned to // the last element prev = arr[size]; // Loop from the end of array up to the // previous index which would contain // the largest wall from the left for(int i = size; i >= prev_index; i--) { // Right end wall will be definitely // smaller than the 'previous index' wall if(arr[i] >= prev) { prev = arr[i]; } else { water += prev - arr[i]; } } } // Return the maximum water return water;} // Driver Codeint main(){ int arr[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxWater(arr, n); return 0;} // This code is contributed by Debidutta Rath", "e": 36722, "s": 33771, "text": null }, { "code": "// Java implementation of the approachclass GFG { // Function to return the maximum // water that can be stored public static int maxWater(int arr[], int n) { int size = n - 1; // Let the first element be stored as // previous, we shall loop from index 1 int prev = arr[0]; // To store previous wall's index int prev_index = 0; int water = 0; // To store the water until a larger wall // is found, if there are no larger walls // then delete temp value from water int temp = 0; for (int i = 1; i <= size; i++) { // If the current wall is taller than // the previous wall then make current // wall as the previous wall and its // index as previous wall's index // for the subsequent loops if (arr[i] >= prev) { prev = arr[i]; prev_index = i; // Because larger or same height wall is found temp = 0; } else { // Since current wall is shorter than // the previous, we subtract previous // wall's height from the current wall's // height and add it to the water water += prev - arr[i]; // Store the same value in temp as well // If we dont find any larger wall then // we will subtract temp from water temp += prev - arr[i]; } } // If the last wall was larger than or equal // to the previous wall then prev_index would // be equal to size of the array (last element) // If we didn't find a wall greater than or equal // to the previous wall from the left then // prev_index must be less than the index // of the last element if (prev_index < size) { // Temp would've stored the water collected // from previous largest wall till the end // of array if no larger wall was found then // it has excess water and remove that // from 'water' var water -= temp; // We start from the end of the array, so previous // should be assigned to the last element prev = arr[size]; // Loop from the end of array up to the 'previous index' // which would contain the \"largest wall from the left\" for (int i = size; i >= prev_index; i--) { // Right end wall will be definitely smaller // than the 'previous index' wall if (arr[i] >= prev) { prev = arr[i]; } else { water += prev - arr[i]; } } } // Return the maximum water return water; } // Driver code public static void main(String[] args) { int arr[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; int n = arr.length; System.out.print(maxWater(arr, n)); }}", "e": 39819, "s": 36722, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the maximum# water that can be storeddef maxWater(arr, n): size = n - 1 # Let the first element be stored as # previous, we shall loop from index 1 prev = arr[0] # To store previous wall's index prev_index = 0 water = 0 # To store the water until a larger wall # is found, if there are no larger walls # then delete temp value from water temp = 0 for i in range(1, size + 1): # If the current wall is taller than # the previous wall then make current # wall as the previous wall and its # index as previous wall's index # for the subsequent loops if (arr[i] >= prev): prev = arr[i] prev_index = i # Because larger or same height wall is found temp = 0 else: # Since current wall is shorter than # the previous, we subtract previous # wall's height from the current wall's # height and add it to the water water += prev - arr[i] # Store the same value in temp as well # If we dont find any larger wall then # we will subtract temp from water temp += prev - arr[i] # If the last wall was larger than or equal # to the previous wall then prev_index would # be equal to size of the array (last element) # If we didn't find a wall greater than or equal # to the previous wall from the left then # prev_index must be less than the index # of the last element if (prev_index < size): # Temp would've stored the water collected # from previous largest wall till the end # of array if no larger wall was found then # it has excess water and remove that # from 'water' var water -= temp # We start from the end of the array, so previous # should be assigned to the last element prev = arr[size] # Loop from the end of array up to the 'previous index' # which would contain the \"largest wall from the left\" for i in range(size, prev_index - 1, -1): # Right end wall will be definitely smaller # than the 'previous index' wall if (arr[i] >= prev): prev = arr[i] else: water += prev - arr[i] # Return the maximum water return water # Driver codearr = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]n = len(arr)print(maxWater(arr, n)) # This code is contributed by Mohit Kumar", "e": 42378, "s": 39819, "text": null }, { "code": "// C# implementation of the approachusing System;class GFG{ // Function to return the maximum // water that can be stored static int maxWater(int[] arr, int n) { int size = n - 1; // Let the first element be stored as // previous, we shall loop from index 1 int prev = arr[0]; // To store previous wall's index int prev_index = 0; int water = 0; // To store the water until a larger wall // is found, if there are no larger walls // then delete temp value from water int temp = 0; for(int i = 1; i <= size; i++) { // If the current wall is taller than // the previous wall then make current // wall as the previous wall and its // index as previous wall's index // for the subsequent loops if (arr[i] >= prev) { prev = arr[i]; prev_index = i; // Because larger or same // height wall is found temp = 0; } else { // Since current wall is shorter than // the previous, we subtract previous // wall's height from the current wall's // height and add it to the water water += prev - arr[i]; // Store the same value in temp as well // If we dont find any larger wall then // we will subtract temp from water temp += prev - arr[i]; } } // If the last wall was larger than or equal // to the previous wall then prev_index would // be equal to size of the array (last element) // If we didn't find a wall greater than or equal // to the previous wall from the left then // prev_index must be less than the index // of the last element if(prev_index < size) { // Temp would've stored the water collected // from previous largest wall till the end // of array if no larger wall was found then // it has excess water and remove that // from water variable water -= temp; // We start from the end of the array, // so previous should be assigned to // the last element prev = arr[size]; // Loop from the end of array up to the // previous index which would contain // the largest wall from the left for(int i = size; i >= prev_index; i--) { // Right end wall will be definitely // smaller than the 'previous index' wall if(arr[i] >= prev) { prev = arr[i]; } else { water += prev - arr[i]; } } } // Return the maximum water return water; } // Driver code static void Main() { int[] arr = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; int n = arr.Length; Console.WriteLine(maxWater(arr, n)); }} // This code is contributed by divyesh072019", "e": 45160, "s": 42378, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Function to return the maximum // water that can be stored function maxWater(arr,n) { let size = n - 1; // Let the first element be stored as // previous, we shall loop from index 1 let prev = arr[0]; // To store previous wall's index let prev_index = 0; let water = 0; // To store the water until a larger wall // is found, if there are no larger walls // then delete temp value from water let temp = 0; for (let i = 1; i <= size; i++) { // If the current wall is taller than // the previous wall then make current // wall as the previous wall and its // index as previous wall's index // for the subsequent loops if (arr[i] >= prev) { prev = arr[i]; prev_index = i; // Because larger or same height wall is found temp = 0; } else { // Since current wall is shorter than // the previous, we subtract previous // wall's height from the current wall's // height and add it to the water water += prev - arr[i]; // Store the same value in temp as well // If we dont find any larger wall then // we will subtract temp from water temp += prev - arr[i]; } } // If the last wall was larger than or equal // to the previous wall then prev_index would // be equal to size of the array (last element) // If we didn't find a wall greater than or equal // to the previous wall from the left then // prev_index must be less than the index // of the last element if (prev_index < size) { // Temp would've stored the water collected // from previous largest wall till the end // of array if no larger wall was found then // it has excess water and remove that // from 'water' var water -= temp; // We start from the end of the array, so previous // should be assigned to the last element prev = arr[size]; // Loop from the end of array up to the 'previous index' // which would contain the \"largest wall from the left\" for (let i = size; i >= prev_index; i--) { // Right end wall will be definitely smaller // than the 'previous index' wall if (arr[i] >= prev) { prev = arr[i]; } else { water += prev - arr[i]; } } } // Return the maximum water return water; } // Driver code let arr=[ 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]; let n = arr.length; document.write(maxWater(arr, n)); // This code is contributed by patel2127 </script>", "e": 48242, "s": 45160, "text": null }, { "code": "// Implementation in C of the above approach // Importing the required header files#include <stdio.h> // Creating MACRO for finding the maximum number #define max(x, y)(((x) > (y)) ? (x) : (y)) // Creating MACRO for finding the minimum number #define min(x, y)(((x) < (y)) ? (x) : (y)) // Function to return the maximum // water that can be storedint maxWater(int arr[], int n) { int size = n - 1; // Let the first element be stored as // previous, we shall loop from index 1 int prev = arr[0]; // To store previous wall's index int prev_index = 0; int water = 0; // To store the water until a larger wall // is found, if there are no larger walls // then delete temp value from water int temp = 0; for (int i = 1; i <= size; i++) { // If the current wall is taller than // the previous wall then make current // wall as the previous wall and its // index as previous wall's index // for the subsequent loops if (arr[i] >= prev) { prev = arr[i]; prev_index = i; // Because larger or same // height wall is found temp = 0; } else { // Since current wall is shorter than // the previous, we subtract previous // wall's height from the current wall's // height and add it to the water water += prev - arr[i]; // Store the same value in temp as well // If we dont find any larger wall then // we will subtract temp from water temp += prev - arr[i]; } } // If the last wall was larger than or equal // to the previous wall then prev_index would // be equal to size of the array (last element) // If we didn't find a wall greater than or equal // to the previous wall from the left then // prev_index must be less than the index // of the last element if (prev_index < size) { // Temp would've stored the water collected // from previous largest wall till the end // of array if no larger wall was found then // it has excess water and remove that // from water variable water -= temp; // We start from the end of the array, // so previous should be assigned to // the last element prev = arr[size]; // Loop from the end of array up to the // previous index which would contain // the largest wall from the left for (int i = size; i >= prev_index; i--) { // Right end wall will be definitely // smaller than the 'previous index' wall if (arr[i] >= prev) { prev = arr[i]; } else { water += prev - arr[i]; } } } // Return the maximum water return water;} // driver code int main() { int arr[] = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; int n = sizeof(arr) / sizeof(arr[0]); printf(\"%d\", maxWater(arr, n)); return 0;}", "e": 51270, "s": 48242, "text": null }, { "code": null, "e": 51272, "s": 51270, "text": "6" }, { "code": null, "e": 51415, "s": 51272, "text": "Complexity Analysis: Time Complexity: O(n). As only one traversal of the array is needed.Auxiliary Space: O(1). As no extra space is required." }, { "code": null, "e": 51484, "s": 51415, "text": "Time Complexity: O(n). As only one traversal of the array is needed." }, { "code": null, "e": 51538, "s": 51484, "text": "Auxiliary Space: O(1). As no extra space is required." }, { "code": null, "e": 51562, "s": 51538, "text": "Method 4 (Using Stack):" }, { "code": null, "e": 51707, "s": 51562, "text": "We can use a Stack to track the bars that are bounded by the longer left and right bars. This can be done using only one iteration using stacks." }, { "code": null, "e": 51717, "s": 51707, "text": "Approach:" }, { "code": null, "e": 51763, "s": 51717, "text": "1. Loop through the indices of the bar array." }, { "code": null, "e": 51805, "s": 51763, "text": "2. For each bar, we can do the following:" }, { "code": null, "e": 51906, "s": 51805, "text": "While the Stack is not empty and the current bar has a height greater than the top bar of the stack," }, { "code": null, "e": 51978, "s": 51906, "text": "Store the index of the top bar in pop_height and pop it from the Stack." }, { "code": null, "e": 52069, "s": 51978, "text": "Find the distance between the left bar(current top) of the popped bar and the current bar." }, { "code": null, "e": 52134, "s": 52069, "text": "Find the minimum height between the top bar and the current bar." }, { "code": null, "e": 52198, "s": 52134, "text": "The maximum water that can be trapped in distance * min_height." }, { "code": null, "e": 52292, "s": 52198, "text": "The water trapped, including the popped bar, is (distance * min_height) – height[pop_height]." }, { "code": null, "e": 52314, "s": 52292, "text": "Add that to the fans." }, { "code": null, "e": 52344, "s": 52314, "text": "3. Final answer will the ans." }, { "code": null, "e": 52348, "s": 52344, "text": "C++" }, { "code": null, "e": 52353, "s": 52348, "text": "Java" }, { "code": null, "e": 52361, "s": 52353, "text": "Python3" }, { "code": null, "e": 52364, "s": 52361, "text": "C#" }, { "code": null, "e": 52375, "s": 52364, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h> using namespace std; // Function to return the maximum// water that can be storedint maxWater(int height[], int n){ // Stores the indices of the bars stack <int> st; // Stores the final result int ans = 0; // Loop through the each bar for(int i = 0; i < n; i++) { // Remove bars from the stack // until the condition holds while ((!st.empty()) && (height[st.top()] < height[i])) { // Store the height of the top // and pop it. int pop_height = height[st.top()]; st.pop(); // If the stack does not have any // bars or the popped bar // has no left boundary if (st.empty()) break; // Get the distance between the // left and right boundary of // popped bar int distance = i - st.top() - 1; // Calculate the min. height int min_height = min(height[st.top()], height[i]) - pop_height; ans += distance * min_height; } // If the stack is either empty or // height of the current bar is less than // or equal to the top bar of stack st.push(i); } return ans;} // Driver codeint main() { int arr[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxWater(arr, n); return 0;} // The code is contributed by Soumitri Chattopadhyay", "e": 54032, "s": 52375, "text": null }, { "code": "import java.util.*;import java.io.*; // Java implementation of the approachclass GFG { // Function to return the maximum // water that can be stored public static int maxWater(int[] height) { // Stores the indices of the bars Stack<Integer> stack = new Stack<>(); // size of the array int n = height.length; // Stores the final result int ans = 0; // Loop through the each bar for (int i = 0; i < n; i++) { // Remove bars from the stack // until the condition holds while ((!stack.isEmpty()) && (height[stack.peek()] < height[i])) { // store the height of the top // and pop it. int pop_height = height[stack.peek()]; stack.pop(); // If the stack does not have any // bars or the popped bar // has no left boundary if (stack.isEmpty()) break; // Get the distance between the // left and right boundary of // popped bar int distance = i - stack.peek() - 1; // Calculate the min. height int min_height = Math.min(height[stack.peek()], height[i]) - pop_height; ans += distance * min_height; } // If the stack is either empty or // height of the current bar is less than // or equal to the top bar of stack stack.push(i); } return ans; } // Driver code public static void main(String[] args) { int arr[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; System.out.print(maxWater(arr)); }}", "e": 55866, "s": 54032, "text": null }, { "code": "# Python implementation of the approach # Function to return the maximum# water that can be storeddef maxWater(height): # Stores the indices of the bars stack = [] # size of the array n = len(height) # Stores the final result ans = 0 # Loop through the each bar for i in range(n): # Remove bars from the stack # until the condition holds while(len(stack) != 0 and (height[stack[-1]] < height[i]) ): # store the height of the top # and pop it. pop_height = height[stack[-1]] stack.pop() # If the stack does not have any # bars or the popped bar # has no left boundary if(len(stack) == 0): break # Get the distance between the # left and right boundary of # popped bar distance = i - stack[-1] - 1 # Calculate the min. height min_height = min(height[stack[-1]],height[i])-pop_height ans += distance * min_height # If the stack is either empty or # height of the current bar is less than # or equal to the top bar of stack stack.append(i) return ans # Driver codearr=[ 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]print(maxWater(arr)) # This code is contributed by rag2127", "e": 57305, "s": 55866, "text": null }, { "code": "using System;using System.Collections;using System.Collections.Generic; // C# implementation of the approachclass GFG { // Function to return the maximum // water that can be stored public static int maxWater(int[] height) { // Stores the indices of the bars Stack stack = new Stack(); // size of the array int n = height.Length; // Stores the final result int ans = 0; // Loop through the each bar for (int i = 0; i < n; i++) { // Remove bars from the stack // until the condition holds while ((stack.Count!=0) && (height[(int)stack.Peek()] < height[i])) { // store the height of the top // and pop it. int pop_height = height[(int)stack.Peek()]; stack.Pop(); // If the stack does not have any // bars or the popped bar // has no left boundary if (stack.Count == 0) break; // Get the distance between the // left and right boundary of // popped bar int distance = i - (int)stack.Peek() - 1; // Calculate the min. height int min_height = Math.Min(height[(int)stack.Peek()], height[i]) - pop_height; ans += distance * min_height; } // If the stack is either empty or // height of the current bar is less than // or equal to the top bar of stack stack.Push(i); } return ans; } // Driver code public static void Main() { int []arr = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; Console.Write(maxWater(arr)); }} // This code is contributed by pratham76.", "e": 58926, "s": 57305, "text": null }, { "code": "<script> // Python implementation of the approach // Function to return the maximum// water that can be storedfunction maxWater(height){ // Stores the indices of the bars let stack = [] // size of the array let n = height.length // Stores the final result let ans = 0 // Loop through the each bar for(let i=0;i<n;i++){ // Remove bars from the stack // until the condition holds while(stack.length != 0 && (height[stack[stack.length-1]] < height[i]) ){ // store the height of the top // and pop it. let pop_height = height[stack.pop()] // If the stack does not have any // bars or the popped bar // has no left boundary if(stack.length == 0) break // Get the distance between the // left and right boundary of // popped bar let distance = i - stack[stack.length - 1] - 1 // Calculate the min. height let min_height =Math.min(height[stack[stack.length - 1]],height[i])-pop_height ans += distance * min_height } // If the stack is either empty or // height of the current bar is less than // or equal to the top bar of stack stack.push(i) } return ans} // Driver codelet arr = [ 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]document.write(maxWater(arr)) // This code is contributed by shinjanpatra </script>", "e": 60501, "s": 58926, "text": null }, { "code": null, "e": 60503, "s": 60501, "text": "6" }, { "code": null, "e": 60547, "s": 60503, "text": "Time Complexity: O(n)Auxiliary Space: O(n) " }, { "code": null, "e": 60579, "s": 60547, "text": "Method 5 (Two Pointer Approach)" }, { "code": null, "e": 60741, "s": 60579, "text": "Approach: At every index, The amount of rainwater stored is the difference between the current index height and a minimum of left max height and right max-height" }, { "code": null, "e": 61605, "s": 60741, "text": "Algorithm :Take two pointers l and r. Initialize l to the starting index 0 and r to the last index n-1Since l is the first element, left_max would be 0, and right max for r would be 0While l <= r, iterate the array. We have two possible conditionsCondition1 : left_max <= right maxConsider Element at index lSince we have traversed all elements to the left of l, left_max is known For the right max of l, We can say that the right max would always be >= current r_max hereSo, min(left_max,right_max) would always equal to left_max in this caseIncrement lCondition2 : left_max > right maxConsider Element at index rSince we have traversed all elements to the right of r, right_max is knownFor the left max of l, We can say that the left max would always be >= current l_max hereSo, min(left_max,right_max) would always equal to right_max in this caseDecrement r" }, { "code": null, "e": 61697, "s": 61605, "text": "Take two pointers l and r. Initialize l to the starting index 0 and r to the last index n-1" }, { "code": null, "e": 61779, "s": 61697, "text": "Since l is the first element, left_max would be 0, and right max for r would be 0" }, { "code": null, "e": 61844, "s": 61779, "text": "While l <= r, iterate the array. We have two possible conditions" }, { "code": null, "e": 62153, "s": 61844, "text": "Condition1 : left_max <= right maxConsider Element at index lSince we have traversed all elements to the left of l, left_max is known For the right max of l, We can say that the right max would always be >= current r_max hereSo, min(left_max,right_max) would always equal to left_max in this caseIncrement l" }, { "code": null, "e": 62181, "s": 62153, "text": "Consider Element at index l" }, { "code": null, "e": 62255, "s": 62181, "text": "Since we have traversed all elements to the left of l, left_max is known " }, { "code": null, "e": 62348, "s": 62255, "text": "For the right max of l, We can say that the right max would always be >= current r_max here" }, { "code": null, "e": 62420, "s": 62348, "text": "So, min(left_max,right_max) would always equal to left_max in this case" }, { "code": null, "e": 62432, "s": 62420, "text": "Increment l" }, { "code": null, "e": 62741, "s": 62432, "text": "Condition2 : left_max > right maxConsider Element at index rSince we have traversed all elements to the right of r, right_max is knownFor the left max of l, We can say that the left max would always be >= current l_max hereSo, min(left_max,right_max) would always equal to right_max in this caseDecrement r" }, { "code": null, "e": 62769, "s": 62741, "text": "Consider Element at index r" }, { "code": null, "e": 62844, "s": 62769, "text": "Since we have traversed all elements to the right of r, right_max is known" }, { "code": null, "e": 62935, "s": 62844, "text": "For the left max of l, We can say that the left max would always be >= current l_max here" }, { "code": null, "e": 63008, "s": 62935, "text": "So, min(left_max,right_max) would always equal to right_max in this case" }, { "code": null, "e": 63020, "s": 63008, "text": "Decrement r" }, { "code": null, "e": 63036, "s": 63020, "text": "Implementation:" }, { "code": null, "e": 63040, "s": 63036, "text": "C++" }, { "code": null, "e": 63045, "s": 63040, "text": "Java" }, { "code": null, "e": 63053, "s": 63045, "text": "Python3" }, { "code": null, "e": 63056, "s": 63053, "text": "C#" }, { "code": null, "e": 63067, "s": 63056, "text": "Javascript" }, { "code": null, "e": 63069, "s": 63067, "text": "C" }, { "code": "// C++ implementation of the approach#include <iostream>using namespace std; int maxWater(int arr[], int n){ // indices to traverse the array int left = 0; int right = n-1; // To store Left max and right max // for two pointers left and right int l_max = 0; int r_max = 0; // To store the total amount // of rain water trapped int result = 0; while (left <= right) { // We need check for minimum of left // and right max for each element if(r_max <= l_max) { // Add the difference between // current value and right max at index r result += max(0, r_max-arr[right]); // Update right max r_max = max(r_max, arr[right]); // Update right pointer right -= 1; } else { // Add the difference between // current value and left max at index l result += max(0, l_max-arr[left]); // Update left max l_max = max(l_max, arr[left]); // Update left pointer left += 1; } } return result;} // Driver codeint main() { int arr[] = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << maxWater(arr, n) << endl; return 0;} // This code is contributed by avanitrachhadiya2155", "e": 64385, "s": 63069, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG { static int maxWater(int[] arr, int n) { // indices to traverse the array int left = 0; int right = n - 1; // To store Left max and right max // for two pointers left and right int l_max = 0; int r_max = 0; // To store the total amount // of rain water trapped int result = 0; while (left <= right) { // We need check for minimum of left // and right max for each element if(r_max <= l_max) { // Add the difference between // current value and right max at index r result += Math.max(0, r_max-arr[right]); // Update right max r_max = Math.max(r_max, arr[right]); // Update right pointer right -= 1; } else { // Add the difference between // current value and left max at index l result += Math.max(0, l_max-arr[left]); // Update left max l_max = Math.max(l_max, arr[left]); // Update left pointer left += 1; } } return result; } // Driver code public static void main(String []args) { int[] arr = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; int n = arr.length; System.out.print(maxWater(arr, n)); }} // This code is contributed by rutvik_56.", "e": 65719, "s": 64385, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the maximum# water that can be stored def maxWater(arr, n): # indices to traverse the array left = 0 right = n-1 # To store Left max and right max # for two pointers left and right l_max = 0 r_max = 0 # To store the total amount # of rain water trapped result = 0 while (left <= right): # We need check for minimum of left # and right max for each element if r_max <= l_max: # Add the difference between #current value and right max at index r result += max(0, r_max-arr[right]) # Update right max r_max = max(r_max, arr[right]) # Update right pointer right -= 1 else: # Add the difference between # current value and left max at index l result += max(0, l_max-arr[left]) # Update left max l_max = max(l_max, arr[left]) # Update left pointer left += 1 return result # Driver codearr = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]n = len(arr)print(maxWater(arr, n)) # This code is contributed by Nikhil Chatragadda", "e": 67016, "s": 65719, "text": null }, { "code": "// C# implementation of the approachusing System;class GFG { static int maxWater(int[] arr, int n) { // indices to traverse the array int left = 0; int right = n-1; // To store Left max and right max // for two pointers left and right int l_max = 0; int r_max = 0; // To store the total amount // of rain water trapped int result = 0; while (left <= right) { // We need check for minimum of left // and right max for each element if(r_max <= l_max) { // Add the difference between // current value and right max at index r result += Math.Max(0, r_max-arr[right]); // Update right max r_max = Math.Max(r_max, arr[right]); // Update right pointer right -= 1; } else { // Add the difference between // current value and left max at index l result += Math.Max(0, l_max-arr[left]); // Update left max l_max = Math.Max(l_max, arr[left]); // Update left pointer left += 1; } } return result; } // Driver code static void Main() { int[] arr = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; int n = arr.Length; Console.WriteLine(maxWater(arr, n)); }} // This code is contributed by divyeshrabadiya07.", "e": 68325, "s": 67016, "text": null }, { "code": "<script> // Javascript implementation of the approachfunction maxWater(arr, n){ // indices to traverse the array let left = 0; let right = n - 1; // To store Left max and right max // for two pointers left and right let l_max = 0; let r_max = 0; // To store the total amount // of rain water trapped let result = 0; while (left <= right) { // We need check for minimum of left // and right max for each element if(r_max <= l_max) { // Add the difference between // current value and right max at index r result += Math.max(0, r_max - arr[right]); // Update right max r_max = Math.max(r_max, arr[right]); // Update right pointer right -= 1; } else { // Add the difference between // current value and left max at index l result += Math.max(0, l_max - arr[left]); // Update left max l_max = Math.max(l_max, arr[left]); // Update left pointer left += 1; } } return result;} // Driver code let arr = [ 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 ];let n = arr.length; document.write(maxWater(arr, n)); // This code is contributed by suresh07 </script>", "e": 69730, "s": 68325, "text": null }, { "code": "// Implementation in C of the above approach // Importing the required header files#include <stdio.h> // Creating MACRO for finding the maximum number #define max(x, y)(((x) > (y)) ? (x) : (y)) // Creating MACRO for finding the minimum number #define min(x, y)(((x) < (y)) ? (x) : (y)) // Function to return the maximum int maxWater(int arr[], int n){ // indices to traverse the array int left = 0; int right = n-1; // To store Left max and right max // for two pointers left and right int l_max = 0; int r_max = 0; // To store the total amount // of rain water trapped int result = 0; while (left <= right) { // We need check for minimum of left // and right max for each element if(r_max <= l_max) { // Add the difference between // current value and right max at index r result += max(0, r_max-arr[right]); // Update right max r_max = max(r_max, arr[right]); // Update right pointer right -= 1; } else { // Add the difference between // current value and left max at index l result += max(0, l_max-arr[left]); // Update left max l_max = max(l_max, arr[left]); // Update left pointer left += 1; } } return result;} // driver code int main() { int arr[] = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; int n = sizeof(arr) / sizeof(arr[0]); printf(\"%d\", maxWater(arr, n)); return 0;}", "e": 71244, "s": 69730, "text": null }, { "code": null, "e": 71246, "s": 71244, "text": "6" }, { "code": null, "e": 71290, "s": 71246, "text": "Time Complexity: O(n)Auxiliary Space: O(1) " }, { "code": null, "e": 71324, "s": 71290, "text": "Method 6 (horizontal scan method)" }, { "code": null, "e": 71600, "s": 71324, "text": "Approach If max_height is the height of the tallest block, then it will be the maximum possible height for any trapped rainwater. And if we traverse each row from left to right for each row from bottom to max_height, we can count the number of blocks that will contain water." }, { "code": null, "e": 73004, "s": 71600, "text": "AlgorithmFind the total number of blocks, i.e., sum of the heights array, num_blocksfind the maximum height, max_heightstore total water in a variable, total = 0keep two pointers, left = 0 and right = n -1, we will use them laterfor each row i from 0 to max_height, do the followingScan heights array from left to right, if height > i (current row), this will be the boundary of one of the sections of trapped water, let us store these indexes.Let the boundary indexes be boundary = [i1, i2, i3 ...]The water stored in current row between i1 and i2 = i2 – i1 – 1, between i2 and i3 = i3 – i2 – 1 and so on.Total water stored in current row = (i2 – i1 – 1) + (i3 – i2 – 1) + ... (in – in-1 -1) = in – i1 – (k – 1), where k in number of blocks in this rowif we find i1 and in i.e., first and last boundary index of each row, we don’t need to scan the whole array. We will not find k, since it is a number of blocks in current row, it will accumulate and it will add up to total number of blocks, which we have found already, and the 1 will accumulate for each row, i.e., it will become max_heightfind i1 by traversing from left towards right till you find h where h > i (current row), similarly, find in by traversing from right towards left.Set left = i1 and right = in and add in – i1 to totalsubtract num_blocks – max_height from total, which was accumulatedtotal will be the quantity of trapped water" }, { "code": null, "e": 73080, "s": 73004, "text": "Find the total number of blocks, i.e., sum of the heights array, num_blocks" }, { "code": null, "e": 73116, "s": 73080, "text": "find the maximum height, max_height" }, { "code": null, "e": 73159, "s": 73116, "text": "store total water in a variable, total = 0" }, { "code": null, "e": 73228, "s": 73159, "text": "keep two pointers, left = 0 and right = n -1, we will use them later" }, { "code": null, "e": 74294, "s": 73228, "text": "for each row i from 0 to max_height, do the followingScan heights array from left to right, if height > i (current row), this will be the boundary of one of the sections of trapped water, let us store these indexes.Let the boundary indexes be boundary = [i1, i2, i3 ...]The water stored in current row between i1 and i2 = i2 – i1 – 1, between i2 and i3 = i3 – i2 – 1 and so on.Total water stored in current row = (i2 – i1 – 1) + (i3 – i2 – 1) + ... (in – in-1 -1) = in – i1 – (k – 1), where k in number of blocks in this rowif we find i1 and in i.e., first and last boundary index of each row, we don’t need to scan the whole array. We will not find k, since it is a number of blocks in current row, it will accumulate and it will add up to total number of blocks, which we have found already, and the 1 will accumulate for each row, i.e., it will become max_heightfind i1 by traversing from left towards right till you find h where h > i (current row), similarly, find in by traversing from right towards left.Set left = i1 and right = in and add in – i1 to total" }, { "code": null, "e": 74457, "s": 74294, "text": "Scan heights array from left to right, if height > i (current row), this will be the boundary of one of the sections of trapped water, let us store these indexes." }, { "code": null, "e": 74513, "s": 74457, "text": "Let the boundary indexes be boundary = [i1, i2, i3 ...]" }, { "code": null, "e": 74621, "s": 74513, "text": "The water stored in current row between i1 and i2 = i2 – i1 – 1, between i2 and i3 = i3 – i2 – 1 and so on." }, { "code": null, "e": 74769, "s": 74621, "text": "Total water stored in current row = (i2 – i1 – 1) + (i3 – i2 – 1) + ... (in – in-1 -1) = in – i1 – (k – 1), where k in number of blocks in this row" }, { "code": null, "e": 75111, "s": 74769, "text": "if we find i1 and in i.e., first and last boundary index of each row, we don’t need to scan the whole array. We will not find k, since it is a number of blocks in current row, it will accumulate and it will add up to total number of blocks, which we have found already, and the 1 will accumulate for each row, i.e., it will become max_height" }, { "code": null, "e": 75258, "s": 75111, "text": "find i1 by traversing from left towards right till you find h where h > i (current row), similarly, find in by traversing from right towards left." }, { "code": null, "e": 75313, "s": 75258, "text": "Set left = i1 and right = in and add in – i1 to total" }, { "code": null, "e": 75380, "s": 75313, "text": "subtract num_blocks – max_height from total, which was accumulated" }, { "code": null, "e": 75424, "s": 75380, "text": "total will be the quantity of trapped water" }, { "code": null, "e": 75439, "s": 75424, "text": "Implementation" }, { "code": null, "e": 75443, "s": 75439, "text": "C++" }, { "code": null, "e": 75448, "s": 75443, "text": "Java" }, { "code": null, "e": 75455, "s": 75448, "text": "Python" }, { "code": null, "e": 75466, "s": 75455, "text": "Javascript" }, { "code": "// C++ program to implement the approach#include <bits/stdc++.h>using namespace std; int trappedWater(vector<int>&heights){ int num_blocks = 0; int n = 0; int max_height = INT_MIN; // Find total blocks, max height and length of array for(auto height : heights){ num_blocks += height; n += 1; max_height = max(max_height, height); } // Total water, left pointer and right pointer initialized to 0 and n - 1 int total = 0; int left = 0; int right = n - 1; for(int i = 0; i < max_height; i++) { // Find leftmost point greater than current row (i) while(heights[left] <= i) left += 1; // Find rightmost point greater than current row (i) while(heights[right] <= i) right -= 1; // water in this row = right - left - (k - 1), where k - 1 accumulates total += right - left; } // k - 1 accumulates to num_blocks - max_height, // subtract it to get actual answer total -= (num_blocks - max_height); return total;} // Driver codeint main(){ vector<int> heights = {0,1,0,2,1,0,1,3,2,1,2,1}; cout << trappedWater(heights) << endl; return 0; } // This code is contributed by shinjanpatra", "e": 76740, "s": 75466, "text": null }, { "code": "//Java program to determine how much amount of water can an elevation//map store given in the form of an array of height of n points import java.io.*; class GFG { public static int trappedWater(int arr[]){ int n = arr.length; //to store the number of blocks int num_blocks=0; //to store the sum of all the heights int max_height = Integer.MIN_VALUE; //to store the maximum height in the array //compute the sum of all heights and the //maximum height given in the array for(int i=0;i<n;i++){ max_height=Math.max(max_height,arr[i]); num_blocks+=arr[i]; } //to store the answer and initialise //the left and right pointers int total=0,left=0,right=n-1; for(int i=0;i<max_height;i++){ //Compute the leftmost point greater than current row (i) while(arr[left]<=i){ left++; } //Compute the rightmost point greater than current row (i) while(arr[right]<=i){ right--; } //water in this row = right - left - (k - 1), where k - 1 accumulates total+=right-left; } //k - 1 accumulates to num_blocks - max_height. // Hence, subtract it to get actual answer total-=num_blocks-max_height; return total; } //Driver Code public static void main (String[] args) { int arr[] = {0,1,0,2,1,0,1,3,2,1,2,1}; //sample array to test System.out.println(trappedWater(arr)); //function call }} //this code is contributed by shruti456rawal", "e": 78442, "s": 76740, "text": null }, { "code": "def trappedWater(heights): num_blocks = 0 n = 0 max_height = float('-inf') # Find total blocks, max height and length of array for height in heights: num_blocks += height n += 1 max_height = max(max_height, height) # Total water, left pointer and right pointer initialized to 0 and n - 1 total = 0 left = 0 right = n - 1 for i in range(max_height): # Find leftmost point greater than current row (i) while heights[left] <= i: left += 1 # Find rightmost point greater than current row (i) while heights[right] <= i: right -= 1 # water in this row = right - left - (k - 1), where k - 1 accumulates total += right - left # k - 1 accumulates to num_blocks - max_height, subtract it to get actual answer total -= (num_blocks - max_height) return total if __name__ == \"__main__\": heights = [0,1,0,2,1,0,1,3,2,1,2,1] print(trappedWater(heights))", "e": 79470, "s": 78442, "text": null }, { "code": "<script> function trappedWater(heights){ let num_blocks = 0 let n = 0 let max_height =Number.MIN_VALUE // Find total blocks, max height and length of array for(let height of heights){ num_blocks += height n += 1 max_height = Math.max(max_height, height) } // Total water, left pointer and right pointer initialized to 0 and n - 1 let total = 0 let left = 0 let right = n - 1 for(let i=0;i<max_height;i++){ // Find leftmost point greater than current row (i) while(heights[left] <= i) left += 1 // Find rightmost point greater than current row (i) while(heights[right] <= i) right -= 1 // water in this row = right - left - (k - 1), where k - 1 accumulates total += right - left } // k - 1 accumulates to num_blocks - max_height, subtract it to get actual answer total -= (num_blocks - max_height) return total} // driver codelet heights = [0,1,0,2,1,0,1,3,2,1,2,1]document.write(trappedWater(heights)) // This code is contributed by shinjanpatra </script>", "e": 80618, "s": 79470, "text": null }, { "code": null, "e": 80620, "s": 80618, "text": "6" }, { "code": null, "e": 80743, "s": 80620, "text": "Time Complexity: O(max_height * k) where k is total change in left and right pointers per row, k < nSpace Complexity: O(1)" }, { "code": null, "e": 80869, "s": 80743, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 80875, "s": 80869, "text": "jit_t" }, { "code": null, "e": 80880, "s": 80875, "text": "vt_m" }, { "code": null, "e": 80894, "s": 80880, "text": "sakhidamaulik" }, { "code": null, "e": 80906, "s": 80894, "text": "Ashwin Subu" }, { "code": null, "e": 80914, "s": 80906, "text": "ankthon" }, { "code": null, "e": 80929, "s": 80914, "text": "mohit kumar 29" }, { "code": null, "e": 80940, "s": 80929, "text": "andrew1234" }, { "code": null, "e": 80956, "s": 80940, "text": "AmiyaRanjanRout" }, { "code": null, "e": 80980, "s": 80956, "text": "Ganeshchowdharysadanala" }, { "code": null, "e": 81000, "s": 80980, "text": "chatterjee0soumitri" }, { "code": null, "e": 81012, "s": 81000, "text": "parascoding" }, { "code": null, "e": 81031, "s": 81012, "text": "shivanisinghss2110" }, { "code": null, "e": 81041, "s": 81031, "text": "nikhil ch" }, { "code": null, "e": 81055, "s": 81041, "text": "divyesh072019" }, { "code": null, "e": 81073, "s": 81055, "text": "divyeshrabadiya07" }, { "code": null, "e": 81083, "s": 81073, "text": "rutvik_56" }, { "code": null, "e": 81093, "s": 81083, "text": "pratham76" }, { "code": null, "e": 81114, "s": 81093, "text": "avanitrachhadiya2155" }, { "code": null, "e": 81122, "s": 81114, "text": "rag2127" }, { "code": null, "e": 81129, "s": 81122, "text": "azmuth" }, { "code": null, "e": 81143, "s": 81129, "text": "kumarishaan01" }, { "code": null, "e": 81152, "s": 81143, "text": "suresh07" }, { "code": null, "e": 81163, "s": 81152, "text": "decode2207" }, { "code": null, "e": 81175, "s": 81163, "text": "unknown2108" }, { "code": null, "e": 81192, "s": 81175, "text": "SubhrodipMohanta" }, { "code": null, "e": 81199, "s": 81192, "text": "ab2127" }, { "code": null, "e": 81209, "s": 81199, "text": "patel2127" }, { "code": null, "e": 81226, "s": 81209, "text": "singhashwani2002" }, { "code": null, "e": 81235, "s": 81226, "text": "theabbie" }, { "code": null, "e": 81251, "s": 81235, "text": "simranarora5sos" }, { "code": null, "e": 81268, "s": 81251, "text": "arorakashish0911" }, { "code": null, "e": 81285, "s": 81268, "text": "surinderdawra388" }, { "code": null, "e": 81303, "s": 81285, "text": "amnindersingh1414" }, { "code": null, "e": 81316, "s": 81303, "text": "shinjanpatra" }, { "code": null, "e": 81331, "s": 81316, "text": "shruti456rawal" }, { "code": null, "e": 81343, "s": 81331, "text": "parthshar48" }, { "code": null, "e": 81352, "s": 81343, "text": "Accolite" }, { "code": null, "e": 81358, "s": 81352, "text": "Adobe" }, { "code": null, "e": 81365, "s": 81358, "text": "Amazon" }, { "code": null, "e": 81374, "s": 81365, "text": "D-E-Shaw" }, { "code": null, "e": 81385, "s": 81374, "text": "MakeMyTrip" }, { "code": null, "e": 81395, "s": 81385, "text": "Microsoft" }, { "code": null, "e": 81400, "s": 81395, "text": "Payu" }, { "code": null, "e": 81407, "s": 81400, "text": "Arrays" }, { "code": null, "e": 81416, "s": 81407, "text": "Accolite" }, { "code": null, "e": 81423, "s": 81416, "text": "Amazon" }, { "code": null, "e": 81433, "s": 81423, "text": "Microsoft" }, { "code": null, "e": 81442, "s": 81433, "text": "D-E-Shaw" }, { "code": null, "e": 81453, "s": 81442, "text": "MakeMyTrip" }, { "code": null, "e": 81458, "s": 81453, "text": "Payu" }, { "code": null, "e": 81464, "s": 81458, "text": "Adobe" }, { "code": null, "e": 81471, "s": 81464, "text": "Arrays" } ]
NumberFormat getPercentInstance() method in Java with Examples - GeeksforGeeks
01 Apr, 2019 The getPercentInstance() method is a built-in method of the java.text.NumberFormat returns a percentage format for the current default FORMAT locale.Syntax:public static final NumberFormat getPercentInstance()Parameters: The function does not accepts any parameter.Return Value: The function returns the NumberFormat instance for percentage formatting.Below is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the percent instance NumberFormat nF = NumberFormat.getPercentInstance(); // Sets the currency to Canadian Dollar nF.setCurrency(Currency .getInstance( Locale.CANADA)); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar Program 2:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the percent instance NumberFormat nF = NumberFormat .getPercentInstance(); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:US Dollar Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getPercentInstance()The getPercentInstance(Locale inLocale) method is a built-in method of the java.text.NumberFormat returns a percentage format for any specified locale.Syntax:public static NumberFormat getPercentInstance(Locale inLocale)Parameters: The function accepts a single mandatory parameter inLocale which describes the locale which is to specified.Return Value: The function returns the NumberFormat instance for percentage formatting.Below is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the percent instance NumberFormat nF = NumberFormat .getPercentInstance( Locale.CANADA); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getPercentInstance(java.util.Locale) The getPercentInstance() method is a built-in method of the java.text.NumberFormat returns a percentage format for the current default FORMAT locale.Syntax:public static final NumberFormat getPercentInstance()Parameters: The function does not accepts any parameter.Return Value: The function returns the NumberFormat instance for percentage formatting.Below is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the percent instance NumberFormat nF = NumberFormat.getPercentInstance(); // Sets the currency to Canadian Dollar nF.setCurrency(Currency .getInstance( Locale.CANADA)); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar Program 2:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the percent instance NumberFormat nF = NumberFormat .getPercentInstance(); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:US Dollar Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getPercentInstance() Syntax: public static final NumberFormat getPercentInstance() Parameters: The function does not accepts any parameter. Return Value: The function returns the NumberFormat instance for percentage formatting. Below is the implementation of the above function: Program 1: // Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the percent instance NumberFormat nF = NumberFormat.getPercentInstance(); // Sets the currency to Canadian Dollar nF.setCurrency(Currency .getInstance( Locale.CANADA)); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }} Canadian Dollar Program 2: // Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the percent instance NumberFormat nF = NumberFormat .getPercentInstance(); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }} US Dollar Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getPercentInstance() The getPercentInstance(Locale inLocale) method is a built-in method of the java.text.NumberFormat returns a percentage format for any specified locale.Syntax:public static NumberFormat getPercentInstance(Locale inLocale)Parameters: The function accepts a single mandatory parameter inLocale which describes the locale which is to specified.Return Value: The function returns the NumberFormat instance for percentage formatting.Below is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the percent instance NumberFormat nF = NumberFormat .getPercentInstance( Locale.CANADA); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getPercentInstance(java.util.Locale) Syntax: public static NumberFormat getPercentInstance(Locale inLocale) Parameters: The function accepts a single mandatory parameter inLocale which describes the locale which is to specified. Return Value: The function returns the NumberFormat instance for percentage formatting. Below is the implementation of the above function: Program 1: // Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the percent instance NumberFormat nF = NumberFormat .getPercentInstance( Locale.CANADA); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }} Canadian Dollar Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getPercentInstance(java.util.Locale) Java-Functions Java-NumberFormat Java-text package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Internal Working of HashMap in Java Comparator Interface in Java with Examples Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n01 Apr, 2019" }, { "code": null, "e": 28219, "s": 25225, "text": "The getPercentInstance() method is a built-in method of the java.text.NumberFormat returns a percentage format for the current default FORMAT locale.Syntax:public static final NumberFormat getPercentInstance()Parameters: The function does not accepts any parameter.Return Value: The function returns the NumberFormat instance for percentage formatting.Below is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the percent instance NumberFormat nF = NumberFormat.getPercentInstance(); // Sets the currency to Canadian Dollar nF.setCurrency(Currency .getInstance( Locale.CANADA)); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar\nProgram 2:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the percent instance NumberFormat nF = NumberFormat .getPercentInstance(); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:US Dollar\nReference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getPercentInstance()The getPercentInstance(Locale inLocale) method is a built-in method of the java.text.NumberFormat returns a percentage format for any specified locale.Syntax:public static NumberFormat getPercentInstance(Locale inLocale)Parameters: The function accepts a single mandatory parameter inLocale which describes the locale which is to specified.Return Value: The function returns the NumberFormat instance for percentage formatting.Below is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the percent instance NumberFormat nF = NumberFormat .getPercentInstance( Locale.CANADA); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar\nReference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getPercentInstance(java.util.Locale)" }, { "code": null, "e": 30011, "s": 28219, "text": "The getPercentInstance() method is a built-in method of the java.text.NumberFormat returns a percentage format for the current default FORMAT locale.Syntax:public static final NumberFormat getPercentInstance()Parameters: The function does not accepts any parameter.Return Value: The function returns the NumberFormat instance for percentage formatting.Below is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the percent instance NumberFormat nF = NumberFormat.getPercentInstance(); // Sets the currency to Canadian Dollar nF.setCurrency(Currency .getInstance( Locale.CANADA)); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar\nProgram 2:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the percent instance NumberFormat nF = NumberFormat .getPercentInstance(); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:US Dollar\nReference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getPercentInstance()" }, { "code": null, "e": 30019, "s": 30011, "text": "Syntax:" }, { "code": null, "e": 30073, "s": 30019, "text": "public static final NumberFormat getPercentInstance()" }, { "code": null, "e": 30130, "s": 30073, "text": "Parameters: The function does not accepts any parameter." }, { "code": null, "e": 30218, "s": 30130, "text": "Return Value: The function returns the NumberFormat instance for percentage formatting." }, { "code": null, "e": 30269, "s": 30218, "text": "Below is the implementation of the above function:" }, { "code": null, "e": 30280, "s": 30269, "text": "Program 1:" }, { "code": "// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the percent instance NumberFormat nF = NumberFormat.getPercentInstance(); // Sets the currency to Canadian Dollar nF.setCurrency(Currency .getInstance( Locale.CANADA)); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}", "e": 30969, "s": 30280, "text": null }, { "code": null, "e": 30986, "s": 30969, "text": "Canadian Dollar\n" }, { "code": null, "e": 30997, "s": 30986, "text": "Program 2:" }, { "code": "// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the percent instance NumberFormat nF = NumberFormat .getPercentInstance(); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}", "e": 31537, "s": 30997, "text": null }, { "code": null, "e": 31548, "s": 31537, "text": "US Dollar\n" }, { "code": null, "e": 31651, "s": 31548, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getPercentInstance()" }, { "code": null, "e": 32854, "s": 31651, "text": "The getPercentInstance(Locale inLocale) method is a built-in method of the java.text.NumberFormat returns a percentage format for any specified locale.Syntax:public static NumberFormat getPercentInstance(Locale inLocale)Parameters: The function accepts a single mandatory parameter inLocale which describes the locale which is to specified.Return Value: The function returns the NumberFormat instance for percentage formatting.Below is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the percent instance NumberFormat nF = NumberFormat .getPercentInstance( Locale.CANADA); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar\nReference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getPercentInstance(java.util.Locale)" }, { "code": null, "e": 32862, "s": 32854, "text": "Syntax:" }, { "code": null, "e": 32925, "s": 32862, "text": "public static NumberFormat getPercentInstance(Locale inLocale)" }, { "code": null, "e": 33046, "s": 32925, "text": "Parameters: The function accepts a single mandatory parameter inLocale which describes the locale which is to specified." }, { "code": null, "e": 33134, "s": 33046, "text": "Return Value: The function returns the NumberFormat instance for percentage formatting." }, { "code": null, "e": 33185, "s": 33134, "text": "Below is the implementation of the above function:" }, { "code": null, "e": 33196, "s": 33185, "text": "Program 1:" }, { "code": "// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the percent instance NumberFormat nF = NumberFormat .getPercentInstance( Locale.CANADA); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}", "e": 33771, "s": 33196, "text": null }, { "code": null, "e": 33788, "s": 33771, "text": "Canadian Dollar\n" }, { "code": null, "e": 33907, "s": 33788, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getPercentInstance(java.util.Locale)" }, { "code": null, "e": 33922, "s": 33907, "text": "Java-Functions" }, { "code": null, "e": 33940, "s": 33922, "text": "Java-NumberFormat" }, { "code": null, "e": 33958, "s": 33940, "text": "Java-text package" }, { "code": null, "e": 33963, "s": 33958, "text": "Java" }, { "code": null, "e": 33968, "s": 33963, "text": "Java" }, { "code": null, "e": 34066, "s": 33968, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34081, "s": 34066, "text": "Stream In Java" }, { "code": null, "e": 34102, "s": 34081, "text": "Constructors in Java" }, { "code": null, "e": 34121, "s": 34102, "text": "Exceptions in Java" }, { "code": null, "e": 34151, "s": 34121, "text": "Functional Interfaces in Java" }, { "code": null, "e": 34197, "s": 34151, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 34214, "s": 34197, "text": "Generics in Java" }, { "code": null, "e": 34235, "s": 34214, "text": "Introduction to Java" }, { "code": null, "e": 34271, "s": 34235, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 34314, "s": 34271, "text": "Comparator Interface in Java with Examples" } ]
CSS ::before selector - GeeksforGeeks
02 Nov, 2021 The ::before selector CSS pseudo-element, is used to add the same content multiple times before the content of other elements. This selector is the same as ::after selector. It helps to create the pseudo-element that represents the first child of the selected element & is generally used for adding decorative content to an element using the content property. Its default value is inline. Syntax: ::before{ content: } Example: The below HTML/CSS code shows the functionality of ::before selector. HTML <!DOCTYPE html><html> <head> <style> p::before { content: " - Remember this"; background-color: blue; } </style></head> <body> <h3>Before Selector</h3> <p>User ID: @dmor1</p> <p>Name: dharam</p> </body> </html> Output: Supported Browsers: Google Chrome 4.0 Edge 12.0 Internet Explorer 9.0 Firefox 3.5 Safari 3.1 Opera 7.0 Note: Internet Explorer 8 and Opera 4-6 supports with single-colon.(::before). arorakashish0911 bhaskargeeksforgeeks CSS-Selectors CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? 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 ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24341, "s": 24313, "text": "\n02 Nov, 2021" }, { "code": null, "e": 24730, "s": 24341, "text": "The ::before selector CSS pseudo-element, is used to add the same content multiple times before the content of other elements. This selector is the same as ::after selector. It helps to create the pseudo-element that represents the first child of the selected element & is generally used for adding decorative content to an element using the content property. Its default value is inline." }, { "code": null, "e": 24738, "s": 24730, "text": "Syntax:" }, { "code": null, "e": 24767, "s": 24738, "text": "::before{\n content:\n}" }, { "code": null, "e": 24846, "s": 24767, "text": "Example: The below HTML/CSS code shows the functionality of ::before selector." }, { "code": null, "e": 24851, "s": 24846, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> p::before { content: \" - Remember this\"; background-color: blue; } </style></head> <body> <h3>Before Selector</h3> <p>User ID: @dmor1</p> <p>Name: dharam</p> </body> </html>", "e": 25103, "s": 24851, "text": null }, { "code": null, "e": 25111, "s": 25103, "text": "Output:" }, { "code": null, "e": 25131, "s": 25111, "text": "Supported Browsers:" }, { "code": null, "e": 25149, "s": 25131, "text": "Google Chrome 4.0" }, { "code": null, "e": 25159, "s": 25149, "text": "Edge 12.0" }, { "code": null, "e": 25181, "s": 25159, "text": "Internet Explorer 9.0" }, { "code": null, "e": 25193, "s": 25181, "text": "Firefox 3.5" }, { "code": null, "e": 25204, "s": 25193, "text": "Safari 3.1" }, { "code": null, "e": 25214, "s": 25204, "text": "Opera 7.0" }, { "code": null, "e": 25294, "s": 25214, "text": "Note: Internet Explorer 8 and Opera 4-6 supports with single-colon.(::before). " }, { "code": null, "e": 25311, "s": 25294, "text": "arorakashish0911" }, { "code": null, "e": 25332, "s": 25311, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 25346, "s": 25332, "text": "CSS-Selectors" }, { "code": null, "e": 25350, "s": 25346, "text": "CSS" }, { "code": null, "e": 25367, "s": 25350, "text": "Web Technologies" }, { "code": null, "e": 25465, "s": 25367, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25515, "s": 25465, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 25577, "s": 25515, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 25625, "s": 25577, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 25683, "s": 25625, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 25738, "s": 25683, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 25778, "s": 25738, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 25811, "s": 25778, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 25856, "s": 25811, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 25899, "s": 25856, "text": "How to fetch data from an API in ReactJS ?" } ]
How to clear the content of a div using JavaScript? - GeeksforGeeks
04 Apr, 2019 JavaScript provides the functionality of clearing the content of div. There are two methods to perform this function, one by using innerHTML property and other by using firstChild property and removeChild() method. Method 1: Using innerHTML Property: The DOM innerHTML property is used to set or return the HTML content of an element. This method set the innerHTML property to none. <!DOCTYPE html><html> <head> <title> Clear the content of a div using JavaScript </title> <style> #clear { background-color:#006600; color:white; padding-top:50px; opacity:0.7; width : 400px; height:250px; border-radius:10%; text-align:center; } </style> <!-- Script to use DOM innerHTML property to clear the content --> <script> function clearcontent(elementID) { document.getElementById(elementID).innerHTML = ""; } </script></head> <body> <div id= "clear"> <form> <label>Enter first number</label><br> <input type = "number" placeholder = "Enter number" name = "input1" min = "0"/> <br><br> <label>Enter Second number</label><br> <input type = "number" placeholder = "Enter number" name = "input2" min = "0"/> <br><br> <label> Click on button to find sum of prime numbers </label><br> <button value = "find sum" type = "submit" onclick = "clearcontent('clear')"> find sum </button><br> </form> </div></body> </html> Output: Before Clicking the button: After Clicking the button: Method 2: Using firstChild property and removeChild() method: The DOM firstChild property is used to return the firstchild Node of its parent node element. It is read-only property and does not return a text node and a comment node. The removeChild() method is used to remove a specified child node of the given element. It returns the removed node as a node object or null if the node doesn’t exist. This method uses firstChild property to return the first child and removeChild() method uses to remove the content of first child. <!DOCTYPE html><html> <head> <title> Clear the content of a div using JavaScript </title> <style> #clear { background-color:#006600; color:white; padding-top:50px; opacity:0.7; width : 400px; height:250px; border-radius:10%; text-align:center; } </style> <!-- Script to use DOM firstChild property and removeChild method to clear the content --> <script> function clearBox(elementID) { var div = document.getElementById(elementID); while(div.firstChild) { div.removeChild(div.firstChild); } } </script></head> <body> <div id= "clear"> <form> <label>Enter first number</label><br> <input type = "number" placeholder = "Enter number" name = "input1" min = "0"/> <br><br> <label>Enter Second number</label><br> <input type = "number" placeholder = "Enter number" name = "input2" min = "0"/> <br><br> <label> Click on button to find sum of prime numbers </label><br> <button value = "find sum" type = "submit" onclick = "clearcontent('clear')"> find sum </button><br> </form> </div></body> </html> Output: Before Clicking the button: After Clicking the button: Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26297, "s": 26269, "text": "\n04 Apr, 2019" }, { "code": null, "e": 26512, "s": 26297, "text": "JavaScript provides the functionality of clearing the content of div. There are two methods to perform this function, one by using innerHTML property and other by using firstChild property and removeChild() method." }, { "code": null, "e": 26680, "s": 26512, "text": "Method 1: Using innerHTML Property: The DOM innerHTML property is used to set or return the HTML content of an element. This method set the innerHTML property to none." }, { "code": "<!DOCTYPE html><html> <head> <title> Clear the content of a div using JavaScript </title> <style> #clear { background-color:#006600; color:white; padding-top:50px; opacity:0.7; width : 400px; height:250px; border-radius:10%; text-align:center; } </style> <!-- Script to use DOM innerHTML property to clear the content --> <script> function clearcontent(elementID) { document.getElementById(elementID).innerHTML = \"\"; } </script></head> <body> <div id= \"clear\"> <form> <label>Enter first number</label><br> <input type = \"number\" placeholder = \"Enter number\" name = \"input1\" min = \"0\"/> <br><br> <label>Enter Second number</label><br> <input type = \"number\" placeholder = \"Enter number\" name = \"input2\" min = \"0\"/> <br><br> <label> Click on button to find sum of prime numbers </label><br> <button value = \"find sum\" type = \"submit\" onclick = \"clearcontent('clear')\"> find sum </button><br> </form> </div></body> </html>", "e": 28060, "s": 26680, "text": null }, { "code": null, "e": 28068, "s": 28060, "text": "Output:" }, { "code": null, "e": 28096, "s": 28068, "text": "Before Clicking the button:" }, { "code": null, "e": 28123, "s": 28096, "text": "After Clicking the button:" }, { "code": null, "e": 28655, "s": 28123, "text": "Method 2: Using firstChild property and removeChild() method: The DOM firstChild property is used to return the firstchild Node of its parent node element. It is read-only property and does not return a text node and a comment node. The removeChild() method is used to remove a specified child node of the given element. It returns the removed node as a node object or null if the node doesn’t exist. This method uses firstChild property to return the first child and removeChild() method uses to remove the content of first child." }, { "code": "<!DOCTYPE html><html> <head> <title> Clear the content of a div using JavaScript </title> <style> #clear { background-color:#006600; color:white; padding-top:50px; opacity:0.7; width : 400px; height:250px; border-radius:10%; text-align:center; } </style> <!-- Script to use DOM firstChild property and removeChild method to clear the content --> <script> function clearBox(elementID) { var div = document.getElementById(elementID); while(div.firstChild) { div.removeChild(div.firstChild); } } </script></head> <body> <div id= \"clear\"> <form> <label>Enter first number</label><br> <input type = \"number\" placeholder = \"Enter number\" name = \"input1\" min = \"0\"/> <br><br> <label>Enter Second number</label><br> <input type = \"number\" placeholder = \"Enter number\" name = \"input2\" min = \"0\"/> <br><br> <label> Click on button to find sum of prime numbers </label><br> <button value = \"find sum\" type = \"submit\" onclick = \"clearcontent('clear')\"> find sum </button><br> </form> </div></body> </html>", "e": 30160, "s": 28655, "text": null }, { "code": null, "e": 30168, "s": 30160, "text": "Output:" }, { "code": null, "e": 30196, "s": 30168, "text": "Before Clicking the button:" }, { "code": null, "e": 30223, "s": 30196, "text": "After Clicking the button:" }, { "code": null, "e": 30230, "s": 30223, "text": "Picked" }, { "code": null, "e": 30241, "s": 30230, "text": "JavaScript" }, { "code": null, "e": 30258, "s": 30241, "text": "Web Technologies" }, { "code": null, "e": 30285, "s": 30258, "text": "Web technologies Questions" }, { "code": null, "e": 30383, "s": 30285, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30423, "s": 30383, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30468, "s": 30423, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30529, "s": 30468, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30601, "s": 30529, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 30653, "s": 30601, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 30693, "s": 30653, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30726, "s": 30693, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30771, "s": 30726, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30814, "s": 30771, "text": "How to fetch data from an API in ReactJS ?" } ]
vars() function in Python - GeeksforGeeks
13 Feb, 2022 This is an inbuilt function in Python. The vars() method takes only one parameter and that too is optional. It takes an object as a parameter which may be can a module, a class, an instance, or any object having __dict__ attribute. Syntax: vars(object) The method returns the __dict__ attribute for a module, class, instance, or any other object if the same has a __dict__ attribute. If the object fails to match the attribute, it raises a TypeError exception. Objects such as modules and instances have an updatable __dict__ attribute however, other objects may have written restrictions on their __dict__ attributes. vars() acts like locals() method when an empty argument is passed which implies that the locals dictionary is only useful for reads since updates to the locals dictionary are ignored. Python3 # Python program to illustrate# working of vars() method in Python class Geeks: def __init__(self, name1 = "Arun", num2 = 46, name3 = "Rishab"): self.name1 = name1 self.num2 = num2 self.name3 = name3 GeeksforGeeks = Geeks()print(vars(GeeksforGeeks)) Output: {'num2': 46, 'name1': 'Arun', 'name3': 'Rishab'} Python3 # Python program to illustrating# the use of vars() and locals# when no argument is passed and# how vars() act as locals().class Geeks(object): def __init__(self): self.num1 = 20 self.num2 = "this is returned" def __repr__(self): return "Geeks() is returned" def loc(self): ans = 21 return locals() # Works same as locals() def code(self): ans = 10 return vars() def prog(self): ans = "this is not printed" return vars(self) if __name__ == "__main__": obj = Geeks() print (obj.loc()) print (obj.code()) print (obj.prog()) Output: {'ans': 21, 'self': Geeks() is returned} {'ans': 10, 'self': Geeks() is returned} {'num1': 20, 'num2': 'this is returned'} adnanirshad158 Python-Built-in-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python sum() function in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 25715, "s": 25687, "text": "\n13 Feb, 2022" }, { "code": null, "e": 25957, "s": 25715, "text": "This is an inbuilt function in Python. The vars() method takes only one parameter and that too is optional. It takes an object as a parameter which may be can a module, a class, an instance, or any object having __dict__ attribute. Syntax: " }, { "code": null, "e": 25970, "s": 25957, "text": "vars(object)" }, { "code": null, "e": 26522, "s": 25970, "text": "The method returns the __dict__ attribute for a module, class, instance, or any other object if the same has a __dict__ attribute. If the object fails to match the attribute, it raises a TypeError exception. Objects such as modules and instances have an updatable __dict__ attribute however, other objects may have written restrictions on their __dict__ attributes. vars() acts like locals() method when an empty argument is passed which implies that the locals dictionary is only useful for reads since updates to the locals dictionary are ignored. " }, { "code": null, "e": 26530, "s": 26522, "text": "Python3" }, { "code": "# Python program to illustrate# working of vars() method in Python class Geeks: def __init__(self, name1 = \"Arun\", num2 = 46, name3 = \"Rishab\"): self.name1 = name1 self.num2 = num2 self.name3 = name3 GeeksforGeeks = Geeks()print(vars(GeeksforGeeks))", "e": 26792, "s": 26530, "text": null }, { "code": null, "e": 26802, "s": 26792, "text": "Output: " }, { "code": null, "e": 26851, "s": 26802, "text": "{'num2': 46, 'name1': 'Arun', 'name3': 'Rishab'}" }, { "code": null, "e": 26861, "s": 26853, "text": "Python3" }, { "code": "# Python program to illustrating# the use of vars() and locals# when no argument is passed and# how vars() act as locals().class Geeks(object): def __init__(self): self.num1 = 20 self.num2 = \"this is returned\" def __repr__(self): return \"Geeks() is returned\" def loc(self): ans = 21 return locals() # Works same as locals() def code(self): ans = 10 return vars() def prog(self): ans = \"this is not printed\" return vars(self) if __name__ == \"__main__\": obj = Geeks() print (obj.loc()) print (obj.code()) print (obj.prog())", "e": 27489, "s": 26861, "text": null }, { "code": null, "e": 27499, "s": 27489, "text": "Output: " }, { "code": null, "e": 27622, "s": 27499, "text": "{'ans': 21, 'self': Geeks() is returned}\n{'ans': 10, 'self': Geeks() is returned}\n{'num1': 20, 'num2': 'this is returned'}" }, { "code": null, "e": 27639, "s": 27624, "text": "adnanirshad158" }, { "code": null, "e": 27665, "s": 27639, "text": "Python-Built-in-functions" }, { "code": null, "e": 27672, "s": 27665, "text": "Python" }, { "code": null, "e": 27770, "s": 27672, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27802, "s": 27770, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27824, "s": 27802, "text": "Enumerate() in Python" }, { "code": null, "e": 27866, "s": 27824, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27892, "s": 27866, "text": "Python String | replace()" }, { "code": null, "e": 27921, "s": 27892, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27958, "s": 27921, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27994, "s": 27958, "text": "Convert integer to string in Python" }, { "code": null, "e": 28036, "s": 27994, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28061, "s": 28036, "text": "sum() function in Python" } ]
BufferedWriter flush() method in Java with Examples - GeeksforGeeks
28 May, 2020 The flush() method of BufferedWriter class in Java is used to flush the characters from the buffered writer stream. Syntax: public void flush() throws IOException Specified By: This method is specified by the flush() method of Flushable interface. Overrides: This method overrides the flush() method of Writer class. Parameters: This method does not accept any parameter. Return value: This method does not return any value. Exceptions: This method throws IOException if an I/O error occurs. Below programs illustrate flush() method in BufferedWriter class in IO package: Program 1: // Java program to illustrate// BufferedWriter flush() method import java.io.*; public class GFG { public static void main(String[] args) throws IOException { // Create the string Writer StringWriter stringWriter = new StringWriter(); // Convert stringWriter to // bufferedWriter BufferedWriter buffWriter = new BufferedWriter( stringWriter); // Write "GEEKS" to buffer writer buffWriter.write( "GEEKSFORGEEKS", 0, 5); // Flush the buffer writer buffWriter.flush(); System.out.println( stringWriter.getBuffer()); }} GEEKS Program 2: // Java program to illustrate// BufferedWriter flush() method import java.io.*; public class GFG { public static void main(String[] args) throws IOException { // Create the string Writer StringWriter stringWriter = new StringWriter(); // Convert stringWriter to // bufferedWriter BufferedWriter buffWriter = new BufferedWriter( stringWriter); // Write "GEEKS" to buffered writer buffWriter.write( "GEEKSFORGEEKS", 0, 5); // Flush the buffered writer buffWriter.flush(); System.out.println( stringWriter.getBuffer()); // Write "GEEKSFORGEEKS" // to buffered writer buffWriter.write( "GEEKSFORGEEKS", 5, 8); // Flush the buffered writer buffWriter.flush(); System.out.println( stringWriter.getBuffer()); }} GEEKS GEEKSFORGEEKS References:https://docs.oracle.com/javase/10/docs/api/java/io/BufferedWriter.html#flush() Java-Functions Java-IO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Hashtable in Java Constructors in Java Different ways of Reading a text file in Java Comparator Interface in Java with Examples Java Math random() method with Examples HashMap containsKey() Method in Java How to Create Array of Objects in Java? Convert Double to Integer in Java Iterating over ArrayLists in Java Generating random numbers in Java
[ { "code": null, "e": 23557, "s": 23529, "text": "\n28 May, 2020" }, { "code": null, "e": 23673, "s": 23557, "text": "The flush() method of BufferedWriter class in Java is used to flush the characters from the buffered writer stream." }, { "code": null, "e": 23681, "s": 23673, "text": "Syntax:" }, { "code": null, "e": 23733, "s": 23681, "text": "public void flush()\n throws IOException\n" }, { "code": null, "e": 23818, "s": 23733, "text": "Specified By: This method is specified by the flush() method of Flushable interface." }, { "code": null, "e": 23887, "s": 23818, "text": "Overrides: This method overrides the flush() method of Writer class." }, { "code": null, "e": 23942, "s": 23887, "text": "Parameters: This method does not accept any parameter." }, { "code": null, "e": 23995, "s": 23942, "text": "Return value: This method does not return any value." }, { "code": null, "e": 24062, "s": 23995, "text": "Exceptions: This method throws IOException if an I/O error occurs." }, { "code": null, "e": 24142, "s": 24062, "text": "Below programs illustrate flush() method in BufferedWriter class in IO package:" }, { "code": null, "e": 24153, "s": 24142, "text": "Program 1:" }, { "code": "// Java program to illustrate// BufferedWriter flush() method import java.io.*; public class GFG { public static void main(String[] args) throws IOException { // Create the string Writer StringWriter stringWriter = new StringWriter(); // Convert stringWriter to // bufferedWriter BufferedWriter buffWriter = new BufferedWriter( stringWriter); // Write \"GEEKS\" to buffer writer buffWriter.write( \"GEEKSFORGEEKS\", 0, 5); // Flush the buffer writer buffWriter.flush(); System.out.println( stringWriter.getBuffer()); }}", "e": 24826, "s": 24153, "text": null }, { "code": null, "e": 24833, "s": 24826, "text": "GEEKS\n" }, { "code": null, "e": 24844, "s": 24833, "text": "Program 2:" }, { "code": "// Java program to illustrate// BufferedWriter flush() method import java.io.*; public class GFG { public static void main(String[] args) throws IOException { // Create the string Writer StringWriter stringWriter = new StringWriter(); // Convert stringWriter to // bufferedWriter BufferedWriter buffWriter = new BufferedWriter( stringWriter); // Write \"GEEKS\" to buffered writer buffWriter.write( \"GEEKSFORGEEKS\", 0, 5); // Flush the buffered writer buffWriter.flush(); System.out.println( stringWriter.getBuffer()); // Write \"GEEKSFORGEEKS\" // to buffered writer buffWriter.write( \"GEEKSFORGEEKS\", 5, 8); // Flush the buffered writer buffWriter.flush(); System.out.println( stringWriter.getBuffer()); }}", "e": 25774, "s": 24844, "text": null }, { "code": null, "e": 25795, "s": 25774, "text": "GEEKS\nGEEKSFORGEEKS\n" }, { "code": null, "e": 25885, "s": 25795, "text": "References:https://docs.oracle.com/javase/10/docs/api/java/io/BufferedWriter.html#flush()" }, { "code": null, "e": 25900, "s": 25885, "text": "Java-Functions" }, { "code": null, "e": 25916, "s": 25900, "text": "Java-IO package" }, { "code": null, "e": 25921, "s": 25916, "text": "Java" }, { "code": null, "e": 25926, "s": 25921, "text": "Java" }, { "code": null, "e": 26024, "s": 25926, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26033, "s": 26024, "text": "Comments" }, { "code": null, "e": 26046, "s": 26033, "text": "Old Comments" }, { "code": null, "e": 26064, "s": 26046, "text": "Hashtable in Java" }, { "code": null, "e": 26085, "s": 26064, "text": "Constructors in Java" }, { "code": null, "e": 26131, "s": 26085, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26174, "s": 26131, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 26214, "s": 26174, "text": "Java Math random() method with Examples" }, { "code": null, "e": 26251, "s": 26214, "text": "HashMap containsKey() Method in Java" }, { "code": null, "e": 26291, "s": 26251, "text": "How to Create Array of Objects in Java?" }, { "code": null, "e": 26325, "s": 26291, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 26359, "s": 26325, "text": "Iterating over ArrayLists in Java" } ]
Move all negative elements to end | Practice | GeeksforGeeks
Given an unsorted array arr[] of size N having both negative and positive integers. The task is place all negative element at the end of array without changing the order of positive element and negative element. Example 1: Input : N = 8 arr[] = {1, -1, 3, 2, -7, -5, 11, 6 } Output : 1 3 2 11 6 -1 -7 -5 Example 2: Input : N=8 arr[] = {-5, 7, -3, -4, 9, 10, -1, 11} Output : 7 9 10 11 -5 -3 -4 -1 Your Task: You don't need to read input or print anything. Your task is to complete the function segregateElements() which takes the array arr[] and its size N as inputs and store the answer in the array arr[] itself. Expected Time Complexity: O(N) Expected Auxiliary Space: O(N) Constraints: 1 ≤ N ≤ 105 -105 ≤ arr[] ≤ 105 0 tanashah3 days ago vector<int>v1,v2; for(int i=0;i<n;i++){ if(arr[i]>0){ v1.push_back(arr[i]); }else{ v2.push_back(arr[i]); } } for(int i=0;i<v2.size();i++){ v1.push_back(v2[i]); } for(int i=0;i<n;i++){ arr[i]=v1[i]; } 0 niravramotiya0035 days ago def segregateElements(self, arr, n): arr1,arr2=[],[] for i in arr: if i<0: arr1.append(i) else: arr2.append(i) arr2.extend(arr1) arr1.clear() for i in range(n): arr[i]=arr2[i] arr2.clear() 0 shividee101 week ago class Solution{ segregateElements(arr,n){ let newArrNegative = []; let newArrPositive = []; for(let i=0; i<n; i++) { if(arr[i] < 0) { newArrNegative.push(arr[i]); } else { newArrPositive.push(arr[i]); } } arr = []; console.log(arr.concat(newArrPositive,newArrNegative)); return arr.concat(newArrPositive,newArrNegative) }}Why is console.log priniting the correct value but return printing the same input array? 0 mannukhurana103971 week ago Java public void segregateElements(int arr[], int n) { // 1 -1 3 2 -7 -5 11 6 // space : 0 // time : O(N*logN) // for(int i=1; i<n; i++){ // n // if(arr[i] >0){ // int j=i-1; //6 // while(j>=0 && arr[j]<0) // 1, n-1 // arr[j+1] = arr[j--]; // arr[++j] = temp; // } // } //------------------------------------------------------------- // space : O(N) // time: O(2N) List<Integer> pos = new LinkedList<Integer>(); List<Integer> neg = new LinkedList<Integer>(); for(int i=0;i<n;i++){ if(arr[i]>0) pos.add(arr[i]); else neg.add(arr[i]); } int i=0; for(int j: pos) arr[i++] = j; for(int j: neg) arr[i++] = j; } 0 iamprakhars2 weeks ago void segregateElements(int arr[],int n) { vector<int>temp; for(int i=0; i<n; i++){ if(arr[i]<0)temp.push_back(arr[i]); } int idx=0; for(int i=0; i<n; i++){ if(arr[i]<0)continue; arr[idx++]=arr[i]; } for(int i=idx; i<n; i++){ arr[i]=temp[i-idx]; } } 0 yadavbanti4952 weeks ago void segregateElements(int arr[],int n) { int count1=0,arr1[n]; for(int i=0;i<n;i++) { if(arr[i]>0) { count1++; } } for(int i=0,j=0;i<n;i++) { if(arr[i]>0) { arr1[j]=arr[i]; j++; } else{ arr1[count1]=arr[i]; count1++; } } for(int i=0;i<n;i++) { arr[i]=arr1[i]; } } 0 lankelokeshkumar2 weeks ago void segregateElements(int arr[],int n) { int cnt=0,temp[n]; for(int i=0;i<n;i++) { if(arr[i]>0) cnt++; } for(int i=0,j=0;i<n;i++) { if(arr[i]>0) { temp[j]=arr[i]; j++; } else { temp[cnt]=arr[i]; cnt++; } } for(int i=0;i<n;i++) { arr[i]=temp[i]; } } 0 suprithsk20012 weeks ago void segregateElements(int arr[],int n) { // Your code goes here vector<int> ans1; vector<int> ans2; for(int i=0;i<n;i++){ if(arr[i]<0){ ans2.push_back(arr[i]); } else{ ans1.push_back(arr[i]); } } for(int i=0;i<ans1.size();i++){ arr[i]=ans1[i]; } int k=ans1.size(); for(int i=0;i<ans2.size() && k<n;i++){ arr[k]=ans2[i]; k++; } } +1 nk01879122 weeks ago //Simple Two pointer java solution class Solution { public void segregateElements(int arr[], int n){ if(arr.length <= 1) return; int start = 0; int end = 0; ArrayList<Integer> list = new ArrayList<>(); while(end < arr.length){ if(arr[end] > -1){ arr[start++] = arr[end]; } else list.add(arr[end]); end++; } end = 0; while(start < arr.length){ arr[start++] = list.get(end++); } }} 0 bhaskarparadox2 weeks ago C++ Solution void segregateElements(int arr[],int n) { vector<int> v; int k = 0; int i = 0; for(int i=0; i<n; i++){ if(arr[i]>=0){ arr[k++] = arr[i]; } else{ v.push_back(arr[i]); } } i = 0; while(k<n){ arr[k++] = v[i++]; } } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 450, "s": 238, "text": "Given an unsorted array arr[] of size N having both negative and positive integers. The task is place all negative element at the end of array without changing the order of positive element and negative element." }, { "code": null, "e": 463, "s": 452, "text": "Example 1:" }, { "code": null, "e": 553, "s": 463, "text": "Input : \nN = 8\narr[] = {1, -1, 3, 2, -7, -5, 11, 6 }\nOutput : \n1 3 2 11 6 -1 -7 -5" }, { "code": null, "e": 565, "s": 553, "text": "\nExample 2:" }, { "code": null, "e": 656, "s": 565, "text": "Input : \nN=8\narr[] = {-5, 7, -3, -4, 9, 10, -1, 11}\nOutput :\n7 9 10 11 -5 -3 -4 -1\n" }, { "code": null, "e": 878, "s": 658, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function segregateElements() which takes the array arr[] and its size N as inputs and store the answer in the array arr[] itself." }, { "code": null, "e": 944, "s": 880, "text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\n " }, { "code": null, "e": 990, "s": 944, "text": "\nConstraints:\n1 ≤ N ≤ 105\n-105 ≤ arr[] ≤ 105" }, { "code": null, "e": 992, "s": 990, "text": "0" }, { "code": null, "e": 1011, "s": 992, "text": "tanashah3 days ago" }, { "code": null, "e": 1360, "s": 1011, "text": " vector<int>v1,v2;\n for(int i=0;i<n;i++){\n if(arr[i]>0){\n v1.push_back(arr[i]);\n }else{\n v2.push_back(arr[i]);\n }\n }\n for(int i=0;i<v2.size();i++){\n v1.push_back(v2[i]);\n }\n for(int i=0;i<n;i++){\n arr[i]=v1[i];\n }" }, { "code": null, "e": 1362, "s": 1360, "text": "0" }, { "code": null, "e": 1389, "s": 1362, "text": "niravramotiya0035 days ago" }, { "code": null, "e": 1683, "s": 1389, "text": "def segregateElements(self, arr, n):\n arr1,arr2=[],[]\n for i in arr:\n if i<0:\n arr1.append(i)\n else:\n arr2.append(i)\n arr2.extend(arr1)\n arr1.clear()\n for i in range(n):\n arr[i]=arr2[i]\n arr2.clear()" }, { "code": null, "e": 1685, "s": 1683, "text": "0" }, { "code": null, "e": 1706, "s": 1685, "text": "shividee101 week ago" }, { "code": null, "e": 2073, "s": 1706, "text": "class Solution{ segregateElements(arr,n){ let newArrNegative = []; let newArrPositive = []; for(let i=0; i<n; i++) { if(arr[i] < 0) { newArrNegative.push(arr[i]); } else { newArrPositive.push(arr[i]); } } arr = []; console.log(arr.concat(newArrPositive,newArrNegative));" }, { "code": null, "e": 2222, "s": 2073, "text": " return arr.concat(newArrPositive,newArrNegative) }}Why is console.log priniting the correct value but return printing the same input array?" }, { "code": null, "e": 2224, "s": 2222, "text": "0" }, { "code": null, "e": 2252, "s": 2224, "text": "mannukhurana103971 week ago" }, { "code": null, "e": 2257, "s": 2252, "text": "Java" }, { "code": null, "e": 3204, "s": 2259, "text": " public void segregateElements(int arr[], int n)\n {\n // 1 -1 3 2 -7 -5 11 6\n \n // space : 0\n // time : O(N*logN)\n \n // for(int i=1; i<n; i++){ // n\n // if(arr[i] >0){\n // int j=i-1; //6\n // while(j>=0 && arr[j]<0) // 1, n-1\n // arr[j+1] = arr[j--];\n // arr[++j] = temp;\n // }\n \n // }\n //------------------------------------------------------------- \n // space : O(N)\n // time: O(2N)\n \n List<Integer> pos = new LinkedList<Integer>(); \n List<Integer> neg = new LinkedList<Integer>();\n for(int i=0;i<n;i++){\n if(arr[i]>0) pos.add(arr[i]);\n else neg.add(arr[i]);\n }\n \n int i=0;\n for(int j: pos)\n arr[i++] = j;\n for(int j: neg)\n arr[i++] = j;\n \n \n \n }" }, { "code": null, "e": 3206, "s": 3204, "text": "0" }, { "code": null, "e": 3229, "s": 3206, "text": "iamprakhars2 weeks ago" }, { "code": null, "e": 3570, "s": 3229, "text": "void segregateElements(int arr[],int n) { vector<int>temp; for(int i=0; i<n; i++){ if(arr[i]<0)temp.push_back(arr[i]); } int idx=0; for(int i=0; i<n; i++){ if(arr[i]<0)continue; arr[idx++]=arr[i]; } for(int i=idx; i<n; i++){ arr[i]=temp[i-idx]; } }" }, { "code": null, "e": 3572, "s": 3570, "text": "0" }, { "code": null, "e": 3597, "s": 3572, "text": "yadavbanti4952 weeks ago" }, { "code": null, "e": 4070, "s": 3597, "text": "void segregateElements(int arr[],int n) { int count1=0,arr1[n]; for(int i=0;i<n;i++) { if(arr[i]>0) { count1++; } } for(int i=0,j=0;i<n;i++) { if(arr[i]>0) { arr1[j]=arr[i]; j++; } else{ arr1[count1]=arr[i]; count1++; } } for(int i=0;i<n;i++) { arr[i]=arr1[i]; } }" }, { "code": null, "e": 4072, "s": 4070, "text": "0" }, { "code": null, "e": 4100, "s": 4072, "text": "lankelokeshkumar2 weeks ago" }, { "code": null, "e": 4451, "s": 4100, "text": " void segregateElements(int arr[],int n) { int cnt=0,temp[n]; for(int i=0;i<n;i++) { if(arr[i]>0) cnt++; } for(int i=0,j=0;i<n;i++) { if(arr[i]>0) { temp[j]=arr[i]; j++; } else { temp[cnt]=arr[i]; cnt++; } } for(int i=0;i<n;i++) { arr[i]=temp[i]; } }" }, { "code": null, "e": 4453, "s": 4451, "text": "0" }, { "code": null, "e": 4478, "s": 4453, "text": "suprithsk20012 weeks ago" }, { "code": null, "e": 4970, "s": 4478, "text": "void segregateElements(int arr[],int n) { // Your code goes here vector<int> ans1; vector<int> ans2; for(int i=0;i<n;i++){ if(arr[i]<0){ ans2.push_back(arr[i]); } else{ ans1.push_back(arr[i]); } } for(int i=0;i<ans1.size();i++){ arr[i]=ans1[i]; } int k=ans1.size(); for(int i=0;i<ans2.size() && k<n;i++){ arr[k]=ans2[i]; k++; } }" }, { "code": null, "e": 4973, "s": 4970, "text": "+1" }, { "code": null, "e": 4994, "s": 4973, "text": "nk01879122 weeks ago" }, { "code": null, "e": 5029, "s": 4994, "text": "//Simple Two pointer java solution" }, { "code": null, "e": 5580, "s": 5029, "text": "class Solution { public void segregateElements(int arr[], int n){ if(arr.length <= 1) return; int start = 0; int end = 0; ArrayList<Integer> list = new ArrayList<>(); while(end < arr.length){ if(arr[end] > -1){ arr[start++] = arr[end]; } else list.add(arr[end]); end++; } end = 0; while(start < arr.length){ arr[start++] = list.get(end++); } }} " }, { "code": null, "e": 5582, "s": 5580, "text": "0" }, { "code": null, "e": 5608, "s": 5582, "text": "bhaskarparadox2 weeks ago" }, { "code": null, "e": 5621, "s": 5608, "text": "C++ Solution" }, { "code": null, "e": 6001, "s": 5621, "text": " void segregateElements(int arr[],int n)\n {\n vector<int> v;\n int k = 0;\n int i = 0;\n for(int i=0; i<n; i++){\n if(arr[i]>=0){\n arr[k++] = arr[i];\n }\n else{\n v.push_back(arr[i]);\n }\n }\n i = 0;\n while(k<n){\n arr[k++] = v[i++];\n }\n }" }, { "code": null, "e": 6147, "s": 6001, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 6183, "s": 6147, "text": " Login to access your submissions. " }, { "code": null, "e": 6193, "s": 6183, "text": "\nProblem\n" }, { "code": null, "e": 6203, "s": 6193, "text": "\nContest\n" }, { "code": null, "e": 6266, "s": 6203, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6414, "s": 6266, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6622, "s": 6414, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 6728, "s": 6622, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Count no. of characters and words in a string in PL/SQL - GeeksforGeeks
05 Jul, 2018 Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations. Given a string and the task is to count the number of characters and words in the given string.Examples: Input: str = 'Geeks for geeks ' Output: Characters = 13 , Words = 3 Input: str = 'A Computer science portal' Output: Characters = 22, Words = 4 Approach is to maintain two counter variables i.e. one for the characters and the other for words. Start traversing character one by one and increment the count and when there is a blank space then increment the count of words.Below is the required implementation: DECLARE -- Declare required variables str VARCHAR2(40) := 'Geeks for Geeks'; noofchars NUMBER(4) := 0; noofwords NUMBER(4) := 1; s CHAR; BEGIN FOR i IN 1..Length(str) LOOP s := Substr(str, i, 1); -- Count no. of characters noofchars := noofchars + 1; -- Count no. of words IF s = ' ' THEN noofwords := noofwords + 1; END IF; END LOOP; dbms_output.Put_line('No. of characters:' ||noofchars); dbms_output.Put_line('No. of words: ' ||noofwords); END; -- Program End Output : No. of characters:15 No. of words: 3 SQL-PL/SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Interview Questions CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? Difference between DELETE, DROP and TRUNCATE SQL | Views Difference between SQL and NoSQL MySQL | Group_CONCAT() Function How to Create a Table With Multiple Foreign Keys in SQL? Difference between DELETE and TRUNCATE Difference between DDL and DML in DBMS
[ { "code": null, "e": 25808, "s": 25780, "text": "\n05 Jul, 2018" }, { "code": null, "e": 26052, "s": 25808, "text": "Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations." }, { "code": null, "e": 26157, "s": 26052, "text": "Given a string and the task is to count the number of characters and words in the given string.Examples:" }, { "code": null, "e": 26303, "s": 26157, "text": "Input: str = 'Geeks for geeks '\nOutput: Characters = 13 , Words = 3\n\nInput: str = 'A Computer science portal'\nOutput: Characters = 22, Words = 4\n" }, { "code": null, "e": 26568, "s": 26303, "text": "Approach is to maintain two counter variables i.e. one for the characters and the other for words. Start traversing character one by one and increment the count and when there is a blank space then increment the count of words.Below is the required implementation:" }, { "code": "DECLARE -- Declare required variables str VARCHAR2(40) := 'Geeks for Geeks'; noofchars NUMBER(4) := 0; noofwords NUMBER(4) := 1; s CHAR; BEGIN FOR i IN 1..Length(str) LOOP s := Substr(str, i, 1); -- Count no. of characters noofchars := noofchars + 1; -- Count no. of words IF s = ' ' THEN noofwords := noofwords + 1; END IF; END LOOP; dbms_output.Put_line('No. of characters:' ||noofchars); dbms_output.Put_line('No. of words: ' ||noofwords); END; -- Program End ", "e": 27199, "s": 26568, "text": null }, { "code": null, "e": 27208, "s": 27199, "text": "Output :" }, { "code": null, "e": 27246, "s": 27208, "text": "No. of characters:15\nNo. of words: 3\n" }, { "code": null, "e": 27257, "s": 27246, "text": "SQL-PL/SQL" }, { "code": null, "e": 27261, "s": 27257, "text": "SQL" }, { "code": null, "e": 27265, "s": 27261, "text": "SQL" }, { "code": null, "e": 27363, "s": 27265, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27387, "s": 27363, "text": "SQL Interview Questions" }, { "code": null, "e": 27398, "s": 27387, "text": "CTE in SQL" }, { "code": null, "e": 27464, "s": 27398, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 27509, "s": 27464, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 27521, "s": 27509, "text": "SQL | Views" }, { "code": null, "e": 27554, "s": 27521, "text": "Difference between SQL and NoSQL" }, { "code": null, "e": 27586, "s": 27554, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 27643, "s": 27586, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 27682, "s": 27643, "text": "Difference between DELETE and TRUNCATE" } ]
Targeting Users In Specific Area Using Geofence API | by Himanshu Verma | Towards Data Science
Google Geofence API is used when you want to notify users if they are near the specific area in the world (such as Shopping Malls, Airport, Restaurants etc.). For example, the customer has installed an online shopping app and if they are near one of the stores that the app has a tie up with, then store could generate a notification in the app to let the customer know that the store near them has a special offer running for them. This way you can engage more users. To use the Geofence API, you’ll have to obtain the Google Maps API key using the following set of steps. Click on THIS link to open the Google Cloud Platform, if you’re not signed in, then please sign in first and create the project. You can give any name to this project or you can just leave it as it is and click on CREATE now. Now ensure that you’ve selected the newly created project. Now click on the menu icon on left and select the APIs & Services and then choose Library from the sub-list. Search Maps SDK for Android and enable this API (don’t forget to enable API because it's important) Now again click on the menu icon on left and choose Credentials and then + CREATE CREDENTIALS and finally click on API Key Copy this API Key and paste it inside the string.xml file We’re going to build an application which will allow you to set your location (or specific area to be precise) on a map. And when you reach the specified location, your app will notify you with a message you defined at the time when you set the location. In the end, you’ll have an app which will look similar to this. To set the location on the map, you can drag the marker on your desired location. Once you specified your location, you can proceed by clicking CONTINUE button. Are you excited now?, I’m sure you’ll be. Google Map API Google Geofence API Service Broadcast Receiver Creating Notification Storing and retrieving custom objects in Shared-preference Now let’s quickly set up our project and proceed. Create a New Android Project, select the empty activity and give any name you want to your project. Add the following dependencies in your app-level build.gradle implementation 'com.google.android.gms:play-services-location:16.0.0'implementation 'com.google.android.gms:play-services-maps:16.0.0'implementation 'com.google.code.gson:gson:2.8.5'implementation "com.google.android.material:material:1.1.0-alpha02" If you encounter the following error in your activity.xml file Then add the following line inside your build.gradle android{ defaultConfig {vectorDrawables.useSupportLibrary = true}} Add the following permissions in your AndroidManifest.xml file <uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> Now add the below meta-data tag in your AndroidManifest.xml file inside the <application> tag, we’ll add the API_KEY here later on. <meta-data android:name="com.google.android.geo.API_KEY" android:value="API_KEY"/> Finally, sync the project and setup done. Let’s get quickly familiar with some android components used in this app Service: A service is an android component which is used to perform background tasks. A task may be of any kind such as uploading photos, syncing user data on server and generating notifications etc. Broadcast Receiver: A broadcast receiver is also a fundamental component of android, it comes handy when you want to perform some actions in your app which are based on future events. For instance, you only want to upload user data to your server when the phone is connected to the WIFI and another example is, you want to start the background service when the user restarts his phone. PendingIntent: PendingIntent is similar to normal intent except that it will not execute immediately. I’ve all the classes, utility functions and constants under the root package. Let’s understand them one by one. MainActivity.kt: This is our home screen which will show you Google Map and two action buttons on the bottom right side. The first button will allow you to zoom in on the map and the plus action button will open new activity which is ReminderActivity.kt, on this screen you can choose your location and set the message and save the reminder. ReminderActivity.kt: As I explained this activity will allow you to set the location and save the reminder in the shared-preference. When you choose the location and save it, you’ll see the circle around the location you specified. This circle is boundary or radius you’ll define in your code. The larger circle means, it will cover the larger area. And as you enter into this area, you’ll be notified by a notification. MyBroadcast Receiver: This is a broadcast receiver which will be fired when the user reaches to the specified location. When this broadcast receiver fires, it will execute the background service. GeofenceTransitionService.kt: This is a service which will be executed by our broadcast receiver and when this executes it generates the notification to let user know he has reached his destination. MyReminder.kt: This is a data class and in its constructor, I’m accepting four parameters and they’re unique id, latitude, longitude, radium and a message. We’ll keep this information in shared-preference and at the same time, we will set the Pending Intent to generate the notification. MyReminderRepository.kt: As you know repository helps us to get the core methods of the application to perform actions we defined for our app. So only this class is responsible for adding a new reminder, removing reminder and setting Pending Intents. We will always create an object of this class and perform the actions. Utils.kt: This is our utility class which contains four methods.vectorToBitmap() method converts the vector image to bitmap, showReminderInMap() method displays the reminder on the map, this is the method which draws the circle around the specified location. And sendNotification() method creates the notification, this method is called by our background service. The last method is getUniqueId() which obviously returns the unique id. AppConstants.kt: This class contains all the constants used for this app. This class also contains a service method and two methods to call the MainActivity.kt and ReminderActivity.kt activities. Enough talking? let’s get back to business... When you create a project, you will have a default ActivityMain.kt class. I want you to create one more class and name it as ReminderActivity.kt. In this class extend AppCompatActivity() class and implement OnMapReadyCallback the interface of Google Map and implement its method onMapReady(). For now, leave everything as it is. Now we’ll create our AppConstants class and define all constants and few methods. In this class, we defined our constants and three methods, newIntentForMainActivity() method will call the MainActivity.kt class and newIntentForReminderActivity() will call the ReminderActivity.kt class. enqueueWork() method will be called by our broadcast receiver to generate the notification.Tip: All constants and methods are defined inside the companion object, and this is because whenever we need to call any of these methods, we won’t have to create object of this class. Now we’ll create Utils.kt and add the following methods When we’ll call this method, we have to pass two parameters i.e context.resources and an id of our image which needs to converted into bitmap. The context.resources returns a resources instance for your application. Inside this method, I got the drawable object, created the Bitmap and Canvas objects. We now have our image in vectorDrawable and we’ll convert this object into bitmap, then draw bitmap on canvas and set its bounds and return. Tip: If you’re not familiar with Canvas, then you can think of it as a blank piece of paper where you can draw any shape. showReminderInMap() method takes context, GoogleMap object and MyReminder class object as an argument and checks if myReminder has a value, then it proceeds further otherwise it does nothing. Inside the if statement I’m getting the latitude and longitude from my myReminder object and casting it to LatLng and in the second if statement, I’m drawing the circle around the specified location. In general, this method is used to draw the circle on a specified location. The sendNotification() method is pretty straightforward, it does nothing except creating the notification. This method is called from the service to show the notification. Now create this class in your root directory and also add this broadcast receiver in your AndroidManifest.xml file. <receiver android:name=".MyBroadcastReceiver" android:enabled="true" android:exported="true" /> This class extends the BroadcastReceiver() class which is an abstract class and implements its onReceive() method. As the onReceive() method is executed, it will execute the enqueueWork() method of AppConstants.kt. This receiver would be registered viaPendingIntent when you will add the reminder. Create this class and declare it in the AndroidManifest.xml file <service android:name=".GeofenceTransitionService" android:exported="true" android:permission="android.permission.BIND_JOB_SERVICE" /> Note: If a job service is declared in the manifest but not protected with BIND_JOB_SERVICE permission, that service will be ignored by the system. This is a service which extends the JobIntentService class, IntentService or JobIntentService is a service which runs in the background on a separate thread and it gets destroyed when the job is done. To use this class we’ll have to implement its required method onHandleWork() . class GeofenceTransitionService : JobIntentService() {override fun onHandleWork(intent: Intent) { val geofencingEvent = GeofencingEvent.fromIntent(intent) repositoryMy = MyReminderRepository(this) if (geofencingEvent.hasError()) { Log.e(AppConstants.LOG_TAG, "An error occured") return } handleEvent(geofencingEvent)}} Inside this method, we can do our task. I’m getting the object of GeofencingEvent class inside this method, if there is an issue, we show the error message otherwise we call the handleEvent() method. private fun handleEvent(event: GeofencingEvent) { if (event.geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER) { val reminder = getFirstReminder(event.triggeringGeofences) val message = reminder?.message val latLng = reminder?.latLng if (message != null && latLng != null) { sendNotification(this, message, latLng) } }} In this method, we first use the GeofencingEvent object and checks whether the user enters in the specified area or not, if it then gets the reminder object from the repository, retrieves its data and send the notification. private fun getFirstReminder(triggeringGeofences: List<Geofence>): MyReminder? { val firstGeofence = triggeringGeofences[0] return repositoryMy.get(firstGeofence.requestId)} getFirstReminder() method returns the object of MyReminder class from the MyRepository class. Below is the full code for this service class Tip: lateinit is a keyword in Kotlin which frees you from not to initialise it at time of declaration but it should be initialised before its use otherwise, you will run into the NullPointerException. You can think of this class as a local server which means it serves us everything we needed to perform any action on the map such as adding a reminder or removing reminder and maintaining all reminders. The following code snippet creates an object of GeofencingClient which helps you to manipulate the geofences. private val geofencingClient = LocationServices.getGeofencingClient(context) Here we’re getting the SharedPreference object and Gson object private val preferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)private val gson = Gson() In the SharedPreference, we’ll store the reminders and using Gson object we’ll convert json string to Java object and vice-versa. Since SharedPreference can hold only primitive values in the form of key-value pairs but we want to store our class object, so how it is possible?. Obviously, we can convert our object to json string and store it in a SharedPreference, whenever we need to use it, we will convert it into a real object. The combination of latitude, longitude and a radius is known as geofence. It’s a circular area at a specific location on the map. Whenever users enter this area, the app will trigger particular behaviour. private fun buildGeofence(myReminder: MyReminder): Geofence? { val latitude = myReminder.latLng?.latitude val longitude = myReminder.latLng?.longitude val radius = myReminder.radius if (latitude != null && longitude != null && radius != null) { return Geofence.Builder() .setRequestId(myReminder.id) .setCircularRegion( latitude, longitude, radius.toFloat() ) .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER) .setExpirationDuration(Geofence.NEVER_EXPIRE) .build() } return null} Look at the code, we’re building the geofence using Geofence.Builder(). In the method setRequestId(), I’m passing unique id since every geofence is unique in its way, you will get this id from your model class. In the setCircularRegion(), I’m setting my latitude, longitude and radius, all these parameters together form a circle on a specific location. The setTransitionTypes() defines the transition type, you can use GEOFENCE_TRANSITION_ENTER to trigger an event when the user enters into the defined area. The setExpirationDuration() method sets the expiry of the geofence, we’re using NEVER_EXPIRE which means that it will never expire until the user removes it. You’ll use this method to build the geofence request. private fun buildGeofencingRequest(geofence: Geofence): GeofencingRequest { return GeofencingRequest.Builder() .setInitialTrigger(0) .addGeofences(listOf(geofence)) .build()} Here you’re setting setInitialTrigger() to 0 which means that you don’t want your app to trigger an event when the app is already inside the geofence. And the next addGeofences() method adds the request to geofence. As you can see in the code snippet, we’re passing MyBroadcastReceiver in the intent object which means that when this pending intent is called, it will call broadcast receiver and this receiver will call GeofenceTransitionService. private val geofencePendingIntent: PendingIntent by lazy { val intent = Intent(context, MyBroadcastReceiver::class.java) PendingIntent.getBroadcast( context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT )} This code will only be executed when GEOFENCE_TRANSITION_ENTER event is triggered. Tip: by lazy property, the value only gets computed when this is used for the first time. This add() method adds the reminder in the SharedPreference and also adds the request to the geofence. fun add(myReminder: MyReminder, success: () -> Unit, failure: (error: String) -> Unit){ val geofence = buildGeofence(myReminder) if (geofence != null && ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { geofencingClient.addGeofences(buildGeofencingRequest(geofence), geofencePendingIntent) .addOnSuccessListener { saveAll(getAll() + myReminder) success() } .addOnFailureListener { failure("An error occured") } }} First of all, we’re checking the permission if it is granted, then we proceed, and next, we’re creating the geofence using the geofencingClient if it is successful, then only we’ll save in shared preference, otherwise report an error message. This method simply removes the reminder from the list. fun remove(myReminder: MyReminder) { val list = getAll() - myReminder saveAll(list)} This method adds all the reminders in the list in shared-preference. private fun saveAll(list: List<MyReminder>) { preferences .edit() .putString(REMINDERS, gson.toJson(list)) .apply()} Notice we’re converting the list to Json string, then we’re storing it. This method returns the list of all reminders we stored in the shared-preference. fun getAll(): List<MyReminder> { if (preferences.contains(REMINDERS)) { val remindersString = preferences.getString(REMINDERS, null) val arrayOfReminders = gson.fromJson( remindersString, Array<MyReminder>::class.java ) if (arrayOfReminders != null) { return arrayOfReminders.toList() } } return listOf()} This function returns the reminder added in the list. fun getLast() = getAll().lastOrNull() Notice this function first calls the getAll() method which returns a list and we call lastOrNull() function which is a method of List class and this method returns the last value. This method returns the first reminder from the list if the list is not null. fun get(requestId: String?) = getAll().firstOrNull { it.id == requestId } {it.id == requestId } is a lambda expression which is performing null checking. When there is only a single parameter inside the lambda expression, then it can be used. Complete code for MyReminderRepository.kt This activity allows us to add the new reminder on the specified location. First of all, create these objects in this activity. private lateinit var map: GoogleMaplateinit var myRepository: MyReminderRepositoryprivate var reminder = MyReminder(latLng = null, radius = null, message = null) Now paste the following code inside your onCreate() method override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_new_reminder) myRepository = MyReminderRepository(this) val mapFragment = supportFragmentManager .findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync(this) instructionTitle.visibility = View.GONE radiusDescription.visibility = View.GONE message.visibility = View.GONE} In this onCreate() method, I’m initialising my repository instance variable and setting the map. Initially, I hide all the TextView. In this method, I’m getting LatLng as well as zoom value from the intent and setting the camera at the centre of the location. private fun centerCamera() { val latLng = intent.extras?.get(AppConstants.LAT_LNG) as LatLng val zoom = intent.extras?.get(AppConstants.ZOOM) as Float map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom))} This method updates the reminder. On calling this method, it will show you circle around the location. private fun showReminderUpdate() { map.clear() showReminderInMap(this, map, reminder)} This method simply guides you through how you can navigate on the map. private fun showConfigureLocationStep() { marker.visibility = View.VISIBLE instructionTitle.visibility = View.VISIBLE radiusDescription.visibility = View.GONE message.visibility = View.GONE instructionTitle.text = "Drag map to set location" next.setOnClickListener { reminder.latLng = map.cameraPosition.target showConfigureRadiusStep() } showReminderUpdate()} This method is same as the above method and it guides you through how to add a message. This message will be shown when you will get a notification. private fun showConfigureMessageStep() { marker.visibility = View.GONE instructionTitle.visibility = View.VISIBLE message.visibility = View.VISIBLE instructionTitle.text = "Enter a message" next.setOnClickListener { reminder.message = message.text.toString() if (reminder.message.isNullOrEmpty()) { message.error = "Message Error" } else { addReminder(reminder) } } showReminderUpdate()} This method calls the add method from the MyReminderRepository class and adds the reminder. If the reminder is added successfully, then it will you Snackbar on the bottom with a message “Reminder added” else failure message. private fun addReminder(myReminder: MyReminder) { myRepository.add(myReminder, success = { setResult(Activity.RESULT_OK) finish() }, failure = { Snackbar.make(main, it, Snackbar.LENGTH_LONG).show() })} Finally modify your onMapReady() override fun onMapReady(googleMap: GoogleMap) { map = googleMap map.uiSettings.isMapToolbarEnabled = false centerCamera() showConfigureLocationStep()} Inside this method, we’re assigning the GoogleMap object to our map and then configuring settings. Complete code for this activity Layout file for this activity The only thing you can notice in <fragment> tag is “android:name=”com.google.android.gms.maps.SupportMapFragment” line and this line helps you to add the Google map on the screen. This is the simplest way of adding a map. And rest of the code inside this file must be quite familiar for you. Finally, this is the last part of our code. This is our home activity which you will see when you first interact with the app. First of all, add these listeners in your activity and implement all its methods. class MainActivity : AppCompatActivity(), OnMapReadyCallback, GoogleMap.OnMarkerClickListener Now create these instance variables. lateinit var myRepository: MyReminderRepository private var map: GoogleMap? = null private lateinit var locationManager: LocationManager In this method, we’re initialising our instance variables first, then getting a map from a fragment from the activity_main.xml file and the listeners on the action buttons. Initially, these buttons will not be visible until the user gives ACCESS_FINE_LOCATION permission. As a user grants the permission, we make the buttons visible to the users inside the onMapAndPermissionReady() method. Look at the below code, here I’m attaching a listener to the button and inside the lambda expression, I’m calling run method of Google map class. This run is also a lambda function. When user presses (+) action button, we take the user to the ReminderActivity.kt class. actionNewReminder.setOnClickListener { map?.run { val intent = AppConstants.newIntentForReminderActivity( this@MainActivity, cameraPosition.target, cameraPosition.zoom ) startActivityForResult(intent, AppConstants.REMINDER_REQUEST_CODE) }} When permission is granted and the map doesn’t equal null, then we’re making visible our buttons and adding a listener to the actionCurrentLocation button. Now if the user presses the actionCurrentLocation button, then we get the location provider and last known location of the user. And if this is not null, then we’ll move the camera to the last know location. When a user clicks on the marker, then an alert dialog pops up to ask user, if he wants to remove the reminder, if he presses “YES” then that reminder gets removed from the list. override fun onMarkerClick(marker: Marker): Boolean { val reminder = myRepository.get(marker.tag as String) if (reminder != null) { showReminderRemoveAlert(reminder) } return true} showReminderRemoveAlert(): This method only creates an alert dialog with two options, i.e OK and Cancel and if a user clicks on “Ok”, then we call removeReminder() to remove it. private fun showReminderRemoveAlert(myReminder: MyReminder) { val alertDialog = AlertDialog.Builder(this).create() alertDialog.run { setMessage("Reminder Removed") setButton( AlertDialog.BUTTON_POSITIVE, "OK" ) { dialog, _ -> removeReminder(myReminder) dialog.dismiss() } setButton( AlertDialog.BUTTON_NEGATIVE, "Cancel" ) { dialog, _ -> dialog.dismiss() } show() }} Complete code of our ActivityMain.kt file Now finally we have our activity_main.xml file Run the app and give permission. If you’re running app on emulator, then click on three dots you’ll see the follow screen. Now set any location you want (I set Connaught Place, New Delhi). And save this location. Now click on the first action button on your app and you’ll see your map will navigate to the specified location. Now add a reminder by click the (+) action button, drag the map to set your location, click on Continue and now type your message and again click Continue. Now your reminder has been saved. Now again click on three dots, change location to somewhere else on emulator and save it. Click on the first button your app, you will reach to the location you set on your emulator. Finally, In the emulator, set your location where you set your reminder while saving it. And wait for a few seconds you’ll a notification. If you have any difficulty with your project, then you can seek help from my Github project. Subscribe to my mailing list to get the early access of my articles directly in your inbox and don’t forget to follow my own publication on Medium The Code Monster to polish your technical knowledge. We’ve learnt how we can use Google map and Geofence APIs in our own project and we also learnt about services and broadcast receivers. Apart from this, we learnt a trick to store custom java object in SharedPreference using Gson and retrieving them using the same.
[ { "code": null, "e": 641, "s": 172, "text": "Google Geofence API is used when you want to notify users if they are near the specific area in the world (such as Shopping Malls, Airport, Restaurants etc.). For example, the customer has installed an online shopping app and if they are near one of the stores that the app has a tie up with, then store could generate a notification in the app to let the customer know that the store near them has a special offer running for them. This way you can engage more users." }, { "code": null, "e": 746, "s": 641, "text": "To use the Geofence API, you’ll have to obtain the Google Maps API key using the following set of steps." }, { "code": null, "e": 875, "s": 746, "text": "Click on THIS link to open the Google Cloud Platform, if you’re not signed in, then please sign in first and create the project." }, { "code": null, "e": 972, "s": 875, "text": "You can give any name to this project or you can just leave it as it is and click on CREATE now." }, { "code": null, "e": 1031, "s": 972, "text": "Now ensure that you’ve selected the newly created project." }, { "code": null, "e": 1140, "s": 1031, "text": "Now click on the menu icon on left and select the APIs & Services and then choose Library from the sub-list." }, { "code": null, "e": 1240, "s": 1140, "text": "Search Maps SDK for Android and enable this API (don’t forget to enable API because it's important)" }, { "code": null, "e": 1363, "s": 1240, "text": "Now again click on the menu icon on left and choose Credentials and then + CREATE CREDENTIALS and finally click on API Key" }, { "code": null, "e": 1421, "s": 1363, "text": "Copy this API Key and paste it inside the string.xml file" }, { "code": null, "e": 1676, "s": 1421, "text": "We’re going to build an application which will allow you to set your location (or specific area to be precise) on a map. And when you reach the specified location, your app will notify you with a message you defined at the time when you set the location." }, { "code": null, "e": 1740, "s": 1676, "text": "In the end, you’ll have an app which will look similar to this." }, { "code": null, "e": 1901, "s": 1740, "text": "To set the location on the map, you can drag the marker on your desired location. Once you specified your location, you can proceed by clicking CONTINUE button." }, { "code": null, "e": 1943, "s": 1901, "text": "Are you excited now?, I’m sure you’ll be." }, { "code": null, "e": 1958, "s": 1943, "text": "Google Map API" }, { "code": null, "e": 1978, "s": 1958, "text": "Google Geofence API" }, { "code": null, "e": 1986, "s": 1978, "text": "Service" }, { "code": null, "e": 2005, "s": 1986, "text": "Broadcast Receiver" }, { "code": null, "e": 2027, "s": 2005, "text": "Creating Notification" }, { "code": null, "e": 2086, "s": 2027, "text": "Storing and retrieving custom objects in Shared-preference" }, { "code": null, "e": 2136, "s": 2086, "text": "Now let’s quickly set up our project and proceed." }, { "code": null, "e": 2236, "s": 2136, "text": "Create a New Android Project, select the empty activity and give any name you want to your project." }, { "code": null, "e": 2298, "s": 2236, "text": "Add the following dependencies in your app-level build.gradle" }, { "code": null, "e": 2548, "s": 2298, "text": "implementation 'com.google.android.gms:play-services-location:16.0.0'implementation 'com.google.android.gms:play-services-maps:16.0.0'implementation 'com.google.code.gson:gson:2.8.5'implementation \"com.google.android.material:material:1.1.0-alpha02\"" }, { "code": null, "e": 2611, "s": 2548, "text": "If you encounter the following error in your activity.xml file" }, { "code": null, "e": 2664, "s": 2611, "text": "Then add the following line inside your build.gradle" }, { "code": null, "e": 2731, "s": 2664, "text": "android{ defaultConfig {vectorDrawables.useSupportLibrary = true}}" }, { "code": null, "e": 2794, "s": 2731, "text": "Add the following permissions in your AndroidManifest.xml file" }, { "code": null, "e": 2931, "s": 2794, "text": "<uses-permission android:name=\"android.permission.INTERNET\" /><uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\" />" }, { "code": null, "e": 3063, "s": 2931, "text": "Now add the below meta-data tag in your AndroidManifest.xml file inside the <application> tag, we’ll add the API_KEY here later on." }, { "code": null, "e": 3152, "s": 3063, "text": "<meta-data android:name=\"com.google.android.geo.API_KEY\" android:value=\"API_KEY\"/>" }, { "code": null, "e": 3194, "s": 3152, "text": "Finally, sync the project and setup done." }, { "code": null, "e": 3267, "s": 3194, "text": "Let’s get quickly familiar with some android components used in this app" }, { "code": null, "e": 3467, "s": 3267, "text": "Service: A service is an android component which is used to perform background tasks. A task may be of any kind such as uploading photos, syncing user data on server and generating notifications etc." }, { "code": null, "e": 3853, "s": 3467, "text": "Broadcast Receiver: A broadcast receiver is also a fundamental component of android, it comes handy when you want to perform some actions in your app which are based on future events. For instance, you only want to upload user data to your server when the phone is connected to the WIFI and another example is, you want to start the background service when the user restarts his phone." }, { "code": null, "e": 3955, "s": 3853, "text": "PendingIntent: PendingIntent is similar to normal intent except that it will not execute immediately." }, { "code": null, "e": 4033, "s": 3955, "text": "I’ve all the classes, utility functions and constants under the root package." }, { "code": null, "e": 4067, "s": 4033, "text": "Let’s understand them one by one." }, { "code": null, "e": 4409, "s": 4067, "text": "MainActivity.kt: This is our home screen which will show you Google Map and two action buttons on the bottom right side. The first button will allow you to zoom in on the map and the plus action button will open new activity which is ReminderActivity.kt, on this screen you can choose your location and set the message and save the reminder." }, { "code": null, "e": 4830, "s": 4409, "text": "ReminderActivity.kt: As I explained this activity will allow you to set the location and save the reminder in the shared-preference. When you choose the location and save it, you’ll see the circle around the location you specified. This circle is boundary or radius you’ll define in your code. The larger circle means, it will cover the larger area. And as you enter into this area, you’ll be notified by a notification." }, { "code": null, "e": 5026, "s": 4830, "text": "MyBroadcast Receiver: This is a broadcast receiver which will be fired when the user reaches to the specified location. When this broadcast receiver fires, it will execute the background service." }, { "code": null, "e": 5225, "s": 5026, "text": "GeofenceTransitionService.kt: This is a service which will be executed by our broadcast receiver and when this executes it generates the notification to let user know he has reached his destination." }, { "code": null, "e": 5513, "s": 5225, "text": "MyReminder.kt: This is a data class and in its constructor, I’m accepting four parameters and they’re unique id, latitude, longitude, radium and a message. We’ll keep this information in shared-preference and at the same time, we will set the Pending Intent to generate the notification." }, { "code": null, "e": 5835, "s": 5513, "text": "MyReminderRepository.kt: As you know repository helps us to get the core methods of the application to perform actions we defined for our app. So only this class is responsible for adding a new reminder, removing reminder and setting Pending Intents. We will always create an object of this class and perform the actions." }, { "code": null, "e": 6271, "s": 5835, "text": "Utils.kt: This is our utility class which contains four methods.vectorToBitmap() method converts the vector image to bitmap, showReminderInMap() method displays the reminder on the map, this is the method which draws the circle around the specified location. And sendNotification() method creates the notification, this method is called by our background service. The last method is getUniqueId() which obviously returns the unique id." }, { "code": null, "e": 6467, "s": 6271, "text": "AppConstants.kt: This class contains all the constants used for this app. This class also contains a service method and two methods to call the MainActivity.kt and ReminderActivity.kt activities." }, { "code": null, "e": 6513, "s": 6467, "text": "Enough talking? let’s get back to business..." }, { "code": null, "e": 6842, "s": 6513, "text": "When you create a project, you will have a default ActivityMain.kt class. I want you to create one more class and name it as ReminderActivity.kt. In this class extend AppCompatActivity() class and implement OnMapReadyCallback the interface of Google Map and implement its method onMapReady(). For now, leave everything as it is." }, { "code": null, "e": 6924, "s": 6842, "text": "Now we’ll create our AppConstants class and define all constants and few methods." }, { "code": null, "e": 7405, "s": 6924, "text": "In this class, we defined our constants and three methods, newIntentForMainActivity() method will call the MainActivity.kt class and newIntentForReminderActivity() will call the ReminderActivity.kt class. enqueueWork() method will be called by our broadcast receiver to generate the notification.Tip: All constants and methods are defined inside the companion object, and this is because whenever we need to call any of these methods, we won’t have to create object of this class." }, { "code": null, "e": 7461, "s": 7405, "text": "Now we’ll create Utils.kt and add the following methods" }, { "code": null, "e": 7904, "s": 7461, "text": "When we’ll call this method, we have to pass two parameters i.e context.resources and an id of our image which needs to converted into bitmap. The context.resources returns a resources instance for your application. Inside this method, I got the drawable object, created the Bitmap and Canvas objects. We now have our image in vectorDrawable and we’ll convert this object into bitmap, then draw bitmap on canvas and set its bounds and return." }, { "code": null, "e": 8026, "s": 7904, "text": "Tip: If you’re not familiar with Canvas, then you can think of it as a blank piece of paper where you can draw any shape." }, { "code": null, "e": 8494, "s": 8026, "text": "showReminderInMap() method takes context, GoogleMap object and MyReminder class object as an argument and checks if myReminder has a value, then it proceeds further otherwise it does nothing. Inside the if statement I’m getting the latitude and longitude from my myReminder object and casting it to LatLng and in the second if statement, I’m drawing the circle around the specified location. In general, this method is used to draw the circle on a specified location." }, { "code": null, "e": 8666, "s": 8494, "text": "The sendNotification() method is pretty straightforward, it does nothing except creating the notification. This method is called from the service to show the notification." }, { "code": null, "e": 8782, "s": 8666, "text": "Now create this class in your root directory and also add this broadcast receiver in your AndroidManifest.xml file." }, { "code": null, "e": 8887, "s": 8782, "text": "<receiver android:name=\".MyBroadcastReceiver\" android:enabled=\"true\" android:exported=\"true\" />" }, { "code": null, "e": 9102, "s": 8887, "text": "This class extends the BroadcastReceiver() class which is an abstract class and implements its onReceive() method. As the onReceive() method is executed, it will execute the enqueueWork() method of AppConstants.kt." }, { "code": null, "e": 9185, "s": 9102, "text": "This receiver would be registered viaPendingIntent when you will add the reminder." }, { "code": null, "e": 9250, "s": 9185, "text": "Create this class and declare it in the AndroidManifest.xml file" }, { "code": null, "e": 9394, "s": 9250, "text": "<service android:name=\".GeofenceTransitionService\" android:exported=\"true\" android:permission=\"android.permission.BIND_JOB_SERVICE\" />" }, { "code": null, "e": 9541, "s": 9394, "text": "Note: If a job service is declared in the manifest but not protected with BIND_JOB_SERVICE permission, that service will be ignored by the system." }, { "code": null, "e": 9821, "s": 9541, "text": "This is a service which extends the JobIntentService class, IntentService or JobIntentService is a service which runs in the background on a separate thread and it gets destroyed when the job is done. To use this class we’ll have to implement its required method onHandleWork() ." }, { "code": null, "e": 10169, "s": 9821, "text": "class GeofenceTransitionService : JobIntentService() {override fun onHandleWork(intent: Intent) { val geofencingEvent = GeofencingEvent.fromIntent(intent) repositoryMy = MyReminderRepository(this) if (geofencingEvent.hasError()) { Log.e(AppConstants.LOG_TAG, \"An error occured\") return } handleEvent(geofencingEvent)}}" }, { "code": null, "e": 10369, "s": 10169, "text": "Inside this method, we can do our task. I’m getting the object of GeofencingEvent class inside this method, if there is an issue, we show the error message otherwise we call the handleEvent() method." }, { "code": null, "e": 10748, "s": 10369, "text": "private fun handleEvent(event: GeofencingEvent) { if (event.geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER) { val reminder = getFirstReminder(event.triggeringGeofences) val message = reminder?.message val latLng = reminder?.latLng if (message != null && latLng != null) { sendNotification(this, message, latLng) } }}" }, { "code": null, "e": 10972, "s": 10748, "text": "In this method, we first use the GeofencingEvent object and checks whether the user enters in the specified area or not, if it then gets the reminder object from the repository, retrieves its data and send the notification." }, { "code": null, "e": 11152, "s": 10972, "text": "private fun getFirstReminder(triggeringGeofences: List<Geofence>): MyReminder? { val firstGeofence = triggeringGeofences[0] return repositoryMy.get(firstGeofence.requestId)}" }, { "code": null, "e": 11246, "s": 11152, "text": "getFirstReminder() method returns the object of MyReminder class from the MyRepository class." }, { "code": null, "e": 11292, "s": 11246, "text": "Below is the full code for this service class" }, { "code": null, "e": 11493, "s": 11292, "text": "Tip: lateinit is a keyword in Kotlin which frees you from not to initialise it at time of declaration but it should be initialised before its use otherwise, you will run into the NullPointerException." }, { "code": null, "e": 11696, "s": 11493, "text": "You can think of this class as a local server which means it serves us everything we needed to perform any action on the map such as adding a reminder or removing reminder and maintaining all reminders." }, { "code": null, "e": 11806, "s": 11696, "text": "The following code snippet creates an object of GeofencingClient which helps you to manipulate the geofences." }, { "code": null, "e": 11883, "s": 11806, "text": "private val geofencingClient = LocationServices.getGeofencingClient(context)" }, { "code": null, "e": 11946, "s": 11883, "text": "Here we’re getting the SharedPreference object and Gson object" }, { "code": null, "e": 12060, "s": 11946, "text": "private val preferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)private val gson = Gson()" }, { "code": null, "e": 12493, "s": 12060, "text": "In the SharedPreference, we’ll store the reminders and using Gson object we’ll convert json string to Java object and vice-versa. Since SharedPreference can hold only primitive values in the form of key-value pairs but we want to store our class object, so how it is possible?. Obviously, we can convert our object to json string and store it in a SharedPreference, whenever we need to use it, we will convert it into a real object." }, { "code": null, "e": 12698, "s": 12493, "text": "The combination of latitude, longitude and a radius is known as geofence. It’s a circular area at a specific location on the map. Whenever users enter this area, the app will trigger particular behaviour." }, { "code": null, "e": 13320, "s": 12698, "text": "private fun buildGeofence(myReminder: MyReminder): Geofence? { val latitude = myReminder.latLng?.latitude val longitude = myReminder.latLng?.longitude val radius = myReminder.radius if (latitude != null && longitude != null && radius != null) { return Geofence.Builder() .setRequestId(myReminder.id) .setCircularRegion( latitude, longitude, radius.toFloat() ) .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER) .setExpirationDuration(Geofence.NEVER_EXPIRE) .build() } return null}" }, { "code": null, "e": 13392, "s": 13320, "text": "Look at the code, we’re building the geofence using Geofence.Builder()." }, { "code": null, "e": 13531, "s": 13392, "text": "In the method setRequestId(), I’m passing unique id since every geofence is unique in its way, you will get this id from your model class." }, { "code": null, "e": 13674, "s": 13531, "text": "In the setCircularRegion(), I’m setting my latitude, longitude and radius, all these parameters together form a circle on a specific location." }, { "code": null, "e": 13830, "s": 13674, "text": "The setTransitionTypes() defines the transition type, you can use GEOFENCE_TRANSITION_ENTER to trigger an event when the user enters into the defined area." }, { "code": null, "e": 13988, "s": 13830, "text": "The setExpirationDuration() method sets the expiry of the geofence, we’re using NEVER_EXPIRE which means that it will never expire until the user removes it." }, { "code": null, "e": 14042, "s": 13988, "text": "You’ll use this method to build the geofence request." }, { "code": null, "e": 14241, "s": 14042, "text": "private fun buildGeofencingRequest(geofence: Geofence): GeofencingRequest { return GeofencingRequest.Builder() .setInitialTrigger(0) .addGeofences(listOf(geofence)) .build()}" }, { "code": null, "e": 14457, "s": 14241, "text": "Here you’re setting setInitialTrigger() to 0 which means that you don’t want your app to trigger an event when the app is already inside the geofence. And the next addGeofences() method adds the request to geofence." }, { "code": null, "e": 14688, "s": 14457, "text": "As you can see in the code snippet, we’re passing MyBroadcastReceiver in the intent object which means that when this pending intent is called, it will call broadcast receiver and this receiver will call GeofenceTransitionService." }, { "code": null, "e": 14931, "s": 14688, "text": "private val geofencePendingIntent: PendingIntent by lazy { val intent = Intent(context, MyBroadcastReceiver::class.java) PendingIntent.getBroadcast( context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT )}" }, { "code": null, "e": 15014, "s": 14931, "text": "This code will only be executed when GEOFENCE_TRANSITION_ENTER event is triggered." }, { "code": null, "e": 15104, "s": 15014, "text": "Tip: by lazy property, the value only gets computed when this is used for the first time." }, { "code": null, "e": 15207, "s": 15104, "text": "This add() method adds the reminder in the SharedPreference and also adds the request to the geofence." }, { "code": null, "e": 15809, "s": 15207, "text": "fun add(myReminder: MyReminder, success: () -> Unit, failure: (error: String) -> Unit){ val geofence = buildGeofence(myReminder) if (geofence != null && ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { geofencingClient.addGeofences(buildGeofencingRequest(geofence), geofencePendingIntent) .addOnSuccessListener { saveAll(getAll() + myReminder) success() } .addOnFailureListener { failure(\"An error occured\") } }}" }, { "code": null, "e": 16052, "s": 15809, "text": "First of all, we’re checking the permission if it is granted, then we proceed, and next, we’re creating the geofence using the geofencingClient if it is successful, then only we’ll save in shared preference, otherwise report an error message." }, { "code": null, "e": 16107, "s": 16052, "text": "This method simply removes the reminder from the list." }, { "code": null, "e": 16198, "s": 16107, "text": "fun remove(myReminder: MyReminder) { val list = getAll() - myReminder saveAll(list)}" }, { "code": null, "e": 16267, "s": 16198, "text": "This method adds all the reminders in the list in shared-preference." }, { "code": null, "e": 16408, "s": 16267, "text": "private fun saveAll(list: List<MyReminder>) { preferences .edit() .putString(REMINDERS, gson.toJson(list)) .apply()}" }, { "code": null, "e": 16480, "s": 16408, "text": "Notice we’re converting the list to Json string, then we’re storing it." }, { "code": null, "e": 16562, "s": 16480, "text": "This method returns the list of all reminders we stored in the shared-preference." }, { "code": null, "e": 16945, "s": 16562, "text": "fun getAll(): List<MyReminder> { if (preferences.contains(REMINDERS)) { val remindersString = preferences.getString(REMINDERS, null) val arrayOfReminders = gson.fromJson( remindersString, Array<MyReminder>::class.java ) if (arrayOfReminders != null) { return arrayOfReminders.toList() } } return listOf()}" }, { "code": null, "e": 16999, "s": 16945, "text": "This function returns the reminder added in the list." }, { "code": null, "e": 17037, "s": 16999, "text": "fun getLast() = getAll().lastOrNull()" }, { "code": null, "e": 17217, "s": 17037, "text": "Notice this function first calls the getAll() method which returns a list and we call lastOrNull() function which is a method of List class and this method returns the last value." }, { "code": null, "e": 17295, "s": 17217, "text": "This method returns the first reminder from the list if the list is not null." }, { "code": null, "e": 17369, "s": 17295, "text": "fun get(requestId: String?) = getAll().firstOrNull { it.id == requestId }" }, { "code": null, "e": 17538, "s": 17369, "text": "{it.id == requestId } is a lambda expression which is performing null checking. When there is only a single parameter inside the lambda expression, then it can be used." }, { "code": null, "e": 17580, "s": 17538, "text": "Complete code for MyReminderRepository.kt" }, { "code": null, "e": 17655, "s": 17580, "text": "This activity allows us to add the new reminder on the specified location." }, { "code": null, "e": 17708, "s": 17655, "text": "First of all, create these objects in this activity." }, { "code": null, "e": 17870, "s": 17708, "text": "private lateinit var map: GoogleMaplateinit var myRepository: MyReminderRepositoryprivate var reminder = MyReminder(latLng = null, radius = null, message = null)" }, { "code": null, "e": 17929, "s": 17870, "text": "Now paste the following code inside your onCreate() method" }, { "code": null, "e": 18353, "s": 17929, "text": "override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_new_reminder) myRepository = MyReminderRepository(this) val mapFragment = supportFragmentManager .findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync(this) instructionTitle.visibility = View.GONE radiusDescription.visibility = View.GONE message.visibility = View.GONE}" }, { "code": null, "e": 18486, "s": 18353, "text": "In this onCreate() method, I’m initialising my repository instance variable and setting the map. Initially, I hide all the TextView." }, { "code": null, "e": 18613, "s": 18486, "text": "In this method, I’m getting LatLng as well as zoom value from the intent and setting the camera at the centre of the location." }, { "code": null, "e": 18832, "s": 18613, "text": "private fun centerCamera() { val latLng = intent.extras?.get(AppConstants.LAT_LNG) as LatLng val zoom = intent.extras?.get(AppConstants.ZOOM) as Float map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom))}" }, { "code": null, "e": 18935, "s": 18832, "text": "This method updates the reminder. On calling this method, it will show you circle around the location." }, { "code": null, "e": 19024, "s": 18935, "text": "private fun showReminderUpdate() { map.clear() showReminderInMap(this, map, reminder)}" }, { "code": null, "e": 19095, "s": 19024, "text": "This method simply guides you through how you can navigate on the map." }, { "code": null, "e": 19470, "s": 19095, "text": "private fun showConfigureLocationStep() { marker.visibility = View.VISIBLE instructionTitle.visibility = View.VISIBLE radiusDescription.visibility = View.GONE message.visibility = View.GONE instructionTitle.text = \"Drag map to set location\" next.setOnClickListener { reminder.latLng = map.cameraPosition.target showConfigureRadiusStep() } showReminderUpdate()}" }, { "code": null, "e": 19619, "s": 19470, "text": "This method is same as the above method and it guides you through how to add a message. This message will be shown when you will get a notification." }, { "code": null, "e": 20036, "s": 19619, "text": "private fun showConfigureMessageStep() { marker.visibility = View.GONE instructionTitle.visibility = View.VISIBLE message.visibility = View.VISIBLE instructionTitle.text = \"Enter a message\" next.setOnClickListener { reminder.message = message.text.toString() if (reminder.message.isNullOrEmpty()) { message.error = \"Message Error\" } else { addReminder(reminder) } } showReminderUpdate()}" }, { "code": null, "e": 20261, "s": 20036, "text": "This method calls the add method from the MyReminderRepository class and adds the reminder. If the reminder is added successfully, then it will you Snackbar on the bottom with a message “Reminder added” else failure message." }, { "code": null, "e": 20505, "s": 20261, "text": "private fun addReminder(myReminder: MyReminder) { myRepository.add(myReminder, success = { setResult(Activity.RESULT_OK) finish() }, failure = { Snackbar.make(main, it, Snackbar.LENGTH_LONG).show() })}" }, { "code": null, "e": 20538, "s": 20505, "text": "Finally modify your onMapReady()" }, { "code": null, "e": 20693, "s": 20538, "text": "override fun onMapReady(googleMap: GoogleMap) { map = googleMap map.uiSettings.isMapToolbarEnabled = false centerCamera() showConfigureLocationStep()}" }, { "code": null, "e": 20792, "s": 20693, "text": "Inside this method, we’re assigning the GoogleMap object to our map and then configuring settings." }, { "code": null, "e": 20824, "s": 20792, "text": "Complete code for this activity" }, { "code": null, "e": 20854, "s": 20824, "text": "Layout file for this activity" }, { "code": null, "e": 21146, "s": 20854, "text": "The only thing you can notice in <fragment> tag is “android:name=”com.google.android.gms.maps.SupportMapFragment” line and this line helps you to add the Google map on the screen. This is the simplest way of adding a map. And rest of the code inside this file must be quite familiar for you." }, { "code": null, "e": 21273, "s": 21146, "text": "Finally, this is the last part of our code. This is our home activity which you will see when you first interact with the app." }, { "code": null, "e": 21355, "s": 21273, "text": "First of all, add these listeners in your activity and implement all its methods." }, { "code": null, "e": 21449, "s": 21355, "text": "class MainActivity : AppCompatActivity(), OnMapReadyCallback, GoogleMap.OnMarkerClickListener" }, { "code": null, "e": 21486, "s": 21449, "text": "Now create these instance variables." }, { "code": null, "e": 21623, "s": 21486, "text": "lateinit var myRepository: MyReminderRepository private var map: GoogleMap? = null private lateinit var locationManager: LocationManager" }, { "code": null, "e": 22014, "s": 21623, "text": "In this method, we’re initialising our instance variables first, then getting a map from a fragment from the activity_main.xml file and the listeners on the action buttons. Initially, these buttons will not be visible until the user gives ACCESS_FINE_LOCATION permission. As a user grants the permission, we make the buttons visible to the users inside the onMapAndPermissionReady() method." }, { "code": null, "e": 22284, "s": 22014, "text": "Look at the below code, here I’m attaching a listener to the button and inside the lambda expression, I’m calling run method of Google map class. This run is also a lambda function. When user presses (+) action button, we take the user to the ReminderActivity.kt class." }, { "code": null, "e": 22584, "s": 22284, "text": "actionNewReminder.setOnClickListener { map?.run { val intent = AppConstants.newIntentForReminderActivity( this@MainActivity, cameraPosition.target, cameraPosition.zoom ) startActivityForResult(intent, AppConstants.REMINDER_REQUEST_CODE) }}" }, { "code": null, "e": 22948, "s": 22584, "text": "When permission is granted and the map doesn’t equal null, then we’re making visible our buttons and adding a listener to the actionCurrentLocation button. Now if the user presses the actionCurrentLocation button, then we get the location provider and last known location of the user. And if this is not null, then we’ll move the camera to the last know location." }, { "code": null, "e": 23127, "s": 22948, "text": "When a user clicks on the marker, then an alert dialog pops up to ask user, if he wants to remove the reminder, if he presses “YES” then that reminder gets removed from the list." }, { "code": null, "e": 23327, "s": 23127, "text": "override fun onMarkerClick(marker: Marker): Boolean { val reminder = myRepository.get(marker.tag as String) if (reminder != null) { showReminderRemoveAlert(reminder) } return true}" }, { "code": null, "e": 23354, "s": 23327, "text": "showReminderRemoveAlert():" }, { "code": null, "e": 23505, "s": 23354, "text": "This method only creates an alert dialog with two options, i.e OK and Cancel and if a user clicks on “Ok”, then we call removeReminder() to remove it." }, { "code": null, "e": 24014, "s": 23505, "text": "private fun showReminderRemoveAlert(myReminder: MyReminder) { val alertDialog = AlertDialog.Builder(this).create() alertDialog.run { setMessage(\"Reminder Removed\") setButton( AlertDialog.BUTTON_POSITIVE, \"OK\" ) { dialog, _ -> removeReminder(myReminder) dialog.dismiss() } setButton( AlertDialog.BUTTON_NEGATIVE, \"Cancel\" ) { dialog, _ -> dialog.dismiss() } show() }}" }, { "code": null, "e": 24056, "s": 24014, "text": "Complete code of our ActivityMain.kt file" }, { "code": null, "e": 24103, "s": 24056, "text": "Now finally we have our activity_main.xml file" }, { "code": null, "e": 24136, "s": 24103, "text": "Run the app and give permission." }, { "code": null, "e": 24316, "s": 24136, "text": "If you’re running app on emulator, then click on three dots you’ll see the follow screen. Now set any location you want (I set Connaught Place, New Delhi). And save this location." }, { "code": null, "e": 24430, "s": 24316, "text": "Now click on the first action button on your app and you’ll see your map will navigate to the specified location." }, { "code": null, "e": 24620, "s": 24430, "text": "Now add a reminder by click the (+) action button, drag the map to set your location, click on Continue and now type your message and again click Continue. Now your reminder has been saved." }, { "code": null, "e": 24710, "s": 24620, "text": "Now again click on three dots, change location to somewhere else on emulator and save it." }, { "code": null, "e": 24803, "s": 24710, "text": "Click on the first button your app, you will reach to the location you set on your emulator." }, { "code": null, "e": 24942, "s": 24803, "text": "Finally, In the emulator, set your location where you set your reminder while saving it. And wait for a few seconds you’ll a notification." }, { "code": null, "e": 25035, "s": 24942, "text": "If you have any difficulty with your project, then you can seek help from my Github project." }, { "code": null, "e": 25235, "s": 25035, "text": "Subscribe to my mailing list to get the early access of my articles directly in your inbox and don’t forget to follow my own publication on Medium The Code Monster to polish your technical knowledge." } ]
FastText sentiment analysis for tweets: A straightforward guide | by Charles Malafosse | Towards Data Science
In this post, we present fastText library, how it achieves faster speed and similar accuracy than some deep neural networks for text classification. Next, we show how to train a sentiment analysis model thanks to data generated with AWS Comprehend. In another article, we show how to use AWS Elastic Beanstalk to create a machine learning server to serve your model. FastText is an open-source NLP library developed by facebook AI and initially released in 2016. Its goal is to provide word embedding and text classification efficiently. According to their authors, it is often on par with deep learning classifiers in terms of accuracy, and many orders of magnitude faster for training and evaluation. [1] This makes fastText an excellent tool to build NLP models and generate live predictions for production environments. The core of FastText relies on the Continuous Bag of Words (CBOW) model for word representation and a hierarchical classifier to speed up training. Continuous Bag of Words (CBOW) is a shallow neural network that is trained to predict a word from its neighbors. FastText replaces the objective of predicting a word with predicting a category. These single-layer models train incredibly fast and can scale very well. Also, fastText replaces the softmax over labels with a hierarchical softmax. Here each node represents a label. This reduces computation as we don’t need to compute all labels probabilities. The limited number of parameters reduces training time. According to the initial paper [1], fastText achieves similar results to other algorithms while training a lot faster. As you can see below, fastText training time is between 1 and 10 seconds versus minutes or hours for other models. Most open datasets for text classification are quite small and we noticed that few, if any, are available for languages other than English. Therefore in addition to provide a guide for sentiment analysis, we want to provide open datasets for sentiment analysis [2]. For these reasons we provide files with lists of tweets and their sentiments in: English tweets dataset => 6.3 millions tweets available. Spanish tweets dataset => 1.2m tweets. French tweets dataset => 250 000 tweets Italian tweets dataset => 425 000 tweets German tweets dataset => 210 000 tweets These were generated thanks to AWS Comprehend API. For Spanish and French, tweets were first translated to English using Google Translate, and then analyzed with AWS Comprehend. Sentiment is classified to either positive, negative, neutral, or mixed. For this article, we use the English tweets dataset. They say that cleaning is usually 80% of a data scientist’s time. Sadly there is no exception here. To obtain the best results, we have to make sure that the data is something close to proper English, and because we work on tweets, this is no easy task. Our goal is to clean tweets to make them easier to read by a machine. There are many techniques out there to clean text. Most famous ones being lemmatization, stemming and stop words. The goal of both stemming and lemmatization is to reduce inflectional forms and derivationally related forms of a word to a common base form. (Ex: am, are, is => be / dog, dogs, dog’s, dogs’ => dog.) These reduce the corpus size and its complexity, allowing for simpler word embedding (am, are and is share the same exact word vector). Stop Words filters common words that add noise or provide no value for machines' understanding of a text. Examples: a, and, the.... While stemming and lemmatization helps for sentiment analysis, stop words filtering is not as straightforward. The goal of stop words is to remove unnecessary words, but if you look at available lists of stop words, the one from the NLTK library for instance, you find words that potentially convey negative sentiments such as: not, don’t, hasn’t.... but for sentiment analysis problem we want to keep negative words. It is evident that “It is a good game” and “It is not a good game”, provide opposite sentiment. Hence one needs to either edit the stop words list to exclude words that convey negative meaning or not use stop words at all. We chose the latter. Furthermore, tweets are short messages that contain loads of emojis, contractions, hashtags, misspelled words and slang. Most of these have little value for sentiment analysis and need to be cleaned: Contractions/slang cleaning. If we want to simplify our problem, we need to remove contractions and translate slang when there is an appropriate alternative. However, it is hard to find a library or database of words that do that. We had to create a list for that purpose. Check my GitHub page to see it. #CONTRACTIONS is a list of contractions and slang and their conversion. { "you've":"you have", "luv":"love", etc...}tweet = tweet.replace("’","'")words = tweet.split()reformed = [CONTRACTIONS[word] if word in CONTRACTIONS else word for word in words]tweet = " ".join(reformed) Fix misspelled word. Here we use a regular expression, using regex, to remove repeating characters in a word. Apart from regex, you could use other libraries that really detect and fix misspellings. Sadly they are quite slow and this is not acceptable in production when you have thousands of tweets to analyze every day. import itertoolstweet = ''.join(''.join(s)[:2] for _, s in itertools.groupby(tweet)) Escaping HTML characters: The Twitter API sometimes returns HTML characters. When this happens we need to convert them to their ASCII form. For instance, %20 is converted to space, and &amp; is converted to &. To do this we use Beautiful Soup, a Python package for parsing HTML and XML documents. from bs4 import BeautifulSouptweet = BeautifulSoup(tweet).get_text() Removal of hashtags/accounts: Names through the use of Twitter hashtags (#) and accounts (@) needs to be removed. We wouldn’t want a football player’s name classified forever as “negative” by our model, just because he has been associated with poor comments in our dataset. tweet = ' '.join(re.sub("(@[A-Za-z0-9]+)|(#[A-Za-z0-9]+)", " ", tweet).split()) Removal of web addresses: tweet = ' '.join(re.sub("(\w+:\/\/\S+)", " ", tweet).split()) Removal of punctuation: Punctuation is not used for “bag of words” techniques. tweet = ' '.join(re.sub("[\.\,\!\?\:\;\-\=]", " ", tweet).split()) Lower case: Convert everything to lower case to avoid case sensitive issues: #Lower casetweet = tweet.lower() Emojis/Smileys: In a tweet, Emojis and Smileys are represented with ‘ \\’ or punctuation, and for this reason are not tokenized correctly. To keep their meaning, we need to convert them to a simpler form. For emojis, there is the python library “emoji” that does exactly that by converting the emoji code to a label. For smileys :-), you have to provide your list, which we do on our GitHub page. #Part for smileys - SMILEY is a list of smiley and their conversion. {"<3" : "love", ":-)" : "smiley", etc...}words = tweet.split()reformed = [SMILEY[word] if word in SMILEY else word for word in words]tweet = " ".join(reformed)#Part for emojistweet = emoji.demojize(tweet) Strip accents: Limited for English but widely used for other languages, accents are often misplaced or forgotten. The easiest way to deal with them is to get rid of them. def strip_accents(text): if 'ø' in text or 'Ø' in text: #Do nothing when finding ø return text text = text.encode('ascii', 'ignore') text = text.decode("utf-8") return str(text) To see everything tied up together, please check the code on my GitHub page [2]. FastText needs labeled data to train the supervised classifier. Labels must start by the prefix __label__ , which is how it recognizes what a label or what a word is. Below is an example of the required format for tweets with label POSITIVE and NEGATIVE. __label__POSITIVE congratulations you played very well yesterday.__label__NEGATIVE disappointing result today.... We use the code below to format the data. def transform_instance(row): cur_row = [] #Prefix the index-ed label with __label__ label = "__label__" + row[0] cur_row.append(label) #Clean tweet and tokenize it cur_row.extend( nltk.word_tokenize(tweet_cleaning_for_sentiment_analysis(row[1].lower())))def preprocess(input_file, output_file, keep=1): with open(output_file, 'w') as csvoutfile: csv_writer = csv.writer(csvoutfile, delimiter=' ', lineterminator='\n') with open(input_file, 'r', newline='') as csvinfile: #,encoding='latin1' csv_reader = csv.reader(csvinfile, delimiter=',', quotechar='"') for row in csv_reader: if row[0].upper() in ['POSITIVE','NEGATIVE','NEUTRAL','MIXED']: row_output = transform_instance(row) csv_writer.writerow(row_output)# Preparing the training dataset preprocess('BetSentimentTweetAnalyzed.csv', 'tweets.train') Category imbalance problem occurs when one label appears more often than others. In such a situation, classifiers tend to be overwhelmed by the large classes and ignore the small ones. Applied to our dataset of English tweets [2], we notice an imbalance of neutral versus positive/negative classes. As a consequence, a primitive strategy of classifying everything as neutral would give an accuracy of 73% (see table below). For the same reason, our model might tend to favor neutral. If unmanaged, category imbalance would make our model simplistic and inaccurate. To deal with this, we have to use upsampling. Upsampling (or oversampling) consists of adding new tweets for the minority classes, positive and negative, to have them reach a number of tweets equal to the majority class, neutral here. We provide a simple code to do that. def upsampling(input_file, output_file, ratio_upsampling=1): # # Create a file with equal number of tweets for each label # input_file: path to file # output_file: path to the output file # ratio_upsampling: ratio of each minority classes vs majority one. 1 mean there will be as much of each class than there is for the majority class. i=0 counts = {} dict_data_by_label = {} i=0 counts = {} dict_data_by_label = {}# GET LABEL LIST AND GET DATA PER LABEL with open(input_file, 'r', newline='') as csvinfile: csv_reader = csv.reader(csvinfile, delimiter=',', quotechar='"') for row in csv_reader: counts[row[0].split()[0]] = counts.get(row[0].split()[0], 0) + 1 if not row[0].split()[0] in dict_data_by_label: dict_data_by_label[row[0].split()[0]]=[row[0]] else: dict_data_by_label[row[0].split()[0]].append(row[0]) i=i+1 if i%10000 ==0: print("read" + str(i))# FIND MAJORITY CLASS majority_class="" count_majority_class=0 for item in dict_data_by_label: if len(dict_data_by_label[item])>count_majority_class: majority_class= item count_majority_class=len(dict_data_by_label[item]) # UPSAMPLE MINORITY CLASS data_upsampled=[] for item in dict_data_by_label: data_upsampled.extend(dict_data_by_label[item]) if item != majority_class: items_added=0 items_to_add = count_majority_class - len(dict_data_by_label[item]) while items_added<items_to_add: data_upsampled.extend(dict_data_by_label[item][:max(0,min(items_to_add-items_added,len(dict_data_by_label[item])))]) items_added = items_added + max(0,min(items_to_add-items_added,len(dict_data_by_label[item])))# WRITE ALL i=0with open(output_file, 'w') as txtoutfile: for row in data_upsampled: txtoutfile.write(row+ '\n' ) i=i+1 if i%10000 ==0: print("writer" + str(i))upsampling( 'tweets.train','uptweets.train') With upsampling, you run the risk of overfitting by repeating over and over the same tweets. But if your dataset is big enough this should not be an issue. Now the fun part. Time to train our machine for sentiments! We use the fastText python wrapper to train our model. You can find implementation examples and documentation on Facebook Research’s GitHub page. Please make sure you install fastText using “git clone ...” and not using “pip install fasttext”. As we already prepared our data, all we need to do now is to use the function fastText.train_supervised. There are tons of options for this function, but for sake of simplicity we focus on the following: input: the path to our training data. lr: Learning rate. We set it at 0.01. epoch: Number times we go through the entire dataset. We use 20. wordNgrams: An n-gram is a contiguous sequence of max n words from a given sample of text, tweet here. We set it at 2. dim: Dimension of word vector. We use 20. The following python code shows the training of our model. hyper_params = {"lr": 0.01, "epoch": 20, "wordNgrams": 2, "dim": 20} # Train the model.model = fastText.train_supervised(input=training_data_path, **hyper_params)print("Model trained with the hyperparameter \n {}".format(hyper_params)) Once trained, we need to assess how good our model is at sentiment analysis. For this, we can use the two measures Precision and Recall which are the output of fastText functionmodel.test. However, due to the nature of our problem, precision and recall give similar figures and we can focus on precision only. The code below implements model.test on the training and validation data to compare the accuracy of our model. Note that for validation, we take a different dataset on which we use the same cleaning process but no upsampling. # CHECK PERFORMANCE result = model.test(training_data_path)validation = model.test(validation_data_path) # DISPLAY ACCURACY OF TRAINED MODELtext_line = str(hyper_params) + ",accuracy:" + str(result[1]) + ",validation:" + str(validation[1]) + '\n' print(text_line) Overall the model gives an accuracy of 97.5% on the training data, and 79.7% on the validation data. Not so bad considering we did not tweak the hyperparameters. Furthermore, research estimates that people only agree around 60 to 80% of the times when judging the sentiment for a particular piece of text. So while we could try to reach for 100% accuracy, we have to keep in mind that humans are fallible... and most importantly that we work on tweets!! We just showed how fastText works and how to train an English sentiment analysis model. We used sentiment data produced by AWS Comprehend. In another article, we explain how to serve your model with a robust cloud infrastructure, using AWS Elastic Beanstalk and a Python Flask application. Should you want to reproduce the results, just go to my gitHub. For the full English dataset just ask me (too big for GitHub). I’ll be happy to share it with you. https://medium.com/@charlesmalafosse/membership [1] Bag of Tricks for Efficient Text Classification, Armand Joulin, Edouard Grave, Piotr Bojanowski, Tomas Mikolov, 2016 [2] https://github.com/charlesmalafosse. My GitHub page with full code for this article. [3] Facebook GitHub with fastText python wrapper. https://github.com/facebookresearch/fastText/tree/master/python [4] Deploy a machine learning model with AWS Elastic Beanstalk https://medium.com/@charlesmalafosse/deploy-a-machine-learning-model-with-aws-elasticbeanstalk-dfcc47b6043e
[ { "code": null, "e": 539, "s": 172, "text": "In this post, we present fastText library, how it achieves faster speed and similar accuracy than some deep neural networks for text classification. Next, we show how to train a sentiment analysis model thanks to data generated with AWS Comprehend. In another article, we show how to use AWS Elastic Beanstalk to create a machine learning server to serve your model." }, { "code": null, "e": 879, "s": 539, "text": "FastText is an open-source NLP library developed by facebook AI and initially released in 2016. Its goal is to provide word embedding and text classification efficiently. According to their authors, it is often on par with deep learning classifiers in terms of accuracy, and many orders of magnitude faster for training and evaluation. [1]" }, { "code": null, "e": 996, "s": 879, "text": "This makes fastText an excellent tool to build NLP models and generate live predictions for production environments." }, { "code": null, "e": 1144, "s": 996, "text": "The core of FastText relies on the Continuous Bag of Words (CBOW) model for word representation and a hierarchical classifier to speed up training." }, { "code": null, "e": 1411, "s": 1144, "text": "Continuous Bag of Words (CBOW) is a shallow neural network that is trained to predict a word from its neighbors. FastText replaces the objective of predicting a word with predicting a category. These single-layer models train incredibly fast and can scale very well." }, { "code": null, "e": 1658, "s": 1411, "text": "Also, fastText replaces the softmax over labels with a hierarchical softmax. Here each node represents a label. This reduces computation as we don’t need to compute all labels probabilities. The limited number of parameters reduces training time." }, { "code": null, "e": 1777, "s": 1658, "text": "According to the initial paper [1], fastText achieves similar results to other algorithms while training a lot faster." }, { "code": null, "e": 1892, "s": 1777, "text": "As you can see below, fastText training time is between 1 and 10 seconds versus minutes or hours for other models." }, { "code": null, "e": 2158, "s": 1892, "text": "Most open datasets for text classification are quite small and we noticed that few, if any, are available for languages other than English. Therefore in addition to provide a guide for sentiment analysis, we want to provide open datasets for sentiment analysis [2]." }, { "code": null, "e": 2239, "s": 2158, "text": "For these reasons we provide files with lists of tweets and their sentiments in:" }, { "code": null, "e": 2296, "s": 2239, "text": "English tweets dataset => 6.3 millions tweets available." }, { "code": null, "e": 2335, "s": 2296, "text": "Spanish tweets dataset => 1.2m tweets." }, { "code": null, "e": 2375, "s": 2335, "text": "French tweets dataset => 250 000 tweets" }, { "code": null, "e": 2416, "s": 2375, "text": "Italian tweets dataset => 425 000 tweets" }, { "code": null, "e": 2456, "s": 2416, "text": "German tweets dataset => 210 000 tweets" }, { "code": null, "e": 2707, "s": 2456, "text": "These were generated thanks to AWS Comprehend API. For Spanish and French, tweets were first translated to English using Google Translate, and then analyzed with AWS Comprehend. Sentiment is classified to either positive, negative, neutral, or mixed." }, { "code": null, "e": 2760, "s": 2707, "text": "For this article, we use the English tweets dataset." }, { "code": null, "e": 3014, "s": 2760, "text": "They say that cleaning is usually 80% of a data scientist’s time. Sadly there is no exception here. To obtain the best results, we have to make sure that the data is something close to proper English, and because we work on tweets, this is no easy task." }, { "code": null, "e": 3198, "s": 3014, "text": "Our goal is to clean tweets to make them easier to read by a machine. There are many techniques out there to clean text. Most famous ones being lemmatization, stemming and stop words." }, { "code": null, "e": 3534, "s": 3198, "text": "The goal of both stemming and lemmatization is to reduce inflectional forms and derivationally related forms of a word to a common base form. (Ex: am, are, is => be / dog, dogs, dog’s, dogs’ => dog.) These reduce the corpus size and its complexity, allowing for simpler word embedding (am, are and is share the same exact word vector)." }, { "code": null, "e": 3666, "s": 3534, "text": "Stop Words filters common words that add noise or provide no value for machines' understanding of a text. Examples: a, and, the...." }, { "code": null, "e": 4328, "s": 3666, "text": "While stemming and lemmatization helps for sentiment analysis, stop words filtering is not as straightforward. The goal of stop words is to remove unnecessary words, but if you look at available lists of stop words, the one from the NLTK library for instance, you find words that potentially convey negative sentiments such as: not, don’t, hasn’t.... but for sentiment analysis problem we want to keep negative words. It is evident that “It is a good game” and “It is not a good game”, provide opposite sentiment. Hence one needs to either edit the stop words list to exclude words that convey negative meaning or not use stop words at all. We chose the latter." }, { "code": null, "e": 4528, "s": 4328, "text": "Furthermore, tweets are short messages that contain loads of emojis, contractions, hashtags, misspelled words and slang. Most of these have little value for sentiment analysis and need to be cleaned:" }, { "code": null, "e": 4833, "s": 4528, "text": "Contractions/slang cleaning. If we want to simplify our problem, we need to remove contractions and translate slang when there is an appropriate alternative. However, it is hard to find a library or database of words that do that. We had to create a list for that purpose. Check my GitHub page to see it." }, { "code": null, "e": 5110, "s": 4833, "text": "#CONTRACTIONS is a list of contractions and slang and their conversion. { \"you've\":\"you have\", \"luv\":\"love\", etc...}tweet = tweet.replace(\"’\",\"'\")words = tweet.split()reformed = [CONTRACTIONS[word] if word in CONTRACTIONS else word for word in words]tweet = \" \".join(reformed)" }, { "code": null, "e": 5432, "s": 5110, "text": "Fix misspelled word. Here we use a regular expression, using regex, to remove repeating characters in a word. Apart from regex, you could use other libraries that really detect and fix misspellings. Sadly they are quite slow and this is not acceptable in production when you have thousands of tweets to analyze every day." }, { "code": null, "e": 5517, "s": 5432, "text": "import itertoolstweet = ''.join(''.join(s)[:2] for _, s in itertools.groupby(tweet))" }, { "code": null, "e": 5814, "s": 5517, "text": "Escaping HTML characters: The Twitter API sometimes returns HTML characters. When this happens we need to convert them to their ASCII form. For instance, %20 is converted to space, and &amp; is converted to &. To do this we use Beautiful Soup, a Python package for parsing HTML and XML documents." }, { "code": null, "e": 5883, "s": 5814, "text": "from bs4 import BeautifulSouptweet = BeautifulSoup(tweet).get_text()" }, { "code": null, "e": 6157, "s": 5883, "text": "Removal of hashtags/accounts: Names through the use of Twitter hashtags (#) and accounts (@) needs to be removed. We wouldn’t want a football player’s name classified forever as “negative” by our model, just because he has been associated with poor comments in our dataset." }, { "code": null, "e": 6237, "s": 6157, "text": "tweet = ' '.join(re.sub(\"(@[A-Za-z0-9]+)|(#[A-Za-z0-9]+)\", \" \", tweet).split())" }, { "code": null, "e": 6263, "s": 6237, "text": "Removal of web addresses:" }, { "code": null, "e": 6325, "s": 6263, "text": "tweet = ' '.join(re.sub(\"(\\w+:\\/\\/\\S+)\", \" \", tweet).split())" }, { "code": null, "e": 6404, "s": 6325, "text": "Removal of punctuation: Punctuation is not used for “bag of words” techniques." }, { "code": null, "e": 6471, "s": 6404, "text": "tweet = ' '.join(re.sub(\"[\\.\\,\\!\\?\\:\\;\\-\\=]\", \" \", tweet).split())" }, { "code": null, "e": 6548, "s": 6471, "text": "Lower case: Convert everything to lower case to avoid case sensitive issues:" }, { "code": null, "e": 6581, "s": 6548, "text": "#Lower casetweet = tweet.lower()" }, { "code": null, "e": 6978, "s": 6581, "text": "Emojis/Smileys: In a tweet, Emojis and Smileys are represented with ‘ \\\\’ or punctuation, and for this reason are not tokenized correctly. To keep their meaning, we need to convert them to a simpler form. For emojis, there is the python library “emoji” that does exactly that by converting the emoji code to a label. For smileys :-), you have to provide your list, which we do on our GitHub page." }, { "code": null, "e": 7252, "s": 6978, "text": "#Part for smileys - SMILEY is a list of smiley and their conversion. {\"<3\" : \"love\", \":-)\" : \"smiley\", etc...}words = tweet.split()reformed = [SMILEY[word] if word in SMILEY else word for word in words]tweet = \" \".join(reformed)#Part for emojistweet = emoji.demojize(tweet)" }, { "code": null, "e": 7423, "s": 7252, "text": "Strip accents: Limited for English but widely used for other languages, accents are often misplaced or forgotten. The easiest way to deal with them is to get rid of them." }, { "code": null, "e": 7632, "s": 7423, "text": "def strip_accents(text): if 'ø' in text or 'Ø' in text: #Do nothing when finding ø return text text = text.encode('ascii', 'ignore') text = text.decode(\"utf-8\") return str(text)" }, { "code": null, "e": 7713, "s": 7632, "text": "To see everything tied up together, please check the code on my GitHub page [2]." }, { "code": null, "e": 7968, "s": 7713, "text": "FastText needs labeled data to train the supervised classifier. Labels must start by the prefix __label__ , which is how it recognizes what a label or what a word is. Below is an example of the required format for tweets with label POSITIVE and NEGATIVE." }, { "code": null, "e": 8082, "s": 7968, "text": "__label__POSITIVE congratulations you played very well yesterday.__label__NEGATIVE disappointing result today...." }, { "code": null, "e": 8124, "s": 8082, "text": "We use the code below to format the data." }, { "code": null, "e": 9040, "s": 8124, "text": "def transform_instance(row): cur_row = [] #Prefix the index-ed label with __label__ label = \"__label__\" + row[0] cur_row.append(label) #Clean tweet and tokenize it cur_row.extend( nltk.word_tokenize(tweet_cleaning_for_sentiment_analysis(row[1].lower())))def preprocess(input_file, output_file, keep=1): with open(output_file, 'w') as csvoutfile: csv_writer = csv.writer(csvoutfile, delimiter=' ', lineterminator='\\n') with open(input_file, 'r', newline='') as csvinfile: #,encoding='latin1' csv_reader = csv.reader(csvinfile, delimiter=',', quotechar='\"') for row in csv_reader: if row[0].upper() in ['POSITIVE','NEGATIVE','NEUTRAL','MIXED']: row_output = transform_instance(row) csv_writer.writerow(row_output)# Preparing the training dataset preprocess('BetSentimentTweetAnalyzed.csv', 'tweets.train')" }, { "code": null, "e": 9225, "s": 9040, "text": "Category imbalance problem occurs when one label appears more often than others. In such a situation, classifiers tend to be overwhelmed by the large classes and ignore the small ones." }, { "code": null, "e": 9605, "s": 9225, "text": "Applied to our dataset of English tweets [2], we notice an imbalance of neutral versus positive/negative classes. As a consequence, a primitive strategy of classifying everything as neutral would give an accuracy of 73% (see table below). For the same reason, our model might tend to favor neutral. If unmanaged, category imbalance would make our model simplistic and inaccurate." }, { "code": null, "e": 9877, "s": 9605, "text": "To deal with this, we have to use upsampling. Upsampling (or oversampling) consists of adding new tweets for the minority classes, positive and negative, to have them reach a number of tweets equal to the majority class, neutral here. We provide a simple code to do that." }, { "code": null, "e": 11987, "s": 9877, "text": "def upsampling(input_file, output_file, ratio_upsampling=1): # # Create a file with equal number of tweets for each label # input_file: path to file # output_file: path to the output file # ratio_upsampling: ratio of each minority classes vs majority one. 1 mean there will be as much of each class than there is for the majority class. i=0 counts = {} dict_data_by_label = {} i=0 counts = {} dict_data_by_label = {}# GET LABEL LIST AND GET DATA PER LABEL with open(input_file, 'r', newline='') as csvinfile: csv_reader = csv.reader(csvinfile, delimiter=',', quotechar='\"') for row in csv_reader: counts[row[0].split()[0]] = counts.get(row[0].split()[0], 0) + 1 if not row[0].split()[0] in dict_data_by_label: dict_data_by_label[row[0].split()[0]]=[row[0]] else: dict_data_by_label[row[0].split()[0]].append(row[0]) i=i+1 if i%10000 ==0: print(\"read\" + str(i))# FIND MAJORITY CLASS majority_class=\"\" count_majority_class=0 for item in dict_data_by_label: if len(dict_data_by_label[item])>count_majority_class: majority_class= item count_majority_class=len(dict_data_by_label[item]) # UPSAMPLE MINORITY CLASS data_upsampled=[] for item in dict_data_by_label: data_upsampled.extend(dict_data_by_label[item]) if item != majority_class: items_added=0 items_to_add = count_majority_class - len(dict_data_by_label[item]) while items_added<items_to_add: data_upsampled.extend(dict_data_by_label[item][:max(0,min(items_to_add-items_added,len(dict_data_by_label[item])))]) items_added = items_added + max(0,min(items_to_add-items_added,len(dict_data_by_label[item])))# WRITE ALL i=0with open(output_file, 'w') as txtoutfile: for row in data_upsampled: txtoutfile.write(row+ '\\n' ) i=i+1 if i%10000 ==0: print(\"writer\" + str(i))upsampling( 'tweets.train','uptweets.train')" }, { "code": null, "e": 12143, "s": 11987, "text": "With upsampling, you run the risk of overfitting by repeating over and over the same tweets. But if your dataset is big enough this should not be an issue." }, { "code": null, "e": 12203, "s": 12143, "text": "Now the fun part. Time to train our machine for sentiments!" }, { "code": null, "e": 12447, "s": 12203, "text": "We use the fastText python wrapper to train our model. You can find implementation examples and documentation on Facebook Research’s GitHub page. Please make sure you install fastText using “git clone ...” and not using “pip install fasttext”." }, { "code": null, "e": 12651, "s": 12447, "text": "As we already prepared our data, all we need to do now is to use the function fastText.train_supervised. There are tons of options for this function, but for sake of simplicity we focus on the following:" }, { "code": null, "e": 12689, "s": 12651, "text": "input: the path to our training data." }, { "code": null, "e": 12727, "s": 12689, "text": "lr: Learning rate. We set it at 0.01." }, { "code": null, "e": 12792, "s": 12727, "text": "epoch: Number times we go through the entire dataset. We use 20." }, { "code": null, "e": 12911, "s": 12792, "text": "wordNgrams: An n-gram is a contiguous sequence of max n words from a given sample of text, tweet here. We set it at 2." }, { "code": null, "e": 12953, "s": 12911, "text": "dim: Dimension of word vector. We use 20." }, { "code": null, "e": 13012, "s": 12953, "text": "The following python code shows the training of our model." }, { "code": null, "e": 13269, "s": 13012, "text": "hyper_params = {\"lr\": 0.01, \"epoch\": 20, \"wordNgrams\": 2, \"dim\": 20} # Train the model.model = fastText.train_supervised(input=training_data_path, **hyper_params)print(\"Model trained with the hyperparameter \\n {}\".format(hyper_params))" }, { "code": null, "e": 13579, "s": 13269, "text": "Once trained, we need to assess how good our model is at sentiment analysis. For this, we can use the two measures Precision and Recall which are the output of fastText functionmodel.test. However, due to the nature of our problem, precision and recall give similar figures and we can focus on precision only." }, { "code": null, "e": 13805, "s": 13579, "text": "The code below implements model.test on the training and validation data to compare the accuracy of our model. Note that for validation, we take a different dataset on which we use the same cleaning process but no upsampling." }, { "code": null, "e": 14082, "s": 13805, "text": "# CHECK PERFORMANCE result = model.test(training_data_path)validation = model.test(validation_data_path) # DISPLAY ACCURACY OF TRAINED MODELtext_line = str(hyper_params) + \",accuracy:\" + str(result[1]) + \",validation:\" + str(validation[1]) + '\\n' print(text_line)" }, { "code": null, "e": 14183, "s": 14082, "text": "Overall the model gives an accuracy of 97.5% on the training data, and 79.7% on the validation data." }, { "code": null, "e": 14536, "s": 14183, "text": "Not so bad considering we did not tweak the hyperparameters. Furthermore, research estimates that people only agree around 60 to 80% of the times when judging the sentiment for a particular piece of text. So while we could try to reach for 100% accuracy, we have to keep in mind that humans are fallible... and most importantly that we work on tweets!!" }, { "code": null, "e": 14826, "s": 14536, "text": "We just showed how fastText works and how to train an English sentiment analysis model. We used sentiment data produced by AWS Comprehend. In another article, we explain how to serve your model with a robust cloud infrastructure, using AWS Elastic Beanstalk and a Python Flask application." }, { "code": null, "e": 14989, "s": 14826, "text": "Should you want to reproduce the results, just go to my gitHub. For the full English dataset just ask me (too big for GitHub). I’ll be happy to share it with you." }, { "code": null, "e": 15037, "s": 14989, "text": "https://medium.com/@charlesmalafosse/membership" }, { "code": null, "e": 15158, "s": 15037, "text": "[1] Bag of Tricks for Efficient Text Classification, Armand Joulin, Edouard Grave, Piotr Bojanowski, Tomas Mikolov, 2016" }, { "code": null, "e": 15247, "s": 15158, "text": "[2] https://github.com/charlesmalafosse. My GitHub page with full code for this article." }, { "code": null, "e": 15361, "s": 15247, "text": "[3] Facebook GitHub with fastText python wrapper. https://github.com/facebookresearch/fastText/tree/master/python" } ]
Aggregate functions in SQL - GeeksforGeeks
20 Aug, 2019 In database management an aggregate function is a function where the values of multiple rows are grouped together as input on certain criteria to form a single value of more significant meaning. Various Aggregate Functions 1) Count() 2) Sum() 3) Avg() 4) Min() 5) Max() Now let us understand each Aggregate function with a example: Id Name Salary ----------------------- 1 A 80 2 B 40 3 C 60 4 D 70 5 E 60 6 F Null Count(): Count(*): Returns total number of records .i.e 6.Count(salary): Return number of Non Null values over the column salary. i.e 5.Count(Distinct Salary): Return number of distinct Non Null values over the column salary .i.e 4 Sum(): sum(salary): Sum all Non Null values of Column salary i.e., 310sum(Distinct salary): Sum of all distinct Non-Null values i.e., 250. Avg(): Avg(salary) = Sum(salary) / count(salary) = 310/5Avg(Distinct salary) = sum(Distinct salary) / Count(Distinct Salary) = 250/4 Min(): Min(salary): Minimum value in the salary column except NULL i.e., 40.Max(salary): Maximum value in the salary i.e., 80. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Trigger | Student Database CTE in SQL Introduction of B-Tree Difference between Clustered and Non-clustered index SQL Interview Questions Introduction of ER Model Data Preprocessing in Data Mining Introduction of DBMS (Database Management System) | Set 1 SQL | Views Difference between DELETE, DROP and TRUNCATE
[ { "code": null, "e": 24036, "s": 24008, "text": "\n20 Aug, 2019" }, { "code": null, "e": 24231, "s": 24036, "text": "In database management an aggregate function is a function where the values of multiple rows are grouped together as input on certain criteria to form a single value of more significant meaning." }, { "code": null, "e": 24261, "s": 24233, "text": "Various Aggregate Functions" }, { "code": null, "e": 24308, "s": 24261, "text": "1) Count()\n2) Sum()\n3) Avg()\n4) Min()\n5) Max()" }, { "code": null, "e": 24372, "s": 24310, "text": "Now let us understand each Aggregate function with a example:" }, { "code": null, "e": 24542, "s": 24372, "text": "Id Name Salary\n-----------------------\n1 A 80\n2 B 40\n3 C 60\n4 D 70\n5 E 60\n6 F Null\n" }, { "code": null, "e": 24553, "s": 24544, "text": "Count():" }, { "code": null, "e": 24779, "s": 24555, "text": "Count(*): Returns total number of records .i.e 6.Count(salary): Return number of Non Null values over the column salary. i.e 5.Count(Distinct Salary): Return number of distinct Non Null values over the column salary .i.e 4" }, { "code": null, "e": 24788, "s": 24781, "text": "Sum():" }, { "code": null, "e": 24923, "s": 24790, "text": "sum(salary): Sum all Non Null values of Column salary i.e., 310sum(Distinct salary): Sum of all distinct Non-Null values i.e., 250." }, { "code": null, "e": 24932, "s": 24925, "text": "Avg():" }, { "code": null, "e": 25060, "s": 24934, "text": "Avg(salary) = Sum(salary) / count(salary) = 310/5Avg(Distinct salary) = sum(Distinct salary) / Count(Distinct Salary) = 250/4" }, { "code": null, "e": 25069, "s": 25062, "text": "Min():" }, { "code": null, "e": 25191, "s": 25071, "text": "Min(salary): Minimum value in the salary column except NULL i.e., 40.Max(salary): Maximum value in the salary i.e., 80." }, { "code": null, "e": 25317, "s": 25193, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 25322, "s": 25317, "text": "DBMS" }, { "code": null, "e": 25327, "s": 25322, "text": "DBMS" }, { "code": null, "e": 25425, "s": 25327, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25456, "s": 25425, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 25467, "s": 25456, "text": "CTE in SQL" }, { "code": null, "e": 25490, "s": 25467, "text": "Introduction of B-Tree" }, { "code": null, "e": 25543, "s": 25490, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 25567, "s": 25543, "text": "SQL Interview Questions" }, { "code": null, "e": 25592, "s": 25567, "text": "Introduction of ER Model" }, { "code": null, "e": 25626, "s": 25592, "text": "Data Preprocessing in Data Mining" }, { "code": null, "e": 25684, "s": 25626, "text": "Introduction of DBMS (Database Management System) | Set 1" }, { "code": null, "e": 25696, "s": 25684, "text": "SQL | Views" } ]
Python | Pandas DatetimeIndex.time - GeeksforGeeks
24 Dec, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas DatetimeIndex.time attribute outputs an Index object containing the time values present in each of the entries of the DatetimeIndex object. Syntax: DatetimeIndex.time Return: numpy array of python datetime.time Example #1: Use DatetimeIndex.time attribute to find the time part of the DatetimeIndex object. # importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'H' represents hourly frequencydidx = pd.DatetimeIndex(start ='2000-01-10 06:30', freq ='H', periods = 3, tz ='Asia/Calcutta') # Print the DatetimeIndexprint(didx) Output : Now we want to find all the time part of DatetimeIndex object. # find all the time values present in the objectdidx.time Output :As we can see in the output, the function has returned an Index object containing the time values present in each entry of the DatetimeIndex object. Example #2: Use DatetimeIndex.time attribute to find the time part of the DatetimeIndex object. # importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 's' represents secondly frequencydidx = pd.DatetimeIndex(start ='2014-08-01 10:05:45', freq ='S', periods = 5, tz ='Asia/Calcutta') # Print the DatetimeIndexprint(didx) Output : Now we want to find all the time part of DatetimeIndex object. # find all the time values present in the objectdidx.time Output :As we can see in the output, the function has returned an Index object containing the time values present in each entry of the DatetimeIndex object. Python pandas-datetimeIndex Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Get unique values from a list Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25665, "s": 25637, "text": "\n24 Dec, 2018" }, { "code": null, "e": 25879, "s": 25665, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 26026, "s": 25879, "text": "Pandas DatetimeIndex.time attribute outputs an Index object containing the time values present in each of the entries of the DatetimeIndex object." }, { "code": null, "e": 26053, "s": 26026, "text": "Syntax: DatetimeIndex.time" }, { "code": null, "e": 26097, "s": 26053, "text": "Return: numpy array of python datetime.time" }, { "code": null, "e": 26193, "s": 26097, "text": "Example #1: Use DatetimeIndex.time attribute to find the time part of the DatetimeIndex object." }, { "code": "# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'H' represents hourly frequencydidx = pd.DatetimeIndex(start ='2000-01-10 06:30', freq ='H', periods = 3, tz ='Asia/Calcutta') # Print the DatetimeIndexprint(didx)", "e": 26464, "s": 26193, "text": null }, { "code": null, "e": 26473, "s": 26464, "text": "Output :" }, { "code": null, "e": 26536, "s": 26473, "text": "Now we want to find all the time part of DatetimeIndex object." }, { "code": "# find all the time values present in the objectdidx.time", "e": 26594, "s": 26536, "text": null }, { "code": null, "e": 26847, "s": 26594, "text": "Output :As we can see in the output, the function has returned an Index object containing the time values present in each entry of the DatetimeIndex object. Example #2: Use DatetimeIndex.time attribute to find the time part of the DatetimeIndex object." }, { "code": "# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 's' represents secondly frequencydidx = pd.DatetimeIndex(start ='2014-08-01 10:05:45', freq ='S', periods = 5, tz ='Asia/Calcutta') # Print the DatetimeIndexprint(didx)", "e": 27124, "s": 26847, "text": null }, { "code": null, "e": 27133, "s": 27124, "text": "Output :" }, { "code": null, "e": 27196, "s": 27133, "text": "Now we want to find all the time part of DatetimeIndex object." }, { "code": "# find all the time values present in the objectdidx.time", "e": 27254, "s": 27196, "text": null }, { "code": null, "e": 27411, "s": 27254, "text": "Output :As we can see in the output, the function has returned an Index object containing the time values present in each entry of the DatetimeIndex object." }, { "code": null, "e": 27439, "s": 27411, "text": "Python pandas-datetimeIndex" }, { "code": null, "e": 27453, "s": 27439, "text": "Python-pandas" }, { "code": null, "e": 27460, "s": 27453, "text": "Python" }, { "code": null, "e": 27558, "s": 27460, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27590, "s": 27558, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27632, "s": 27590, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27674, "s": 27632, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27730, "s": 27674, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27757, "s": 27730, "text": "Python Classes and Objects" }, { "code": null, "e": 27788, "s": 27757, "text": "Python | os.path.join() method" }, { "code": null, "e": 27817, "s": 27788, "text": "Create a directory in Python" }, { "code": null, "e": 27839, "s": 27817, "text": "Defaultdict in Python" }, { "code": null, "e": 27878, "s": 27839, "text": "Python | Get unique values from a list" } ]
Advanced C++ | Virtual Copy Constructor - GeeksforGeeks
24 Feb, 2022 In the virtual constructor idiom we have seen the way to construct an object whose type is not determined until runtime. Is it possible to create an object without knowing it’s exact class type? The virtual copy constructor address this question.Sometimes we may need to construct an object from another existing object. Precisely the copy constructor does the same. The initial state of new object will be based on another existing object state. The compiler places call to copy constructor when an object being instantiated from another object. However, the compiler needs concrete type information to invoke appropriate copy constructor. C #include <iostream>using namespace std; class Base{public: //}; class Derived : public Base{public: Derived() { cout << "Derived created" << endl; } Derived(const Derived &rhs) { cout << "Derived created by deep copy" << endl; } ~Derived() { cout << "Derived destroyed" << endl; }}; int main(){ Derived s1; Derived s2 = s1; // Compiler invokes "copy constructor" // Type of s1 and s2 are concrete to compiler // How can we create Derived1 or Derived2 object // from pointer (reference) to Base class pointing Derived object? return 0;} What if we can’t decide from which type of object, the copy construction to be made? For example, virtual constructor creates an object of class hierarchy at runtime based on some input. When we want to copy construct an object from another object created by virtual constructor, we can’t use usual copy constructor. We need a special cloning function that can duplicate the object at runtime.As an example, consider a drawing application. You can select an object already drawn on the canvas and paste one more instance of the same object. From the programmer perspective, we can’t decide which object will be copy-pasted as it is runtime decision. We need virtual copy constructor to help.Similarly, consider clip board application. A clip board can hold different type of objects, and copy objects from existing objects, pastes them on application canvas. Again, what type of object to be copied is a runtime decision. Virtual copy constructor fills the gap here. See the example below, C #include <iostream>using namespace std; //// LIBRARY STARTclass Base{public: Base() { } virtual // Ensures to invoke actual object destructor ~Base() { } virtual void ChangeAttributes() = 0; // The "Virtual Constructor" static Base *Create(int id); // The "Virtual Copy Constructor" virtual Base *Clone() = 0;}; class Derived1 : public Base{public: Derived1() { cout << "Derived1 created" << endl; } Derived1(const Derived1& rhs) { cout << "Derived1 created by deep copy" << endl; } ~Derived1() { cout << "~Derived1 destroyed" << endl; } void ChangeAttributes() { cout << "Derived1 Attributes Changed" << endl; } Base *Clone() { return new Derived1(*this); }}; class Derived2 : public Base{public: Derived2() { cout << "Derived2 created" << endl; } Derived2(const Derived2& rhs) { cout << "Derived2 created by deep copy" << endl; } ~Derived2() { cout << "~Derived2 destroyed" << endl; } void ChangeAttributes() { cout << "Derived2 Attributes Changed" << endl; } Base *Clone() { return new Derived2(*this); }}; class Derived3 : public Base{public: Derived3() { cout << "Derived3 created" << endl; } Derived3(const Derived3& rhs) { cout << "Derived3 created by deep copy" << endl; } ~Derived3() { cout << "~Derived3 destroyed" << endl; } void ChangeAttributes() { cout << "Derived3 Attributes Changed" << endl; } Base *Clone() { return new Derived3(*this); }}; // We can also declare "Create" outside Base.// But is more relevant to limit it's scope to BaseBase *Base::Create(int id){ // Just expand the if-else ladder, if new Derived class is created // User need not be recompiled to create newly added class objects if( id == 1 ) { return new Derived1; } else if( id == 2 ) { return new Derived2; } else { return new Derived3; }}//// LIBRARY END //// UTILITY SRARTclass User{public: User() : pBase(0) { // Creates any object of Base hierarchy at runtime int input; cout << "Enter ID (1, 2 or 3): "; cin >> input; while( (input != 1) && (input != 2) && (input != 3) ) { cout << "Enter ID (1, 2 or 3 only): "; cin >> input; } // Create objects via the "Virtual Constructor" pBase = Base::Create(input); } ~User() { if( pBase ) { delete pBase; pBase = 0; } } void Action() { // Duplicate current object Base *pNewBase = pBase->Clone(); // Change its attributes pNewBase->ChangeAttributes(); // Dispose the created object delete pNewBase; } private: Base *pBase;}; //// UTILITY END //// Consumer of User (UTILITY) classint main(){ User *user = new User(); user->Action(); delete user;} User class creating an object with the help of virtual constructor. The object to be created is based on user input. Action() is making duplicate of object being created and modifying it’s attributes. The duplicate object being created with the help of Clone() virtual function which is also considered as virtual copy constructor. The concept behind Clone() method is building block of prototype pattern.— Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. simmytarika5 C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Function Pointer in C fork() in C std::string class in C++ TCP Server-Client implementation in C Structures in C Vector in C++ STL Inheritance in C++ Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 25813, "s": 25785, "text": "\n24 Feb, 2022" }, { "code": null, "e": 26455, "s": 25813, "text": "In the virtual constructor idiom we have seen the way to construct an object whose type is not determined until runtime. Is it possible to create an object without knowing it’s exact class type? The virtual copy constructor address this question.Sometimes we may need to construct an object from another existing object. Precisely the copy constructor does the same. The initial state of new object will be based on another existing object state. The compiler places call to copy constructor when an object being instantiated from another object. However, the compiler needs concrete type information to invoke appropriate copy constructor. " }, { "code": null, "e": 26457, "s": 26455, "text": "C" }, { "code": "#include <iostream>using namespace std; class Base{public: //}; class Derived : public Base{public: Derived() { cout << \"Derived created\" << endl; } Derived(const Derived &rhs) { cout << \"Derived created by deep copy\" << endl; } ~Derived() { cout << \"Derived destroyed\" << endl; }}; int main(){ Derived s1; Derived s2 = s1; // Compiler invokes \"copy constructor\" // Type of s1 and s2 are concrete to compiler // How can we create Derived1 or Derived2 object // from pointer (reference) to Base class pointing Derived object? return 0;}", "e": 27086, "s": 26457, "text": null }, { "code": null, "e": 28077, "s": 27086, "text": "What if we can’t decide from which type of object, the copy construction to be made? For example, virtual constructor creates an object of class hierarchy at runtime based on some input. When we want to copy construct an object from another object created by virtual constructor, we can’t use usual copy constructor. We need a special cloning function that can duplicate the object at runtime.As an example, consider a drawing application. You can select an object already drawn on the canvas and paste one more instance of the same object. From the programmer perspective, we can’t decide which object will be copy-pasted as it is runtime decision. We need virtual copy constructor to help.Similarly, consider clip board application. A clip board can hold different type of objects, and copy objects from existing objects, pastes them on application canvas. Again, what type of object to be copied is a runtime decision. Virtual copy constructor fills the gap here. See the example below, " }, { "code": null, "e": 28079, "s": 28077, "text": "C" }, { "code": "#include <iostream>using namespace std; //// LIBRARY STARTclass Base{public: Base() { } virtual // Ensures to invoke actual object destructor ~Base() { } virtual void ChangeAttributes() = 0; // The \"Virtual Constructor\" static Base *Create(int id); // The \"Virtual Copy Constructor\" virtual Base *Clone() = 0;}; class Derived1 : public Base{public: Derived1() { cout << \"Derived1 created\" << endl; } Derived1(const Derived1& rhs) { cout << \"Derived1 created by deep copy\" << endl; } ~Derived1() { cout << \"~Derived1 destroyed\" << endl; } void ChangeAttributes() { cout << \"Derived1 Attributes Changed\" << endl; } Base *Clone() { return new Derived1(*this); }}; class Derived2 : public Base{public: Derived2() { cout << \"Derived2 created\" << endl; } Derived2(const Derived2& rhs) { cout << \"Derived2 created by deep copy\" << endl; } ~Derived2() { cout << \"~Derived2 destroyed\" << endl; } void ChangeAttributes() { cout << \"Derived2 Attributes Changed\" << endl; } Base *Clone() { return new Derived2(*this); }}; class Derived3 : public Base{public: Derived3() { cout << \"Derived3 created\" << endl; } Derived3(const Derived3& rhs) { cout << \"Derived3 created by deep copy\" << endl; } ~Derived3() { cout << \"~Derived3 destroyed\" << endl; } void ChangeAttributes() { cout << \"Derived3 Attributes Changed\" << endl; } Base *Clone() { return new Derived3(*this); }}; // We can also declare \"Create\" outside Base.// But is more relevant to limit it's scope to BaseBase *Base::Create(int id){ // Just expand the if-else ladder, if new Derived class is created // User need not be recompiled to create newly added class objects if( id == 1 ) { return new Derived1; } else if( id == 2 ) { return new Derived2; } else { return new Derived3; }}//// LIBRARY END //// UTILITY SRARTclass User{public: User() : pBase(0) { // Creates any object of Base hierarchy at runtime int input; cout << \"Enter ID (1, 2 or 3): \"; cin >> input; while( (input != 1) && (input != 2) && (input != 3) ) { cout << \"Enter ID (1, 2 or 3 only): \"; cin >> input; } // Create objects via the \"Virtual Constructor\" pBase = Base::Create(input); } ~User() { if( pBase ) { delete pBase; pBase = 0; } } void Action() { // Duplicate current object Base *pNewBase = pBase->Clone(); // Change its attributes pNewBase->ChangeAttributes(); // Dispose the created object delete pNewBase; } private: Base *pBase;}; //// UTILITY END //// Consumer of User (UTILITY) classint main(){ User *user = new User(); user->Action(); delete user;}", "e": 31123, "s": 28079, "text": null }, { "code": null, "e": 31663, "s": 31123, "text": "User class creating an object with the help of virtual constructor. The object to be created is based on user input. Action() is making duplicate of object being created and modifying it’s attributes. The duplicate object being created with the help of Clone() virtual function which is also considered as virtual copy constructor. The concept behind Clone() method is building block of prototype pattern.— Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 31676, "s": 31663, "text": "simmytarika5" }, { "code": null, "e": 31687, "s": 31676, "text": "C Language" }, { "code": null, "e": 31691, "s": 31687, "text": "C++" }, { "code": null, "e": 31695, "s": 31691, "text": "CPP" }, { "code": null, "e": 31793, "s": 31695, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31815, "s": 31793, "text": "Function Pointer in C" }, { "code": null, "e": 31827, "s": 31815, "text": "fork() in C" }, { "code": null, "e": 31852, "s": 31827, "text": "std::string class in C++" }, { "code": null, "e": 31890, "s": 31852, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 31906, "s": 31890, "text": "Structures in C" }, { "code": null, "e": 31924, "s": 31906, "text": "Vector in C++ STL" }, { "code": null, "e": 31943, "s": 31924, "text": "Inheritance in C++" }, { "code": null, "e": 31989, "s": 31943, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 32032, "s": 31989, "text": "Map in C++ Standard Template Library (STL)" } ]
Code and Techniques for Exploratory Data Analysis | Towards Data Science
Disclaimer: you are reading Part 1 “Exploratory Data Analysis Framework”. Part 2 shows how to build a baseline model based on the insights of the analysis below. It is a very common situation when you need to show the value of the data to your clients by generating insights and building a first baseline model. As a Data Science Consultant, you might be getting such requests on a weekly basis. Therefore, it makes sense to build a basic framework for Exploratory Data Analysis that helps you to evaluate the data quality and show first insights to the client. In this article, I describe an Exploratory Data Analysis Framework that I use while analysing new datasets. The framework includes: · Assessment of the data quality · Overview of the data distributions · Analysis of the different types of data (geolocation, time series, nominal etc.) · Association (or Correlation) analysis · Building a baseline model (which is described in Part 2 of the analysis) The proposed framework is not exhaustive, but covers a wide range of cases and can be used as a starting point for the development of a more elaborate framework. It serves as a first sanity check before we approach any complex modelling. The full notebook can be found on GitHub. In this example, I use the road accident safety data found at data.gov.uk. This dataset contains different types of data: Geo, Time Series, Categorical, and Continues variables that are very close to a real world scenario where the data come from multiple sources and might be of different types. The end goal is to develop a model to predict the probability of a police officer to attend an accident. We also should evaluate the quality of data at our disposal and demonstrate which factors have the highest impact on the model’s decision. First I am importing the packages that we need for the exploratory data analysis. import pandas as pd import numpy as np import missingno as msno import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline ACCEDENTS_PATH = "data/Acc.csv" acc_df = pd.read_csv(ACCEDENTS_PATH, parse_dates=["Date"], dtype={"Accident_Index": object}) Apart from the standard packages like pandas, numpy, and matplotlib I imported missingno which is a pandas compatible library for visualising missing values. As I do not want the accident dataframe to be changed during the data exploration phase, the data are copied to a separate variable. All the subsequent steps of the data analysis will be performed on the copy and I will get back to the original dataset once entering the modelling phase (in Part 2). data = acc_df.copy() data.head() 5 rows × 32 columns The dataset contains 32 variables most of which are categorical. We can check the meaning of each variable and its values in the Variable Lookup. First, we need to assess the variables datatypes, as some of them might need type casting. data.info() <class 'pandas.core.frame.DataFrame'> RangeIndex: 129982 entries, 0 to 129981 Data columns (total 32 columns): Accident_Index 129982 non-null object Location_Easting_OSGR 129963 non-null float64 Location_Northing_OSGR 129963 non-null float64 Longitude 129953 non-null float64 Latitude 129953 non-null float64 Police_Force 129982 non-null int64 Accident_Severity 129982 non-null int64 Number_of_Vehicles 129982 non-null int64 Number_of_Casualties 129982 non-null int64 Date 129982 non-null datetime64[ns] Day_of_Week 129982 non-null int64 Time 129979 non-null object Local_Authority_(District) 129982 non-null int64 Local_Authority_(Highway) 129982 non-null object 1st_Road_Class 129982 non-null int64 1st_Road_Number 129982 non-null int64 Road_Type 129982 non-null int64 Speed_limit 129982 non-null int64 Junction_Detail 129982 non-null int64 Junction_Control 129982 non-null int64 2nd_Road_Class 129982 non-null int64 2nd_Road_Number 129982 non-null int64 Pedestrian_Crossing-Human_Control 129982 non-null int64 Pedestrian_Crossing-Physical_Facilities 129982 non-null int64 Light_Conditions 129982 non-null int64 Weather_Conditions 129982 non-null int64 Road_Surface_Conditions 129982 non-null int64 Special_Conditions_at_Site 129982 non-null int64 Carriageway_Hazards 129982 non-null int64 Urban_or_Rural_Area 129982 non-null int64 Did_Police_Officer_Attend_Scene_of_Accident 129982 non-null int64 LSOA_of_Accident_Location 122851 non-null object dtypes: datetime64[ns](1), float64(4), int64(23), object(4) memory usage: 31.7+ MB Most of the variables in the accident dataset are numerical. There is also one variable that I explicitly set up as a datetime object while reading, and we also have four object variables: Accident_Index — index of the accident Time — time in a format HH:mm Local_Authority_(Highway), LSOA_of_Accident_Location — categorical variables that contain information about location of the accident. Before we jump into a deeper analysis of the variables in the dataset, let’s get an overview of the missing values. As mentioned earlier, to get a quick impression of the pattern of missing values I use missingno package because of the graphical representation of the dataset that it provides. It allows us to quickly detect patterns in missing data and then come-up with a judgment whether the data are missing at random. Based on that we would need to develop a strategy on how to handle the missing values. In the accident dataset, the missing values are indicated with a value of “-1”. First of all, we need to replace it with a NaN value, so we can get an overview of a pattern of missing observations. As I am only interested in the variables that contain missing values I visualise only the columns that contain NaN values. The diagram shows missing observations in each column and the bar on the right shows each row’s data completeness. As we can see, there are a few columns where missing values seem to be associated: Junction_Control with 2nd_Road_Class Pedestrian_Crossing-Human_Control with Pedestrian_Crossing-Physical_Facilities Road_Surface_Conditions with Special_Conditions_at_Site and Carriageway_Hazards That means that the values are not missing at random which we need to keep in mind while working on the strategy for handling missing values. Also some variables like Junction_Control will be shown to have a significant impact on the response variable. Therefore in future, the missing values should be completed, e.g. by vehicle sensor data. To get a better feel of the data we are dealing with, I will plot a histogram of each numerical value. As we have been seeing, the dataset contains different types of data: Geographical, Categorical, Time Series. All types of data should be addressed and analysed individually. Most of the variables are categorical with a low cardinality. We also see that some pairs of features like Longitude and Location_Easting_OSGR Latitude and Location_Northing_OSGR have very similar distributions. They likely duplicate the information. Therefore we can concentrate on analysing only Latitude as well as Longitude and omit Location_Easting_OSGR as well as Location_Northing_OSGR for now. Let’s take a brief look at the variable that we want to forecast, as further analysis will be performed in its context. The response variable contains three classes. I will merge class 2 and 3 to a negative class, as I am interested only in predicting a probability of the police officer to attend an accident. As we can see the classes in the response variable are imbalanced which is something to keep in mind when training the model. Since there are quite some variables describing the location of the accident, I will check if location is an important factor to predict whether a police officer will attend the accident. Red — Not Attended Grey — Attended The plot shows that there are areas where police officer are less likely to attend an accident. When we train a model, Longitude and Latitude might be variables with a high discriminative power. Hypotheses testing In this section, I will test a few hypotheses about the relations between the variables in the dataset. A common way to check for the relations between the variables is to calculate correlation (e.g. Pearson Correlation Coefficient). However, the vast majority of the variables in the accident dataset are categorical. We can not use correlation on our dataset, as correlation measures linear relationships between two quantitative variables. Therefore, I use Chi-Squared Test to identify a significant association between two categorical variables. After staring at the data for a while, I came up with a hypothesis that one of the most important factors for a police officer to make a decision wether or not to attend an accident would be the accident severity. Then our first hypothesis to test would be the following: H0: The severity of the accident has no impact on the probability of a police officer to attend an accident. Remember, the null hypothesis is always a hypothesis of no change and our job now is to check whether we have enough evidence to reject it. We can observe a difference between the groups, but we need to quantify these relationships. For that, I will perform a Chi-Squared Test at a 5% level of significance. To perform a Chi-Squared Test I use the researchpy package. Researchpy produces Pandas DataFrames that contain relevant statistical testing information that is commonly required for academic research. Chi-Squared test run by researchpy provides us with three values: Pearson Chi-Square — is computed by taking a sum of squared differences between observed and expected frequencies normalised by expected frequency. It is used to calculate a p-value, which is another output of Chi-Squared Test p-value — probability of the observed result assuming that H0 is correct Cramer’s V — is an effect size which quantifies the association between two categorical variables. We could have used Pearson Chi-Square statistic to quantify the relationships, however as with covariance, it is not bounded and tends to grow with the number of dimensions and samples. Therefore, to make a comparable measure of the effect size across datasets of different sizes, we need to normalise the Pearson Chi-Square statistic by dividing it by the sample size and the minimum dimension minus 1. It will give us a value between 0 and +1 which is called Cramer’s V. The result of the Chi-Squared Test suggests that there is a statistically significant evidence to show that H0 is false. Given evidence and data we reject H0 that there is no association between the variables Accident_Severity and Did_Police_Officer_Attend_Scene_of_Accident with a p-value < 0.005 and effect size 0.1. Now that we know that the association is significant, we want to test where the relationship is between the levels of the variables. In order to do this, we need to conduct multiple 2×2 Chi-Squared Tests. However, conducting multiple tests on the same dependent variable increases the chance of false positives, thus increasing the likelihood of getting a significant result by chance alone. To account for false positives we need to adjust a significance to the number of comparisons being performed by correcting its level. This correction calls Bonferroni correction. I will use the stats package from scipy for that, as an alternative method to researchpy. Something to keep in mind is that scipy does not provide the result in a Pandas Dataframe. The chi-squared test using the Bonferroni-adjusted level of significance=0.017 shows that all comparisons are significant. However, it is quite time consuming to run Chi-Squared Tests for each pair of variables in our dataset. Therefore, I will build an association matrix as the last step of the data exploration. There are Date and Time variables in the dataset and it is always a good idea to check for the time dependent patterns and add some new variables to help our model to make a decision. First, let’s take a glimpse at the Time variable. We can observe two rush hour periods where accidents are more likely to happen: between 7–9 AM and 15–18 PM. Knowing that the amount of police officers is constant across the time, I would assume that during the rush hours the attendance would be lower, as there might be not enough police officers to attend all the accidents. Therefore, I will create a variable indicating a rush hour and test for its association with the probability of the police officer to attend an accident. There is a slight difference between the groups. In order to quantify these relationships I will run another Chi-Squared Test. H0: Rush hour has no impact on the probability of a police officer to attends an accident The result of the Chi-Squared Test suggests that there is a statistically significant evidence that H0 is false. Given evidence and data we reject H0 that there is no association between the variables Rush_Hour and Did_Police_Officer_Attend_Scene_of_Accident with a p-value<0.005 and effect size 0.04. Another time related variable in the accident dataset is Date. I will plot the total number of accidents per day to analyse a time depended trend. The plot shows a cyclical pattern, which might suggest that there is some sort of seasonality. I will plot an ACF and PACF plots to check whether there is a significant seasonal component in the time series. The ACF plot shows a significant trend component at lag 1 and significant seasonal component at lags 6 and 7, which might indicate a weekend. I will plot the number of accidents per weekday to check if the behaviour on the weekends is different. We can observe a slight drop in overall accidents and those that were attended during the weekends. I will model weekends explicitly and then check if a newly created variable has a significant association with the probability of a police officer to attend an accident. H0: Weekends have no impact on the probability of a police officer to attend an accident. The result of the Chi-Squared Test suggests that there is statistically significant evidence to show that H0 is false. Given the evidence and data, we reject H0 that there is no association between the variables Weekend and Did_Police_Officer_Attend_Scene_of_Accident with a p-value<0.005 and effect size 0.04. We have already tested a few hypotheses and engineered two new features, Rush_Hour and Weekend. Now let’s join the other data that are available at data.gov.uk. First, I will join the data from the casualties dataset. The casualties dataset mainly contains categorical variables. From the first three rows we can see that the Accident_Index is not unique for each row, as one accident may lead to multiple casualties. For us that implies that we can not join the accidents and casualties data tables directly, but rather need to do some feature engineering. For the first evaluation let’s join just a few variables from the casualties dataset. I will shape a few hypotheses and assume that police officers are more likely to attend an accident if one of the following is true: Casualties are pedestrians People below 18 or above 65 years old The driver is below 18, or above 65 years old Therefore, I will create new binary variables, join them to the accident dataset, and test whether there is a significant association with the response variable. The Chi-Squared Test showed a significant association between newly created variables and probability of a police officer to attend an accident at a significance level of 0.05 and p-value<0.005. Now let’s join a third datasource available at data.gov.uk, which is a dataset of vehicles that being involved in the accident. From the first few rows, we can see that Accident_Index is not unique for each row, as one accident may involve several vehicles. Again we need to do feature engineering to join the data. I will shape a few hypotheses and assume that police officers are more likely to attend an accident if one of the following is true: Cycle is involved in the accident Taxi, Van, or Public transport is involved in the accident The driver is below 18, or above 65 years old As in a case with the casualties dataset, I will create related binary variables, join them to the accident dataset, and test whether there is a significant association with the response variable. The Chi-Squared Test shows a significant association between the newly created variables and the probability of a police officer to attend an accident at a significance level of 0.05. Undoubtedly, much more sophisticated feature engineering can be performed on these three datasets, including building categorical embeddings. However, our objective is to build a first prototype model and to show to the client the value of the data by generating quick insights and spotting interesting relationships between the variables (e.g. geographical data with accident attendance, accidents seasonality etc.). To stay pragmatic I will end the feature engineering for now. The last thing I would like to do before entering the modelling phase is to build an association matrix for the categorical variables to summarise the analysis that has been done. I will build an association matrix by calculating Cramer’s V statistic for cross categorial association, which is the effect size provided by the researchpy package. As mentioned already, an important detail to keep in mind is that Cramer’s V tends to overestimate the strength of association for the large and high dimensional samples. Therefore we need to implement a bias correction, which is described on Wikipedia. I use a very nice implementation of the bias correction from Ziggy Eunicien. The variable we are interested in forecasting, “Did_Police_Officer_Attend_Scene_of_Accident”, is located in the first column (and row) of the matrix. Unsurprisingly, the time-related variables are strongly associated with each other: Date, Day_of_Week, and Weekend. The location-related variables in the dataset, Police_Force, Local_Authority_(District), Local_Authority_(Highway), and LSOA_of_Accident_Location have a high association with the probability of a police officer to attend an accident. This is consistent with the findings presented under the analysis of geographical data. In Part 1 of Exploratory Data Analysis I analysed the UK the road accident safety data. A data quality assurance was conducted with the result that there is a pattern in missing data. Sensor data should be used to improve the accuracy of the forecasts. The analysis of geographical data showed that there are relationships between the location of the accident and the probability of a police officer to attend it. This implies that there are districts (for example East London) and regions that require a higher number of police officers to be on staff. It is especially important during rush hours when the percentage of not attended accidents increases. The analysis of variables from casualties and vehicles datasets showed that a police officer is more likely to attend an accident if pedestrians and people under 18 or above 65 years old were casualties. Also, a certain type of vehicles (bicycles and public transport) lead to a higher likelihood of a police officer to attend the accident. That is a valuable insight for predictive analytics. In Part 2 I will show how to build a baseline model based on the insights we learned during the exploratory phase.
[ { "code": null, "e": 333, "s": 171, "text": "Disclaimer: you are reading Part 1 “Exploratory Data Analysis Framework”. Part 2 shows how to build a baseline model based on the insights of the analysis below." }, { "code": null, "e": 865, "s": 333, "text": "It is a very common situation when you need to show the value of the data to your clients by generating insights and building a first baseline model. As a Data Science Consultant, you might be getting such requests on a weekly basis. Therefore, it makes sense to build a basic framework for Exploratory Data Analysis that helps you to evaluate the data quality and show first insights to the client. In this article, I describe an Exploratory Data Analysis Framework that I use while analysing new datasets. The framework includes:" }, { "code": null, "e": 898, "s": 865, "text": "· Assessment of the data quality" }, { "code": null, "e": 935, "s": 898, "text": "· Overview of the data distributions" }, { "code": null, "e": 1018, "s": 935, "text": "· Analysis of the different types of data (geolocation, time series, nominal etc.)" }, { "code": null, "e": 1058, "s": 1018, "text": "· Association (or Correlation) analysis" }, { "code": null, "e": 1133, "s": 1058, "text": "· Building a baseline model (which is described in Part 2 of the analysis)" }, { "code": null, "e": 1413, "s": 1133, "text": "The proposed framework is not exhaustive, but covers a wide range of cases and can be used as a starting point for the development of a more elaborate framework. It serves as a first sanity check before we approach any complex modelling. The full notebook can be found on GitHub." }, { "code": null, "e": 1710, "s": 1413, "text": "In this example, I use the road accident safety data found at data.gov.uk. This dataset contains different types of data: Geo, Time Series, Categorical, and Continues variables that are very close to a real world scenario where the data come from multiple sources and might be of different types." }, { "code": null, "e": 1954, "s": 1710, "text": "The end goal is to develop a model to predict the probability of a police officer to attend an accident. We also should evaluate the quality of data at our disposal and demonstrate which factors have the highest impact on the model’s decision." }, { "code": null, "e": 2036, "s": 1954, "text": "First I am importing the packages that we need for the exploratory data analysis." }, { "code": null, "e": 2176, "s": 2036, "text": "import pandas as pd\nimport numpy as np\n\nimport missingno as msno\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n%matplotlib inline\n" }, { "code": null, "e": 2346, "s": 2176, "text": "ACCEDENTS_PATH = \"data/Acc.csv\"\nacc_df = pd.read_csv(ACCEDENTS_PATH, \n parse_dates=[\"Date\"], \n dtype={\"Accident_Index\": object})\n" }, { "code": null, "e": 2504, "s": 2346, "text": "Apart from the standard packages like pandas, numpy, and matplotlib I imported missingno which is a pandas compatible library for visualising missing values." }, { "code": null, "e": 2804, "s": 2504, "text": "As I do not want the accident dataframe to be changed during the data exploration phase, the data are copied to a separate variable. All the subsequent steps of the data analysis will be performed on the copy and I will get back to the original dataset once entering the modelling phase (in Part 2)." }, { "code": null, "e": 2826, "s": 2804, "text": "data = acc_df.copy()\n" }, { "code": null, "e": 2839, "s": 2826, "text": "data.head()\n" }, { "code": null, "e": 2859, "s": 2839, "text": "5 rows × 32 columns" }, { "code": null, "e": 3096, "s": 2859, "text": "The dataset contains 32 variables most of which are categorical. We can check the meaning of each variable and its values in the Variable Lookup. First, we need to assess the variables datatypes, as some of them might need type casting." }, { "code": null, "e": 3109, "s": 3096, "text": "data.info()\n" }, { "code": null, "e": 5533, "s": 3109, "text": "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 129982 entries, 0 to 129981\nData columns (total 32 columns):\nAccident_Index 129982 non-null object\nLocation_Easting_OSGR 129963 non-null float64\nLocation_Northing_OSGR 129963 non-null float64\nLongitude 129953 non-null float64\nLatitude 129953 non-null float64\nPolice_Force 129982 non-null int64\nAccident_Severity 129982 non-null int64\nNumber_of_Vehicles 129982 non-null int64\nNumber_of_Casualties 129982 non-null int64\nDate 129982 non-null datetime64[ns]\nDay_of_Week 129982 non-null int64\nTime 129979 non-null object\nLocal_Authority_(District) 129982 non-null int64\nLocal_Authority_(Highway) 129982 non-null object\n1st_Road_Class 129982 non-null int64\n1st_Road_Number 129982 non-null int64\nRoad_Type 129982 non-null int64\nSpeed_limit 129982 non-null int64\nJunction_Detail 129982 non-null int64\nJunction_Control 129982 non-null int64\n2nd_Road_Class 129982 non-null int64\n2nd_Road_Number 129982 non-null int64\nPedestrian_Crossing-Human_Control 129982 non-null int64\nPedestrian_Crossing-Physical_Facilities 129982 non-null int64\nLight_Conditions 129982 non-null int64\nWeather_Conditions 129982 non-null int64\nRoad_Surface_Conditions 129982 non-null int64\nSpecial_Conditions_at_Site 129982 non-null int64\nCarriageway_Hazards 129982 non-null int64\nUrban_or_Rural_Area 129982 non-null int64\nDid_Police_Officer_Attend_Scene_of_Accident 129982 non-null int64\nLSOA_of_Accident_Location 122851 non-null object\ndtypes: datetime64[ns](1), float64(4), int64(23), object(4)\nmemory usage: 31.7+ MB\n" }, { "code": null, "e": 5722, "s": 5533, "text": "Most of the variables in the accident dataset are numerical. There is also one variable that I explicitly set up as a datetime object while reading, and we also have four object variables:" }, { "code": null, "e": 5761, "s": 5722, "text": "Accident_Index — index of the accident" }, { "code": null, "e": 5791, "s": 5761, "text": "Time — time in a format HH:mm" }, { "code": null, "e": 5925, "s": 5791, "text": "Local_Authority_(Highway), LSOA_of_Accident_Location — categorical variables that contain information about location of the accident." }, { "code": null, "e": 6041, "s": 5925, "text": "Before we jump into a deeper analysis of the variables in the dataset, let’s get an overview of the missing values." }, { "code": null, "e": 6435, "s": 6041, "text": "As mentioned earlier, to get a quick impression of the pattern of missing values I use missingno package because of the graphical representation of the dataset that it provides. It allows us to quickly detect patterns in missing data and then come-up with a judgment whether the data are missing at random. Based on that we would need to develop a strategy on how to handle the missing values." }, { "code": null, "e": 6633, "s": 6435, "text": "In the accident dataset, the missing values are indicated with a value of “-1”. First of all, we need to replace it with a NaN value, so we can get an overview of a pattern of missing observations." }, { "code": null, "e": 6871, "s": 6633, "text": "As I am only interested in the variables that contain missing values I visualise only the columns that contain NaN values. The diagram shows missing observations in each column and the bar on the right shows each row’s data completeness." }, { "code": null, "e": 6954, "s": 6871, "text": "As we can see, there are a few columns where missing values seem to be associated:" }, { "code": null, "e": 6991, "s": 6954, "text": "Junction_Control with 2nd_Road_Class" }, { "code": null, "e": 7070, "s": 6991, "text": "Pedestrian_Crossing-Human_Control with Pedestrian_Crossing-Physical_Facilities" }, { "code": null, "e": 7150, "s": 7070, "text": "Road_Surface_Conditions with Special_Conditions_at_Site and Carriageway_Hazards" }, { "code": null, "e": 7292, "s": 7150, "text": "That means that the values are not missing at random which we need to keep in mind while working on the strategy for handling missing values." }, { "code": null, "e": 7493, "s": 7292, "text": "Also some variables like Junction_Control will be shown to have a significant impact on the response variable. Therefore in future, the missing values should be completed, e.g. by vehicle sensor data." }, { "code": null, "e": 7596, "s": 7493, "text": "To get a better feel of the data we are dealing with, I will plot a histogram of each numerical value." }, { "code": null, "e": 7771, "s": 7596, "text": "As we have been seeing, the dataset contains different types of data: Geographical, Categorical, Time Series. All types of data should be addressed and analysed individually." }, { "code": null, "e": 7878, "s": 7771, "text": "Most of the variables are categorical with a low cardinality. We also see that some pairs of features like" }, { "code": null, "e": 7914, "s": 7878, "text": "Longitude and Location_Easting_OSGR" }, { "code": null, "e": 7950, "s": 7914, "text": "Latitude and Location_Northing_OSGR" }, { "code": null, "e": 8173, "s": 7950, "text": "have very similar distributions. They likely duplicate the information. Therefore we can concentrate on analysing only Latitude as well as Longitude and omit Location_Easting_OSGR as well as Location_Northing_OSGR for now." }, { "code": null, "e": 8293, "s": 8173, "text": "Let’s take a brief look at the variable that we want to forecast, as further analysis will be performed in its context." }, { "code": null, "e": 8484, "s": 8293, "text": "The response variable contains three classes. I will merge class 2 and 3 to a negative class, as I am interested only in predicting a probability of the police officer to attend an accident." }, { "code": null, "e": 8610, "s": 8484, "text": "As we can see the classes in the response variable are imbalanced which is something to keep in mind when training the model." }, { "code": null, "e": 8798, "s": 8610, "text": "Since there are quite some variables describing the location of the accident, I will check if location is an important factor to predict whether a police officer will attend the accident." }, { "code": null, "e": 8817, "s": 8798, "text": "Red — Not Attended" }, { "code": null, "e": 8833, "s": 8817, "text": "Grey — Attended" }, { "code": null, "e": 9028, "s": 8833, "text": "The plot shows that there are areas where police officer are less likely to attend an accident. When we train a model, Longitude and Latitude might be variables with a high discriminative power." }, { "code": null, "e": 9047, "s": 9028, "text": "Hypotheses testing" }, { "code": null, "e": 9597, "s": 9047, "text": "In this section, I will test a few hypotheses about the relations between the variables in the dataset. A common way to check for the relations between the variables is to calculate correlation (e.g. Pearson Correlation Coefficient). However, the vast majority of the variables in the accident dataset are categorical. We can not use correlation on our dataset, as correlation measures linear relationships between two quantitative variables. Therefore, I use Chi-Squared Test to identify a significant association between two categorical variables." }, { "code": null, "e": 9869, "s": 9597, "text": "After staring at the data for a while, I came up with a hypothesis that one of the most important factors for a police officer to make a decision wether or not to attend an accident would be the accident severity. Then our first hypothesis to test would be the following:" }, { "code": null, "e": 9978, "s": 9869, "text": "H0: The severity of the accident has no impact on the probability of a police officer to attend an accident." }, { "code": null, "e": 10118, "s": 9978, "text": "Remember, the null hypothesis is always a hypothesis of no change and our job now is to check whether we have enough evidence to reject it." }, { "code": null, "e": 10286, "s": 10118, "text": "We can observe a difference between the groups, but we need to quantify these relationships. For that, I will perform a Chi-Squared Test at a 5% level of significance." }, { "code": null, "e": 10487, "s": 10286, "text": "To perform a Chi-Squared Test I use the researchpy package. Researchpy produces Pandas DataFrames that contain relevant statistical testing information that is commonly required for academic research." }, { "code": null, "e": 10553, "s": 10487, "text": "Chi-Squared test run by researchpy provides us with three values:" }, { "code": null, "e": 10780, "s": 10553, "text": "Pearson Chi-Square — is computed by taking a sum of squared differences between observed and expected frequencies normalised by expected frequency. It is used to calculate a p-value, which is another output of Chi-Squared Test" }, { "code": null, "e": 10853, "s": 10780, "text": "p-value — probability of the observed result assuming that H0 is correct" }, { "code": null, "e": 11425, "s": 10853, "text": "Cramer’s V — is an effect size which quantifies the association between two categorical variables. We could have used Pearson Chi-Square statistic to quantify the relationships, however as with covariance, it is not bounded and tends to grow with the number of dimensions and samples. Therefore, to make a comparable measure of the effect size across datasets of different sizes, we need to normalise the Pearson Chi-Square statistic by dividing it by the sample size and the minimum dimension minus 1. It will give us a value between 0 and +1 which is called Cramer’s V." }, { "code": null, "e": 11744, "s": 11425, "text": "The result of the Chi-Squared Test suggests that there is a statistically significant evidence to show that H0 is false. Given evidence and data we reject H0 that there is no association between the variables Accident_Severity and Did_Police_Officer_Attend_Scene_of_Accident with a p-value < 0.005 and effect size 0.1." }, { "code": null, "e": 12496, "s": 11744, "text": "Now that we know that the association is significant, we want to test where the relationship is between the levels of the variables. In order to do this, we need to conduct multiple 2×2 Chi-Squared Tests. However, conducting multiple tests on the same dependent variable increases the chance of false positives, thus increasing the likelihood of getting a significant result by chance alone. To account for false positives we need to adjust a significance to the number of comparisons being performed by correcting its level. This correction calls Bonferroni correction. I will use the stats package from scipy for that, as an alternative method to researchpy. Something to keep in mind is that scipy does not provide the result in a Pandas Dataframe." }, { "code": null, "e": 12811, "s": 12496, "text": "The chi-squared test using the Bonferroni-adjusted level of significance=0.017 shows that all comparisons are significant. However, it is quite time consuming to run Chi-Squared Tests for each pair of variables in our dataset. Therefore, I will build an association matrix as the last step of the data exploration." }, { "code": null, "e": 13045, "s": 12811, "text": "There are Date and Time variables in the dataset and it is always a good idea to check for the time dependent patterns and add some new variables to help our model to make a decision. First, let’s take a glimpse at the Time variable." }, { "code": null, "e": 13527, "s": 13045, "text": "We can observe two rush hour periods where accidents are more likely to happen: between 7–9 AM and 15–18 PM. Knowing that the amount of police officers is constant across the time, I would assume that during the rush hours the attendance would be lower, as there might be not enough police officers to attend all the accidents. Therefore, I will create a variable indicating a rush hour and test for its association with the probability of the police officer to attend an accident." }, { "code": null, "e": 13654, "s": 13527, "text": "There is a slight difference between the groups. In order to quantify these relationships I will run another Chi-Squared Test." }, { "code": null, "e": 13744, "s": 13654, "text": "H0: Rush hour has no impact on the probability of a police officer to attends an accident" }, { "code": null, "e": 14046, "s": 13744, "text": "The result of the Chi-Squared Test suggests that there is a statistically significant evidence that H0 is false. Given evidence and data we reject H0 that there is no association between the variables Rush_Hour and Did_Police_Officer_Attend_Scene_of_Accident with a p-value<0.005 and effect size 0.04." }, { "code": null, "e": 14193, "s": 14046, "text": "Another time related variable in the accident dataset is Date. I will plot the total number of accidents per day to analyse a time depended trend." }, { "code": null, "e": 14401, "s": 14193, "text": "The plot shows a cyclical pattern, which might suggest that there is some sort of seasonality. I will plot an ACF and PACF plots to check whether there is a significant seasonal component in the time series." }, { "code": null, "e": 14647, "s": 14401, "text": "The ACF plot shows a significant trend component at lag 1 and significant seasonal component at lags 6 and 7, which might indicate a weekend. I will plot the number of accidents per weekday to check if the behaviour on the weekends is different." }, { "code": null, "e": 14917, "s": 14647, "text": "We can observe a slight drop in overall accidents and those that were attended during the weekends. I will model weekends explicitly and then check if a newly created variable has a significant association with the probability of a police officer to attend an accident." }, { "code": null, "e": 15007, "s": 14917, "text": "H0: Weekends have no impact on the probability of a police officer to attend an accident." }, { "code": null, "e": 15318, "s": 15007, "text": "The result of the Chi-Squared Test suggests that there is statistically significant evidence to show that H0 is false. Given the evidence and data, we reject H0 that there is no association between the variables Weekend and Did_Police_Officer_Attend_Scene_of_Accident with a p-value<0.005 and effect size 0.04." }, { "code": null, "e": 15536, "s": 15318, "text": "We have already tested a few hypotheses and engineered two new features, Rush_Hour and Weekend. Now let’s join the other data that are available at data.gov.uk. First, I will join the data from the casualties dataset." }, { "code": null, "e": 15962, "s": 15536, "text": "The casualties dataset mainly contains categorical variables. From the first three rows we can see that the Accident_Index is not unique for each row, as one accident may lead to multiple casualties. For us that implies that we can not join the accidents and casualties data tables directly, but rather need to do some feature engineering. For the first evaluation let’s join just a few variables from the casualties dataset." }, { "code": null, "e": 16095, "s": 15962, "text": "I will shape a few hypotheses and assume that police officers are more likely to attend an accident if one of the following is true:" }, { "code": null, "e": 16122, "s": 16095, "text": "Casualties are pedestrians" }, { "code": null, "e": 16160, "s": 16122, "text": "People below 18 or above 65 years old" }, { "code": null, "e": 16206, "s": 16160, "text": "The driver is below 18, or above 65 years old" }, { "code": null, "e": 16368, "s": 16206, "text": "Therefore, I will create new binary variables, join them to the accident dataset, and test whether there is a significant association with the response variable." }, { "code": null, "e": 16563, "s": 16368, "text": "The Chi-Squared Test showed a significant association between newly created variables and probability of a police officer to attend an accident at a significance level of 0.05 and p-value<0.005." }, { "code": null, "e": 16691, "s": 16563, "text": "Now let’s join a third datasource available at data.gov.uk, which is a dataset of vehicles that being involved in the accident." }, { "code": null, "e": 16879, "s": 16691, "text": "From the first few rows, we can see that Accident_Index is not unique for each row, as one accident may involve several vehicles. Again we need to do feature engineering to join the data." }, { "code": null, "e": 17012, "s": 16879, "text": "I will shape a few hypotheses and assume that police officers are more likely to attend an accident if one of the following is true:" }, { "code": null, "e": 17046, "s": 17012, "text": "Cycle is involved in the accident" }, { "code": null, "e": 17105, "s": 17046, "text": "Taxi, Van, or Public transport is involved in the accident" }, { "code": null, "e": 17151, "s": 17105, "text": "The driver is below 18, or above 65 years old" }, { "code": null, "e": 17348, "s": 17151, "text": "As in a case with the casualties dataset, I will create related binary variables, join them to the accident dataset, and test whether there is a significant association with the response variable." }, { "code": null, "e": 17532, "s": 17348, "text": "The Chi-Squared Test shows a significant association between the newly created variables and the probability of a police officer to attend an accident at a significance level of 0.05." }, { "code": null, "e": 18689, "s": 17532, "text": "Undoubtedly, much more sophisticated feature engineering can be performed on these three datasets, including building categorical embeddings. However, our objective is to build a first prototype model and to show to the client the value of the data by generating quick insights and spotting interesting relationships between the variables (e.g. geographical data with accident attendance, accidents seasonality etc.). To stay pragmatic I will end the feature engineering for now. The last thing I would like to do before entering the modelling phase is to build an association matrix for the categorical variables to summarise the analysis that has been done. I will build an association matrix by calculating Cramer’s V statistic for cross categorial association, which is the effect size provided by the researchpy package. As mentioned already, an important detail to keep in mind is that Cramer’s V tends to overestimate the strength of association for the large and high dimensional samples. Therefore we need to implement a bias correction, which is described on Wikipedia. I use a very nice implementation of the bias correction from Ziggy Eunicien." }, { "code": null, "e": 18839, "s": 18689, "text": "The variable we are interested in forecasting, “Did_Police_Officer_Attend_Scene_of_Accident”, is located in the first column (and row) of the matrix." }, { "code": null, "e": 18955, "s": 18839, "text": "Unsurprisingly, the time-related variables are strongly associated with each other: Date, Day_of_Week, and Weekend." }, { "code": null, "e": 19277, "s": 18955, "text": "The location-related variables in the dataset, Police_Force, Local_Authority_(District), Local_Authority_(Highway), and LSOA_of_Accident_Location have a high association with the probability of a police officer to attend an accident. This is consistent with the findings presented under the analysis of geographical data." }, { "code": null, "e": 19530, "s": 19277, "text": "In Part 1 of Exploratory Data Analysis I analysed the UK the road accident safety data. A data quality assurance was conducted with the result that there is a pattern in missing data. Sensor data should be used to improve the accuracy of the forecasts." }, { "code": null, "e": 19933, "s": 19530, "text": "The analysis of geographical data showed that there are relationships between the location of the accident and the probability of a police officer to attend it. This implies that there are districts (for example East London) and regions that require a higher number of police officers to be on staff. It is especially important during rush hours when the percentage of not attended accidents increases." }, { "code": null, "e": 20327, "s": 19933, "text": "The analysis of variables from casualties and vehicles datasets showed that a police officer is more likely to attend an accident if pedestrians and people under 18 or above 65 years old were casualties. Also, a certain type of vehicles (bicycles and public transport) lead to a higher likelihood of a police officer to attend the accident. That is a valuable insight for predictive analytics." } ]
Next Greater Frequency Element - GeeksforGeeks
16 Nov, 2021 Given an array, for each element find the value of the nearest element to the right which is having a frequency greater than as that of the current element. If there does not exist an answer for a position, then make the value ‘-1’. Examples: Input : a[] = [1, 1, 2, 3, 4, 2, 1] Output : [-1, -1, 1, 2, 2, 1, -1] Explanation: Given array a[] = [1, 1, 2, 3, 4, 2, 1] Frequency of each element is: 3, 3, 2, 1, 1, 2, 3 Lets calls Next Greater Frequency element as NGF 1. For element a[0] = 1 which has a frequency = 3, As it has frequency of 3 and no other next element has frequency more than 3 so '-1' 2. For element a[1] = 1 it will be -1 same logic like a[0] 3. For element a[2] = 2 which has frequency = 2, NGF element is 1 at position = 6 with frequency of 3 > 2 4. For element a[3] = 3 which has frequency = 1, NGF element is 2 at position = 5 with frequency of 2 > 1 5. For element a[4] = 4 which has frequency = 1, NGF element is 2 at position = 5 with frequency of 2 > 1 6. For element a[5] = 2 which has frequency = 2, NGF element is 1 at position = 6 with frequency of 3 > 2 7. For element a[6] = 1 there is no element to its right, hence -1 Input : a[] = [1, 1, 1, 2, 2, 2, 2, 11, 3, 3] Output : [2, 2, 2, -1, -1, -1, -1, 3, -1, -1] Naive approach: A simple hashing technique is to use values as the index is being used to store the frequency of each element. Create a list suppose to store the frequency of each number in the array. (Single traversal is required). Now use two loops. The outer loop picks all the elements one by one. The inner loop looks for the first element whose frequency is greater than the frequency of the current element. If a greater frequency element is found then that element is printed, otherwise -1 is printed. Time complexity: O(n*n) Efficient approach: We can use hashing and stack data structure to efficiently solve for many cases. A simple hashing technique is to use values as index and frequency of each element as value. We use the stack data structure to store the position of elements in the array. 1) Create a list to use values as index to store frequency of each element. 2) Push the position of first element to stack. 3) Pick rest of the position of elements one by one and follow following steps in loop. .......a) Mark the position of current element as ‘i’ . ....... b) If the frequency of the element which is pointed by the top of stack is greater than frequency of the current element, push the current position i to the stack ....... c) If the frequency of the element which is pointed by the top of stack is less than frequency of the current element and the stack is not empty then follow these steps: .......i) continue popping the stack .......ii) if the condition in step c fails then push the current position i to the stack 4) After the loop in step 3 is over, pop all the elements from stack and print -1 as next greater frequency element for them does not exist. Below is the implementation of the above problem. C++ Java Python3 C# Javascript // C++ program of Next Greater Frequency Element#include <iostream>#include <stack>#include <stdio.h> using namespace std; /*NFG function to find the next greater frequencyelement for each element in the array*/void NFG(int a[], int n, int freq[]){ // stack data structure to store the position // of array element stack<int> s; s.push(0); // res to store the value of next greater // frequency element for each element int res[n] = { 0 }; for (int i = 1; i < n; i++) { /* If the frequency of the element which is pointed by the top of stack is greater than frequency of the current element then push the current position i in stack*/ if (freq[a[s.top()]] > freq[a[i]]) s.push(i); else { /*If the frequency of the element which is pointed by the top of stack is less than frequency of the current element, then pop the stack and continuing popping until the above condition is true while the stack is not empty*/ while ( !s.empty() && freq[a[s.top()]] < freq[a[i]]) { res[s.top()] = a[i]; s.pop(); } // now push the current element s.push(i); } } while (!s.empty()) { res[s.top()] = -1; s.pop(); } for (int i = 0; i < n; i++) { // Print the res list containing next // greater frequency element cout << res[i] << " "; }} // Driver codeint main(){ int a[] = { 1, 1, 2, 3, 4, 2, 1 }; int len = 7; int max = INT16_MIN; for (int i = 0; i < len; i++) { // Getting the max element of the array if (a[i] > max) { max = a[i]; } } int freq[max + 1] = { 0 }; // Calculating frequency of each element for (int i = 0; i < len; i++) { freq[a[i]]++; } // Function call NFG(a, len, freq); return 0;} // Java program of Next Greater Frequency Elementimport java.util.*; class GFG { /*NFG function to find the next greater frequency element for each element in the array*/ static void NFG(int a[], int n, int freq[]) { // stack data structure to store the position // of array element Stack<Integer> s = new Stack<Integer>(); s.push(0); // res to store the value of next greater // frequency element for each element int res[] = new int[n]; for (int i = 0; i < n; i++) res[i] = 0; for (int i = 1; i < n; i++) { /* If the frequency of the element which is pointed by the top of stack is greater than frequency of the current element then push the current position i in stack*/ if (freq[a[s.peek()]] > freq[a[i]]) s.push(i); else { /*If the frequency of the element which is pointed by the top of stack is less than frequency of the current element, then pop the stack and continuing popping until the above condition is true while the stack is not empty*/ while (freq[a[s.peek()]] < freq[a[i]] && s.size() > 0) { res[s.peek()] = a[i]; s.pop(); } // now push the current element s.push(i); } } while (s.size() > 0) { res[s.peek()] = -1; s.pop(); } for (int i = 0; i < n; i++) { // Print the res list containing next // greater frequency element System.out.print(res[i] + " "); } } // Driver code public static void main(String args[]) { int a[] = { 1, 1, 2, 3, 4, 2, 1 }; int len = 7; int max = Integer.MIN_VALUE; for (int i = 0; i < len; i++) { // Getting the max element of the array if (a[i] > max) { max = a[i]; } } int freq[] = new int[max + 1]; for (int i = 0; i < max + 1; i++) freq[i] = 0; // Calculating frequency of each element for (int i = 0; i < len; i++) { freq[a[i]]++; } // Function call NFG(a, len, freq); }} // This code is contributed by Arnab Kundu '''NFG function to find the next greater frequency element for each element in the array''' def NFG(a, n): if (n <= 0): print("List empty") return [] # stack data structure to store the position # of array element stack = [0]*n # freq is a dictionary which maintains the # frequency of each element freq = {} for i in a: freq[a[i]] = 0 for i in a: freq[a[i]] += 1 # res to store the value of next greater # frequency element for each element res = [0]*n # initialize top of stack to -1 top = -1 # push the first position of array in the stack top += 1 stack[top] = 0 # now iterate for the rest of elements for i in range(1, n): ''' If the frequency of the element which is pointed by the top of stack is greater than frequency of the current element then push the current position i in stack''' if (freq[a[stack[top]]] > freq[a[i]]): top += 1 stack[top] = i else: ''' If the frequency of the element which is pointed by the top of stack is less than frequency of the current element, then pop the stack and continuing popping until the above condition is true while the stack is not empty''' while (top > -1 and freq[a[stack[top]]] < freq[a[i]]): res[stack[top]] = a[i] top -= 1 # now push the current element top += 1 stack[top] = i '''After iterating over the loop, the remaining position of elements in stack do not have the next greater element, so print -1 for them''' while (top > -1): res[stack[top]] = -1 top -= 1 # return the res list containing next # greater frequency element return res # Driver Codeprint(NFG([1, 1, 2, 3, 4, 2, 1], 7)) // C# program of Next Greater Frequency Elementusing System;using System.Collections; class GFG { /*NFG function to find the next greater frequency element for each element in the array*/ static void NFG(int[] a, int n, int[] freq) { // stack data structure to store // the position of array element Stack s = new Stack(); s.Push(0); // res to store the value of next greater // frequency element for each element int[] res = new int[n]; for (int i = 0; i < n; i++) res[i] = 0; for (int i = 1; i < n; i++) { /* If the frequency of the element which is pointed by the top of stack is greater than frequency of the current element then Push the current position i in stack*/ if (freq[a[(int)s.Peek()]] > freq[a[i]]) s.Push(i); else { /*If the frequency of the element which is pointed by the top of stack is less than frequency of the current element, then Pop the stack and continuing Popping until the above condition is true while the stack is not empty*/ while (freq[a[(int)(int)s.Peek()]] < freq[a[i]] && s.Count > 0) { res[(int)s.Peek()] = a[i]; s.Pop(); } // now Push the current element s.Push(i); } } while (s.Count > 0) { res[(int)s.Peek()] = -1; s.Pop(); } for (int i = 0; i < n; i++) { // Print the res list containing next // greater frequency element Console.Write(res[i] + " "); } } // Driver code public static void Main(String[] args) { int[] a = { 1, 1, 2, 3, 4, 2, 1 }; int len = 7; int max = int.MinValue; for (int i = 0; i < len; i++) { // Getting the max element of the array if (a[i] > max) { max = a[i]; } } int[] freq = new int[max + 1]; for (int i = 0; i < max + 1; i++) freq[i] = 0; // Calculating frequency of each element for (int i = 0; i < len; i++) { freq[a[i]]++; } NFG(a, len, freq); }} // This code is contributed by Arnab Kundu <script> // Javascript program of Next Greater Frequency Element /*NFG function to find the next greater frequency element for each element in the array*/ function NFG(a, n, freq) { // stack data structure to store // the position of array element let s = []; s.push(0); // res to store the value of next greater // frequency element for each element let res = new Array(n); for (let i = 0; i < n; i++) res[i] = 0; for (let i = 1; i < n; i++) { /* If the frequency of the element which is pointed by the top of stack is greater than frequency of the current element then Push the current position i in stack*/ if (freq[a[s[s.length - 1]]] > freq[a[i]]) s.push(i); else { /*If the frequency of the element which is pointed by the top of stack is less than frequency of the current element, then Pop the stack and continuing Popping until the above condition is true while the stack is not empty*/ while (freq[a[s[s.length - 1]]] < freq[a[i]] && s.length > 0) { res[s[s.length - 1]] = a[i]; s.pop(); } // now Push the current element s.push(i); } } while (s.length > 0) { res[s[s.length - 1]] = -1; s.pop(); } document.write("["); for (let i = 0; i < n - 1; i++) { // Print the res list containing next // greater frequency element document.write(res[i] + ", "); } document.write(res[n - 1] + "]"); } let a = [ 1, 1, 2, 3, 4, 2, 1 ]; let len = 7; let max = Number.MIN_VALUE; for (let i = 0; i < len; i++) { // Getting the max element of the array if (a[i] > max) { max = a[i]; } } let freq = new Array(max + 1); for (let i = 0; i < max + 1; i++) freq[i] = 0; // Calculating frequency of each element for (let i = 0; i < len; i++) { freq[a[i]]++; } NFG(a, len, freq); // This code is contributed by vaibhavrabadiya117.</script> Output: [-1, -1, 1, 2, 2, 1, -1] Time complexity: O(n). Space Efficient Approach: using a hash map instead of a list as mentioned in the above approach. Steps: Create a class pair to store pair<int, int> with pair<element, frequency>.Create a hash map with pair as generics to store keys as the element and values as the frequency of every element.Iterate the array and save the element and its frequency in the hashmap.Create a res array that stores the resultant array.Initially make res[n-1] = -1 and push the element in the end along with its frequency into the stack.Iterate through the array in reverse order.If the frequency of the element which is pointed at the top of the stack is less than the frequency of the current element and the stack is not empty then pop.Continue till the loop fails.If the stack is empty, it means that there is no element with a higher frequency. So, place -1 as the next higher frequency element in the resultant array.If the stack is not empty, it means that the top of the stack has a higher frequency element. Put it in the resultant array as the next higher frequency.Push the current element along with its frequency. Create a class pair to store pair<int, int> with pair<element, frequency>. Create a hash map with pair as generics to store keys as the element and values as the frequency of every element. Iterate the array and save the element and its frequency in the hashmap. Create a res array that stores the resultant array. Initially make res[n-1] = -1 and push the element in the end along with its frequency into the stack. Iterate through the array in reverse order. If the frequency of the element which is pointed at the top of the stack is less than the frequency of the current element and the stack is not empty then pop. Continue till the loop fails. If the stack is empty, it means that there is no element with a higher frequency. So, place -1 as the next higher frequency element in the resultant array. If the stack is not empty, it means that the top of the stack has a higher frequency element. Put it in the resultant array as the next higher frequency. Push the current element along with its frequency. C++ Java Python3 C# Javascript // C++ program of Next Greater Frequency Element#include <bits/stdc++.h>using namespace std; stack<pair<int,int>> mystack;map<int, int> mymap; /*NFG function to find the next greater frequencyelement for each element and for placing it in theresultant array */void NGF(int arr[], int res[], int n) { // Initially store the frequencies of all elements // in a hashmap for(int i = 0; i < n; i++) { mymap[arr[i]] += 1; } // Get the frequency of the last element int curr_freq = mymap[arr[n-1]]; // push it to the stack mystack.push({arr[n-1], curr_freq}); // place -1 as next greater freq for the last // element as it does not have next greater. res[n-1] = -1; // iterate through array in reverse order for(int i = n-2;i>=0;i--) { curr_freq = mymap[arr[i]]; /* If the frequency of the element which is pointed by the top of stack is greater than frequency of the current element then push the current position i in stack*/ while(mystack.size() > 0 && curr_freq >= mystack.top().second) mystack.pop(); // If the stack is empty, place -1. If it is not empty // then we will have next higher freq element at the top of the stack. res[i] = (mystack.size() == 0) ? -1 : mystack.top().first; // push the element at current position mystack.push({arr[i], mymap[arr[i]]}); }} int main(){ int arr[] = {1, 1, 1, 2, 2, 2, 2, 11, 3, 3}; int n = sizeof(arr) / sizeof(arr[0]); int res[n]; NGF(arr, res, n); cout << "["; for(int i = 0; i < n - 1; i++) { cout << res[i] << ", "; } cout << res[n - 1] << "]"; return 0;} // This code is contributed by divyeshrabadiya07. // Java program of Next Greater Frequency Elementimport java.util.*; class GFG { Stack<Pair> mystack = new Stack<>(); HashMap<Integer,Integer> mymap = new HashMap<>(); class Pair{ int data; int freq; Pair(int data,int freq){ this.data = data; this.freq = freq; } } /*NFG function to find the next greater frequency element for each element and for placing it in the resultant array */ void NGF(int[] arr,int[] res) { int n = arr.length; //Initially store the frequencies of all elements //in a hashmap for(int i = 0;i<n;i++) { if(mymap.containsKey(arr[i])) mymap.put(arr[i], mymap.get(arr[i]) + 1); else mymap.put(arr[i], 1); } //Get the frequency of the last element int curr_freq = mymap.get(arr[n-1]); //push it to the stack mystack.push(new Pair(arr[n-1],curr_freq)); //place -1 as next greater freq for the last //element as it does not have next greater. res[n-1] = -1; //iterate through array in reverse order for(int i = n-2;i>=0;i--) { curr_freq = mymap.get(arr[i]); /* If the frequency of the element which is pointed by the top of stack is greater than frequency of the current element then push the current position i in stack*/ while(!mystack.isEmpty() && curr_freq >= mystack.peek().freq) mystack.pop(); //If the stack is empty, place -1. If it is not empty //then we will have next higher freq element at the top of the stack. res[i] = (mystack.isEmpty()) ? -1 : mystack.peek().data; //push the element at current position mystack.push(new Pair(arr[i],mymap.get(arr[i]))); } } //Driver function public static void main(String args[]) { GFG obj = new GFG(); int[] arr = {1, 1, 1, 2, 2, 2, 2, 11, 3, 3}; int res[] = new int[arr.length]; obj.NGF(arr, res); System.out.println(Arrays.toString(res)); }} //This method is contributed by Likhita AVL # Python3 program of Next Greater Frequency Element mystack = []mymap = {} """NFG function to find the next greater frequencyelement for each element and for placing it in theresultant array """def NGF(arr, res): n = len(arr) # Initially store the frequencies of all elements # in a hashmap for i in range(n): if arr[i] in mymap: mymap[arr[i]] += 1 else: mymap[arr[i]] = 1 # Get the frequency of the last element curr_freq = mymap[arr[n-1]] # push it to the stack mystack.append([arr[n-1],curr_freq]) # place -1 as next greater freq for the last # element as it does not have next greater. res[n-1] = -1 # iterate through array in reverse order for i in range(n - 2, -1, -1): curr_freq = mymap[arr[i]] """ If the frequency of the element which is pointed by the top of stack is greater than frequency of the current element then push the current position i in stack""" while len(mystack) > 0 and curr_freq >= mystack[-1][1]: mystack.pop() # If the stack is empty, place -1. If it is not empty # then we will have next higher freq element at the top of the stack. if (len(mystack) == 0): res[i] = -1 else: res[i] = mystack[-1][0] # push the element at current position mystack.append([arr[i],mymap[arr[i]]]) arr = [1, 1, 1, 2, 2, 2, 2, 11, 3, 3] res = [0]*(len(arr))NGF(arr, res)print(res) # This code is contributed by rameshtravel07. // C# program of Next Greater Frequency Elementusing System;using System.Collections.Generic;class GFG { static Stack<Tuple<int,int>> mystack = new Stack<Tuple<int,int>>(); static Dictionary<int, int> mymap = new Dictionary<int, int>(); /*NFG function to find the next greater frequency element for each element and for placing it in the resultant array */ static void NGF(int[] arr,int[] res) { int n = arr.Length; // Initially store the frequencies of all elements // in a hashmap for(int i = 0; i < n; i++) { if(mymap.ContainsKey(arr[i])) mymap[arr[i]] = mymap[arr[i]] + 1; else mymap[arr[i]] = 1; } // Get the frequency of the last element int curr_freq = mymap[arr[n-1]]; // push it to the stack mystack.Push(new Tuple<int,int>(arr[n-1],curr_freq)); // place -1 as next greater freq for the last // element as it does not have next greater. res[n-1] = -1; // iterate through array in reverse order for(int i = n-2;i>=0;i--) { curr_freq = mymap[arr[i]]; /* If the frequency of the element which is pointed by the top of stack is greater than frequency of the current element then push the current position i in stack*/ while(mystack.Count > 0 && curr_freq >= mystack.Peek().Item2) mystack.Pop(); // If the stack is empty, place -1. If it is not empty // then we will have next higher freq element at the top of the stack. res[i] = (mystack.Count == 0) ? -1 : mystack.Peek().Item1; // push the element at current position mystack.Push(new Tuple<int,int>(arr[i],mymap[arr[i]])); } } // Driver code static void Main() { int[] arr = {1, 1, 1, 2, 2, 2, 2, 11, 3, 3}; int[] res = new int[arr.Length]; NGF(arr, res); Console.Write("["); for(int i = 0; i < arr.Length - 1; i++) { Console.Write(res[i] + ", "); } Console.Write(res[arr.Length - 1] + "]"); }} // This code is contributed by mukesh07. <script>// Javascript program of Next Greater Frequency Element class Pair{ constructor(data,freq) { this.data = data; this.freq = freq; }} let mystack = [];let mymap = new Map(); /*NFG function to find the next greater frequency element for each element and for placing it in the resultant array */function NGF(arr,res){ let n = arr.length; //Initially store the frequencies of all elements //in a hashmap for(let i = 0;i<n;i++) { if(mymap.has(arr[i])) mymap.set(arr[i], mymap.get(arr[i]) + 1); else mymap.set(arr[i], 1); } // Get the frequency of the last element let curr_freq = mymap.get(arr[n-1]); // push it to the stack mystack.push(new Pair(arr[n-1],curr_freq)); // place -1 as next greater freq for the last // element as it does not have next greater. res[n-1] = -1; // iterate through array in reverse order for(let i = n - 2; i >= 0; i--) { curr_freq = mymap.get(arr[i]); /* If the frequency of the element which is pointed by the top of stack is greater than frequency of the current element then push the current position i in stack*/ while(mystack.length!=0 && curr_freq >= mystack[mystack.length-1].freq) mystack.pop(); // If the stack is empty, place -1. If it is not empty // then we will have next higher freq element at the top of the stack. res[i] = (mystack.length==0) ? -1 : mystack[mystack.length-1].data; // push the element at current position mystack.push(new Pair(arr[i],mymap.get(arr[i]))); }} // Driver functionlet arr=[1, 1, 1, 2, 2, 2, 2, 11, 3, 3];let res = new Array(arr.length);NGF(arr, res);document.write((res).join(" ")); // This code is contributed by avanitrachhadiya2155</script> [2, 2, 2, -1, -1, -1, -1, 3, -1, -1] Time Complexity: O(n). This article is contributed by Sruti Rai . Thank you Koustav for your valuable support. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Logarithm andrew1234 Akanksha_Rai droyder rajukumarbhui avllikhita vaibhavrabadiya117 avanitrachhadiya2155 rameshtravel07 mukesh07 divyeshrabadiya07 HardhikMallipeddi Arrays Hash Stack Arrays Hash Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Introduction to Arrays Multidimensional Arrays in Java Python | Using 2D arrays/lists the right way Linked List vs Array Queue | Set 1 (Introduction and Array Implementation) Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing) Hashing | Set 2 (Separate Chaining) Count pairs with given sum
[ { "code": null, "e": 25132, "s": 25104, "text": "\n16 Nov, 2021" }, { "code": null, "e": 25365, "s": 25132, "text": "Given an array, for each element find the value of the nearest element to the right which is having a frequency greater than as that of the current element. If there does not exist an answer for a position, then make the value ‘-1’." }, { "code": null, "e": 25376, "s": 25365, "text": "Examples: " }, { "code": null, "e": 26424, "s": 25376, "text": "Input : a[] = [1, 1, 2, 3, 4, 2, 1] \nOutput : [-1, -1, 1, 2, 2, 1, -1]\nExplanation:\nGiven array a[] = [1, 1, 2, 3, 4, 2, 1] \nFrequency of each element is: 3, 3, 2, 1, 1, 2, 3\nLets calls Next Greater Frequency element as NGF\n1. For element a[0] = 1 which has a frequency = 3,\n As it has frequency of 3 and no other next element \n has frequency more than 3 so '-1'\n2. For element a[1] = 1 it will be -1 same logic \n like a[0]\n3. For element a[2] = 2 which has frequency = 2,\n NGF element is 1 at position = 6 with frequency \n of 3 > 2\n4. For element a[3] = 3 which has frequency = 1,\n NGF element is 2 at position = 5 with frequency \n of 2 > 1\n5. For element a[4] = 4 which has frequency = 1,\n NGF element is 2 at position = 5 with frequency \n of 2 > 1\n6. For element a[5] = 2 which has frequency = 2,\n NGF element is 1 at position = 6 with frequency\n of 3 > 2\n7. For element a[6] = 1 there is no element to its \n right, hence -1 \n\nInput : a[] = [1, 1, 1, 2, 2, 2, 2, 11, 3, 3]\nOutput : [2, 2, 2, -1, -1, -1, -1, 3, -1, -1]" }, { "code": null, "e": 26958, "s": 26424, "text": "Naive approach: A simple hashing technique is to use values as the index is being used to store the frequency of each element. Create a list suppose to store the frequency of each number in the array. (Single traversal is required). Now use two loops. The outer loop picks all the elements one by one. The inner loop looks for the first element whose frequency is greater than the frequency of the current element. If a greater frequency element is found then that element is printed, otherwise -1 is printed. Time complexity: O(n*n)" }, { "code": null, "e": 27232, "s": 26958, "text": "Efficient approach: We can use hashing and stack data structure to efficiently solve for many cases. A simple hashing technique is to use values as index and frequency of each element as value. We use the stack data structure to store the position of elements in the array." }, { "code": null, "e": 28117, "s": 27232, "text": "1) Create a list to use values as index to store frequency of each element. 2) Push the position of first element to stack. 3) Pick rest of the position of elements one by one and follow following steps in loop. .......a) Mark the position of current element as ‘i’ . ....... b) If the frequency of the element which is pointed by the top of stack is greater than frequency of the current element, push the current position i to the stack ....... c) If the frequency of the element which is pointed by the top of stack is less than frequency of the current element and the stack is not empty then follow these steps: .......i) continue popping the stack .......ii) if the condition in step c fails then push the current position i to the stack 4) After the loop in step 3 is over, pop all the elements from stack and print -1 as next greater frequency element for them does not exist." }, { "code": null, "e": 28168, "s": 28117, "text": "Below is the implementation of the above problem. " }, { "code": null, "e": 28172, "s": 28168, "text": "C++" }, { "code": null, "e": 28177, "s": 28172, "text": "Java" }, { "code": null, "e": 28185, "s": 28177, "text": "Python3" }, { "code": null, "e": 28188, "s": 28185, "text": "C#" }, { "code": null, "e": 28199, "s": 28188, "text": "Javascript" }, { "code": "// C++ program of Next Greater Frequency Element#include <iostream>#include <stack>#include <stdio.h> using namespace std; /*NFG function to find the next greater frequencyelement for each element in the array*/void NFG(int a[], int n, int freq[]){ // stack data structure to store the position // of array element stack<int> s; s.push(0); // res to store the value of next greater // frequency element for each element int res[n] = { 0 }; for (int i = 1; i < n; i++) { /* If the frequency of the element which is pointed by the top of stack is greater than frequency of the current element then push the current position i in stack*/ if (freq[a[s.top()]] > freq[a[i]]) s.push(i); else { /*If the frequency of the element which is pointed by the top of stack is less than frequency of the current element, then pop the stack and continuing popping until the above condition is true while the stack is not empty*/ while ( !s.empty() && freq[a[s.top()]] < freq[a[i]]) { res[s.top()] = a[i]; s.pop(); } // now push the current element s.push(i); } } while (!s.empty()) { res[s.top()] = -1; s.pop(); } for (int i = 0; i < n; i++) { // Print the res list containing next // greater frequency element cout << res[i] << \" \"; }} // Driver codeint main(){ int a[] = { 1, 1, 2, 3, 4, 2, 1 }; int len = 7; int max = INT16_MIN; for (int i = 0; i < len; i++) { // Getting the max element of the array if (a[i] > max) { max = a[i]; } } int freq[max + 1] = { 0 }; // Calculating frequency of each element for (int i = 0; i < len; i++) { freq[a[i]]++; } // Function call NFG(a, len, freq); return 0;}", "e": 30196, "s": 28199, "text": null }, { "code": "// Java program of Next Greater Frequency Elementimport java.util.*; class GFG { /*NFG function to find the next greater frequency element for each element in the array*/ static void NFG(int a[], int n, int freq[]) { // stack data structure to store the position // of array element Stack<Integer> s = new Stack<Integer>(); s.push(0); // res to store the value of next greater // frequency element for each element int res[] = new int[n]; for (int i = 0; i < n; i++) res[i] = 0; for (int i = 1; i < n; i++) { /* If the frequency of the element which is pointed by the top of stack is greater than frequency of the current element then push the current position i in stack*/ if (freq[a[s.peek()]] > freq[a[i]]) s.push(i); else { /*If the frequency of the element which is pointed by the top of stack is less than frequency of the current element, then pop the stack and continuing popping until the above condition is true while the stack is not empty*/ while (freq[a[s.peek()]] < freq[a[i]] && s.size() > 0) { res[s.peek()] = a[i]; s.pop(); } // now push the current element s.push(i); } } while (s.size() > 0) { res[s.peek()] = -1; s.pop(); } for (int i = 0; i < n; i++) { // Print the res list containing next // greater frequency element System.out.print(res[i] + \" \"); } } // Driver code public static void main(String args[]) { int a[] = { 1, 1, 2, 3, 4, 2, 1 }; int len = 7; int max = Integer.MIN_VALUE; for (int i = 0; i < len; i++) { // Getting the max element of the array if (a[i] > max) { max = a[i]; } } int freq[] = new int[max + 1]; for (int i = 0; i < max + 1; i++) freq[i] = 0; // Calculating frequency of each element for (int i = 0; i < len; i++) { freq[a[i]]++; } // Function call NFG(a, len, freq); }} // This code is contributed by Arnab Kundu", "e": 32705, "s": 30196, "text": null }, { "code": "'''NFG function to find the next greater frequency element for each element in the array''' def NFG(a, n): if (n <= 0): print(\"List empty\") return [] # stack data structure to store the position # of array element stack = [0]*n # freq is a dictionary which maintains the # frequency of each element freq = {} for i in a: freq[a[i]] = 0 for i in a: freq[a[i]] += 1 # res to store the value of next greater # frequency element for each element res = [0]*n # initialize top of stack to -1 top = -1 # push the first position of array in the stack top += 1 stack[top] = 0 # now iterate for the rest of elements for i in range(1, n): ''' If the frequency of the element which is pointed by the top of stack is greater than frequency of the current element then push the current position i in stack''' if (freq[a[stack[top]]] > freq[a[i]]): top += 1 stack[top] = i else: ''' If the frequency of the element which is pointed by the top of stack is less than frequency of the current element, then pop the stack and continuing popping until the above condition is true while the stack is not empty''' while (top > -1 and freq[a[stack[top]]] < freq[a[i]]): res[stack[top]] = a[i] top -= 1 # now push the current element top += 1 stack[top] = i '''After iterating over the loop, the remaining position of elements in stack do not have the next greater element, so print -1 for them''' while (top > -1): res[stack[top]] = -1 top -= 1 # return the res list containing next # greater frequency element return res # Driver Codeprint(NFG([1, 1, 2, 3, 4, 2, 1], 7))", "e": 34607, "s": 32705, "text": null }, { "code": "// C# program of Next Greater Frequency Elementusing System;using System.Collections; class GFG { /*NFG function to find the next greater frequency element for each element in the array*/ static void NFG(int[] a, int n, int[] freq) { // stack data structure to store // the position of array element Stack s = new Stack(); s.Push(0); // res to store the value of next greater // frequency element for each element int[] res = new int[n]; for (int i = 0; i < n; i++) res[i] = 0; for (int i = 1; i < n; i++) { /* If the frequency of the element which is pointed by the top of stack is greater than frequency of the current element then Push the current position i in stack*/ if (freq[a[(int)s.Peek()]] > freq[a[i]]) s.Push(i); else { /*If the frequency of the element which is pointed by the top of stack is less than frequency of the current element, then Pop the stack and continuing Popping until the above condition is true while the stack is not empty*/ while (freq[a[(int)(int)s.Peek()]] < freq[a[i]] && s.Count > 0) { res[(int)s.Peek()] = a[i]; s.Pop(); } // now Push the current element s.Push(i); } } while (s.Count > 0) { res[(int)s.Peek()] = -1; s.Pop(); } for (int i = 0; i < n; i++) { // Print the res list containing next // greater frequency element Console.Write(res[i] + \" \"); } } // Driver code public static void Main(String[] args) { int[] a = { 1, 1, 2, 3, 4, 2, 1 }; int len = 7; int max = int.MinValue; for (int i = 0; i < len; i++) { // Getting the max element of the array if (a[i] > max) { max = a[i]; } } int[] freq = new int[max + 1]; for (int i = 0; i < max + 1; i++) freq[i] = 0; // Calculating frequency of each element for (int i = 0; i < len; i++) { freq[a[i]]++; } NFG(a, len, freq); }} // This code is contributed by Arnab Kundu", "e": 37138, "s": 34607, "text": null }, { "code": "<script> // Javascript program of Next Greater Frequency Element /*NFG function to find the next greater frequency element for each element in the array*/ function NFG(a, n, freq) { // stack data structure to store // the position of array element let s = []; s.push(0); // res to store the value of next greater // frequency element for each element let res = new Array(n); for (let i = 0; i < n; i++) res[i] = 0; for (let i = 1; i < n; i++) { /* If the frequency of the element which is pointed by the top of stack is greater than frequency of the current element then Push the current position i in stack*/ if (freq[a[s[s.length - 1]]] > freq[a[i]]) s.push(i); else { /*If the frequency of the element which is pointed by the top of stack is less than frequency of the current element, then Pop the stack and continuing Popping until the above condition is true while the stack is not empty*/ while (freq[a[s[s.length - 1]]] < freq[a[i]] && s.length > 0) { res[s[s.length - 1]] = a[i]; s.pop(); } // now Push the current element s.push(i); } } while (s.length > 0) { res[s[s.length - 1]] = -1; s.pop(); } document.write(\"[\"); for (let i = 0; i < n - 1; i++) { // Print the res list containing next // greater frequency element document.write(res[i] + \", \"); } document.write(res[n - 1] + \"]\"); } let a = [ 1, 1, 2, 3, 4, 2, 1 ]; let len = 7; let max = Number.MIN_VALUE; for (let i = 0; i < len; i++) { // Getting the max element of the array if (a[i] > max) { max = a[i]; } } let freq = new Array(max + 1); for (let i = 0; i < max + 1; i++) freq[i] = 0; // Calculating frequency of each element for (let i = 0; i < len; i++) { freq[a[i]]++; } NFG(a, len, freq); // This code is contributed by vaibhavrabadiya117.</script>", "e": 39599, "s": 37138, "text": null }, { "code": null, "e": 39607, "s": 39599, "text": "Output:" }, { "code": null, "e": 39632, "s": 39607, "text": "[-1, -1, 1, 2, 2, 1, -1]" }, { "code": null, "e": 39655, "s": 39632, "text": "Time complexity: O(n)." }, { "code": null, "e": 39752, "s": 39655, "text": "Space Efficient Approach: using a hash map instead of a list as mentioned in the above approach." }, { "code": null, "e": 39759, "s": 39752, "text": "Steps:" }, { "code": null, "e": 40761, "s": 39759, "text": "Create a class pair to store pair<int, int> with pair<element, frequency>.Create a hash map with pair as generics to store keys as the element and values as the frequency of every element.Iterate the array and save the element and its frequency in the hashmap.Create a res array that stores the resultant array.Initially make res[n-1] = -1 and push the element in the end along with its frequency into the stack.Iterate through the array in reverse order.If the frequency of the element which is pointed at the top of the stack is less than the frequency of the current element and the stack is not empty then pop.Continue till the loop fails.If the stack is empty, it means that there is no element with a higher frequency. So, place -1 as the next higher frequency element in the resultant array.If the stack is not empty, it means that the top of the stack has a higher frequency element. Put it in the resultant array as the next higher frequency.Push the current element along with its frequency." }, { "code": null, "e": 40836, "s": 40761, "text": "Create a class pair to store pair<int, int> with pair<element, frequency>." }, { "code": null, "e": 40951, "s": 40836, "text": "Create a hash map with pair as generics to store keys as the element and values as the frequency of every element." }, { "code": null, "e": 41024, "s": 40951, "text": "Iterate the array and save the element and its frequency in the hashmap." }, { "code": null, "e": 41076, "s": 41024, "text": "Create a res array that stores the resultant array." }, { "code": null, "e": 41178, "s": 41076, "text": "Initially make res[n-1] = -1 and push the element in the end along with its frequency into the stack." }, { "code": null, "e": 41222, "s": 41178, "text": "Iterate through the array in reverse order." }, { "code": null, "e": 41382, "s": 41222, "text": "If the frequency of the element which is pointed at the top of the stack is less than the frequency of the current element and the stack is not empty then pop." }, { "code": null, "e": 41412, "s": 41382, "text": "Continue till the loop fails." }, { "code": null, "e": 41568, "s": 41412, "text": "If the stack is empty, it means that there is no element with a higher frequency. So, place -1 as the next higher frequency element in the resultant array." }, { "code": null, "e": 41722, "s": 41568, "text": "If the stack is not empty, it means that the top of the stack has a higher frequency element. Put it in the resultant array as the next higher frequency." }, { "code": null, "e": 41773, "s": 41722, "text": "Push the current element along with its frequency." }, { "code": null, "e": 41777, "s": 41773, "text": "C++" }, { "code": null, "e": 41782, "s": 41777, "text": "Java" }, { "code": null, "e": 41790, "s": 41782, "text": "Python3" }, { "code": null, "e": 41793, "s": 41790, "text": "C#" }, { "code": null, "e": 41804, "s": 41793, "text": "Javascript" }, { "code": "// C++ program of Next Greater Frequency Element#include <bits/stdc++.h>using namespace std; stack<pair<int,int>> mystack;map<int, int> mymap; /*NFG function to find the next greater frequencyelement for each element and for placing it in theresultant array */void NGF(int arr[], int res[], int n) { // Initially store the frequencies of all elements // in a hashmap for(int i = 0; i < n; i++) { mymap[arr[i]] += 1; } // Get the frequency of the last element int curr_freq = mymap[arr[n-1]]; // push it to the stack mystack.push({arr[n-1], curr_freq}); // place -1 as next greater freq for the last // element as it does not have next greater. res[n-1] = -1; // iterate through array in reverse order for(int i = n-2;i>=0;i--) { curr_freq = mymap[arr[i]]; /* If the frequency of the element which is pointed by the top of stack is greater than frequency of the current element then push the current position i in stack*/ while(mystack.size() > 0 && curr_freq >= mystack.top().second) mystack.pop(); // If the stack is empty, place -1. If it is not empty // then we will have next higher freq element at the top of the stack. res[i] = (mystack.size() == 0) ? -1 : mystack.top().first; // push the element at current position mystack.push({arr[i], mymap[arr[i]]}); }} int main(){ int arr[] = {1, 1, 1, 2, 2, 2, 2, 11, 3, 3}; int n = sizeof(arr) / sizeof(arr[0]); int res[n]; NGF(arr, res, n); cout << \"[\"; for(int i = 0; i < n - 1; i++) { cout << res[i] << \", \"; } cout << res[n - 1] << \"]\"; return 0;} // This code is contributed by divyeshrabadiya07.", "e": 43606, "s": 41804, "text": null }, { "code": "// Java program of Next Greater Frequency Elementimport java.util.*; class GFG { Stack<Pair> mystack = new Stack<>(); HashMap<Integer,Integer> mymap = new HashMap<>(); class Pair{ int data; int freq; Pair(int data,int freq){ this.data = data; this.freq = freq; } } /*NFG function to find the next greater frequency element for each element and for placing it in the resultant array */ void NGF(int[] arr,int[] res) { int n = arr.length; //Initially store the frequencies of all elements //in a hashmap for(int i = 0;i<n;i++) { if(mymap.containsKey(arr[i])) mymap.put(arr[i], mymap.get(arr[i]) + 1); else mymap.put(arr[i], 1); } //Get the frequency of the last element int curr_freq = mymap.get(arr[n-1]); //push it to the stack mystack.push(new Pair(arr[n-1],curr_freq)); //place -1 as next greater freq for the last //element as it does not have next greater. res[n-1] = -1; //iterate through array in reverse order for(int i = n-2;i>=0;i--) { curr_freq = mymap.get(arr[i]); /* If the frequency of the element which is pointed by the top of stack is greater than frequency of the current element then push the current position i in stack*/ while(!mystack.isEmpty() && curr_freq >= mystack.peek().freq) mystack.pop(); //If the stack is empty, place -1. If it is not empty //then we will have next higher freq element at the top of the stack. res[i] = (mystack.isEmpty()) ? -1 : mystack.peek().data; //push the element at current position mystack.push(new Pair(arr[i],mymap.get(arr[i]))); } } //Driver function public static void main(String args[]) { GFG obj = new GFG(); int[] arr = {1, 1, 1, 2, 2, 2, 2, 11, 3, 3}; int res[] = new int[arr.length]; obj.NGF(arr, res); System.out.println(Arrays.toString(res)); }} //This method is contributed by Likhita AVL", "e": 45870, "s": 43606, "text": null }, { "code": "# Python3 program of Next Greater Frequency Element mystack = []mymap = {} \"\"\"NFG function to find the next greater frequencyelement for each element and for placing it in theresultant array \"\"\"def NGF(arr, res): n = len(arr) # Initially store the frequencies of all elements # in a hashmap for i in range(n): if arr[i] in mymap: mymap[arr[i]] += 1 else: mymap[arr[i]] = 1 # Get the frequency of the last element curr_freq = mymap[arr[n-1]] # push it to the stack mystack.append([arr[n-1],curr_freq]) # place -1 as next greater freq for the last # element as it does not have next greater. res[n-1] = -1 # iterate through array in reverse order for i in range(n - 2, -1, -1): curr_freq = mymap[arr[i]] \"\"\" If the frequency of the element which is pointed by the top of stack is greater than frequency of the current element then push the current position i in stack\"\"\" while len(mystack) > 0 and curr_freq >= mystack[-1][1]: mystack.pop() # If the stack is empty, place -1. If it is not empty # then we will have next higher freq element at the top of the stack. if (len(mystack) == 0): res[i] = -1 else: res[i] = mystack[-1][0] # push the element at current position mystack.append([arr[i],mymap[arr[i]]]) arr = [1, 1, 1, 2, 2, 2, 2, 11, 3, 3] res = [0]*(len(arr))NGF(arr, res)print(res) # This code is contributed by rameshtravel07.", "e": 47459, "s": 45870, "text": null }, { "code": "// C# program of Next Greater Frequency Elementusing System;using System.Collections.Generic;class GFG { static Stack<Tuple<int,int>> mystack = new Stack<Tuple<int,int>>(); static Dictionary<int, int> mymap = new Dictionary<int, int>(); /*NFG function to find the next greater frequency element for each element and for placing it in the resultant array */ static void NGF(int[] arr,int[] res) { int n = arr.Length; // Initially store the frequencies of all elements // in a hashmap for(int i = 0; i < n; i++) { if(mymap.ContainsKey(arr[i])) mymap[arr[i]] = mymap[arr[i]] + 1; else mymap[arr[i]] = 1; } // Get the frequency of the last element int curr_freq = mymap[arr[n-1]]; // push it to the stack mystack.Push(new Tuple<int,int>(arr[n-1],curr_freq)); // place -1 as next greater freq for the last // element as it does not have next greater. res[n-1] = -1; // iterate through array in reverse order for(int i = n-2;i>=0;i--) { curr_freq = mymap[arr[i]]; /* If the frequency of the element which is pointed by the top of stack is greater than frequency of the current element then push the current position i in stack*/ while(mystack.Count > 0 && curr_freq >= mystack.Peek().Item2) mystack.Pop(); // If the stack is empty, place -1. If it is not empty // then we will have next higher freq element at the top of the stack. res[i] = (mystack.Count == 0) ? -1 : mystack.Peek().Item1; // push the element at current position mystack.Push(new Tuple<int,int>(arr[i],mymap[arr[i]])); } } // Driver code static void Main() { int[] arr = {1, 1, 1, 2, 2, 2, 2, 11, 3, 3}; int[] res = new int[arr.Length]; NGF(arr, res); Console.Write(\"[\"); for(int i = 0; i < arr.Length - 1; i++) { Console.Write(res[i] + \", \"); } Console.Write(res[arr.Length - 1] + \"]\"); }} // This code is contributed by mukesh07.", "e": 49710, "s": 47459, "text": null }, { "code": "<script>// Javascript program of Next Greater Frequency Element class Pair{ constructor(data,freq) { this.data = data; this.freq = freq; }} let mystack = [];let mymap = new Map(); /*NFG function to find the next greater frequency element for each element and for placing it in the resultant array */function NGF(arr,res){ let n = arr.length; //Initially store the frequencies of all elements //in a hashmap for(let i = 0;i<n;i++) { if(mymap.has(arr[i])) mymap.set(arr[i], mymap.get(arr[i]) + 1); else mymap.set(arr[i], 1); } // Get the frequency of the last element let curr_freq = mymap.get(arr[n-1]); // push it to the stack mystack.push(new Pair(arr[n-1],curr_freq)); // place -1 as next greater freq for the last // element as it does not have next greater. res[n-1] = -1; // iterate through array in reverse order for(let i = n - 2; i >= 0; i--) { curr_freq = mymap.get(arr[i]); /* If the frequency of the element which is pointed by the top of stack is greater than frequency of the current element then push the current position i in stack*/ while(mystack.length!=0 && curr_freq >= mystack[mystack.length-1].freq) mystack.pop(); // If the stack is empty, place -1. If it is not empty // then we will have next higher freq element at the top of the stack. res[i] = (mystack.length==0) ? -1 : mystack[mystack.length-1].data; // push the element at current position mystack.push(new Pair(arr[i],mymap.get(arr[i]))); }} // Driver functionlet arr=[1, 1, 1, 2, 2, 2, 2, 11, 3, 3];let res = new Array(arr.length);NGF(arr, res);document.write((res).join(\" \")); // This code is contributed by avanitrachhadiya2155</script>", "e": 51753, "s": 49710, "text": null }, { "code": null, "e": 51790, "s": 51753, "text": "[2, 2, 2, -1, -1, -1, -1, 3, -1, -1]" }, { "code": null, "e": 51813, "s": 51790, "text": "Time Complexity: O(n)." }, { "code": null, "e": 52277, "s": 51813, "text": "This article is contributed by Sruti Rai . Thank you Koustav for your valuable support. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 52287, "s": 52277, "text": "Logarithm" }, { "code": null, "e": 52298, "s": 52287, "text": "andrew1234" }, { "code": null, "e": 52311, "s": 52298, "text": "Akanksha_Rai" }, { "code": null, "e": 52319, "s": 52311, "text": "droyder" }, { "code": null, "e": 52333, "s": 52319, "text": "rajukumarbhui" }, { "code": null, "e": 52344, "s": 52333, "text": "avllikhita" }, { "code": null, "e": 52363, "s": 52344, "text": "vaibhavrabadiya117" }, { "code": null, "e": 52384, "s": 52363, "text": "avanitrachhadiya2155" }, { "code": null, "e": 52399, "s": 52384, "text": "rameshtravel07" }, { "code": null, "e": 52408, "s": 52399, "text": "mukesh07" }, { "code": null, "e": 52426, "s": 52408, "text": "divyeshrabadiya07" }, { "code": null, "e": 52444, "s": 52426, "text": "HardhikMallipeddi" }, { "code": null, "e": 52451, "s": 52444, "text": "Arrays" }, { "code": null, "e": 52456, "s": 52451, "text": "Hash" }, { "code": null, "e": 52462, "s": 52456, "text": "Stack" }, { "code": null, "e": 52469, "s": 52462, "text": "Arrays" }, { "code": null, "e": 52474, "s": 52469, "text": "Hash" }, { "code": null, "e": 52480, "s": 52474, "text": "Stack" }, { "code": null, "e": 52578, "s": 52480, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 52587, "s": 52578, "text": "Comments" }, { "code": null, "e": 52600, "s": 52587, "text": "Old Comments" }, { "code": null, "e": 52623, "s": 52600, "text": "Introduction to Arrays" }, { "code": null, "e": 52655, "s": 52623, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 52700, "s": 52655, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 52721, "s": 52700, "text": "Linked List vs Array" }, { "code": null, "e": 52775, "s": 52721, "text": "Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 52811, "s": 52775, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 52842, "s": 52811, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 52876, "s": 52842, "text": "Hashing | Set 3 (Open Addressing)" }, { "code": null, "e": 52912, "s": 52876, "text": "Hashing | Set 2 (Separate Chaining)" } ]
Java signum() method with Examples - GeeksforGeeks
09 Apr, 2018 The java.lang.Math.signum() returns the Sign function of a value passed to it as argument. The signum() function returns the following values depending on the argument passed to it: If the argument passed is greater than zero, then the signum() function will return 1.0. If the argument passed is equal to zero, then the signum() function will return 0. If the argument passed is less than zero, then the signum() function will return -1.0. Note: If the argument passed is NaN, then the result is NaN. If the argument passed is positive zero or negative zero then the result will be same as that of the argument. Syntax: public static double signum(double d) Parameter : a : the value whose signum function is to be returned. Return : This method returns the signum function value of the argument passed to it. Example 1 : To show working of java.lang.Math.signum() method. // Java program to demonstrate working// of java.lang.Math.signum() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { // when the argument is greater than zero double a = 30; System.out.println(Math.signum(a)); // when the argument is equals to zero a = 0; System.out.println(Math.signum(a)); // when the argument is less than zero a = -30; System.out.println(Math.signum(a)); }} Output: 1.0 0 -1.0 Example 2 : To show working of java.lang.Math.signum() method when argument is NaN. // Java program to demonstrate working// of java.lang.Math.signum() methodimport java.lang.Math; // importing java.lang package public class GFG { public static void main(String[] args) { double nan = Double.NaN; double result; // Here argument is NaN, output will be NaN result = Math.signum(nan); System.out.println(result); // Here argument is positive zero result = Math.signum(0); System.out.println(result); // Here argument is negative zero result = Math.signum(-0); System.out.println(result); }} Output: NaN 0.0 0.0 Java-lang package java-math Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Initialize an ArrayList in Java HashMap in Java with Examples Interfaces in Java Object Oriented Programming (OOPs) Concept in Java ArrayList in Java How to iterate any Map in Java Multidimensional Arrays in Java LinkedList in Java Stack Class in Java Overriding in Java
[ { "code": null, "e": 24840, "s": 24812, "text": "\n09 Apr, 2018" }, { "code": null, "e": 25022, "s": 24840, "text": "The java.lang.Math.signum() returns the Sign function of a value passed to it as argument. The signum() function returns the following values depending on the argument passed to it:" }, { "code": null, "e": 25111, "s": 25022, "text": "If the argument passed is greater than zero, then the signum() function will return 1.0." }, { "code": null, "e": 25194, "s": 25111, "text": "If the argument passed is equal to zero, then the signum() function will return 0." }, { "code": null, "e": 25281, "s": 25194, "text": "If the argument passed is less than zero, then the signum() function will return -1.0." }, { "code": null, "e": 25453, "s": 25281, "text": "Note: If the argument passed is NaN, then the result is NaN. If the argument passed is positive zero or negative zero then the result will be same as that of the argument." }, { "code": null, "e": 25461, "s": 25453, "text": "Syntax:" }, { "code": null, "e": 25653, "s": 25461, "text": "public static double signum(double d)\nParameter :\na : the value whose signum function is to be returned.\nReturn :\nThis method returns the signum function value of \nthe argument passed to it.\n" }, { "code": null, "e": 25716, "s": 25653, "text": "Example 1 : To show working of java.lang.Math.signum() method." }, { "code": "// Java program to demonstrate working// of java.lang.Math.signum() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { // when the argument is greater than zero double a = 30; System.out.println(Math.signum(a)); // when the argument is equals to zero a = 0; System.out.println(Math.signum(a)); // when the argument is less than zero a = -30; System.out.println(Math.signum(a)); }}", "e": 26225, "s": 25716, "text": null }, { "code": null, "e": 26233, "s": 26225, "text": "Output:" }, { "code": null, "e": 26245, "s": 26233, "text": "1.0\n0\n-1.0\n" }, { "code": null, "e": 26329, "s": 26245, "text": "Example 2 : To show working of java.lang.Math.signum() method when argument is NaN." }, { "code": "// Java program to demonstrate working// of java.lang.Math.signum() methodimport java.lang.Math; // importing java.lang package public class GFG { public static void main(String[] args) { double nan = Double.NaN; double result; // Here argument is NaN, output will be NaN result = Math.signum(nan); System.out.println(result); // Here argument is positive zero result = Math.signum(0); System.out.println(result); // Here argument is negative zero result = Math.signum(-0); System.out.println(result); }}", "e": 26929, "s": 26329, "text": null }, { "code": null, "e": 26937, "s": 26929, "text": "Output:" }, { "code": null, "e": 26950, "s": 26937, "text": "NaN\n0.0\n0.0\n" }, { "code": null, "e": 26968, "s": 26950, "text": "Java-lang package" }, { "code": null, "e": 26978, "s": 26968, "text": "java-math" }, { "code": null, "e": 26983, "s": 26978, "text": "Java" }, { "code": null, "e": 26988, "s": 26983, "text": "Java" }, { "code": null, "e": 27086, "s": 26988, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27095, "s": 27086, "text": "Comments" }, { "code": null, "e": 27108, "s": 27095, "text": "Old Comments" }, { "code": null, "e": 27140, "s": 27108, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27170, "s": 27140, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27189, "s": 27170, "text": "Interfaces in Java" }, { "code": null, "e": 27240, "s": 27189, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27258, "s": 27240, "text": "ArrayList in Java" }, { "code": null, "e": 27289, "s": 27258, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27321, "s": 27289, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27340, "s": 27321, "text": "LinkedList in Java" }, { "code": null, "e": 27360, "s": 27340, "text": "Stack Class in Java" } ]
C program to copy the contents of one file to another file?
C Files I/O − Create, Open, Read, Write and Close a File A File can be used to store a large volume of persistent data. Like many other languages 'C' provides the following file management functions, Creation of a file Opening a file Reading a file Writing to a file Closing a file Following are the most important file management functions available in 'C,' Input: sourcefile = x1.txt targefile = x2.txt Output: File copied successfully. In this program we will copy a file to another file, firstly you will specify a file to copy. We will open the file and then read the file that we wish to copy in "read" mode and target file in "write" mode. #include <iostream> #include <stdlib.h> using namespace std; int main() { char ch;// source_file[20], target_file[20]; FILE *source, *target; char source_file[]="x1.txt"; char target_file[]="x2.txt"; source = fopen(source_file, "r"); if (source == NULL) { printf("Press any key to exit...\n"); exit(EXIT_FAILURE); } target = fopen(target_file, "w"); if (target == NULL) { fclose(source); printf("Press any key to exit...\n"); exit(EXIT_FAILURE); } while ((ch = fgetc(source)) != EOF) fputc(ch, target); printf("File copied successfully.\n"); fclose(source); fclose(target); return 0; }
[ { "code": null, "e": 1119, "s": 1062, "text": "C Files I/O − Create, Open, Read, Write and Close a File" }, { "code": null, "e": 1262, "s": 1119, "text": "A File can be used to store a large volume of persistent data. Like many other languages 'C' provides the following file management functions," }, { "code": null, "e": 1281, "s": 1262, "text": "Creation of a file" }, { "code": null, "e": 1296, "s": 1281, "text": "Opening a file" }, { "code": null, "e": 1311, "s": 1296, "text": "Reading a file" }, { "code": null, "e": 1329, "s": 1311, "text": "Writing to a file" }, { "code": null, "e": 1344, "s": 1329, "text": "Closing a file" }, { "code": null, "e": 1421, "s": 1344, "text": "Following are the most important file management functions available in 'C,'" }, { "code": null, "e": 1501, "s": 1421, "text": "Input:\nsourcefile = x1.txt\ntargefile = x2.txt\nOutput: File copied successfully." }, { "code": null, "e": 1709, "s": 1501, "text": "In this program we will copy a file to another file, firstly you will specify a file to copy. We will open the file and then read the file that we wish to copy in \"read\" mode and target file in \"write\" mode." }, { "code": null, "e": 2376, "s": 1709, "text": "#include <iostream>\n#include <stdlib.h>\nusing namespace std;\nint main() {\n char ch;// source_file[20], target_file[20];\n FILE *source, *target;\n char source_file[]=\"x1.txt\";\n char target_file[]=\"x2.txt\";\n source = fopen(source_file, \"r\");\n if (source == NULL) {\n printf(\"Press any key to exit...\\n\");\n exit(EXIT_FAILURE);\n }\n target = fopen(target_file, \"w\");\n if (target == NULL) {\n fclose(source);\n printf(\"Press any key to exit...\\n\");\n exit(EXIT_FAILURE);\n }\n while ((ch = fgetc(source)) != EOF)\n fputc(ch, target);\n printf(\"File copied successfully.\\n\");\n fclose(source);\n fclose(target);\n return 0;\n}" } ]
How to handle Assertion Error in Java?
In order to handle the assertion error, we need to declare the assertion statement in the try block and catch the assertion error in the catch block. Let us see a program on how to handle Assertion Error in Java − public class Example { public static void main(String[] args) throws Exception { try { assert args.length > 0; } catch (AssertionError e) { System.out.println(e.getMessage()); } } }
[ { "code": null, "e": 1212, "s": 1062, "text": "In order to handle the assertion error, we need to declare the assertion statement in the try block and catch the assertion error in the catch block." }, { "code": null, "e": 1276, "s": 1212, "text": "Let us see a program on how to handle Assertion Error in Java −" }, { "code": null, "e": 1506, "s": 1276, "text": "public class Example {\n public static void main(String[] args) throws Exception {\n try {\n assert args.length > 0;\n }\n catch (AssertionError e) {\n System.out.println(e.getMessage());\n }\n }\n}" } ]
Bootstrap regression in R. Estimation of regression coefficients... | by Serafim Petrov | Towards Data Science
Bootstrap is a method of random sampling with replacement. Among its other applications such as hypothesis testing, it is a simple yet powerful approach for checking the stability of regression coefficients. In our previous article, we explored the permutation test, which is a related concept but executed without replacement. Linear regression relies on several assumptions, and the coefficients of the formulas are presumably normally distributed under the CLT. It shows that on average if we repeated the experiment thousands and thousands of times, the line would be in confidence intervals.The bootstrap approach does not rely on those assumptions*, but simply performs thousands of estimations. *(Please note, that the bootstrap approach does not violate or bypass the normality assumptions, but rather than relying on the CLT, it builds its own, the Bootstrap distribution, which is asymptotically normal) In this article, we will explore the Bootstrapping method and estimate regression coefficients of simulated data using R. We will simulate a dataset of one exploratory variable from the Gaussian distribution, and one response variable constructed by adding random noise to the exploratory variable. The population data would have 1000 observations. set.seed(2021)n <- 1000x <- rnorm(n)y <- x + rnorm(n)population.data <- as.data.frame(cbind(x, y)) We will take a sample of 20 observations from these data. sample.data <- population.data[sample(nrow(population.data), 20, replace = TRUE),] Let’s explore the simple regression models both for population and for sample data: We can see, that the intercept is biased for the sample data; however, the slope coefficient is very close to the population one, even though we have only 20 observations in our sample dataset. The standard errors are much higher for the sample model. If we plot the models, we can see how close the lines are: The Bootstrap approach asks a question: what if we resample the data with replacement and estimate the coefficients, how extreme would it be? Here is a simple loop of 1000 trials, which resamples with replacement these 20 observations from our sample dataset, runs the regression model and saves the coefficients we get there. In the end, we would have 1000 pairs of coefficients. We would take the average of these coefficients, and compare them with the other models we previously obtained: We can see, in this particular example, the intercept is closer to the population model, and the slope is at around the same precision level as the sample model. But what we are more interested, is the precision of confidence intervals. We can see, that the precision is almost identical to the sample model’s, and even slightly tighter for the intercept. First, the bootstrap representation: These are 1000 possible regression lines we have estimated. Now let’s add to the plot population, sample, and average bootstrap lines: We can see that they essentially capture the data in the same way. Now let’s add the confidence intervals from the sample data: This completes our research: we may conclude, that the bootstrapping approach returns essentially the same results but in a statistically different fashion. We do not rely on assumptions but simulate the data using a brute force method. This could be especially useful when we have doubts about the distribution the data arrived from, or want to check the stability of the coefficients, particularly for small datasets. You can find the full code here on GitHub. In this article, we have explored the bootstrap approach for estimating regression coefficients. We used a simple regression model for simplicity and clear representation of this powerful technique. We concluded that this approach is essentially equal to the OLS models, however without relying on the assumptions. It is a powerful method for estimating the uncertainty of the coefficients and could be used along with traditional methods to check the stability of the models. Connect on LinkedIn
[ { "code": null, "e": 500, "s": 172, "text": "Bootstrap is a method of random sampling with replacement. Among its other applications such as hypothesis testing, it is a simple yet powerful approach for checking the stability of regression coefficients. In our previous article, we explored the permutation test, which is a related concept but executed without replacement." }, { "code": null, "e": 1086, "s": 500, "text": "Linear regression relies on several assumptions, and the coefficients of the formulas are presumably normally distributed under the CLT. It shows that on average if we repeated the experiment thousands and thousands of times, the line would be in confidence intervals.The bootstrap approach does not rely on those assumptions*, but simply performs thousands of estimations. *(Please note, that the bootstrap approach does not violate or bypass the normality assumptions, but rather than relying on the CLT, it builds its own, the Bootstrap distribution, which is asymptotically normal)" }, { "code": null, "e": 1208, "s": 1086, "text": "In this article, we will explore the Bootstrapping method and estimate regression coefficients of simulated data using R." }, { "code": null, "e": 1435, "s": 1208, "text": "We will simulate a dataset of one exploratory variable from the Gaussian distribution, and one response variable constructed by adding random noise to the exploratory variable. The population data would have 1000 observations." }, { "code": null, "e": 1534, "s": 1435, "text": "set.seed(2021)n <- 1000x <- rnorm(n)y <- x + rnorm(n)population.data <- as.data.frame(cbind(x, y))" }, { "code": null, "e": 1592, "s": 1534, "text": "We will take a sample of 20 observations from these data." }, { "code": null, "e": 1675, "s": 1592, "text": "sample.data <- population.data[sample(nrow(population.data), 20, replace = TRUE),]" }, { "code": null, "e": 1759, "s": 1675, "text": "Let’s explore the simple regression models both for population and for sample data:" }, { "code": null, "e": 2011, "s": 1759, "text": "We can see, that the intercept is biased for the sample data; however, the slope coefficient is very close to the population one, even though we have only 20 observations in our sample dataset. The standard errors are much higher for the sample model." }, { "code": null, "e": 2070, "s": 2011, "text": "If we plot the models, we can see how close the lines are:" }, { "code": null, "e": 2212, "s": 2070, "text": "The Bootstrap approach asks a question: what if we resample the data with replacement and estimate the coefficients, how extreme would it be?" }, { "code": null, "e": 2451, "s": 2212, "text": "Here is a simple loop of 1000 trials, which resamples with replacement these 20 observations from our sample dataset, runs the regression model and saves the coefficients we get there. In the end, we would have 1000 pairs of coefficients." }, { "code": null, "e": 2563, "s": 2451, "text": "We would take the average of these coefficients, and compare them with the other models we previously obtained:" }, { "code": null, "e": 2800, "s": 2563, "text": "We can see, in this particular example, the intercept is closer to the population model, and the slope is at around the same precision level as the sample model. But what we are more interested, is the precision of confidence intervals." }, { "code": null, "e": 2919, "s": 2800, "text": "We can see, that the precision is almost identical to the sample model’s, and even slightly tighter for the intercept." }, { "code": null, "e": 2956, "s": 2919, "text": "First, the bootstrap representation:" }, { "code": null, "e": 3091, "s": 2956, "text": "These are 1000 possible regression lines we have estimated. Now let’s add to the plot population, sample, and average bootstrap lines:" }, { "code": null, "e": 3219, "s": 3091, "text": "We can see that they essentially capture the data in the same way. Now let’s add the confidence intervals from the sample data:" }, { "code": null, "e": 3639, "s": 3219, "text": "This completes our research: we may conclude, that the bootstrapping approach returns essentially the same results but in a statistically different fashion. We do not rely on assumptions but simulate the data using a brute force method. This could be especially useful when we have doubts about the distribution the data arrived from, or want to check the stability of the coefficients, particularly for small datasets." }, { "code": null, "e": 3682, "s": 3639, "text": "You can find the full code here on GitHub." }, { "code": null, "e": 4159, "s": 3682, "text": "In this article, we have explored the bootstrap approach for estimating regression coefficients. We used a simple regression model for simplicity and clear representation of this powerful technique. We concluded that this approach is essentially equal to the OLS models, however without relying on the assumptions. It is a powerful method for estimating the uncertainty of the coefficients and could be used along with traditional methods to check the stability of the models." } ]
A Complete Guide to Python Lists. Use Python Lists Like a Pro | by Erdem Isbilen | Towards Data Science
In this article, I will try to explain Python lists, along with exploring why and when to use them, meanwhile giving you some hints about the correct usage of the list methods. Let’s understand the Python list data structure in detail with step by step explanations and examples. Lists are one of the most frequently used built-in data structures in Python. You can create a list by placing all the items inside square brackets[ ], separated by commas. Lists can contain any type of object and this makes them very useful and versatile. Fundamental characteristics of Python lists are as follows; They are mutable, ordered, dynamic and array type (sequence) data structures. Let's explore each of these characteristics in further detail; New elements can be added or removed in runtime. Lists are not fixed-size objects, so they are called dynamic data structures. The order in which you specify the elements when you define a list is maintained so lists are ordered. Lists can be changed after they have created. You can add, remove items or modify the value of available items in a list object. You do not need to have another copy of the list object for revising it. So they are called mutable objects. Although Python lists are not fixed-size and constrained like arrays in C++ or Java, they are still array type data structures where the items contained are stored in memory sequentially and accessed by an index number representing the memory block for a specific element. A list object can contain duplicate elements. Let’s get a basic understanding of when to use lists over another data structure; When we want to store a collection of heterogeneous objects in a single data structure. We can store any of the primitive data structures (integers, strings, etc) as well as compound data structures (lists, sets, tuples, dictionaries, etc) inside a single list object. When we want to keep the order of data unchanged. The order we put the items into the lists is preserved, we can access the elements with the same order as we put them in. As lists are mutable, it is not a good idea to use them to store data that shouldn’t be modified in the first place. There are many ways of creating and initializing lists. You can use square brackets[] or list(iterable) constructor as shown below; # empty list with square bracketsempty_list = []# empty list with square bracketsempty_list = list()# list of integersinteger_list = [1, 2, 3]# list with mixed data typesmixed_list = [8, "Hi", 3.3]# list from an iterable objectiterable_list = list("data-science")# a nested listnested_list = ["cat", [3, 2], ['d']] Lists support sequence operations like Indexing, Slicing, Membership, Concatenation, Length, Iteration and some others as they are sequence type objects. Indexing: Items in a list can be accessed by index using the indexing operator. Python indexing starts from zero. You can use a negative integer as an index to start from the end. If you use an integer beyond the length of the list then you get IndexError. If your index is not an integer then you get TypeError. # list of integersinteger_list = [1, 2, 3, 4, 5, 6, 7]# indexingprint(integer_list[0]) #prints '1'print(integer_list[6]) #prints '7'print(integer_list[-1]) #prints '7'print(integer_list[-7]) #prints '1'print(integer_list['a']) #TypeError: list indices must be integersprint(integer_list[7]) #IndexError: index is out of range Slicing: Slicing is a very powerful tool as it helps you to create another list with a range of objects contained in the original list. Slicing seems unintuitive at first but once you grasp the basics you can use them easily to enhance the lists operations. # list of integersinteger_list = [1, 2, 3, 4, 5, 6, 7]# slicing with [start:end] takes all elements between 'start' to 'end' does not include 'end' elementprint(integer_list[1:3]) # prints '[2, 3]'# slicing with [start:] includes all elements after 'start' including the 'start'th elementprint(integer_list[2:]) # prints [3, 4, 5, 6, 7]# slicing with [:ends] includes all elements before 'end' and does not include the 'end'th elementprint(integer_list[:5]) # prints [1, 2, 3, 4, 5]# slicing with negative integers to start indexing from endprint(integer_list[-2:]) # prints [6, 7]print(integer_list[:-5]) # prints [1, 2] Membership: You can check whether if a specific object is member of a list or not. To do this, you can use ‘in’ or ‘not in’ membership operators. # list of integersinteger_list = [1, 2, 3, 4, 5, 6, 7]# membership4 in integer_list # True8 in integer_list # False4 not in integer_list # False8 not in integer_list # True Concatenation: You can use ‘+’ or ‘*’ operators to concatenate the lists. # list of integersinteger_list = [1, 2, 3]# list of stringsstring_list = ['data', 'science', 'rocks']integer_list + string_list #[1, 2, 3, 'data', 'science', 'rocks']string_list * 2 #['data', 'science', 'rocks', 'data', 'science', 'rocks'] Length: If you pass a list to the ‘len()’ function, you will get the length of the list in return. # list of integersinteger_list = [1, 2, 3, 4, 5, 6, 7]# len() with listslen(integer_list) # 7 Iteration: Lists are iterable objects so you can iterate over a list with for loops. # list of integersinteger_list = [1, 2, 3]# iterate over list elementsfor element in integer_list: print(element) # 1 2 3 Other operations: There are some additional operations that apply to most of the sequences such as max(), min(), count(), index(). Let’s see how you can use them with list objects; # list of integersinteger_list = [1, 2, 3, 1, 8, 1]# max(), min()max(integer_list) # 8min(integer_list) # 1# count(), index()integer_list.index(3) # 2integer_list.index(1) # 0integer_list.count(1) # 3integer_list.count(9) # 0 Here are the remaining methods you can use with the list-objects. append(element): Adds a single element to the end of the list. This method modifies the original list and does not return a new list; # list of integersinteger_list = [1, 2, 3]# append()integer_list.append(5)print(integer_list)# output# [1, 2, 3, 5] extend(other_list): Adds the elements in other_list to the end of the original list; integer_list = [1, 2, 3]string_list = ['data', 'science']# extend()integer_list.extend(string_list) #[1, 2, 3, 'data', 'science']integer_list.extend('rocks') #[1, 2, 3, 'data', 'science', 'r', 'o', 'c', 'k', 's'] insert(index, element): Inserts a single element at the given index and shifts the elements after to the right. string_list = ['data', 'science']# insert()string_list.insert(1,'-') #['data', '-', 'science']string_list.insert(3,'rocks') #['data', '-', 'science', 'rocks'] sort(key=None, reverse=False) — Sorts the given list, does not return a new list object. sort() function sort the list in ascending order. You can provide reverser = True if you need to sort the list in descending order. You can also define a custom sorting order by creating a function to define which element of list items to be used as a key for ordering. As you can see in the below example, second_char(string_element) function returns the second character of each string element in the original list. The list then sorted based on the return value of the second_char function. integer_list = [1, 2, 3, 1, 8, 1]# sort()integer_list.sort()print(integer_list)integer_list.sort(reverse=True)print(integer_list)# custom sortstring_list = ['science', 'rocks', 'data']def second_char(string_element): return string_element[1]string_list.sort(key=second_char, reverse=False)print(string_list) reverse() — Reverse simply reverse the list order. This function does not return a new list. remove(element): Finds the first instance of the given element and removes it. Throws ValueError, if the given element is not present. integer_list = [1, 2, 3, 1, 8, 1]# remove()integer_list.remove(1)print(integer_list) #[2, 3, 1, 8, 1]integer_list.remove(1)print(integer_list) #[2, 3, 8, 1]integer_list.remove(2)print(integer_list) #[3, 8, 1]integer_list.remove(9) #ValueError: list.remove(x): x not in list pop(index): Removes and returns the element at the given index. Removes and returns the last element if the index is no provided. integer_list = [1, 2, 3, 4, 5, 6, 7]# pop()integer_list.pop(3)#returns 4print(integer_list)#[1, 2, 3, 5, 6, 7]integer_list.pop() #returns 7print(integer_list)#[1, 2, 3, 5, 6] List comprehensions provide an elegant and concise way of creating lists. The syntax for the list comprehensions; new_list = [expression for member in iterable(if conditional)]integer_list = [x for x in range(10) if x % 2 == 0 if x % 5 == 0]print(integer_list) #[0, 10, 20, 30] As data structures are fundamental parts of our programs, it is really important to have a solid understanding of Python lists to create efficient programs. I explained why and when to use the lists, some of the key takeaways are listed below; Fundamental characteristics of Python lists are as follows; They are mutable, ordered, dynamic and array type (sequence) data structures. We can use the lists when we want to store a collection of heterogeneous objects in a single data structure. New elements can be added or removed in runtime. Lists are not fixed-size objects, so they are called dynamic data structures. The order in which you specify the elements when you define a list is maintained so lists are ordered. Thank you for reading!
[ { "code": null, "e": 349, "s": 172, "text": "In this article, I will try to explain Python lists, along with exploring why and when to use them, meanwhile giving you some hints about the correct usage of the list methods." }, { "code": null, "e": 452, "s": 349, "text": "Let’s understand the Python list data structure in detail with step by step explanations and examples." }, { "code": null, "e": 709, "s": 452, "text": "Lists are one of the most frequently used built-in data structures in Python. You can create a list by placing all the items inside square brackets[ ], separated by commas. Lists can contain any type of object and this makes them very useful and versatile." }, { "code": null, "e": 847, "s": 709, "text": "Fundamental characteristics of Python lists are as follows; They are mutable, ordered, dynamic and array type (sequence) data structures." }, { "code": null, "e": 910, "s": 847, "text": "Let's explore each of these characteristics in further detail;" }, { "code": null, "e": 1037, "s": 910, "text": "New elements can be added or removed in runtime. Lists are not fixed-size objects, so they are called dynamic data structures." }, { "code": null, "e": 1140, "s": 1037, "text": "The order in which you specify the elements when you define a list is maintained so lists are ordered." }, { "code": null, "e": 1378, "s": 1140, "text": "Lists can be changed after they have created. You can add, remove items or modify the value of available items in a list object. You do not need to have another copy of the list object for revising it. So they are called mutable objects." }, { "code": null, "e": 1651, "s": 1378, "text": "Although Python lists are not fixed-size and constrained like arrays in C++ or Java, they are still array type data structures where the items contained are stored in memory sequentially and accessed by an index number representing the memory block for a specific element." }, { "code": null, "e": 1697, "s": 1651, "text": "A list object can contain duplicate elements." }, { "code": null, "e": 1779, "s": 1697, "text": "Let’s get a basic understanding of when to use lists over another data structure;" }, { "code": null, "e": 2048, "s": 1779, "text": "When we want to store a collection of heterogeneous objects in a single data structure. We can store any of the primitive data structures (integers, strings, etc) as well as compound data structures (lists, sets, tuples, dictionaries, etc) inside a single list object." }, { "code": null, "e": 2220, "s": 2048, "text": "When we want to keep the order of data unchanged. The order we put the items into the lists is preserved, we can access the elements with the same order as we put them in." }, { "code": null, "e": 2337, "s": 2220, "text": "As lists are mutable, it is not a good idea to use them to store data that shouldn’t be modified in the first place." }, { "code": null, "e": 2469, "s": 2337, "text": "There are many ways of creating and initializing lists. You can use square brackets[] or list(iterable) constructor as shown below;" }, { "code": null, "e": 2784, "s": 2469, "text": "# empty list with square bracketsempty_list = []# empty list with square bracketsempty_list = list()# list of integersinteger_list = [1, 2, 3]# list with mixed data typesmixed_list = [8, \"Hi\", 3.3]# list from an iterable objectiterable_list = list(\"data-science\")# a nested listnested_list = [\"cat\", [3, 2], ['d']]" }, { "code": null, "e": 2938, "s": 2784, "text": "Lists support sequence operations like Indexing, Slicing, Membership, Concatenation, Length, Iteration and some others as they are sequence type objects." }, { "code": null, "e": 3251, "s": 2938, "text": "Indexing: Items in a list can be accessed by index using the indexing operator. Python indexing starts from zero. You can use a negative integer as an index to start from the end. If you use an integer beyond the length of the list then you get IndexError. If your index is not an integer then you get TypeError." }, { "code": null, "e": 3577, "s": 3251, "text": "# list of integersinteger_list = [1, 2, 3, 4, 5, 6, 7]# indexingprint(integer_list[0]) #prints '1'print(integer_list[6]) #prints '7'print(integer_list[-1]) #prints '7'print(integer_list[-7]) #prints '1'print(integer_list['a']) #TypeError: list indices must be integersprint(integer_list[7]) #IndexError: index is out of range" }, { "code": null, "e": 3835, "s": 3577, "text": "Slicing: Slicing is a very powerful tool as it helps you to create another list with a range of objects contained in the original list. Slicing seems unintuitive at first but once you grasp the basics you can use them easily to enhance the lists operations." }, { "code": null, "e": 4458, "s": 3835, "text": "# list of integersinteger_list = [1, 2, 3, 4, 5, 6, 7]# slicing with [start:end] takes all elements between 'start' to 'end' does not include 'end' elementprint(integer_list[1:3]) # prints '[2, 3]'# slicing with [start:] includes all elements after 'start' including the 'start'th elementprint(integer_list[2:]) # prints [3, 4, 5, 6, 7]# slicing with [:ends] includes all elements before 'end' and does not include the 'end'th elementprint(integer_list[:5]) # prints [1, 2, 3, 4, 5]# slicing with negative integers to start indexing from endprint(integer_list[-2:]) # prints [6, 7]print(integer_list[:-5]) # prints [1, 2]" }, { "code": null, "e": 4604, "s": 4458, "text": "Membership: You can check whether if a specific object is member of a list or not. To do this, you can use ‘in’ or ‘not in’ membership operators." }, { "code": null, "e": 4777, "s": 4604, "text": "# list of integersinteger_list = [1, 2, 3, 4, 5, 6, 7]# membership4 in integer_list # True8 in integer_list # False4 not in integer_list # False8 not in integer_list # True" }, { "code": null, "e": 4851, "s": 4777, "text": "Concatenation: You can use ‘+’ or ‘*’ operators to concatenate the lists." }, { "code": null, "e": 5091, "s": 4851, "text": "# list of integersinteger_list = [1, 2, 3]# list of stringsstring_list = ['data', 'science', 'rocks']integer_list + string_list #[1, 2, 3, 'data', 'science', 'rocks']string_list * 2 #['data', 'science', 'rocks', 'data', 'science', 'rocks']" }, { "code": null, "e": 5190, "s": 5091, "text": "Length: If you pass a list to the ‘len()’ function, you will get the length of the list in return." }, { "code": null, "e": 5284, "s": 5190, "text": "# list of integersinteger_list = [1, 2, 3, 4, 5, 6, 7]# len() with listslen(integer_list) # 7" }, { "code": null, "e": 5369, "s": 5284, "text": "Iteration: Lists are iterable objects so you can iterate over a list with for loops." }, { "code": null, "e": 5494, "s": 5369, "text": "# list of integersinteger_list = [1, 2, 3]# iterate over list elementsfor element in integer_list: print(element) # 1 2 3" }, { "code": null, "e": 5675, "s": 5494, "text": "Other operations: There are some additional operations that apply to most of the sequences such as max(), min(), count(), index(). Let’s see how you can use them with list objects;" }, { "code": null, "e": 5901, "s": 5675, "text": "# list of integersinteger_list = [1, 2, 3, 1, 8, 1]# max(), min()max(integer_list) # 8min(integer_list) # 1# count(), index()integer_list.index(3) # 2integer_list.index(1) # 0integer_list.count(1) # 3integer_list.count(9) # 0" }, { "code": null, "e": 5967, "s": 5901, "text": "Here are the remaining methods you can use with the list-objects." }, { "code": null, "e": 6101, "s": 5967, "text": "append(element): Adds a single element to the end of the list. This method modifies the original list and does not return a new list;" }, { "code": null, "e": 6217, "s": 6101, "text": "# list of integersinteger_list = [1, 2, 3]# append()integer_list.append(5)print(integer_list)# output# [1, 2, 3, 5]" }, { "code": null, "e": 6302, "s": 6217, "text": "extend(other_list): Adds the elements in other_list to the end of the original list;" }, { "code": null, "e": 6515, "s": 6302, "text": "integer_list = [1, 2, 3]string_list = ['data', 'science']# extend()integer_list.extend(string_list) #[1, 2, 3, 'data', 'science']integer_list.extend('rocks') #[1, 2, 3, 'data', 'science', 'r', 'o', 'c', 'k', 's']" }, { "code": null, "e": 6627, "s": 6515, "text": "insert(index, element): Inserts a single element at the given index and shifts the elements after to the right." }, { "code": null, "e": 6786, "s": 6627, "text": "string_list = ['data', 'science']# insert()string_list.insert(1,'-') #['data', '-', 'science']string_list.insert(3,'rocks') #['data', '-', 'science', 'rocks']" }, { "code": null, "e": 7369, "s": 6786, "text": "sort(key=None, reverse=False) — Sorts the given list, does not return a new list object. sort() function sort the list in ascending order. You can provide reverser = True if you need to sort the list in descending order. You can also define a custom sorting order by creating a function to define which element of list items to be used as a key for ordering. As you can see in the below example, second_char(string_element) function returns the second character of each string element in the original list. The list then sorted based on the return value of the second_char function." }, { "code": null, "e": 7678, "s": 7369, "text": "integer_list = [1, 2, 3, 1, 8, 1]# sort()integer_list.sort()print(integer_list)integer_list.sort(reverse=True)print(integer_list)# custom sortstring_list = ['science', 'rocks', 'data']def second_char(string_element): return string_element[1]string_list.sort(key=second_char, reverse=False)print(string_list)" }, { "code": null, "e": 7771, "s": 7678, "text": "reverse() — Reverse simply reverse the list order. This function does not return a new list." }, { "code": null, "e": 7906, "s": 7771, "text": "remove(element): Finds the first instance of the given element and removes it. Throws ValueError, if the given element is not present." }, { "code": null, "e": 8181, "s": 7906, "text": "integer_list = [1, 2, 3, 1, 8, 1]# remove()integer_list.remove(1)print(integer_list) #[2, 3, 1, 8, 1]integer_list.remove(1)print(integer_list) #[2, 3, 8, 1]integer_list.remove(2)print(integer_list) #[3, 8, 1]integer_list.remove(9) #ValueError: list.remove(x): x not in list" }, { "code": null, "e": 8311, "s": 8181, "text": "pop(index): Removes and returns the element at the given index. Removes and returns the last element if the index is no provided." }, { "code": null, "e": 8486, "s": 8311, "text": "integer_list = [1, 2, 3, 4, 5, 6, 7]# pop()integer_list.pop(3)#returns 4print(integer_list)#[1, 2, 3, 5, 6, 7]integer_list.pop() #returns 7print(integer_list)#[1, 2, 3, 5, 6]" }, { "code": null, "e": 8600, "s": 8486, "text": "List comprehensions provide an elegant and concise way of creating lists. The syntax for the list comprehensions;" }, { "code": null, "e": 8765, "s": 8600, "text": "new_list = [expression for member in iterable(if conditional)]integer_list = [x for x in range(10) if x % 2 == 0 if x % 5 == 0]print(integer_list) #[0, 10, 20, 30]" }, { "code": null, "e": 8922, "s": 8765, "text": "As data structures are fundamental parts of our programs, it is really important to have a solid understanding of Python lists to create efficient programs." }, { "code": null, "e": 9009, "s": 8922, "text": "I explained why and when to use the lists, some of the key takeaways are listed below;" }, { "code": null, "e": 9147, "s": 9009, "text": "Fundamental characteristics of Python lists are as follows; They are mutable, ordered, dynamic and array type (sequence) data structures." }, { "code": null, "e": 9256, "s": 9147, "text": "We can use the lists when we want to store a collection of heterogeneous objects in a single data structure." }, { "code": null, "e": 9383, "s": 9256, "text": "New elements can be added or removed in runtime. Lists are not fixed-size objects, so they are called dynamic data structures." }, { "code": null, "e": 9486, "s": 9383, "text": "The order in which you specify the elements when you define a list is maintained so lists are ordered." } ]
Angular Material - Switches
The md-switch, an Angular directive, is used to show a switch. The following table lists out the parameters and description of the different attributes of md-switch. * ng-model The assignable angular expression to data-bind to. name The property name of the form under which the control is published. ng-true-value The value to which the expression should be set when selected. ng-false-value The value to which the expression should be set when not selected. ng-change The Angular expression to be executed when input changes due to user interaction with the input element. ng-disabled En/Disable based on the expression. md-no-ink The use of attribute indicates the use of ripple ink effects. aria-label This publishes the button label used by the screen-readers for accessibility. This defaults to the switch's text. The following example shows the use of md-swipe-* and also the uses of swipe components. am_switches.htm <html lang = "en"> <head> <link rel = "stylesheet" href = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script> <link rel = "stylesheet" href = "https://fonts.googleapis.com/icon?family=Material+Icons"> <script language = "javascript"> angular .module('firstApplication', ['ngMaterial']) .controller('switchController', switchController); function switchController ($scope) { $scope.data = { switch1: true, switch2: false, switch3: false, switch4: true, switch5: true, switch6: false }; $scope.message = 'false'; $scope.onChange = function(state) { $scope.message = state; }; } </script> </head> <body ng-app = "firstApplication"> <div id = "switchContainer" ng-controller = "switchController as ctrl" layout = "column" ng-cloak> <md-switch ng-model = "data.switch1" aria-label = "Switch 1"> Switch 1: {{ data.switch1 }} </md-switch> <md-switch ng-model = "data.switch2" aria-label = "Switch 2" ng-true-value = "'true'" ng-false-value = "'false'" class = "md-warn"> Switch 2 (md-warn): {{ data.switch2 }} </md-switch> <md-switch ng-disabled = "true" aria-label = "Disabled switch" ng-model = "disabledModel"> Switch 3 (Disabled) </md-switch> <md-switch ng-disabled = "true" aria-label = "Disabled active switch" ng-model = "data.switch4"> Switch 4 (Disabled, Active) </md-switch> <md-switch class = "md-primary" md-no-ink aria-label = "Switch No Ink" ng-model = "data.switch5"> Switch 5 (md-primary): No Ink </md-switch> <md-switch ng-model = "data.switch6" aria-label = "Switch 6" ng-change = "onChange(data.switch6)"> Switch 6 : {{ message }} </md-switch> </div> </body> </html> Verify the result. 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": 2253, "s": 2190, "text": "The md-switch, an Angular directive, is used to show a switch." }, { "code": null, "e": 2356, "s": 2253, "text": "The following table lists out the parameters and description of the different attributes of md-switch." }, { "code": null, "e": 2367, "s": 2356, "text": "* ng-model" }, { "code": null, "e": 2418, "s": 2367, "text": "The assignable angular expression to data-bind to." }, { "code": null, "e": 2423, "s": 2418, "text": "name" }, { "code": null, "e": 2491, "s": 2423, "text": "The property name of the form under which the control is published." }, { "code": null, "e": 2505, "s": 2491, "text": "ng-true-value" }, { "code": null, "e": 2568, "s": 2505, "text": "The value to which the expression should be set when selected." }, { "code": null, "e": 2583, "s": 2568, "text": "ng-false-value" }, { "code": null, "e": 2650, "s": 2583, "text": "The value to which the expression should be set when not selected." }, { "code": null, "e": 2660, "s": 2650, "text": "ng-change" }, { "code": null, "e": 2765, "s": 2660, "text": "The Angular expression to be executed when input changes due to user interaction with the input element." }, { "code": null, "e": 2777, "s": 2765, "text": "ng-disabled" }, { "code": null, "e": 2813, "s": 2777, "text": "En/Disable based on the expression." }, { "code": null, "e": 2823, "s": 2813, "text": "md-no-ink" }, { "code": null, "e": 2885, "s": 2823, "text": "The use of attribute indicates the use of ripple ink effects." }, { "code": null, "e": 2896, "s": 2885, "text": "aria-label" }, { "code": null, "e": 3010, "s": 2896, "text": "This publishes the button label used by the screen-readers for accessibility. This defaults to the switch's text." }, { "code": null, "e": 3099, "s": 3010, "text": "The following example shows the use of md-swipe-* and also the uses of swipe components." }, { "code": null, "e": 3115, "s": 3099, "text": "am_switches.htm" }, { "code": null, "e": 5888, "s": 3115, "text": "<html lang = \"en\">\n <head>\n <link rel = \"stylesheet\"\n href = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js\"></script>\n <link rel = \"stylesheet\" href = \"https://fonts.googleapis.com/icon?family=Material+Icons\">\n \n <script language = \"javascript\">\n angular\n .module('firstApplication', ['ngMaterial'])\n .controller('switchController', switchController);\n\n function switchController ($scope) {\n $scope.data = {\n switch1: true,\n switch2: false,\n switch3: false,\n switch4: true,\n switch5: true,\n switch6: false\n };\n \n $scope.message = 'false';\n $scope.onChange = function(state) {\n $scope.message = state;\n };\n }\t \n </script> \n </head>\n \n <body ng-app = \"firstApplication\"> \n <div id = \"switchContainer\" ng-controller = \"switchController as ctrl\"\n layout = \"column\" ng-cloak>\n <md-switch ng-model = \"data.switch1\" aria-label = \"Switch 1\">\n Switch 1: {{ data.switch1 }}\n </md-switch>\n \n <md-switch ng-model = \"data.switch2\" aria-label = \"Switch 2\"\n ng-true-value = \"'true'\" ng-false-value = \"'false'\" class = \"md-warn\">\n Switch 2 (md-warn): {{ data.switch2 }}\n </md-switch>\n \n <md-switch ng-disabled = \"true\" aria-label = \"Disabled switch\"\n ng-model = \"disabledModel\">\n Switch 3 (Disabled)\n </md-switch>\n \n <md-switch ng-disabled = \"true\" aria-label = \"Disabled active switch\"\n ng-model = \"data.switch4\">\n Switch 4 (Disabled, Active)\n </md-switch>\n \n <md-switch class = \"md-primary\" md-no-ink aria-label = \"Switch No Ink\"\n ng-model = \"data.switch5\">\n Switch 5 (md-primary): No Ink\n </md-switch>\n \n <md-switch ng-model = \"data.switch6\" aria-label = \"Switch 6\"\n ng-change = \"onChange(data.switch6)\">\n Switch 6 : {{ message }}\n </md-switch> \n </div>\n </body>\n</html>" }, { "code": null, "e": 5907, "s": 5888, "text": "Verify the result." }, { "code": null, "e": 5942, "s": 5907, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5956, "s": 5942, "text": " Anadi Sharma" }, { "code": null, "e": 5991, "s": 5956, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6005, "s": 5991, "text": " Anadi Sharma" }, { "code": null, "e": 6040, "s": 6005, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6060, "s": 6040, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 6095, "s": 6060, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6112, "s": 6095, "text": " Frahaan Hussain" }, { "code": null, "e": 6145, "s": 6112, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 6157, "s": 6145, "text": " Senol Atac" }, { "code": null, "e": 6192, "s": 6157, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6204, "s": 6192, "text": " Senol Atac" }, { "code": null, "e": 6211, "s": 6204, "text": " Print" }, { "code": null, "e": 6222, "s": 6211, "text": " Add Notes" } ]
Python | Numpy matrix.min() - GeeksforGeeks
15 Apr, 2019 With the help of Numpy matrix.min() method, we can get the minimum value from given matrix. Syntax : matrix.min() Return : Return minimum value from given matrix Example #1 :In this example we can see that we are able to get the minimum value from a given matrix with the help of method matrix.min(). # import the important module in pythonimport numpy as np # make matrix with numpygfg = np.matrix('[64, 1; 12, 3]') # applying matrix.min() methodgeeks = gfg.min() print(geeks) 1 Example #2 : # import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1, 2, 3; 4, 5, 6; 7, 8, -9]') # applying matrix.min() methodgeeks = gfg.min() print(geeks) -9 Python numpy-Matrix Function Python-numpy 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 How to Install PIP on Windows ? Enumerate() in Python Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Create a Pandas DataFrame from Lists Reading and Writing to text files in Python
[ { "code": null, "e": 24664, "s": 24636, "text": "\n15 Apr, 2019" }, { "code": null, "e": 24756, "s": 24664, "text": "With the help of Numpy matrix.min() method, we can get the minimum value from given matrix." }, { "code": null, "e": 24778, "s": 24756, "text": "Syntax : matrix.min()" }, { "code": null, "e": 24826, "s": 24778, "text": "Return : Return minimum value from given matrix" }, { "code": null, "e": 24965, "s": 24826, "text": "Example #1 :In this example we can see that we are able to get the minimum value from a given matrix with the help of method matrix.min()." }, { "code": "# import the important module in pythonimport numpy as np # make matrix with numpygfg = np.matrix('[64, 1; 12, 3]') # applying matrix.min() methodgeeks = gfg.min() print(geeks)", "e": 25163, "s": 24965, "text": null }, { "code": null, "e": 25166, "s": 25163, "text": "1\n" }, { "code": null, "e": 25179, "s": 25166, "text": "Example #2 :" }, { "code": "# import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1, 2, 3; 4, 5, 6; 7, 8, -9]') # applying matrix.min() methodgeeks = gfg.min() print(geeks)", "e": 25393, "s": 25179, "text": null }, { "code": null, "e": 25397, "s": 25393, "text": "-9\n" }, { "code": null, "e": 25426, "s": 25397, "text": "Python numpy-Matrix Function" }, { "code": null, "e": 25439, "s": 25426, "text": "Python-numpy" }, { "code": null, "e": 25446, "s": 25439, "text": "Python" }, { "code": null, "e": 25544, "s": 25446, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25553, "s": 25544, "text": "Comments" }, { "code": null, "e": 25566, "s": 25553, "text": "Old Comments" }, { "code": null, "e": 25584, "s": 25566, "text": "Python Dictionary" }, { "code": null, "e": 25619, "s": 25584, "text": "Read a file line by line in Python" }, { "code": null, "e": 25651, "s": 25619, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25673, "s": 25651, "text": "Enumerate() in Python" }, { "code": null, "e": 25703, "s": 25673, "text": "Iterate over a list in Python" }, { "code": null, "e": 25745, "s": 25703, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 25771, "s": 25745, "text": "Python String | replace()" }, { "code": null, "e": 25814, "s": 25771, "text": "Python program to convert a list to string" }, { "code": null, "e": 25851, "s": 25814, "text": "Create a Pandas DataFrame from Lists" } ]
Python os.chflags() Method
The method chflags() sets the flags of path to the numeric flags. The flags may take a combination (bitwise OR) of the various values described below. Note − This method is available Python version 2.6 onwards. Most of the flags can be changed by super-user only. Following is the syntax for chflags() method − os.chflags(path, flags) path − This is complete path of the directory to be changed to a new location. path − This is complete path of the directory to be changed to a new location. flags − The flags specified are formed by OR'ing the following values − os.UF_NODUMP − Do not dump the file. os.UF_IMMUTABLE − The file may not be changed. os.UF_APPEND − The file may only be appended to. os.UF_NOUNLINK − The file may not be renamed or deleted. os.UF_OPAQUE − The directory is opaque when viewed through a union stack. os.SF_ARCHIVED − The file may be archived. os.SF_IMMUTABLE − The file may not be changed. os.SF_APPEND − The file may only be appended to. os.SF_NOUNLINK − The file may not be renamed or deleted. os.SF_SNAPSHOT − The file is a snapshot file. flags − The flags specified are formed by OR'ing the following values − os.UF_NODUMP − Do not dump the file. os.UF_NODUMP − Do not dump the file. os.UF_IMMUTABLE − The file may not be changed. os.UF_IMMUTABLE − The file may not be changed. os.UF_APPEND − The file may only be appended to. os.UF_APPEND − The file may only be appended to. os.UF_NOUNLINK − The file may not be renamed or deleted. os.UF_NOUNLINK − The file may not be renamed or deleted. os.UF_OPAQUE − The directory is opaque when viewed through a union stack. os.UF_OPAQUE − The directory is opaque when viewed through a union stack. os.SF_ARCHIVED − The file may be archived. os.SF_ARCHIVED − The file may be archived. os.SF_IMMUTABLE − The file may not be changed. os.SF_IMMUTABLE − The file may not be changed. os.SF_APPEND − The file may only be appended to. os.SF_APPEND − The file may only be appended to. os.SF_NOUNLINK − The file may not be renamed or deleted. os.SF_NOUNLINK − The file may not be renamed or deleted. os.SF_SNAPSHOT − The file is a snapshot file. os.SF_SNAPSHOT − The file is a snapshot file. This method does not return any value. The following example shows the usage of chflags() method. #!/usr/bin/python import os import stat path = "/tmp/foo.txt" # Set a flag so that file may not be renamed or deleted. flags = os.SF_NOUNLINK retval = os.chflags( path, flags) print "Return Value: %s" % retval When we run above program, it produces following result − Return Value : None 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2395, "s": 2244, "text": "The method chflags() sets the flags of path to the numeric flags. The flags may take a combination (bitwise OR) of the various values described below." }, { "code": null, "e": 2508, "s": 2395, "text": "Note − This method is available Python version 2.6 onwards. Most of the flags can be changed by super-user only." }, { "code": null, "e": 2555, "s": 2508, "text": "Following is the syntax for chflags() method −" }, { "code": null, "e": 2580, "s": 2555, "text": "os.chflags(path, flags)\n" }, { "code": null, "e": 2659, "s": 2580, "text": "path − This is complete path of the directory to be changed to a new location." }, { "code": null, "e": 2738, "s": 2659, "text": "path − This is complete path of the directory to be changed to a new location." }, { "code": null, "e": 3319, "s": 2738, "text": "flags − The flags specified are formed by OR'ing the following values −\n\nos.UF_NODUMP − Do not dump the file.\nos.UF_IMMUTABLE − The file may not be changed.\nos.UF_APPEND − The file may only be appended to.\nos.UF_NOUNLINK − The file may not be renamed or deleted.\nos.UF_OPAQUE − The directory is opaque when viewed through a union stack.\nos.SF_ARCHIVED − The file may be archived.\nos.SF_IMMUTABLE − The file may not be changed.\nos.SF_APPEND − The file may only be appended to.\nos.SF_NOUNLINK − The file may not be renamed or deleted.\nos.SF_SNAPSHOT − The file is a snapshot file.\n\n" }, { "code": null, "e": 3391, "s": 3319, "text": "flags − The flags specified are formed by OR'ing the following values −" }, { "code": null, "e": 3428, "s": 3391, "text": "os.UF_NODUMP − Do not dump the file." }, { "code": null, "e": 3465, "s": 3428, "text": "os.UF_NODUMP − Do not dump the file." }, { "code": null, "e": 3512, "s": 3465, "text": "os.UF_IMMUTABLE − The file may not be changed." }, { "code": null, "e": 3559, "s": 3512, "text": "os.UF_IMMUTABLE − The file may not be changed." }, { "code": null, "e": 3608, "s": 3559, "text": "os.UF_APPEND − The file may only be appended to." }, { "code": null, "e": 3657, "s": 3608, "text": "os.UF_APPEND − The file may only be appended to." }, { "code": null, "e": 3714, "s": 3657, "text": "os.UF_NOUNLINK − The file may not be renamed or deleted." }, { "code": null, "e": 3771, "s": 3714, "text": "os.UF_NOUNLINK − The file may not be renamed or deleted." }, { "code": null, "e": 3845, "s": 3771, "text": "os.UF_OPAQUE − The directory is opaque when viewed through a union stack." }, { "code": null, "e": 3919, "s": 3845, "text": "os.UF_OPAQUE − The directory is opaque when viewed through a union stack." }, { "code": null, "e": 3962, "s": 3919, "text": "os.SF_ARCHIVED − The file may be archived." }, { "code": null, "e": 4005, "s": 3962, "text": "os.SF_ARCHIVED − The file may be archived." }, { "code": null, "e": 4052, "s": 4005, "text": "os.SF_IMMUTABLE − The file may not be changed." }, { "code": null, "e": 4099, "s": 4052, "text": "os.SF_IMMUTABLE − The file may not be changed." }, { "code": null, "e": 4148, "s": 4099, "text": "os.SF_APPEND − The file may only be appended to." }, { "code": null, "e": 4197, "s": 4148, "text": "os.SF_APPEND − The file may only be appended to." }, { "code": null, "e": 4254, "s": 4197, "text": "os.SF_NOUNLINK − The file may not be renamed or deleted." }, { "code": null, "e": 4311, "s": 4254, "text": "os.SF_NOUNLINK − The file may not be renamed or deleted." }, { "code": null, "e": 4357, "s": 4311, "text": "os.SF_SNAPSHOT − The file is a snapshot file." }, { "code": null, "e": 4403, "s": 4357, "text": "os.SF_SNAPSHOT − The file is a snapshot file." }, { "code": null, "e": 4442, "s": 4403, "text": "This method does not return any value." }, { "code": null, "e": 4501, "s": 4442, "text": "The following example shows the usage of chflags() method." }, { "code": null, "e": 4713, "s": 4501, "text": "#!/usr/bin/python\nimport os\nimport stat\n\npath = \"/tmp/foo.txt\"\n\n# Set a flag so that file may not be renamed or deleted.\nflags = os.SF_NOUNLINK\nretval = os.chflags( path, flags)\nprint \"Return Value: %s\" % retval" }, { "code": null, "e": 4771, "s": 4713, "text": "When we run above program, it produces following result −" }, { "code": null, "e": 4792, "s": 4771, "text": "Return Value : None\n" }, { "code": null, "e": 4829, "s": 4792, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4845, "s": 4829, "text": " Malhar Lathkar" }, { "code": null, "e": 4878, "s": 4845, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 4897, "s": 4878, "text": " Arnab Chakraborty" }, { "code": null, "e": 4932, "s": 4897, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 4954, "s": 4932, "text": " In28Minutes Official" }, { "code": null, "e": 4988, "s": 4954, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 5016, "s": 4988, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5051, "s": 5016, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 5065, "s": 5051, "text": " Lets Kode It" }, { "code": null, "e": 5098, "s": 5065, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 5115, "s": 5098, "text": " Abhilash Nelson" }, { "code": null, "e": 5122, "s": 5115, "text": " Print" }, { "code": null, "e": 5133, "s": 5122, "text": " Add Notes" } ]
C++ Library - <typeinfo>
It contains type information and stores information about a type. It can be used to compare two types or to retrieve information identifying a type. Following is the declaration for std::type_info. class type_info; class type_info; It contains type information. It throws exception on failure to dynamic cast. It throws exception on typeid of null pointe. It throws exception on failure to dynamic cast. It throws exception on typeid of null pointe. Print Add Notes Bookmark this page
[ { "code": null, "e": 2752, "s": 2603, "text": "It contains type information and stores information about a type. It can be used to compare two types or to retrieve information identifying a type." }, { "code": null, "e": 2801, "s": 2752, "text": "Following is the declaration for std::type_info." }, { "code": null, "e": 2818, "s": 2801, "text": "class type_info;" }, { "code": null, "e": 2835, "s": 2818, "text": "class type_info;" }, { "code": null, "e": 2865, "s": 2835, "text": "It contains type information." }, { "code": null, "e": 2913, "s": 2865, "text": "It throws exception on failure to dynamic cast." }, { "code": null, "e": 2959, "s": 2913, "text": "It throws exception on typeid of null pointe." }, { "code": null, "e": 3007, "s": 2959, "text": "It throws exception on failure to dynamic cast." }, { "code": null, "e": 3053, "s": 3007, "text": "It throws exception on typeid of null pointe." }, { "code": null, "e": 3060, "s": 3053, "text": " Print" }, { "code": null, "e": 3071, "s": 3060, "text": " Add Notes" } ]
Angular Material - Progress Bars
The md-progress-circular and md-progress-linear are Angular progress directives, and are used to show loading content message in application. The following table lists out the parameters and description of the different attributes of md-progress-circular. * md-mode Select from one of the two modes: 'determinate' and 'indeterminate'. If the md-mode value is set as undefined or specified as not 1 of the two (2) valid modes, then .ng-hide will be auto-applied as a style to the component; if not configured, the md-mode = "indeterminate" will be auto injected as an attribute. If value = "" is also specified, however, then md-mode = "determinate" will be autoinjected instead. value In determinate mode, this number represents the percentage of the circular progress. By default, this is 0. md-diameter This specifies the diameter of the circular progress. The value may be a percentage (eg '25%') or a pixel-size value (eg '48'). If this attribute is not present, then a default value of '48px' is assumed. The following example shows the use of the md-progress-circular directive and also the uses of circular progress bars. am_circularprogressbars.htm <html lang = "en"> <head> <link rel = "stylesheet" href = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script> <link rel = "stylesheet" href = "https://fonts.googleapis.com/icon?family=Material+Icons"> <script language = "javascript"> angular .module('firstApplication', ['ngMaterial']) .controller('progressbarsController', progressbarsController); function progressbarsController ($scope, $interval) { var self = this, j = 0, counter = 0; self.modes = [ ]; self.activated = true; self.determinateValue = 30; self.toggleActivation = function() { if ( !self.activated ) self.modes = [ ]; if ( self.activated ) j = counter = 0; }; $interval(function() { self.determinateValue += 1; if (self.determinateValue > 100) { self.determinateValue = 30; } if ( (j < 5) && !self.modes[j] && self.activated ) { self.modes[j] = 'indeterminate'; } if ( counter++ % 4 == 0 ) j++; }, 100, 0, true); } </script> </head> <body ng-app = "firstApplication"> <div id = "progressbarsContainer" ng-controller = "progressbarsController as ctrl" layout = "column" ng-cloak> <h4 style = "margin-top:10px">Determinate </h4><p></p> <div layout = "row" layout-sm = "column" layout-align = "space-around"> <md-progress-circular md-mode = "determinate" value = "{{ctrl.determinateValue}}"></md-progress-circular> </div> <h4 style = "margin-top:10px">Indeterminate </h4> <div layout = "row" layout-sm = "column" layout-align = "space-around"> <md-progress-circular md-mode = "indeterminate"></md-progress-circular> </div> <h4 style = "margin-top:10px">Theme Based</h4> <div layout = "row" layout-sm = "column" layout-align = "space-around"> <md-progress-circular class = "md-hue-2" md-mode = "{{ctrl.modes[0]}}" md-diameter = "20px"></md-progress-circular> <md-progress-circular class = "md-accent" md-mode = "{{ctrl.modes[1]}}" md-diameter = "40"></md-progress-circular> <md-progress-circular class = "md-accent md-hue-1" md-mode = "{{ctrl.modes[2]}}" md-diameter = "60"></md-progress-circular> <md-progress-circular class = "md-warn md-hue-3" md-mode = "{{ctrl.modes[3]}}" md-diameter = "70"></md-progress-circular> <md-progress-circular md-mode = "{{ctrl.modes[4]}}" md-diameter = "96"> </md-progress-circular> </div> <hr ng-class = "{'visible' : ctrl.activated}"> <div id = "loaders" layout = "row" layout-align = "start center"> <p>Progress Circular Indicators: </p> <h5>Off</h5> <md-switch ng-model = "ctrl.activated" ng-change = "ctrl.toggleActivation()" aria-label = "Toggle Progress Circular Indicators"> <h5>On</h5> </md-switch> </div> </div> </body> </html> Verify the result. Progress Circular Indicators: . The following table lists out the parameters and description of the different attributes of md-progress-linear. * md-mode Select from one of the two modes: 'determinate' and 'indeterminate'. If the md-mode value is set as undefined or specified as not 1 of the two (2) valid modes, then .ng-hide will be auto-applied as a style to the component; if not configured, the md-mode = "indeterminate" will be auto injected as an attribute. If value = "" is also specified, however, then md-mode="determinate" will be auto-injected instead. md-buffer-value In determinate mode, this number represents the percentage of the primary progress bar. By default, this is 0. md-diameter In the buffer mode, this number represents the percentage of the secondary progress bar. By default, this is 0. The following example shows the use of the md-progress-circular directive and also the uses of linear progress bars. am_linearprogressbars.htm <html lang = "en"> <head> <link rel = "stylesheet" href = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script> <link rel = "stylesheet" href = "https://fonts.googleapis.com/icon?family=Material+Icons"> <script language = "javascript"> angular .module('firstApplication', ['ngMaterial']) .controller('progressbarsController', progressbarsController); function progressbarsController ($scope, $interval) { var self = this, j = 0, counter = 0; self.modes = [ ]; self.activated = true; self.determinateValue = 30; self.toggleActivation = function() { if ( !self.activated ) self.modes = [ ]; if ( self.activated ) j = counter = 0; }; $interval(function() { self.determinateValue += 1; if (self.determinateValue > 100) { self.determinateValue = 30; } if ( (j < 5) && !self.modes[j] && self.activated ) { self.modes[j] = 'indeterminate'; } if ( counter++ % 4 == 0 ) j++; }, 100, 0, true); } </script> </head> <body ng-app = "firstApplication"> <div id = "progressbarsContainer" ng-controller = "progressbarsController as ctrl" layout = "column" ng-cloak> <h4 style = "margin-top:10px">Determinate </h4><p></p> <div layout = "row" layout-sm = "column" layout-align = "space-around"> <md-progress-linear md-mode = "determinate" value = "{{ctrl.determinateValue}}"></md-progress-circular> </div> <h4 style = "margin-top:10px">Indeterminate </h4> <div layout = "row" layout-sm = "column" layout-align = "space-around"> <md-progress-linear md-mode = "indeterminate"></md-progress-circular> </div> <h4 style = "margin-top:10px">Buffer</h4> <div layout = "row" layout-sm = "column" layout-align = "space-around"> <md-progress-linear class = "md-warn" md-mode = "{{ctrl.modes[0]}}" value = "{{ctrl.determinateValue}}" md-buffer-value = "{{ctrl.determinateValue2}}"></md-progress-linear> </div> <hr ng-class = "{'visible' : ctrl.activated}"> <div id = "loaders" layout = "row" layout-align = "start center"> <p>Progress Buffer Indicators: </p> <h5>Off</h5> <md-switch ng-model = "ctrl.activated" ng-change = "ctrl.toggleActivation()" aria-label = "Toggle Buffer Progress Indicators"> <h5>On</h5> </md-switch> </div> </div> </body> </html> Verify the result. Progress Buffer Indicators: . 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": 2332, "s": 2190, "text": "The md-progress-circular and md-progress-linear are Angular progress directives, and are used to show loading content message in application." }, { "code": null, "e": 2446, "s": 2332, "text": "The following table lists out the parameters and description of the different attributes of md-progress-circular." }, { "code": null, "e": 2456, "s": 2446, "text": "* md-mode" }, { "code": null, "e": 2869, "s": 2456, "text": "Select from one of the two modes: 'determinate' and 'indeterminate'. If the md-mode value is set as undefined or specified as not 1 of the two (2) valid modes, then .ng-hide will be auto-applied as a style to the component; if not configured, the md-mode = \"indeterminate\" will be auto injected as an attribute. If value = \"\" is also specified, however, then md-mode = \"determinate\" will be autoinjected instead." }, { "code": null, "e": 2875, "s": 2869, "text": "value" }, { "code": null, "e": 2983, "s": 2875, "text": "In determinate mode, this number represents the percentage of the circular progress. By default, this is 0." }, { "code": null, "e": 2995, "s": 2983, "text": "md-diameter" }, { "code": null, "e": 3200, "s": 2995, "text": "This specifies the diameter of the circular progress. The value may be a percentage (eg '25%') or a pixel-size value (eg '48'). If this attribute is not present, then a default value of '48px' is assumed." }, { "code": null, "e": 3319, "s": 3200, "text": "The following example shows the use of the md-progress-circular directive and also the uses of circular progress bars." }, { "code": null, "e": 3347, "s": 3319, "text": "am_circularprogressbars.htm" }, { "code": null, "e": 7392, "s": 3347, "text": "<html lang = \"en\">\n <head>\n <link rel = \"stylesheet\"\n href = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js\"></script>\n <link rel = \"stylesheet\" href = \"https://fonts.googleapis.com/icon?family=Material+Icons\">\n \n <script language = \"javascript\">\n angular\n .module('firstApplication', ['ngMaterial'])\n .controller('progressbarsController', progressbarsController);\n\n function progressbarsController ($scope, $interval) {\n var self = this, j = 0, counter = 0;\n self.modes = [ ];\n self.activated = true;\n self.determinateValue = 30;\n \n self.toggleActivation = function() {\n if ( !self.activated ) self.modes = [ ];\n if ( self.activated ) j = counter = 0;\n };\n \n $interval(function() {\n self.determinateValue += 1;\n\n if (self.determinateValue > 100) {\n self.determinateValue = 30;\n }\n \n if ( (j < 5) && !self.modes[j] && self.activated ) {\n self.modes[j] = 'indeterminate';\n }\n if ( counter++ % 4 == 0 ) j++;\n }, 100, 0, true);\n }\n </script> \n </head>\n \n <body ng-app = \"firstApplication\"> \n <div id = \"progressbarsContainer\" ng-controller = \"progressbarsController as ctrl\"\n layout = \"column\" ng-cloak>\n \n <h4 style = \"margin-top:10px\">Determinate </h4><p></p>\n <div layout = \"row\" layout-sm = \"column\" layout-align = \"space-around\">\n <md-progress-circular md-mode = \"determinate\"\n value = \"{{ctrl.determinateValue}}\"></md-progress-circular>\n </div>\n \n <h4 style = \"margin-top:10px\">Indeterminate </h4>\n <div layout = \"row\" layout-sm = \"column\" layout-align = \"space-around\">\n <md-progress-circular md-mode = \"indeterminate\"></md-progress-circular>\n </div>\n \n <h4 style = \"margin-top:10px\">Theme Based</h4>\n <div layout = \"row\" layout-sm = \"column\" layout-align = \"space-around\">\n <md-progress-circular class = \"md-hue-2\" md-mode = \"{{ctrl.modes[0]}}\" \n md-diameter = \"20px\"></md-progress-circular>\n \n <md-progress-circular class = \"md-accent\" md-mode = \"{{ctrl.modes[1]}}\"\n md-diameter = \"40\"></md-progress-circular>\n \n <md-progress-circular class = \"md-accent md-hue-1\" md-mode = \"{{ctrl.modes[2]}}\"\n md-diameter = \"60\"></md-progress-circular>\n \n <md-progress-circular class = \"md-warn md-hue-3\" md-mode = \"{{ctrl.modes[3]}}\"\n md-diameter = \"70\"></md-progress-circular>\n \n <md-progress-circular md-mode = \"{{ctrl.modes[4]}}\" md-diameter = \"96\">\n </md-progress-circular>\n </div>\n \n <hr ng-class = \"{'visible' : ctrl.activated}\">\n <div id = \"loaders\" layout = \"row\" layout-align = \"start center\">\n <p>Progress Circular Indicators: </p>\n <h5>Off</h5>\n <md-switch\n ng-model = \"ctrl.activated\"\n ng-change = \"ctrl.toggleActivation()\"\n aria-label = \"Toggle Progress Circular Indicators\">\n <h5>On</h5>\n </md-switch>\n </div>\n \n </div>\n </body>\n</html>" }, { "code": null, "e": 7411, "s": 7392, "text": "Verify the result." }, { "code": null, "e": 7444, "s": 7411, "text": "Progress Circular Indicators: ." }, { "code": null, "e": 7556, "s": 7444, "text": "The following table lists out the parameters and description of the different attributes of md-progress-linear." }, { "code": null, "e": 7566, "s": 7556, "text": "* md-mode" }, { "code": null, "e": 7978, "s": 7566, "text": "Select from one of the two modes: 'determinate' and 'indeterminate'. If the md-mode value is set as undefined or specified as not 1 of the two (2) valid modes, then .ng-hide will be auto-applied as a style to the component; if not configured, the md-mode = \"indeterminate\" will be auto injected as an attribute. If value = \"\" is also specified, however, then md-mode=\"determinate\" will be auto-injected instead." }, { "code": null, "e": 7994, "s": 7978, "text": "md-buffer-value" }, { "code": null, "e": 8105, "s": 7994, "text": "In determinate mode, this number represents the percentage of the primary progress bar. By default, this is 0." }, { "code": null, "e": 8117, "s": 8105, "text": "md-diameter" }, { "code": null, "e": 8229, "s": 8117, "text": "In the buffer mode, this number represents the percentage of the secondary progress bar. By default, this is 0." }, { "code": null, "e": 8346, "s": 8229, "text": "The following example shows the use of the md-progress-circular directive and also the uses of linear progress bars." }, { "code": null, "e": 8372, "s": 8346, "text": "am_linearprogressbars.htm" }, { "code": null, "e": 11873, "s": 8372, "text": "<html lang = \"en\">\n <head>\n <link rel = \"stylesheet\"\n href = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js\"></script>\n <link rel = \"stylesheet\" href = \"https://fonts.googleapis.com/icon?family=Material+Icons\">\n \n <script language = \"javascript\">\n angular\n .module('firstApplication', ['ngMaterial'])\n .controller('progressbarsController', progressbarsController);\n\n function progressbarsController ($scope, $interval) {\n var self = this, j = 0, counter = 0;\n self.modes = [ ];\n self.activated = true;\n self.determinateValue = 30;\n \n self.toggleActivation = function() {\n if ( !self.activated ) self.modes = [ ];\n if ( self.activated ) j = counter = 0;\n };\n \n $interval(function() {\n self.determinateValue += 1;\n if (self.determinateValue > 100) {\n self.determinateValue = 30;\n }\n \n if ( (j < 5) && !self.modes[j] && self.activated ) {\n self.modes[j] = 'indeterminate';\n }\n \n if ( counter++ % 4 == 0 ) j++;\n }, 100, 0, true);\n }\n </script> \n </head>\n \n <body ng-app = \"firstApplication\"> \n <div id = \"progressbarsContainer\" ng-controller = \"progressbarsController as ctrl\"\n layout = \"column\" ng-cloak>\n \n <h4 style = \"margin-top:10px\">Determinate </h4><p></p>\n <div layout = \"row\" layout-sm = \"column\" layout-align = \"space-around\">\n <md-progress-linear md-mode = \"determinate\"\n value = \"{{ctrl.determinateValue}}\"></md-progress-circular>\n </div>\n \n <h4 style = \"margin-top:10px\">Indeterminate </h4>\n <div layout = \"row\" layout-sm = \"column\" layout-align = \"space-around\">\n <md-progress-linear md-mode = \"indeterminate\"></md-progress-circular>\n </div>\n \n <h4 style = \"margin-top:10px\">Buffer</h4>\n <div layout = \"row\" layout-sm = \"column\" layout-align = \"space-around\">\n <md-progress-linear class = \"md-warn\" md-mode = \"{{ctrl.modes[0]}}\"\n value = \"{{ctrl.determinateValue}}\"\n md-buffer-value = \"{{ctrl.determinateValue2}}\"></md-progress-linear>\n </div>\n \n <hr ng-class = \"{'visible' : ctrl.activated}\">\n <div id = \"loaders\" layout = \"row\" layout-align = \"start center\">\n <p>Progress Buffer Indicators: </p>\n <h5>Off</h5>\n <md-switch\n ng-model = \"ctrl.activated\"\n ng-change = \"ctrl.toggleActivation()\"\n aria-label = \"Toggle Buffer Progress Indicators\">\n <h5>On</h5>\n </md-switch>\n </div>\n \n </div>\n </body>\n</html>" }, { "code": null, "e": 11892, "s": 11873, "text": "Verify the result." }, { "code": null, "e": 11923, "s": 11892, "text": "Progress Buffer Indicators: ." }, { "code": null, "e": 11958, "s": 11923, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 11972, "s": 11958, "text": " Anadi Sharma" }, { "code": null, "e": 12007, "s": 11972, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 12021, "s": 12007, "text": " Anadi Sharma" }, { "code": null, "e": 12056, "s": 12021, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 12076, "s": 12056, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 12111, "s": 12076, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 12128, "s": 12111, "text": " Frahaan Hussain" }, { "code": null, "e": 12161, "s": 12128, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 12173, "s": 12161, "text": " Senol Atac" }, { "code": null, "e": 12208, "s": 12173, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 12220, "s": 12208, "text": " Senol Atac" }, { "code": null, "e": 12227, "s": 12220, "text": " Print" }, { "code": null, "e": 12238, "s": 12227, "text": " Add Notes" } ]
GRE Algebra | Coordinate Geometry | Set 2 - GeeksforGeeks
21 Jan, 2021 Prerequisite – GRE Algebra | Coordinate Geometry Geometry is the branch of mathematics that is concerned with property and relation between points, lines, solids, surfaces, and high dimensional objects. Coordinate geometry is the branch of mathematics that deals with two-dimensional figures i.e. x-axis and y-axis in the plane. The X-axis signifies the horizontal plane while Y-axis signifies the vertical plane. Example : A point is denoted by a combination of both the X-axis and the Y-axis. Points M, N, and L all are points denoted on a two-dimensional plane with X and Y values. M, N, and L have 2, -2, and -3 respectively as their X-axis values while 1.5, -3, and 1.5 respectively as their Y-axis values. Number line : The number line is a ruler that increases in both directions as per our choice of measurement. On the number line, we can tell where any number is positioned with respect to the origin. Representing a number on a number line. 2 is represented on x-axis 2 points to the right of the origin. The number can be represented on both the axis, X-axis, and Y-axis. Representing X-axis values : Representing Y-axis values : Representation of range : If a number is positive we can represent it as shown in the figure below. Quadrant plane : X and Y values determine the different quadrant the point lies in. Four quadrants are there on basis of different combinations of x and y values. 1st Quadrant = X > 0: Y > 0; 2nd Quadrant = X < 0: Y > 0; 3rd Quadrant = X < 0; Y < 0; 4th Quadrant = X > 0; Y < 0; Lines in the plane : The relationship between two x and y has an equation like 2x + 4 = 8y, a line is formed. It can also be generalized in form of : y = mx + c m and c represent constant numbers. These are also called linear equation Slope of the line : In equation y = mx + c, m is called to the slope of the equation. m = Numerator / Denominator = Rise / Run = Change in Y /Change in X Positive Slope : When m > 0 Negative Slope : When m < 0 Intercept of a line : A point where a coordinate axis is intersected by a line is called an intercept. There are two types of intercept : X-intercept – It is where the line intercepts the x-axis. The X intercept is a point on the line where the value of Y is zero. In the diagram shown below (-4, 0) is the -4 is the x-intercept. Y-intercept – It is where the line intercepts the y-axis. The Y-intercept is a point on the line where the value of x is zero. In the diagram shown below (-0, 6) is the 6 is the y-intercept. Distance between two-point: Pythagoras theorem is used to calculate the distance between two points. For example, what is the distance between (1,3) and (7,-5) Steps to find the distance between two points : Draw a right triangle connecting the points. Find the length of two triangles by calculating the run and riseRise is equal to change in y-axis = 3 – (-5) = 8 (Vertical leg)Run is equal to change in x-axis = 7 -1 = 6 (Horizontal leg) Rise is equal to change in y-axis = 3 – (-5) = 8 (Vertical leg) Run is equal to change in x-axis = 7 -1 = 6 (Horizontal leg) Use Pythagoras theorem to calculate the distance which is the diagonal shown in right angle triangle diagram i.e. c62 + 82 = c236 + 64 = c2100 = c2c = 10 62 + 82 = c2 36 + 64 = c2 100 = c2 c = 10 The distance between the two points is 10 units. Intersection of two lines : Line in the coordinate plane is the relationship between two x and y has an equation like 2x + 4 = 8y. Values of x and y satisfy this equation like (2,1) 2x + 4 = 8y (2,1) 2*2 + 4 = 8*1 4 + 4 = 8 8 = 8 LHS is equal to RHS On the other hand point (3,1) doesn't lie on the line. 2*3 + 4 = 8*1 6 + 4 = 8 10 = 8 LHS is not equal to RHS So what do we mean by when two lines intersect in the coordinate plane? Two lines intersect in a coordinate plane means that at that particular point, both of the equations that are representing different line holds true for that particular point. That is, the pair of numbers (x,y) that represents the point of intersection solves equations. Finding this point is similar to solving these equations. You can find the intersection by using algebra more easily than by graphing two lines. At what point y = 2x - 8 intersect the line represented by 2x + 3y = 10. Let's solve these equations for x and y. y = 2x - 8 (equation 1) 2x = 10 - 3y (equation 2) Putting equation 2 in equation 1 y = 10 -3y - 8 4y = 2 y = 1/2 To find value of x, put value of x in equation 1 1/2 = 2x - 8 1 = 2(2x - 8) 1 = 4x - 16 4x = 1 + 16 4x = 17 x = 17/4 Thus, the point of intersection of two lines is (17/4, 1/2). If lines in a plane do not intersect, then the lines are parallel. In this case, there is NO pair of numbers(x, y) that satisfies both equations at the same time. Two linear equations can represent a single point, or they can represent parallel lines that never intersect. There is one other possibility: the two-equation might represent the same line. In this case, infinitely many points (x, y) along the line satisfy the two equations( which must actually be the same equation in disguise). Aptitude Picked placement GRE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GRE 2021 Preparation Test Series - Boost Your Preparation GRE | List of words to enhance your vocabulary with root alphabet ‘G’ GRE | List of words to enhance your vocabulary GRE Data Analysis | Counting Methods GRE | List of words to enhance your vocabulary with alphabet 'S' GRE Arithmetic | Percent GRE | List of words to enhance your vocabulary with alphabet 'V' GRE Data Analysis | Probability GRE | List of words to enhance your vocabulary with root alphabet 'H' GRE | List of words to enhance your vocabulary with alphabet 'M'
[ { "code": null, "e": 24740, "s": 24712, "text": "\n21 Jan, 2021" }, { "code": null, "e": 24789, "s": 24740, "text": "Prerequisite – GRE Algebra | Coordinate Geometry" }, { "code": null, "e": 24943, "s": 24789, "text": "Geometry is the branch of mathematics that is concerned with property and relation between points, lines, solids, surfaces, and high dimensional objects." }, { "code": null, "e": 25154, "s": 24943, "text": "Coordinate geometry is the branch of mathematics that deals with two-dimensional figures i.e. x-axis and y-axis in the plane. The X-axis signifies the horizontal plane while Y-axis signifies the vertical plane." }, { "code": null, "e": 25452, "s": 25154, "text": "Example : A point is denoted by a combination of both the X-axis and the Y-axis. Points M, N, and L all are points denoted on a two-dimensional plane with X and Y values. M, N, and L have 2, -2, and -3 respectively as their X-axis values while 1.5, -3, and 1.5 respectively as their Y-axis values." }, { "code": null, "e": 25466, "s": 25452, "text": "Number line :" }, { "code": null, "e": 25652, "s": 25466, "text": "The number line is a ruler that increases in both directions as per our choice of measurement. On the number line, we can tell where any number is positioned with respect to the origin." }, { "code": null, "e": 25756, "s": 25652, "text": "Representing a number on a number line. 2 is represented on x-axis 2 points to the right of the origin." }, { "code": null, "e": 25825, "s": 25756, "text": "The number can be represented on both the axis, X-axis, and Y-axis. " }, { "code": null, "e": 25854, "s": 25825, "text": "Representing X-axis values :" }, { "code": null, "e": 25883, "s": 25854, "text": "Representing Y-axis values :" }, { "code": null, "e": 25983, "s": 25883, "text": "Representation of range : If a number is positive we can represent it as shown in the figure below." }, { "code": null, "e": 26146, "s": 25983, "text": "Quadrant plane : X and Y values determine the different quadrant the point lies in. Four quadrants are there on basis of different combinations of x and y values." }, { "code": null, "e": 26175, "s": 26146, "text": "1st Quadrant = X > 0: Y > 0;" }, { "code": null, "e": 26204, "s": 26175, "text": "2nd Quadrant = X < 0: Y > 0;" }, { "code": null, "e": 26233, "s": 26204, "text": "3rd Quadrant = X < 0; Y < 0;" }, { "code": null, "e": 26262, "s": 26233, "text": "4th Quadrant = X > 0; Y < 0;" }, { "code": null, "e": 26283, "s": 26262, "text": "Lines in the plane :" }, { "code": null, "e": 26412, "s": 26283, "text": "The relationship between two x and y has an equation like 2x + 4 = 8y, a line is formed. It can also be generalized in form of :" }, { "code": null, "e": 26497, "s": 26412, "text": "y = mx + c\nm and c represent constant numbers.\nThese are also called linear equation" }, { "code": null, "e": 26517, "s": 26497, "text": "Slope of the line :" }, { "code": null, "e": 26583, "s": 26517, "text": "In equation y = mx + c, m is called to the slope of the equation." }, { "code": null, "e": 26652, "s": 26583, "text": "m = Numerator / Denominator = Rise / Run = Change in Y /Change in X" }, { "code": null, "e": 26680, "s": 26652, "text": "Positive Slope : When m > 0" }, { "code": null, "e": 26708, "s": 26680, "text": "Negative Slope : When m < 0" }, { "code": null, "e": 26731, "s": 26708, "text": "Intercept of a line : " }, { "code": null, "e": 26813, "s": 26731, "text": "A point where a coordinate axis is intersected by a line is called an intercept. " }, { "code": null, "e": 26848, "s": 26813, "text": "There are two types of intercept :" }, { "code": null, "e": 27040, "s": 26848, "text": "X-intercept – It is where the line intercepts the x-axis. The X intercept is a point on the line where the value of Y is zero. In the diagram shown below (-4, 0) is the -4 is the x-intercept." }, { "code": null, "e": 27231, "s": 27040, "text": "Y-intercept – It is where the line intercepts the y-axis. The Y-intercept is a point on the line where the value of x is zero. In the diagram shown below (-0, 6) is the 6 is the y-intercept." }, { "code": null, "e": 27259, "s": 27231, "text": "Distance between two-point:" }, { "code": null, "e": 27391, "s": 27259, "text": "Pythagoras theorem is used to calculate the distance between two points. For example, what is the distance between (1,3) and (7,-5)" }, { "code": null, "e": 27439, "s": 27391, "text": "Steps to find the distance between two points :" }, { "code": null, "e": 27484, "s": 27439, "text": "Draw a right triangle connecting the points." }, { "code": null, "e": 27672, "s": 27484, "text": "Find the length of two triangles by calculating the run and riseRise is equal to change in y-axis = 3 – (-5) = 8 (Vertical leg)Run is equal to change in x-axis = 7 -1 = 6 (Horizontal leg)" }, { "code": null, "e": 27736, "s": 27672, "text": "Rise is equal to change in y-axis = 3 – (-5) = 8 (Vertical leg)" }, { "code": null, "e": 27797, "s": 27736, "text": "Run is equal to change in x-axis = 7 -1 = 6 (Horizontal leg)" }, { "code": null, "e": 27951, "s": 27797, "text": "Use Pythagoras theorem to calculate the distance which is the diagonal shown in right angle triangle diagram i.e. c62 + 82 = c236 + 64 = c2100 = c2c = 10" }, { "code": null, "e": 27964, "s": 27951, "text": "62 + 82 = c2" }, { "code": null, "e": 27977, "s": 27964, "text": "36 + 64 = c2" }, { "code": null, "e": 27986, "s": 27977, "text": "100 = c2" }, { "code": null, "e": 27993, "s": 27986, "text": "c = 10" }, { "code": null, "e": 28043, "s": 27993, "text": "The distance between the two points is 10 units. " }, { "code": null, "e": 28071, "s": 28043, "text": "Intersection of two lines :" }, { "code": null, "e": 28175, "s": 28071, "text": "Line in the coordinate plane is the relationship between two x and y has an equation like 2x + 4 = 8y. " }, { "code": null, "e": 28405, "s": 28175, "text": "Values of x and y satisfy this equation like (2,1)\n2x + 4 = 8y (2,1)\n2*2 + 4 = 8*1\n4 + 4 = 8\n8 = 8\nLHS is equal to RHS\nOn the other hand point (3,1) doesn't lie on the line.\n2*3 + 4 = 8*1\n6 + 4 = 8\n10 = 8\nLHS is not equal to RHS" }, { "code": null, "e": 28893, "s": 28405, "text": "So what do we mean by when two lines intersect in the coordinate plane? Two lines intersect in a coordinate plane means that at that particular point, both of the equations that are representing different line holds true for that particular point. That is, the pair of numbers (x,y) that represents the point of intersection solves equations. Finding this point is similar to solving these equations. You can find the intersection by using algebra more easily than by graphing two lines." }, { "code": null, "e": 29300, "s": 28893, "text": "At what point y = 2x - 8 intersect the line represented by 2x + 3y = 10. \nLet's solve these equations for x and y.\ny = 2x - 8 (equation 1)\n2x = 10 - 3y (equation 2)\nPutting equation 2 in equation 1\ny = 10 -3y - 8\n4y = 2\ny = 1/2\nTo find value of x, put value of x in equation 1\n1/2 = 2x - 8\n1 = 2(2x - 8)\n1 = 4x - 16\n4x = 1 + 16\n4x = 17\nx = 17/4\nThus, the point of intersection of two lines is (17/4, 1/2)." }, { "code": null, "e": 29464, "s": 29300, "text": "If lines in a plane do not intersect, then the lines are parallel. In this case, there is NO pair of numbers(x, y) that satisfies both equations at the same time. " }, { "code": null, "e": 29795, "s": 29464, "text": "Two linear equations can represent a single point, or they can represent parallel lines that never intersect. There is one other possibility: the two-equation might represent the same line. In this case, infinitely many points (x, y) along the line satisfy the two equations( which must actually be the same equation in disguise)." }, { "code": null, "e": 29804, "s": 29795, "text": "Aptitude" }, { "code": null, "e": 29811, "s": 29804, "text": "Picked" }, { "code": null, "e": 29821, "s": 29811, "text": "placement" }, { "code": null, "e": 29825, "s": 29821, "text": "GRE" }, { "code": null, "e": 29923, "s": 29825, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29981, "s": 29923, "text": "GRE 2021 Preparation Test Series - Boost Your Preparation" }, { "code": null, "e": 30051, "s": 29981, "text": "GRE | List of words to enhance your vocabulary with root alphabet ‘G’" }, { "code": null, "e": 30098, "s": 30051, "text": "GRE | List of words to enhance your vocabulary" }, { "code": null, "e": 30135, "s": 30098, "text": "GRE Data Analysis | Counting Methods" }, { "code": null, "e": 30200, "s": 30135, "text": "GRE | List of words to enhance your vocabulary with alphabet 'S'" }, { "code": null, "e": 30225, "s": 30200, "text": "GRE Arithmetic | Percent" }, { "code": null, "e": 30290, "s": 30225, "text": "GRE | List of words to enhance your vocabulary with alphabet 'V'" }, { "code": null, "e": 30322, "s": 30290, "text": "GRE Data Analysis | Probability" }, { "code": null, "e": 30392, "s": 30322, "text": "GRE | List of words to enhance your vocabulary with root alphabet 'H'" } ]
C++11 reverse range-based for-loop
To get the reversed range-based for loop, we have used boost library. This boost library is vepy popular and it has some strong functionalities. Here we can use some array or containers, then by using boost::adaptors::reverse() we can use the range base for loop in reverse order. #include <list;> #include <iostream> #include <boost/range/adaptor/reversed.hpp> using namespace std; int main() { std::list<int> x {11, 44, 77, 55, 44, 22, 33, 30, 88, 99, 55, 44}; cout >> "Normal Loop" >> endl; for (auto i : x) std::cout >> i >> '\n'; cout >> "Reversed Loop" >> endl; for (auto i : boost::adaptors::reverse(x)) std::cout >> i >> '\n'; } Normal Loop 11 44 77 55 44 22 33 30 88 99 55 44 Reversed Loop 44 55 99 88 30 33 22 44 55 77 44 11
[ { "code": null, "e": 1207, "s": 1062, "text": "To get the reversed range-based for loop, we have used boost library. This boost library is vepy popular and it has some strong functionalities." }, { "code": null, "e": 1343, "s": 1207, "text": "Here we can use some array or containers, then by using boost::adaptors::reverse() we can use the range base for loop in reverse order." }, { "code": null, "e": 1726, "s": 1343, "text": "#include <list;>\n#include <iostream>\n#include <boost/range/adaptor/reversed.hpp>\nusing namespace std;\nint main() {\n std::list<int> x {11, 44, 77, 55, 44, 22, 33, 30, 88, 99, 55, 44};\n cout >> \"Normal Loop\" >> endl;\n for (auto i : x)\n std::cout >> i >> '\\n';\n cout >> \"Reversed Loop\" >> endl;\n for (auto i : boost::adaptors::reverse(x))\n std::cout >> i >> '\\n';\n}" }, { "code": null, "e": 1824, "s": 1726, "text": "Normal Loop\n11\n44\n77\n55\n44\n22\n33\n30\n88\n99\n55\n44\nReversed Loop\n44\n55\n99\n88\n30\n33\n22\n44\n55\n77\n44\n11" } ]
How to check which packages are loaded in R?
We can do this by using sessionInfo(). > sessionInfo() R version 3.6.1 (2019-07-05) Platform: x86_64-w64-mingw32/x64 (64-bit) Running under: Windows 10 x64 (build 18363) Matrix products: default Random number generation: RNG: Mersenne-Twister Normal: Inversion Sample: Rounding locale: [1] LC_COLLATE=English_India.1252 LC_CTYPE=English_India.1252 [3] LC_MONETARY=English_India.1252 LC_NUMERIC=C [5] LC_TIME=English_India.1252 attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] ggplot2_3.2.1 loaded via a namespace (and not attached): [1] Rcpp_1.0.2 withr_2.1.2 crayon_1.3.4 dplyr_0.8.3 [5] assertthat_0.2.1 grid_3.6.1 R6_2.4.0 gtable_0.3.0 [9] magrittr_1.5 scales_1.0.0 pillar_1.4.2 rlang_0.4.0 [13] lazyeval_0.2.2 glue_1.3.1 purrr_0.3.2 munsell_0.5.0 [17] compiler_3.6.1 pkgconfig_2.0.2 colorspace_1.4-1 tidyselect_0.2.5 [21] tibble_2.1.3 So here we have base packages and ggplot2 version 3.2.1 package currently loaded in my R.
[ { "code": null, "e": 1101, "s": 1062, "text": "We can do this by using sessionInfo()." }, { "code": null, "e": 1962, "s": 1101, "text": "> sessionInfo()\nR version 3.6.1 (2019-07-05)\nPlatform: x86_64-w64-mingw32/x64 (64-bit)\nRunning under: Windows 10 x64 (build 18363)\nMatrix products: default\nRandom number generation:\nRNG: Mersenne-Twister\nNormal: Inversion\nSample: Rounding\nlocale:\n[1] LC_COLLATE=English_India.1252 LC_CTYPE=English_India.1252\n[3] LC_MONETARY=English_India.1252 LC_NUMERIC=C\n[5] LC_TIME=English_India.1252\nattached base packages:\n[1] stats graphics grDevices utils datasets methods base\nother attached packages:\n[1] ggplot2_3.2.1\nloaded via a namespace (and not attached):\n[1] Rcpp_1.0.2 withr_2.1.2 crayon_1.3.4 dplyr_0.8.3\n[5] assertthat_0.2.1 grid_3.6.1 R6_2.4.0 gtable_0.3.0\n[9] magrittr_1.5 scales_1.0.0 pillar_1.4.2 rlang_0.4.0\n[13] lazyeval_0.2.2 glue_1.3.1 purrr_0.3.2 munsell_0.5.0\n[17] compiler_3.6.1 pkgconfig_2.0.2 colorspace_1.4-1 tidyselect_0.2.5\n[21] tibble_2.1.3" }, { "code": null, "e": 2052, "s": 1962, "text": "So here we have base packages and ggplot2 version 3.2.1 package currently loaded in my\nR." } ]
Area of circle inscribed in a Isosceles Trapezoid - GeeksforGeeks
22 Feb, 2022 Given two bases of the isosceles trapezoid ABCD as a and b, the task is to find the area of circle inscribed in this trapezoid Examples: Input: a = 10, b = 30 Output: Area = 235.57 Input: a = 20, b = 36 Output: Area = 565.38 Derivation: Given a circle inscribed in trapezium ABCD (sides AB = n and CD = m), we need to find out the height of the trapezium i.e., (AL), which is half of the radius of the circle to find the area of the circle. For finding the height of circle we do following operation. The circle will always touch the sides of trapezium at their midpoints, Say the midpoints of AB, BD, CD, AC are G, F, H, E, and join them with the center of the circle.Now from Symmetry, we can see that The circle will always touch the sides of trapezium at their midpoints, Say the midpoints of AB, BD, CD, AC are G, F, H, E, and join them with the center of the circle. Now from Symmetry, we can see that AG = AE = n/2, EC = CG = m/2, HD = DF = n/2, GB = FB = m/2 Now in Triangle ACL apply the Pythagoras theorem. Now in Triangle ACL apply the Pythagoras theorem. Hypotenuse AC = m/2 + n/2 Base CL = CH - AG = m/2 - n/2 we get Perpendicular AL = Square_root(m * n) Therefore the height of the Trapezium = AL = Square_Root(Product of given sides)Now the radius of the circle is simple half of the height and hence the area can be calculated easily. Therefore the height of the Trapezium = AL = Square_Root(Product of given sides) Now the radius of the circle is simple half of the height and hence the area can be calculated easily. Approach: Find the height of the trapezoid as (square_root( m * n )).Find the radius of the incircle Find the height of the trapezoid as (square_root( m * n )). Find the radius of the incircle R = height / 2 = square_root(m * n) / 2 Now find the area of the circle Now find the area of the circle = Pi * R2 = ( 3.141 * m * n ) / 4 Below is the implementation of the above approach: C++ Java Python3 C# Javascript // CPP implementation to find// the area of the circle// inscribed in a trapezoid// having non- parallel sides m, n#include<bits/stdc++.h>using namespace std; // Function to find area of circle// inscribed in a trapezoid// having non- parallel sides m, ndouble area_of_circle(int m, int n){ // radius of circle by the // formula i.e. root( m * n) / 2 // area of circle = (3.141 ) * ( R ** 2 ) int square_of_radius = ( m * n ) / 4; double area = ( 3.141 * square_of_radius ); return area;} // Driver Codeint main(){ int n = 10; int m = 30; cout << (area_of_circle(m, n));} // This code is contributed by mohit kumar 29 // Java Program to find// the area of the circle// inscribed in a trapezoid// having non- parallel sides m, nclass GFG{ // Function to find area of circle // inscribed in a trapezoid // having non- parallel sides m, n static double area_of_circle(int m, int n) { // radius of circle by the // formula i.e. root( m * n) / 2 // area of circle = (3.141 ) * ( R ** 2 ) int square_of_radius = ( m * n ) / 4; double area = ( 3.141 * square_of_radius ); return area; } // Driver code public static void main (String[] args) { int n = 10; int m = 30; System.out.println(area_of_circle(m, n)); }} // This code is contributed by Yash_R # Python 3 implementation to find# the area of the circle# inscribed in a trapezoid# having non- parallel sides m, n # Function to find area of circle# inscribed in a trapezoid# having non- parallel sides m, ndef area_of_circle(m, n): # radius of circle by the # formula i.e. root( m * n) / 2 # area of circle = (3.141 ) * ( R ** 2 ) square_of_radius = ( m * n ) / 4 area = ( 3.141 * square_of_radius ) return area # Driver Codeif __name__=='__main__': n = 10 m = 30 print(area_of_circle(m, n)) // C# Program to find// the area of the circle// inscribed in a trapezoid// having non- parallel sides m, nusing System; class GFG{ // Function to find area of circle// inscribed in a trapezoid// having non- parallel sides m, nstatic double area_of_circle(int m, int n){ // radius of circle by the // formula i.e. root( m * n) / 2 // area of circle = (3.141 ) * ( R ** 2 ) int square_of_radius = ( m * n ) / 4; double area = ( 3.141 * square_of_radius ); return area;} // Driver codepublic static void Main (){ int n = 10; int m = 30; Console.WriteLine(area_of_circle(m, n));}} // This code is contributed by Sanjit_Prasad <script> // Javascript Program to find// the area of the circle// inscribed in a trapezoid// having non- parallel sides m, n // Function to find area of circle// inscribed in a trapezoid// having non- parallel sides m, nfunction area_of_circle(m, n){ // Radius of circle by the // formula i.e. root( m * n) / 2 // area of circle = (3.141 ) * ( R ** 2 ) var square_of_radius = ( m * n ) / 4; var area = ( 3.141 * square_of_radius ); return area;} // Driver Codevar n = 10;var m = 30; document.write(area_of_circle(m, n)); // This code is contributed by Khushboogoyal499 </script> 235.575 mohit kumar 29 Sanjit_Prasad Yash_R khushboogoyal499 varshagumber28 sumitgumber28 simmytarika5 area-volume-programs Aptitude Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments | | Question 44 Puzzle | How much money did the man have before entering the bank? Order and Ranking Questions & Answers Aptitude | GATE CS 1998 | Question 77 Seating Arrangement | Aptitude Circle and Lattice Points Closest Pair of Points using Divide and Conquer algorithm How to check if two given line segments intersect? Program for distance between two points on earth How to check if a given point lies inside or outside a polygon?
[ { "code": null, "e": 24599, "s": 24571, "text": "\n22 Feb, 2022" }, { "code": null, "e": 24727, "s": 24599, "text": "Given two bases of the isosceles trapezoid ABCD as a and b, the task is to find the area of circle inscribed in this trapezoid " }, { "code": null, "e": 24739, "s": 24727, "text": "Examples: " }, { "code": null, "e": 24830, "s": 24739, "text": "Input: a = 10, b = 30 \nOutput: Area = 235.57\n\nInput: a = 20, b = 36 \nOutput: Area = 565.38" }, { "code": null, "e": 25046, "s": 24830, "text": "Derivation: Given a circle inscribed in trapezium ABCD (sides AB = n and CD = m), we need to find out the height of the trapezium i.e., (AL), which is half of the radius of the circle to find the area of the circle." }, { "code": null, "e": 25107, "s": 25046, "text": "For finding the height of circle we do following operation. " }, { "code": null, "e": 25312, "s": 25107, "text": "The circle will always touch the sides of trapezium at their midpoints, Say the midpoints of AB, BD, CD, AC are G, F, H, E, and join them with the center of the circle.Now from Symmetry, we can see that " }, { "code": null, "e": 25481, "s": 25312, "text": "The circle will always touch the sides of trapezium at their midpoints, Say the midpoints of AB, BD, CD, AC are G, F, H, E, and join them with the center of the circle." }, { "code": null, "e": 25518, "s": 25481, "text": "Now from Symmetry, we can see that " }, { "code": null, "e": 25579, "s": 25518, "text": "AG = AE = n/2, \nEC = CG = m/2, \nHD = DF = n/2,\nGB = FB = m/2" }, { "code": null, "e": 25631, "s": 25579, "text": "Now in Triangle ACL apply the Pythagoras theorem. " }, { "code": null, "e": 25683, "s": 25631, "text": "Now in Triangle ACL apply the Pythagoras theorem. " }, { "code": null, "e": 25786, "s": 25683, "text": "Hypotenuse AC = m/2 + n/2\nBase CL = CH - AG = m/2 - n/2\n\nwe get \nPerpendicular AL = Square_root(m * n)" }, { "code": null, "e": 25969, "s": 25786, "text": "Therefore the height of the Trapezium = AL = Square_Root(Product of given sides)Now the radius of the circle is simple half of the height and hence the area can be calculated easily." }, { "code": null, "e": 26050, "s": 25969, "text": "Therefore the height of the Trapezium = AL = Square_Root(Product of given sides)" }, { "code": null, "e": 26153, "s": 26050, "text": "Now the radius of the circle is simple half of the height and hence the area can be calculated easily." }, { "code": null, "e": 26165, "s": 26153, "text": "Approach: " }, { "code": null, "e": 26258, "s": 26165, "text": "Find the height of the trapezoid as (square_root( m * n )).Find the radius of the incircle " }, { "code": null, "e": 26318, "s": 26258, "text": "Find the height of the trapezoid as (square_root( m * n ))." }, { "code": null, "e": 26352, "s": 26318, "text": "Find the radius of the incircle " }, { "code": null, "e": 26395, "s": 26352, "text": "R = height / 2 \n = square_root(m * n) / 2" }, { "code": null, "e": 26428, "s": 26395, "text": "Now find the area of the circle " }, { "code": null, "e": 26461, "s": 26428, "text": "Now find the area of the circle " }, { "code": null, "e": 26496, "s": 26461, "text": "= Pi * R2 \n= ( 3.141 * m * n ) / 4" }, { "code": null, "e": 26548, "s": 26496, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26552, "s": 26548, "text": "C++" }, { "code": null, "e": 26557, "s": 26552, "text": "Java" }, { "code": null, "e": 26565, "s": 26557, "text": "Python3" }, { "code": null, "e": 26568, "s": 26565, "text": "C#" }, { "code": null, "e": 26579, "s": 26568, "text": "Javascript" }, { "code": "// CPP implementation to find// the area of the circle// inscribed in a trapezoid// having non- parallel sides m, n#include<bits/stdc++.h>using namespace std; // Function to find area of circle// inscribed in a trapezoid// having non- parallel sides m, ndouble area_of_circle(int m, int n){ // radius of circle by the // formula i.e. root( m * n) / 2 // area of circle = (3.141 ) * ( R ** 2 ) int square_of_radius = ( m * n ) / 4; double area = ( 3.141 * square_of_radius ); return area;} // Driver Codeint main(){ int n = 10; int m = 30; cout << (area_of_circle(m, n));} // This code is contributed by mohit kumar 29", "e": 27225, "s": 26579, "text": null }, { "code": "// Java Program to find// the area of the circle// inscribed in a trapezoid// having non- parallel sides m, nclass GFG{ // Function to find area of circle // inscribed in a trapezoid // having non- parallel sides m, n static double area_of_circle(int m, int n) { // radius of circle by the // formula i.e. root( m * n) / 2 // area of circle = (3.141 ) * ( R ** 2 ) int square_of_radius = ( m * n ) / 4; double area = ( 3.141 * square_of_radius ); return area; } // Driver code public static void main (String[] args) { int n = 10; int m = 30; System.out.println(area_of_circle(m, n)); }} // This code is contributed by Yash_R", "e": 27959, "s": 27225, "text": null }, { "code": "# Python 3 implementation to find# the area of the circle# inscribed in a trapezoid# having non- parallel sides m, n # Function to find area of circle# inscribed in a trapezoid# having non- parallel sides m, ndef area_of_circle(m, n): # radius of circle by the # formula i.e. root( m * n) / 2 # area of circle = (3.141 ) * ( R ** 2 ) square_of_radius = ( m * n ) / 4 area = ( 3.141 * square_of_radius ) return area # Driver Codeif __name__=='__main__': n = 10 m = 30 print(area_of_circle(m, n))", "e": 28489, "s": 27959, "text": null }, { "code": "// C# Program to find// the area of the circle// inscribed in a trapezoid// having non- parallel sides m, nusing System; class GFG{ // Function to find area of circle// inscribed in a trapezoid// having non- parallel sides m, nstatic double area_of_circle(int m, int n){ // radius of circle by the // formula i.e. root( m * n) / 2 // area of circle = (3.141 ) * ( R ** 2 ) int square_of_radius = ( m * n ) / 4; double area = ( 3.141 * square_of_radius ); return area;} // Driver codepublic static void Main (){ int n = 10; int m = 30; Console.WriteLine(area_of_circle(m, n));}} // This code is contributed by Sanjit_Prasad", "e": 29144, "s": 28489, "text": null }, { "code": "<script> // Javascript Program to find// the area of the circle// inscribed in a trapezoid// having non- parallel sides m, n // Function to find area of circle// inscribed in a trapezoid// having non- parallel sides m, nfunction area_of_circle(m, n){ // Radius of circle by the // formula i.e. root( m * n) / 2 // area of circle = (3.141 ) * ( R ** 2 ) var square_of_radius = ( m * n ) / 4; var area = ( 3.141 * square_of_radius ); return area;} // Driver Codevar n = 10;var m = 30; document.write(area_of_circle(m, n)); // This code is contributed by Khushboogoyal499 </script>", "e": 29751, "s": 29144, "text": null }, { "code": null, "e": 29759, "s": 29751, "text": "235.575" }, { "code": null, "e": 29776, "s": 29761, "text": "mohit kumar 29" }, { "code": null, "e": 29790, "s": 29776, "text": "Sanjit_Prasad" }, { "code": null, "e": 29797, "s": 29790, "text": "Yash_R" }, { "code": null, "e": 29814, "s": 29797, "text": "khushboogoyal499" }, { "code": null, "e": 29829, "s": 29814, "text": "varshagumber28" }, { "code": null, "e": 29843, "s": 29829, "text": "sumitgumber28" }, { "code": null, "e": 29856, "s": 29843, "text": "simmytarika5" }, { "code": null, "e": 29877, "s": 29856, "text": "area-volume-programs" }, { "code": null, "e": 29886, "s": 29877, "text": "Aptitude" }, { "code": null, "e": 29896, "s": 29886, "text": "Geometric" }, { "code": null, "e": 29909, "s": 29896, "text": "Mathematical" }, { "code": null, "e": 29922, "s": 29909, "text": "Mathematical" }, { "code": null, "e": 29932, "s": 29922, "text": "Geometric" }, { "code": null, "e": 30030, "s": 29932, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30039, "s": 30030, "text": "Comments" }, { "code": null, "e": 30052, "s": 30039, "text": "Old Comments" }, { "code": null, "e": 30068, "s": 30052, "text": "| | Question 44" }, { "code": null, "e": 30135, "s": 30068, "text": "Puzzle | How much money did the man have before entering the bank?" }, { "code": null, "e": 30173, "s": 30135, "text": "Order and Ranking Questions & Answers" }, { "code": null, "e": 30211, "s": 30173, "text": "Aptitude | GATE CS 1998 | Question 77" }, { "code": null, "e": 30242, "s": 30211, "text": "Seating Arrangement | Aptitude" }, { "code": null, "e": 30268, "s": 30242, "text": "Circle and Lattice Points" }, { "code": null, "e": 30326, "s": 30268, "text": "Closest Pair of Points using Divide and Conquer algorithm" }, { "code": null, "e": 30377, "s": 30326, "text": "How to check if two given line segments intersect?" }, { "code": null, "e": 30426, "s": 30377, "text": "Program for distance between two points on earth" } ]
Java AWT | GridLayout Class - GeeksforGeeks
21 Aug, 2018 GridLayout class represents a layout manager with a specified number of rows and columns in a rectangular grid. The GridLayout container is divided into an equal-sized of rectangles, and one of the components is placed in each rectangle. Every rectangle cell has the same size therefore, they contain a component, which fills the entire cell. When the user changes or adjusts the size of the container, the size of each rectangles changes accordingly. Constructors of the class: GridLayout(): It Creates a grid layout with a default of one column per component, in a single row.GridLayout(int rw, int cl): It creates a grid layout with the specified number of rows and columns.GridLayout(int rw, int cl, int hgap, int vgap): It creates a grid layout with the specified number of rows and columns with horizontal and vertical gap. GridLayout(): It Creates a grid layout with a default of one column per component, in a single row. GridLayout(int rw, int cl): It creates a grid layout with the specified number of rows and columns. GridLayout(int rw, int cl, int hgap, int vgap): It creates a grid layout with the specified number of rows and columns with horizontal and vertical gap. Commonly Used Methods: addLayoutComponent(String str, Component cmp): Adds the specified component with the specified name to the layout. setColumns(int cl): Sets the number of columns in this layout to the specified value. setHgap(int hgap): Sets the horizontal gap between components to the specified value. setRows(int rw): Sets the number of rows in this layout to the specified value. setVgap(int vgap): Sets the vertical gap between components to the specified value. layoutContainer(Container pr): Lays out the specified container using this layout. toString(): Returns the string representation of this grid layout’s values. Below programs illustrate the GridLayout class: Program 1: In below program we are passing the argument in GridLayout. We create 4 JLabel components named “one“, “two“, “three“, “four” and create 2 JButton components named “buttonsave” and “buttonexit” and create 4 Jtextfield components named “tname“, “tcode“, “tdesig“, “tsalary” and all of add them to the JFrame by the method add(). We will set the visibility and size of the frame by using setVisible() and setSize() method. The layout is set by using setLayout() method.// Java program to illustrate the GridLayoutimport javax.swing.*;import java.awt.*; // class GridLayout extends JFramepublic class GridLayoutDemo extends JFrame { GridLayoutDemo() { // Creating Object P1 of JPanel class JPanel p1 = new JPanel(); // set the layout p1.setLayout(new GridLayout(4, 2)); // Creating Object of "FlowLayout" class FlowLayout layout = new FlowLayout(); // Creating Object P2 of JPanel class JPanel p2 = new JPanel(); // set the layout p2.setLayout(layout); // Declaration of objects of JLabel class. JLabel one, two, three, four; // Declaration of objects of JTextField class. JTextField tname, tsalary, tcode, tdesig; // Declaration of objects of JButton class. JButton buttonSave, buttonExit; // Initialization of object // "one" of JLabel class. one = new JLabel("NAME"); // Initialization of object // "tname" of JTextField class. tname = new JTextField(20); // Initialization of object // "two" of JLabel class. two = new JLabel("CODE"); // Initialization of object // "tcode" of JTextField class. tcode = new JTextField(20); // Initialization of object // "three" of JLabel class. three = new JLabel("DESIGNATION"); // Initialization of object // "tdesig" of JTextField class. tdesig = new JTextField(20); // Initialization of object // "four" of JLabel class. four = new JLabel("SALARY"); // Initialization of object // "tsalary" of JTextField class. tsalary = new JTextField(20); // Initialization of object // "buttonsave" of JButton class. buttonSave = new JButton("SAVE"); // Initialization of object // "buttonexit" of JButton class. buttonExit = new JButton("EXIT"); // Adding Jlabel "one" on JFrame. p1.add(one); // Adding JTextField "tname" on JFrame. p1.add(tname); // Adding Jlabel "two" on JFrame. p1.add(two); // Adding JTextField "tcode" on JFrame. p1.add(tcode); // Adding Jlabel "three" on JFrame. p1.add(three); // Adding JTextField "tdesig" on JFrame. p1.add(tdesig); // Adding Jlabel "four" on JFrame. p1.add(four); // Adding JTextField "tsalary" on JFrame. p1.add(tsalary); // Adding JButton "buttonsave" on JFrame. p2.add(buttonSave); // Adding JButton "buttonexit" on JFrame. p2.add(buttonExit); // add the p1 object which // refer to the Jpanel add(p1, "North"); // add the p2 object which // refer to the Jpanel add(p2, "South"); // Function to set visible // status of JFrame. setVisible(true); // this Keyword refers to current // object. Function to set size of JFrame. this.setSize(400, 180);} // Main Method public static void main(String args[]) { // calling the constructor new GridLayoutDemo(); }}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/Untitled-14.mp400:0000:0000:22Use Up/Down Arrow keys to increase or decrease volume. // Java program to illustrate the GridLayoutimport javax.swing.*;import java.awt.*; // class GridLayout extends JFramepublic class GridLayoutDemo extends JFrame { GridLayoutDemo() { // Creating Object P1 of JPanel class JPanel p1 = new JPanel(); // set the layout p1.setLayout(new GridLayout(4, 2)); // Creating Object of "FlowLayout" class FlowLayout layout = new FlowLayout(); // Creating Object P2 of JPanel class JPanel p2 = new JPanel(); // set the layout p2.setLayout(layout); // Declaration of objects of JLabel class. JLabel one, two, three, four; // Declaration of objects of JTextField class. JTextField tname, tsalary, tcode, tdesig; // Declaration of objects of JButton class. JButton buttonSave, buttonExit; // Initialization of object // "one" of JLabel class. one = new JLabel("NAME"); // Initialization of object // "tname" of JTextField class. tname = new JTextField(20); // Initialization of object // "two" of JLabel class. two = new JLabel("CODE"); // Initialization of object // "tcode" of JTextField class. tcode = new JTextField(20); // Initialization of object // "three" of JLabel class. three = new JLabel("DESIGNATION"); // Initialization of object // "tdesig" of JTextField class. tdesig = new JTextField(20); // Initialization of object // "four" of JLabel class. four = new JLabel("SALARY"); // Initialization of object // "tsalary" of JTextField class. tsalary = new JTextField(20); // Initialization of object // "buttonsave" of JButton class. buttonSave = new JButton("SAVE"); // Initialization of object // "buttonexit" of JButton class. buttonExit = new JButton("EXIT"); // Adding Jlabel "one" on JFrame. p1.add(one); // Adding JTextField "tname" on JFrame. p1.add(tname); // Adding Jlabel "two" on JFrame. p1.add(two); // Adding JTextField "tcode" on JFrame. p1.add(tcode); // Adding Jlabel "three" on JFrame. p1.add(three); // Adding JTextField "tdesig" on JFrame. p1.add(tdesig); // Adding Jlabel "four" on JFrame. p1.add(four); // Adding JTextField "tsalary" on JFrame. p1.add(tsalary); // Adding JButton "buttonsave" on JFrame. p2.add(buttonSave); // Adding JButton "buttonexit" on JFrame. p2.add(buttonExit); // add the p1 object which // refer to the Jpanel add(p1, "North"); // add the p2 object which // refer to the Jpanel add(p2, "South"); // Function to set visible // status of JFrame. setVisible(true); // this Keyword refers to current // object. Function to set size of JFrame. this.setSize(400, 180);} // Main Method public static void main(String args[]) { // calling the constructor new GridLayoutDemo(); }} Output: Program 2: In below program we are passing the argument in GridLayout. We create 5 JButton components named “btn1“, “btn2“, “btn3“, “btn4“, “btn5” and then add them to the JFrame by the method add(). We will set the visibility and size of the frame by using setvisible() and setsize() method. The layout is set by using setLayout() method.// Java program to illustrate the GridLayoutimport java.awt.*;import javax.swing.*; // create a class griddemopublic class Griddemo { // Main Methodpublic static void main(String[] args){ // Creating Object of JFrame class // with new name frame JFrame frame = new JFrame("GridLayout Demo"); // Initialization of object // "btn1" of JButton class. JButton btn1 = new JButton("Button 1"); // Initialization of object // "btn2" of JButton class. JButton btn2 = new JButton("Button 2"); // Initialization of object // "btn3" of JButton class. JButton btn3 = new JButton("Button 3"); // Initialization of object // "btn4" of JButton class. JButton btn4 = new JButton("Button 4"); // Initialization of object // "btn5" of JButton class. JButton btn5 = new JButton("Button 5"); // Creating Object Panel of JPanel class // create grid layout with 3 rows, // 2 columns with horizontal and // vertical gap set to 10 JPanel panel = new JPanel(new GridLayout(3, 2, 10, 10)); // Adding JButton "btn1" on JPanel. panel.add(btn1); // Adding JButton "btn2" on JPanel. panel.add(btn2); // Adding JButton "btn3" on JPanel. panel.add(btn3); // Adding JButton "btn4" on JPanel. panel.add(btn4); // Adding JButton "btn5" on JPanel. panel.add(btn5); // Function to close the operation of JFrame. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Function to set size of JFrame. frame.setSize(300, 150); // Function to get the content of JFrame. frame.getContentPane().add(panel); // Function to set visible status of JFrame. frame.setVisible(true);}}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/Untitled-13Trim-2.mp400:0000:0000:16Use Up/Down Arrow keys to increase or decrease volume. // Java program to illustrate the GridLayoutimport java.awt.*;import javax.swing.*; // create a class griddemopublic class Griddemo { // Main Methodpublic static void main(String[] args){ // Creating Object of JFrame class // with new name frame JFrame frame = new JFrame("GridLayout Demo"); // Initialization of object // "btn1" of JButton class. JButton btn1 = new JButton("Button 1"); // Initialization of object // "btn2" of JButton class. JButton btn2 = new JButton("Button 2"); // Initialization of object // "btn3" of JButton class. JButton btn3 = new JButton("Button 3"); // Initialization of object // "btn4" of JButton class. JButton btn4 = new JButton("Button 4"); // Initialization of object // "btn5" of JButton class. JButton btn5 = new JButton("Button 5"); // Creating Object Panel of JPanel class // create grid layout with 3 rows, // 2 columns with horizontal and // vertical gap set to 10 JPanel panel = new JPanel(new GridLayout(3, 2, 10, 10)); // Adding JButton "btn1" on JPanel. panel.add(btn1); // Adding JButton "btn2" on JPanel. panel.add(btn2); // Adding JButton "btn3" on JPanel. panel.add(btn3); // Adding JButton "btn4" on JPanel. panel.add(btn4); // Adding JButton "btn5" on JPanel. panel.add(btn5); // Function to close the operation of JFrame. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Function to set size of JFrame. frame.setSize(300, 150); // Function to get the content of JFrame. frame.getContentPane().add(panel); // Function to set visible status of JFrame. frame.setVisible(true);}} Output: Note: The above programs might not run in an online IDE. Please use an offline compiler. Reference: https://docs.oracle.com/javase/7/docs/api/java/awt/GridLayout.html Java-AWT Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java Stream 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": 25699, "s": 25671, "text": "\n21 Aug, 2018" }, { "code": null, "e": 26151, "s": 25699, "text": "GridLayout class represents a layout manager with a specified number of rows and columns in a rectangular grid. The GridLayout container is divided into an equal-sized of rectangles, and one of the components is placed in each rectangle. Every rectangle cell has the same size therefore, they contain a component, which fills the entire cell. When the user changes or adjusts the size of the container, the size of each rectangles changes accordingly." }, { "code": null, "e": 26178, "s": 26151, "text": "Constructors of the class:" }, { "code": null, "e": 26529, "s": 26178, "text": "GridLayout(): It Creates a grid layout with a default of one column per component, in a single row.GridLayout(int rw, int cl): It creates a grid layout with the specified number of rows and columns.GridLayout(int rw, int cl, int hgap, int vgap): It creates a grid layout with the specified number of rows and columns with horizontal and vertical gap." }, { "code": null, "e": 26629, "s": 26529, "text": "GridLayout(): It Creates a grid layout with a default of one column per component, in a single row." }, { "code": null, "e": 26729, "s": 26629, "text": "GridLayout(int rw, int cl): It creates a grid layout with the specified number of rows and columns." }, { "code": null, "e": 26882, "s": 26729, "text": "GridLayout(int rw, int cl, int hgap, int vgap): It creates a grid layout with the specified number of rows and columns with horizontal and vertical gap." }, { "code": null, "e": 26905, "s": 26882, "text": "Commonly Used Methods:" }, { "code": null, "e": 27020, "s": 26905, "text": "addLayoutComponent(String str, Component cmp): Adds the specified component with the specified name to the layout." }, { "code": null, "e": 27106, "s": 27020, "text": "setColumns(int cl): Sets the number of columns in this layout to the specified value." }, { "code": null, "e": 27192, "s": 27106, "text": "setHgap(int hgap): Sets the horizontal gap between components to the specified value." }, { "code": null, "e": 27272, "s": 27192, "text": "setRows(int rw): Sets the number of rows in this layout to the specified value." }, { "code": null, "e": 27356, "s": 27272, "text": "setVgap(int vgap): Sets the vertical gap between components to the specified value." }, { "code": null, "e": 27439, "s": 27356, "text": "layoutContainer(Container pr): Lays out the specified container using this layout." }, { "code": null, "e": 27515, "s": 27439, "text": "toString(): Returns the string representation of this grid layout’s values." }, { "code": null, "e": 27563, "s": 27515, "text": "Below programs illustrate the GridLayout class:" }, { "code": null, "e": 31093, "s": 27563, "text": "Program 1: In below program we are passing the argument in GridLayout. We create 4 JLabel components named “one“, “two“, “three“, “four” and create 2 JButton components named “buttonsave” and “buttonexit” and create 4 Jtextfield components named “tname“, “tcode“, “tdesig“, “tsalary” and all of add them to the JFrame by the method add(). We will set the visibility and size of the frame by using setVisible() and setSize() method. The layout is set by using setLayout() method.// Java program to illustrate the GridLayoutimport javax.swing.*;import java.awt.*; // class GridLayout extends JFramepublic class GridLayoutDemo extends JFrame { GridLayoutDemo() { // Creating Object P1 of JPanel class JPanel p1 = new JPanel(); // set the layout p1.setLayout(new GridLayout(4, 2)); // Creating Object of \"FlowLayout\" class FlowLayout layout = new FlowLayout(); // Creating Object P2 of JPanel class JPanel p2 = new JPanel(); // set the layout p2.setLayout(layout); // Declaration of objects of JLabel class. JLabel one, two, three, four; // Declaration of objects of JTextField class. JTextField tname, tsalary, tcode, tdesig; // Declaration of objects of JButton class. JButton buttonSave, buttonExit; // Initialization of object // \"one\" of JLabel class. one = new JLabel(\"NAME\"); // Initialization of object // \"tname\" of JTextField class. tname = new JTextField(20); // Initialization of object // \"two\" of JLabel class. two = new JLabel(\"CODE\"); // Initialization of object // \"tcode\" of JTextField class. tcode = new JTextField(20); // Initialization of object // \"three\" of JLabel class. three = new JLabel(\"DESIGNATION\"); // Initialization of object // \"tdesig\" of JTextField class. tdesig = new JTextField(20); // Initialization of object // \"four\" of JLabel class. four = new JLabel(\"SALARY\"); // Initialization of object // \"tsalary\" of JTextField class. tsalary = new JTextField(20); // Initialization of object // \"buttonsave\" of JButton class. buttonSave = new JButton(\"SAVE\"); // Initialization of object // \"buttonexit\" of JButton class. buttonExit = new JButton(\"EXIT\"); // Adding Jlabel \"one\" on JFrame. p1.add(one); // Adding JTextField \"tname\" on JFrame. p1.add(tname); // Adding Jlabel \"two\" on JFrame. p1.add(two); // Adding JTextField \"tcode\" on JFrame. p1.add(tcode); // Adding Jlabel \"three\" on JFrame. p1.add(three); // Adding JTextField \"tdesig\" on JFrame. p1.add(tdesig); // Adding Jlabel \"four\" on JFrame. p1.add(four); // Adding JTextField \"tsalary\" on JFrame. p1.add(tsalary); // Adding JButton \"buttonsave\" on JFrame. p2.add(buttonSave); // Adding JButton \"buttonexit\" on JFrame. p2.add(buttonExit); // add the p1 object which // refer to the Jpanel add(p1, \"North\"); // add the p2 object which // refer to the Jpanel add(p2, \"South\"); // Function to set visible // status of JFrame. setVisible(true); // this Keyword refers to current // object. Function to set size of JFrame. this.setSize(400, 180);} // Main Method public static void main(String args[]) { // calling the constructor new GridLayoutDemo(); }}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/Untitled-14.mp400:0000:0000:22Use Up/Down Arrow keys to increase or decrease volume." }, { "code": "// Java program to illustrate the GridLayoutimport javax.swing.*;import java.awt.*; // class GridLayout extends JFramepublic class GridLayoutDemo extends JFrame { GridLayoutDemo() { // Creating Object P1 of JPanel class JPanel p1 = new JPanel(); // set the layout p1.setLayout(new GridLayout(4, 2)); // Creating Object of \"FlowLayout\" class FlowLayout layout = new FlowLayout(); // Creating Object P2 of JPanel class JPanel p2 = new JPanel(); // set the layout p2.setLayout(layout); // Declaration of objects of JLabel class. JLabel one, two, three, four; // Declaration of objects of JTextField class. JTextField tname, tsalary, tcode, tdesig; // Declaration of objects of JButton class. JButton buttonSave, buttonExit; // Initialization of object // \"one\" of JLabel class. one = new JLabel(\"NAME\"); // Initialization of object // \"tname\" of JTextField class. tname = new JTextField(20); // Initialization of object // \"two\" of JLabel class. two = new JLabel(\"CODE\"); // Initialization of object // \"tcode\" of JTextField class. tcode = new JTextField(20); // Initialization of object // \"three\" of JLabel class. three = new JLabel(\"DESIGNATION\"); // Initialization of object // \"tdesig\" of JTextField class. tdesig = new JTextField(20); // Initialization of object // \"four\" of JLabel class. four = new JLabel(\"SALARY\"); // Initialization of object // \"tsalary\" of JTextField class. tsalary = new JTextField(20); // Initialization of object // \"buttonsave\" of JButton class. buttonSave = new JButton(\"SAVE\"); // Initialization of object // \"buttonexit\" of JButton class. buttonExit = new JButton(\"EXIT\"); // Adding Jlabel \"one\" on JFrame. p1.add(one); // Adding JTextField \"tname\" on JFrame. p1.add(tname); // Adding Jlabel \"two\" on JFrame. p1.add(two); // Adding JTextField \"tcode\" on JFrame. p1.add(tcode); // Adding Jlabel \"three\" on JFrame. p1.add(three); // Adding JTextField \"tdesig\" on JFrame. p1.add(tdesig); // Adding Jlabel \"four\" on JFrame. p1.add(four); // Adding JTextField \"tsalary\" on JFrame. p1.add(tsalary); // Adding JButton \"buttonsave\" on JFrame. p2.add(buttonSave); // Adding JButton \"buttonexit\" on JFrame. p2.add(buttonExit); // add the p1 object which // refer to the Jpanel add(p1, \"North\"); // add the p2 object which // refer to the Jpanel add(p2, \"South\"); // Function to set visible // status of JFrame. setVisible(true); // this Keyword refers to current // object. Function to set size of JFrame. this.setSize(400, 180);} // Main Method public static void main(String args[]) { // calling the constructor new GridLayoutDemo(); }}", "e": 33991, "s": 31093, "text": null }, { "code": null, "e": 33999, "s": 33991, "text": "Output:" }, { "code": null, "e": 36199, "s": 33999, "text": "Program 2: In below program we are passing the argument in GridLayout. We create 5 JButton components named “btn1“, “btn2“, “btn3“, “btn4“, “btn5” and then add them to the JFrame by the method add(). We will set the visibility and size of the frame by using setvisible() and setsize() method. The layout is set by using setLayout() method.// Java program to illustrate the GridLayoutimport java.awt.*;import javax.swing.*; // create a class griddemopublic class Griddemo { // Main Methodpublic static void main(String[] args){ // Creating Object of JFrame class // with new name frame JFrame frame = new JFrame(\"GridLayout Demo\"); // Initialization of object // \"btn1\" of JButton class. JButton btn1 = new JButton(\"Button 1\"); // Initialization of object // \"btn2\" of JButton class. JButton btn2 = new JButton(\"Button 2\"); // Initialization of object // \"btn3\" of JButton class. JButton btn3 = new JButton(\"Button 3\"); // Initialization of object // \"btn4\" of JButton class. JButton btn4 = new JButton(\"Button 4\"); // Initialization of object // \"btn5\" of JButton class. JButton btn5 = new JButton(\"Button 5\"); // Creating Object Panel of JPanel class // create grid layout with 3 rows, // 2 columns with horizontal and // vertical gap set to 10 JPanel panel = new JPanel(new GridLayout(3, 2, 10, 10)); // Adding JButton \"btn1\" on JPanel. panel.add(btn1); // Adding JButton \"btn2\" on JPanel. panel.add(btn2); // Adding JButton \"btn3\" on JPanel. panel.add(btn3); // Adding JButton \"btn4\" on JPanel. panel.add(btn4); // Adding JButton \"btn5\" on JPanel. panel.add(btn5); // Function to close the operation of JFrame. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Function to set size of JFrame. frame.setSize(300, 150); // Function to get the content of JFrame. frame.getContentPane().add(panel); // Function to set visible status of JFrame. frame.setVisible(true);}}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/Untitled-13Trim-2.mp400:0000:0000:16Use Up/Down Arrow keys to increase or decrease volume." }, { "code": "// Java program to illustrate the GridLayoutimport java.awt.*;import javax.swing.*; // create a class griddemopublic class Griddemo { // Main Methodpublic static void main(String[] args){ // Creating Object of JFrame class // with new name frame JFrame frame = new JFrame(\"GridLayout Demo\"); // Initialization of object // \"btn1\" of JButton class. JButton btn1 = new JButton(\"Button 1\"); // Initialization of object // \"btn2\" of JButton class. JButton btn2 = new JButton(\"Button 2\"); // Initialization of object // \"btn3\" of JButton class. JButton btn3 = new JButton(\"Button 3\"); // Initialization of object // \"btn4\" of JButton class. JButton btn4 = new JButton(\"Button 4\"); // Initialization of object // \"btn5\" of JButton class. JButton btn5 = new JButton(\"Button 5\"); // Creating Object Panel of JPanel class // create grid layout with 3 rows, // 2 columns with horizontal and // vertical gap set to 10 JPanel panel = new JPanel(new GridLayout(3, 2, 10, 10)); // Adding JButton \"btn1\" on JPanel. panel.add(btn1); // Adding JButton \"btn2\" on JPanel. panel.add(btn2); // Adding JButton \"btn3\" on JPanel. panel.add(btn3); // Adding JButton \"btn4\" on JPanel. panel.add(btn4); // Adding JButton \"btn5\" on JPanel. panel.add(btn5); // Function to close the operation of JFrame. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Function to set size of JFrame. frame.setSize(300, 150); // Function to get the content of JFrame. frame.getContentPane().add(panel); // Function to set visible status of JFrame. frame.setVisible(true);}}", "e": 37900, "s": 36199, "text": null }, { "code": null, "e": 37908, "s": 37900, "text": "Output:" }, { "code": null, "e": 37997, "s": 37908, "text": "Note: The above programs might not run in an online IDE. Please use an offline compiler." }, { "code": null, "e": 38075, "s": 37997, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/awt/GridLayout.html" }, { "code": null, "e": 38084, "s": 38075, "text": "Java-AWT" }, { "code": null, "e": 38089, "s": 38084, "text": "Java" }, { "code": null, "e": 38094, "s": 38089, "text": "Java" }, { "code": null, "e": 38192, "s": 38094, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38243, "s": 38192, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 38273, "s": 38243, "text": "HashMap in Java with Examples" }, { "code": null, "e": 38292, "s": 38273, "text": "Interfaces in Java" }, { "code": null, "e": 38307, "s": 38292, "text": "Stream In Java" }, { "code": null, "e": 38338, "s": 38307, "text": "How to iterate any Map in Java" }, { "code": null, "e": 38356, "s": 38338, "text": "ArrayList in Java" }, { "code": null, "e": 38388, "s": 38356, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 38408, "s": 38388, "text": "Stack Class in Java" }, { "code": null, "e": 38440, "s": 38408, "text": "Multidimensional Arrays in Java" } ]
Maximum count of Equilateral Triangles that can be formed within given Equilateral Triangle - GeeksforGeeks
23 Mar, 2021 Given two integers N and K where N denotes the unit size of a bigger Equilateral Triangle, the task is to find the number of an equilateral triangle of size K that are present in the bigger triangle of side N. Examples: Input: N = 4, K = 3 Output: 3Explanation:There are 3 equilateral triangles of 3 unit size which are present in the Bigger equilateral triangle of size 4 units. Input: N = 4, K = 2Output: 7Explanation:There are 7 equilateral triangles of 2 unit size which are present in the Bigger equilateral triangle of size 4 units. Naive Approach: The idea is to iterate over all possible sizes of the bigger equilateral triangle for checking the number of triangles with the required size K and print the total count of triangles. Time Complexity: O(N)Auxiliary Space: O(1) Efficient Approach: To optimize the above approach, observe the following points: The number of triangles with a peak in the upward direction of size K present in size N equals to ((N – K +1 ) * (N – K + 2))/2. The number of inverted triangles with a peak in the downward direction of size K present in size N equals to ((N – 2K + 1) * (N – 2K + 2))/2. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <iostream>using namespace std; // Function to find the number of// equilateral triangle formed// within another triangleint No_of_Triangle(int N, int K){ // Check for the valid condition if (N < K) return -1; else { int Tri_up = 0; // Number of triangles having // upward peak Tri_up = ((N - K + 1) * (N - K + 2)) / 2; int Tri_down = 0; // Number of inverted triangles Tri_down = ((N - 2 * K + 1) * (N - 2 * K + 2)) / 2; // Total no. of K sized triangle return Tri_up + Tri_down; }} // Driver Codeint main(){ // Given N and K int N = 4, K = 2; // Function Call cout << No_of_Triangle(N, K); return 0;} // Java program for the above approachimport java.util.*;class GFG{ // Function to find the number of// equilateral triangle formed// within another trianglestatic int No_of_Triangle(int N, int K){ // Check for the valid condition if (N < K) return -1; else { int Tri_up = 0; // Number of triangles having // upward peak Tri_up = ((N - K + 1) * (N - K + 2)) / 2; int Tri_down = 0; // Number of inverted triangles Tri_down = ((N - 2 * K + 1) * (N - 2 * K + 2)) / 2; // Total no. of K sized triangle return Tri_up + Tri_down; }} // Driver Codepublic static void main(String[] args){ // Given N and K int N = 4, K = 2; // Function Call System.out.print(No_of_Triangle(N, K));}} // This code is contributed by PrinciRaj1992 # Python3 program for the above approach # Function to find the number of# equilateral triangle formed# within another triangledef No_of_Triangle(N, K): # Check for the valid condition if (N < K): return -1; else: Tri_up = 0; # Number of triangles having # upward peak Tri_up = ((N - K + 1) * (N - K + 2)) // 2; Tri_down = 0; # Number of inverted triangles Tri_down = ((N - 2 * K + 1) * (N - 2 * K + 2)) // 2; # Total no. of K sized triangle return Tri_up + Tri_down; # Driver Codeif __name__ == '__main__': # Given N and K N = 4; K = 2; # Function Call print(No_of_Triangle(N, K)); # This code is contributed by sapnasingh4991 // C# program for the above approachusing System;class GFG{ // Function to find the number of// equilateral triangle formed// within another trianglestatic int No_of_Triangle(int N, int K){ // Check for the valid condition if (N < K) return -1; else { int Tri_up = 0; // Number of triangles having // upward peak Tri_up = ((N - K + 1) * (N - K + 2)) / 2; int Tri_down = 0; // Number of inverted triangles Tri_down = ((N - 2 * K + 1) * (N - 2 * K + 2)) / 2; // Total no. of K sized triangle return Tri_up + Tri_down; }} // Driver Codepublic static void Main(String[] args){ // Given N and K int N = 4, K = 2; // Function Call Console.Write(No_of_Triangle(N, K));}} // This code is contributed by Rajput-Ji <script> // JavaScript program for the above approach // Function to find the number of// equilateral triangle formed// within another trianglefunction No_of_Triangle(N, K){ // Check for the valid condition if (N < K) return -1; else { let Tri_up = 0; // Number of triangles having // upward peak Tri_up = Math.floor(((N - K + 1) * (N - K + 2)) / 2); let Tri_down = 0; // Number of inverted triangles Tri_down = Math.floor(((N - 2 * K + 1) * (N - 2 * K + 2)) / 2); // Total no. of K sized triangle return Tri_up + Tri_down; }} // Driver Code // Given N and K let N = 4, K = 2; // Function Call document.write(No_of_Triangle(N, K)); // This code is contributed by Surbhi Tyagi. </script> 7 Time Complexity: O(1)Auxiliary Space: O(1) princiraj1992 Rajput-Ji sapnasingh4991 surbhityagi15 triangle Geometric Greedy Mathematical Greedy Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for distance between two points on earth Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Convex Hull | Set 2 (Graham Scan) Check whether a given point lies inside a triangle or not Dijkstra's shortest path algorithm | Greedy Algo-7 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Program for array rotation Write a program to print all permutations of a given string
[ { "code": null, "e": 26259, "s": 26231, "text": "\n23 Mar, 2021" }, { "code": null, "e": 26469, "s": 26259, "text": "Given two integers N and K where N denotes the unit size of a bigger Equilateral Triangle, the task is to find the number of an equilateral triangle of size K that are present in the bigger triangle of side N." }, { "code": null, "e": 26479, "s": 26469, "text": "Examples:" }, { "code": null, "e": 26499, "s": 26479, "text": "Input: N = 4, K = 3" }, { "code": null, "e": 26639, "s": 26499, "text": "Output: 3Explanation:There are 3 equilateral triangles of 3 unit size which are present in the Bigger equilateral triangle of size 4 units." }, { "code": null, "e": 26799, "s": 26639, "text": "Input: N = 4, K = 2Output: 7Explanation:There are 7 equilateral triangles of 2 unit size which are present in the Bigger equilateral triangle of size 4 units. " }, { "code": null, "e": 26999, "s": 26799, "text": "Naive Approach: The idea is to iterate over all possible sizes of the bigger equilateral triangle for checking the number of triangles with the required size K and print the total count of triangles." }, { "code": null, "e": 27042, "s": 26999, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 27124, "s": 27042, "text": "Efficient Approach: To optimize the above approach, observe the following points:" }, { "code": null, "e": 27253, "s": 27124, "text": "The number of triangles with a peak in the upward direction of size K present in size N equals to ((N – K +1 ) * (N – K + 2))/2." }, { "code": null, "e": 27395, "s": 27253, "text": "The number of inverted triangles with a peak in the downward direction of size K present in size N equals to ((N – 2K + 1) * (N – 2K + 2))/2." }, { "code": null, "e": 27446, "s": 27395, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27450, "s": 27446, "text": "C++" }, { "code": null, "e": 27455, "s": 27450, "text": "Java" }, { "code": null, "e": 27463, "s": 27455, "text": "Python3" }, { "code": null, "e": 27466, "s": 27463, "text": "C#" }, { "code": null, "e": 27477, "s": 27466, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <iostream>using namespace std; // Function to find the number of// equilateral triangle formed// within another triangleint No_of_Triangle(int N, int K){ // Check for the valid condition if (N < K) return -1; else { int Tri_up = 0; // Number of triangles having // upward peak Tri_up = ((N - K + 1) * (N - K + 2)) / 2; int Tri_down = 0; // Number of inverted triangles Tri_down = ((N - 2 * K + 1) * (N - 2 * K + 2)) / 2; // Total no. of K sized triangle return Tri_up + Tri_down; }} // Driver Codeint main(){ // Given N and K int N = 4, K = 2; // Function Call cout << No_of_Triangle(N, K); return 0;}", "e": 28299, "s": 27477, "text": null }, { "code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to find the number of// equilateral triangle formed// within another trianglestatic int No_of_Triangle(int N, int K){ // Check for the valid condition if (N < K) return -1; else { int Tri_up = 0; // Number of triangles having // upward peak Tri_up = ((N - K + 1) * (N - K + 2)) / 2; int Tri_down = 0; // Number of inverted triangles Tri_down = ((N - 2 * K + 1) * (N - 2 * K + 2)) / 2; // Total no. of K sized triangle return Tri_up + Tri_down; }} // Driver Codepublic static void main(String[] args){ // Given N and K int N = 4, K = 2; // Function Call System.out.print(No_of_Triangle(N, K));}} // This code is contributed by PrinciRaj1992", "e": 29141, "s": 28299, "text": null }, { "code": "# Python3 program for the above approach # Function to find the number of# equilateral triangle formed# within another triangledef No_of_Triangle(N, K): # Check for the valid condition if (N < K): return -1; else: Tri_up = 0; # Number of triangles having # upward peak Tri_up = ((N - K + 1) * (N - K + 2)) // 2; Tri_down = 0; # Number of inverted triangles Tri_down = ((N - 2 * K + 1) * (N - 2 * K + 2)) // 2; # Total no. of K sized triangle return Tri_up + Tri_down; # Driver Codeif __name__ == '__main__': # Given N and K N = 4; K = 2; # Function Call print(No_of_Triangle(N, K)); # This code is contributed by sapnasingh4991", "e": 29909, "s": 29141, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ // Function to find the number of// equilateral triangle formed// within another trianglestatic int No_of_Triangle(int N, int K){ // Check for the valid condition if (N < K) return -1; else { int Tri_up = 0; // Number of triangles having // upward peak Tri_up = ((N - K + 1) * (N - K + 2)) / 2; int Tri_down = 0; // Number of inverted triangles Tri_down = ((N - 2 * K + 1) * (N - 2 * K + 2)) / 2; // Total no. of K sized triangle return Tri_up + Tri_down; }} // Driver Codepublic static void Main(String[] args){ // Given N and K int N = 4, K = 2; // Function Call Console.Write(No_of_Triangle(N, K));}} // This code is contributed by Rajput-Ji", "e": 30736, "s": 29909, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to find the number of// equilateral triangle formed// within another trianglefunction No_of_Triangle(N, K){ // Check for the valid condition if (N < K) return -1; else { let Tri_up = 0; // Number of triangles having // upward peak Tri_up = Math.floor(((N - K + 1) * (N - K + 2)) / 2); let Tri_down = 0; // Number of inverted triangles Tri_down = Math.floor(((N - 2 * K + 1) * (N - 2 * K + 2)) / 2); // Total no. of K sized triangle return Tri_up + Tri_down; }} // Driver Code // Given N and K let N = 4, K = 2; // Function Call document.write(No_of_Triangle(N, K)); // This code is contributed by Surbhi Tyagi. </script>", "e": 31590, "s": 30736, "text": null }, { "code": null, "e": 31592, "s": 31590, "text": "7" }, { "code": null, "e": 31637, "s": 31594, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 31651, "s": 31637, "text": "princiraj1992" }, { "code": null, "e": 31661, "s": 31651, "text": "Rajput-Ji" }, { "code": null, "e": 31676, "s": 31661, "text": "sapnasingh4991" }, { "code": null, "e": 31690, "s": 31676, "text": "surbhityagi15" }, { "code": null, "e": 31699, "s": 31690, "text": "triangle" }, { "code": null, "e": 31709, "s": 31699, "text": "Geometric" }, { "code": null, "e": 31716, "s": 31709, "text": "Greedy" }, { "code": null, "e": 31729, "s": 31716, "text": "Mathematical" }, { "code": null, "e": 31736, "s": 31729, "text": "Greedy" }, { "code": null, "e": 31749, "s": 31736, "text": "Mathematical" }, { "code": null, "e": 31759, "s": 31749, "text": "Geometric" }, { "code": null, "e": 31857, "s": 31759, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31906, "s": 31857, "text": "Program for distance between two points on earth" }, { "code": null, "e": 31959, "s": 31906, "text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)" }, { "code": null, "e": 32010, "s": 31959, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" }, { "code": null, "e": 32044, "s": 32010, "text": "Convex Hull | Set 2 (Graham Scan)" }, { "code": null, "e": 32102, "s": 32044, "text": "Check whether a given point lies inside a triangle or not" }, { "code": null, "e": 32153, "s": 32102, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 32211, "s": 32153, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 32262, "s": 32211, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 32289, "s": 32262, "text": "Program for array rotation" } ]
LRU Cache Implementation - GeeksforGeeks
CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More Competitive Programming Data Structures with C++ Data Science Explore More Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More DSA- Self Paced CIP JAVA / Python / C++ Explore More School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more School Guide Python Programming Learn To Make Apps Explore more All Courses TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin ML & Data ScienceMachine LearningData Science Machine Learning Data Science CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP Software DesignsSoftware Design PatternsSystem Design Tutorial Software Design Patterns System Design Tutorial School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes School Programming MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Student Chapter Geek on the Top Internship Careers JobsApply for JobsPost a JobJOB-A-THON Apply for Jobs Post a Job JOB-A-THON PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems All DSA Problems Problem of the Day Interview Series: Weekly Contests Bi-Wizard Coding: School Contests Contests and Events Practice SDE Sheet Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems Top 50 Array Problems Top 50 String Problems Top 50 Tree Problems Top 50 Graph Problems Top 50 DP Problems WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri Geeks Digest Quizzes Geeks Campus Gblog Articles IDE Campus Mantri Sign In Sign In Home Saved Videos Courses For Working Professionals LIVE DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More Self-Paced DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More For Students LIVE Competitive Programming Data Structures with C++ Data Science Explore More Self-Paced DSA- Self Paced CIP JAVA / Python / C++ Explore More School Courses School Guide Python Programming Learn To Make Apps Explore more Algorithms Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Analysis of Algorithms Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Interview Corner Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes Languages C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin ML & Data Science Machine Learning Data Science CS Subjects Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering GATE GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS Web Technologies HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP Software Designs Software Design Patterns System Design Tutorial School Learning School Programming Mathematics Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Maths Notes (Class 8-12) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes NCERT Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution RD Sharma Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Physics Notes (Class 8-11) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes CS Exams/PSUs ISRO ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam UGC NET UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers Student Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Student Chapter Geek on the Top Internship Careers Curated DSA Lists Top 50 Array Problems Top 50 String Problems Top 50 Tree Problems Top 50 Graph Problems Top 50 DP Problems Tutorials Jobs Apply for Jobs Post a Job JOB-A-THON Practice All DSA Problems Problem of the Day Interview Series: Weekly Contests Bi-Wizard Coding: School Contests Contests and Events Practice SDE Sheet For Working Professionals LIVE DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More Self-Paced DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More For Students LIVE Competitive Programming Data Structures with C++ Data Science Explore More Competitive Programming Data Structures with C++ Data Science Explore More Self-Paced DSA- Self Paced CIP JAVA / Python / C++ Explore More DSA- Self Paced CIP JAVA / Python / C++ Explore More School Courses School Guide Python Programming Learn To Make Apps Explore more School Guide Python Programming Learn To Make Apps Explore more Algorithms Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Analysis of Algorithms Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Interview Corner Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes Languages C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin ML & Data Science Machine Learning Data Science Machine Learning Data Science CS Subjects Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering GATE GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS Web Technologies HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP Software Designs Software Design Patterns System Design Tutorial Software Design Patterns System Design Tutorial School Learning School Programming School Programming Mathematics Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Maths Notes (Class 8-12) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes NCERT Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution RD Sharma Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Physics Notes (Class 8-11) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes CS Exams/PSUs ISRO ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam UGC NET UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers Student Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Student Chapter Geek on the Top Internship Careers Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Student Chapter Geek on the Top Internship Careers Curated DSA Lists Top 50 Array Problems Top 50 String Problems Top 50 Tree Problems Top 50 Graph Problems Top 50 DP Problems Top 50 Array Problems Top 50 String Problems Top 50 Tree Problems Top 50 Graph Problems Top 50 DP Problems Tutorials Jobs Apply for Jobs Post a Job JOB-A-THON Apply for Jobs Post a Job JOB-A-THON Practice All DSA Problems Problem of the Day Interview Series: Weekly Contests Bi-Wizard Coding: School Contests Contests and Events Practice SDE Sheet All DSA Problems Problem of the Day Interview Series: Weekly Contests Bi-Wizard Coding: School Contests Contests and Events Practice SDE Sheet GBlog Puzzles What's New ? Array Matrix Strings Hashing Linked List Stack Queue Binary Tree Binary Search Tree Heap Graph Searching Sorting Divide & Conquer Mathematical Geometric Bitwise Greedy Backtracking Branch and Bound Dynamic Programming Pattern Searching Randomized Data StructuresArrayIntroduction to ArraysArrays in C/C++Arrays in JavaProgram for array rotationReversal algorithm for array rotationBlock swap algorithm for array rotationRearrange an array such that arr[i] = iWrite a program to reverse an array or stringRearrange array such that arr[i] >= arr[j] if i is even and arr[i]<=arr[j] if i is odd and j < iLinked ListLinked List | Set 1 (Introduction)Linked List vs ArrayLinked List | Set 2 (Inserting a node)Linked List | Set 3 (Deleting a node)Delete a Linked List node at a given positionCircular Linked List | Set 1 (Introduction and Applications)Circular Linked List | Set 2 (Traversal)Split a Circular Linked List into two halvesSorted insert for circular linked listStackStack Data Structure (Introduction and Program)Stack in C++ STLStack Class in JavaStack in PythonC# Stack with ExamplesQueue using StacksDesign and Implement Special Stack Data Structure | Added Space Optimized VersionImplement two stacks in an arrayImplement Stack using QueuesQueueQueue | Set 1 (Introduction and Array Implementation)Applications of Queue Data StructurePriority Queue | Set 1 (Introduction)Applications of Priority QueueDeque | Set 1 (Introduction and Applications)LRU Cache ImplementationQueue – Linked List ImplementationBinary TreeBinary Tree | Set 1 (Introduction)Binary Tree | Set 2 (Properties)Binary Tree | Set 3 (Types of Binary Tree)Tree Traversals (Inorder, Preorder and Postorder)Inorder Tree Traversal without RecursionInorder Tree Traversal without recursion and without stack!Construct Tree from given Inorder and Preorder traversalsConstruct a tree from Inorder and Level order traversals | Set 1Construct Complete Binary Tree from its Linked List RepresentationBinary Search TreeBinary Search Tree | Set 1 (Search and Insertion)Binary Search Tree | Set 2 (Delete)Advantages of BST over Hash TableConstruct BST from given preorder traversal | Set 1Construct BST from given preorder traversal | Set 2Binary Tree to Binary Search Tree ConversionSorted Linked List to Balanced BSTSorted Array to Balanced BSTFind the node with minimum value in a Binary Search TreeHeapBinary HeapTime Complexity of building a heapApplications of Heap Data StructureBinomial HeapFibonacci Heap | Set 1 (Introduction)Leftist Tree / Leftist HeapK-ary HeapHeapSortIterative HeapSortHashingHashing | Set 1 (Introduction)Index Mapping (or Trivial Hashing) with negatives allowedHashing | Set 2 (Separate Chaining)Hashing | Set 3 (Open Addressing)Double HashingPrint a Binary Tree in Vertical Order | Set 2 (Map based Method)Find whether an array is subset of another array | Added Method 5Union and Intersection of two linked lists | Set-3 (Hashing)Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)GraphGraph and its representationsBreadth First Search or BFS for a GraphDepth First Search or DFS for a GraphDetect Cycle in a Directed GraphDetect cycle in an undirected graphDetect Cycle in a directed graph using colorsTopological SortingAll Topological Sorts of a Directed Acyclic GraphKahn’s algorithm for Topological SortingMatrixRotate Matrix ElementsInplace rotate square matrix by 90 degrees | Set 1Rotate a matrix by 90 degree without using any extra space | Set 2Rotate a Matrix by 180 degreeRotate each ring of matrix anticlockwise by K elementsTurn an image by 90 degreeCheck if all rows of a matrix are circular rotations of each otherSort the given matrixFind the row with maximum number of 1sFind median in row wise sorted matrixAdvanced Data StructureMemory efficient doubly linked listXOR Linked List – A Memory Efficient Doubly Linked List | Set 1XOR Linked List – A Memory Efficient Doubly Linked List | Set 2Memory efficient doubly linked listXOR Linked List – A Memory Efficient Doubly Linked List | Set 1XOR Linked List – A Memory Efficient Doubly Linked List | Set 2 Introduction to Arrays Arrays in C/C++ Arrays in Java Program for array rotation Reversal algorithm for array rotation Block swap algorithm for array rotation Rearrange an array such that arr[i] = i Write a program to reverse an array or string Rearrange array such that arr[i] >= arr[j] if i is even and arr[i]<=arr[j] if i is odd and j < i Linked List | Set 1 (Introduction) Linked List vs Array Linked List | Set 2 (Inserting a node) Linked List | Set 3 (Deleting a node) Delete a Linked List node at a given position Circular Linked List | Set 1 (Introduction and Applications) Circular Linked List | Set 2 (Traversal) Split a Circular Linked List into two halves Sorted insert for circular linked list Stack Data Structure (Introduction and Program) Stack in C++ STL Stack Class in Java Stack in Python C# Stack with Examples Queue using Stacks Design and Implement Special Stack Data Structure | Added Space Optimized Version Implement two stacks in an array Implement Stack using Queues Queue | Set 1 (Introduction and Array Implementation) Applications of Queue Data Structure Priority Queue | Set 1 (Introduction) Applications of Priority Queue Deque | Set 1 (Introduction and Applications) LRU Cache Implementation Queue – Linked List Implementation Binary Tree | Set 1 (Introduction) Binary Tree | Set 2 (Properties) Binary Tree | Set 3 (Types of Binary Tree) Tree Traversals (Inorder, Preorder and Postorder) Inorder Tree Traversal without Recursion Inorder Tree Traversal without recursion and without stack! Construct Tree from given Inorder and Preorder traversals Construct a tree from Inorder and Level order traversals | Set 1 Construct Complete Binary Tree from its Linked List Representation Binary Search Tree | Set 1 (Search and Insertion) Binary Search Tree | Set 2 (Delete) Advantages of BST over Hash Table Construct BST from given preorder traversal | Set 1 Construct BST from given preorder traversal | Set 2 Binary Tree to Binary Search Tree Conversion Sorted Linked List to Balanced BST Sorted Array to Balanced BST Find the node with minimum value in a Binary Search Tree Binary Heap Time Complexity of building a heap Applications of Heap Data Structure Binomial Heap Fibonacci Heap | Set 1 (Introduction) Leftist Tree / Leftist Heap K-ary Heap HeapSort Iterative HeapSort Hashing | Set 1 (Introduction) Index Mapping (or Trivial Hashing) with negatives allowed Hashing | Set 2 (Separate Chaining) Hashing | Set 3 (Open Addressing) Double Hashing Print a Binary Tree in Vertical Order | Set 2 (Map based Method) Find whether an array is subset of another array | Added Method 5 Union and Intersection of two linked lists | Set-3 (Hashing) Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Graph and its representations Breadth First Search or BFS for a Graph Depth First Search or DFS for a Graph Detect Cycle in a Directed Graph Detect cycle in an undirected graph Detect Cycle in a directed graph using colors Topological Sorting All Topological Sorts of a Directed Acyclic Graph Kahn’s algorithm for Topological Sorting Rotate Matrix Elements Inplace rotate square matrix by 90 degrees | Set 1 Rotate a matrix by 90 degree without using any extra space | Set 2 Rotate a Matrix by 180 degree Rotate each ring of matrix anticlockwise by K elements Turn an image by 90 degree Check if all rows of a matrix are circular rotations of each other Sort the given matrix Find the row with maximum number of 1s Find median in row wise sorted matrix Memory efficient doubly linked list XOR Linked List – A Memory Efficient Doubly Linked List | Set 1 XOR Linked List – A Memory Efficient Doubly Linked List | Set 2 Memory efficient doubly linked list XOR Linked List – A Memory Efficient Doubly Linked List | Set 1 XOR Linked List – A Memory Efficient Doubly Linked List | Set 2 Data StructuresArrayIntroduction to ArraysArrays in C/C++Arrays in JavaProgram for array rotationReversal algorithm for array rotationBlock swap algorithm for array rotationRearrange an array such that arr[i] = iWrite a program to reverse an array or stringRearrange array such that arr[i] >= arr[j] if i is even and arr[i]<=arr[j] if i is odd and j < iLinked ListLinked List | Set 1 (Introduction)Linked List vs ArrayLinked List | Set 2 (Inserting a node)Linked List | Set 3 (Deleting a node)Delete a Linked List node at a given positionCircular Linked List | Set 1 (Introduction and Applications)Circular Linked List | Set 2 (Traversal)Split a Circular Linked List into two halvesSorted insert for circular linked listStackStack Data Structure (Introduction and Program)Stack in C++ STLStack Class in JavaStack in PythonC# Stack with ExamplesQueue using StacksDesign and Implement Special Stack Data Structure | Added Space Optimized VersionImplement two stacks in an arrayImplement Stack using QueuesQueueQueue | Set 1 (Introduction and Array Implementation)Applications of Queue Data StructurePriority Queue | Set 1 (Introduction)Applications of Priority QueueDeque | Set 1 (Introduction and Applications)LRU Cache ImplementationQueue – Linked List ImplementationBinary TreeBinary Tree | Set 1 (Introduction)Binary Tree | Set 2 (Properties)Binary Tree | Set 3 (Types of Binary Tree)Tree Traversals (Inorder, Preorder and Postorder)Inorder Tree Traversal without RecursionInorder Tree Traversal without recursion and without stack!Construct Tree from given Inorder and Preorder traversalsConstruct a tree from Inorder and Level order traversals | Set 1Construct Complete Binary Tree from its Linked List RepresentationBinary Search TreeBinary Search Tree | Set 1 (Search and Insertion)Binary Search Tree | Set 2 (Delete)Advantages of BST over Hash TableConstruct BST from given preorder traversal | Set 1Construct BST from given preorder traversal | Set 2Binary Tree to Binary Search Tree ConversionSorted Linked List to Balanced BSTSorted Array to Balanced BSTFind the node with minimum value in a Binary Search TreeHeapBinary HeapTime Complexity of building a heapApplications of Heap Data StructureBinomial HeapFibonacci Heap | Set 1 (Introduction)Leftist Tree / Leftist HeapK-ary HeapHeapSortIterative HeapSortHashingHashing | Set 1 (Introduction)Index Mapping (or Trivial Hashing) with negatives allowedHashing | Set 2 (Separate Chaining)Hashing | Set 3 (Open Addressing)Double HashingPrint a Binary Tree in Vertical Order | Set 2 (Map based Method)Find whether an array is subset of another array | Added Method 5Union and Intersection of two linked lists | Set-3 (Hashing)Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)GraphGraph and its representationsBreadth First Search or BFS for a GraphDepth First Search or DFS for a GraphDetect Cycle in a Directed GraphDetect cycle in an undirected graphDetect Cycle in a directed graph using colorsTopological SortingAll Topological Sorts of a Directed Acyclic GraphKahn’s algorithm for Topological SortingMatrixRotate Matrix ElementsInplace rotate square matrix by 90 degrees | Set 1Rotate a matrix by 90 degree without using any extra space | Set 2Rotate a Matrix by 180 degreeRotate each ring of matrix anticlockwise by K elementsTurn an image by 90 degreeCheck if all rows of a matrix are circular rotations of each otherSort the given matrixFind the row with maximum number of 1sFind median in row wise sorted matrixAdvanced Data StructureMemory efficient doubly linked listXOR Linked List – A Memory Efficient Doubly Linked List | Set 1XOR Linked List – A Memory Efficient Doubly Linked List | Set 2Memory efficient doubly linked listXOR Linked List – A Memory Efficient Doubly Linked List | Set 1XOR Linked List – A Memory Efficient Doubly Linked List | Set 2 Introduction to Arrays Arrays in C/C++ Arrays in Java Program for array rotation Reversal algorithm for array rotation Block swap algorithm for array rotation Rearrange an array such that arr[i] = i Write a program to reverse an array or string Rearrange array such that arr[i] >= arr[j] if i is even and arr[i]<=arr[j] if i is odd and j < i Linked List | Set 1 (Introduction) Linked List vs Array Linked List | Set 2 (Inserting a node) Linked List | Set 3 (Deleting a node) Delete a Linked List node at a given position Circular Linked List | Set 1 (Introduction and Applications) Circular Linked List | Set 2 (Traversal) Split a Circular Linked List into two halves Sorted insert for circular linked list Stack Data Structure (Introduction and Program) Stack in C++ STL Stack Class in Java Stack in Python C# Stack with Examples Queue using Stacks Design and Implement Special Stack Data Structure | Added Space Optimized Version Implement two stacks in an array Implement Stack using Queues Queue | Set 1 (Introduction and Array Implementation) Applications of Queue Data Structure Priority Queue | Set 1 (Introduction) Applications of Priority Queue Deque | Set 1 (Introduction and Applications) LRU Cache Implementation Queue – Linked List Implementation Binary Tree | Set 1 (Introduction) Binary Tree | Set 2 (Properties) Binary Tree | Set 3 (Types of Binary Tree) Tree Traversals (Inorder, Preorder and Postorder) Inorder Tree Traversal without Recursion Inorder Tree Traversal without recursion and without stack! Construct Tree from given Inorder and Preorder traversals Construct a tree from Inorder and Level order traversals | Set 1 Construct Complete Binary Tree from its Linked List Representation Binary Search Tree | Set 1 (Search and Insertion) Binary Search Tree | Set 2 (Delete) Advantages of BST over Hash Table Construct BST from given preorder traversal | Set 1 Construct BST from given preorder traversal | Set 2 Binary Tree to Binary Search Tree Conversion Sorted Linked List to Balanced BST Sorted Array to Balanced BST Find the node with minimum value in a Binary Search Tree Binary Heap Time Complexity of building a heap Applications of Heap Data Structure Binomial Heap Fibonacci Heap | Set 1 (Introduction) Leftist Tree / Leftist Heap K-ary Heap HeapSort Iterative HeapSort Hashing | Set 1 (Introduction) Index Mapping (or Trivial Hashing) with negatives allowed Hashing | Set 2 (Separate Chaining) Hashing | Set 3 (Open Addressing) Double Hashing Print a Binary Tree in Vertical Order | Set 2 (Map based Method) Find whether an array is subset of another array | Added Method 5 Union and Intersection of two linked lists | Set-3 (Hashing) Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Graph and its representations Breadth First Search or BFS for a Graph Depth First Search or DFS for a Graph Detect Cycle in a Directed Graph Detect cycle in an undirected graph Detect Cycle in a directed graph using colors Topological Sorting All Topological Sorts of a Directed Acyclic Graph Kahn’s algorithm for Topological Sorting Rotate Matrix Elements Inplace rotate square matrix by 90 degrees | Set 1 Rotate a matrix by 90 degree without using any extra space | Set 2 Rotate a Matrix by 180 degree Rotate each ring of matrix anticlockwise by K elements Turn an image by 90 degree Check if all rows of a matrix are circular rotations of each other Sort the given matrix Find the row with maximum number of 1s Find median in row wise sorted matrix Memory efficient doubly linked list XOR Linked List – A Memory Efficient Doubly Linked List | Set 1 XOR Linked List – A Memory Efficient Doubly Linked List | Set 2 Memory efficient doubly linked list XOR Linked List – A Memory Efficient Doubly Linked List | Set 1 XOR Linked List – A Memory Efficient Doubly Linked List | Set 2 Difficulty Level : Hard How to implement LRU caching scheme? What data structures should be used? We are given the total possible page numbers that can be referred. We are also given cache (or memory) size (The number of page frames that the cache can hold at a time). The LRU caching scheme is to remove the least recently used frame when the cache is full and a new page is referenced which is not there in the cache. Please see the Galvin book for more details (see the LRU page replacement slide here). We use two data structures to implement an LRU Cache. Queue is implemented using a doubly-linked list. The maximum size of the queue will be equal to the total number of frames available (cache size). The most recently used pages will be near the front end and the least recently pages will be near the rear end.A Hash with page number as key and address of the corresponding queue node as value. Queue is implemented using a doubly-linked list. The maximum size of the queue will be equal to the total number of frames available (cache size). The most recently used pages will be near the front end and the least recently pages will be near the rear end. A Hash with page number as key and address of the corresponding queue node as value. When a page is referenced, the required page may be in the memory. If it is in the memory, we need to detach the node of the list and bring it to the front of the queue. If the required page is not in memory, we bring that in memory. In simple words, we add a new node to the front of the queue and update the corresponding node address in the hash. If the queue is full, i.e. all the frames are full, we remove a node from the rear of the queue, and add the new node to the front of the queue. Example – Consider the following reference string : 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5 Find the number of page faults using the least recently used (LRU) page replacement algorithm with 3-page frames. Explanation – Note: Initially no page is in the memory. C++ C Java // We can use stl container list as a double// ended queue to store the cache keys, with// the descending time of reference from front// to back and a set container to check presence// of a key. But to fetch the address of the key// in the list using find(), it takes O(N) time.// This can be optimized by storing a reference// (iterator) to each key in a hash map.#include <bits/stdc++.h>using namespace std; class LRUCache { // store keys of cache list<int> dq; // store references of key in cache unordered_map<int, list<int>::iterator> ma; int csize; // maximum capacity of cache public: LRUCache(int); void refer(int); void display();}; // Declare the sizeLRUCache::LRUCache(int n){ csize = n;} // Refers key x with in the LRU cachevoid LRUCache::refer(int x){ // not present in cache if (ma.find(x) == ma.end()) { // cache is full if (dq.size() == csize) { // delete least recently used element int last = dq.back(); // Pops the last element dq.pop_back(); // Erase the last ma.erase(last); } } // present in cache else dq.erase(ma[x]); // update reference dq.push_front(x); ma[x] = dq.begin();} // Function to display contents of cachevoid LRUCache::display(){ // Iterate in the deque and print // all the elements in it for (auto it = dq.begin(); it != dq.end(); it++) cout << (*it) << " "; cout << endl;} // Driver Codeint main(){ LRUCache ca(4); ca.refer(1); ca.refer(2); ca.refer(3); ca.refer(1); ca.refer(4); ca.refer(5); ca.display(); return 0;}// This code is contributed by Satish Srinivas // A C program to show implementation of LRU cache#include <stdio.h>#include <stdlib.h> // A Queue Node (Queue is implemented using Doubly Linked List)typedef struct QNode { struct QNode *prev, *next; unsigned pageNumber; // the page number stored in this QNode} QNode; // A Queue (A FIFO collection of Queue Nodes)typedef struct Queue { unsigned count; // Number of filled frames unsigned numberOfFrames; // total number of frames QNode *front, *rear;} Queue; // A hash (Collection of pointers to Queue Nodes)typedef struct Hash { int capacity; // how many pages can be there QNode** array; // an array of queue nodes} Hash; // A utility function to create a new Queue Node. The queue Node// will store the given 'pageNumber'QNode* newQNode(unsigned pageNumber){ // Allocate memory and assign 'pageNumber' QNode* temp = (QNode*)malloc(sizeof(QNode)); temp->pageNumber = pageNumber; // Initialize prev and next as NULL temp->prev = temp->next = NULL; return temp;} // A utility function to create an empty Queue.// The queue can have at most 'numberOfFrames' nodesQueue* createQueue(int numberOfFrames){ Queue* queue = (Queue*)malloc(sizeof(Queue)); // The queue is empty queue->count = 0; queue->front = queue->rear = NULL; // Number of frames that can be stored in memory queue->numberOfFrames = numberOfFrames; return queue;} // A utility function to create an empty Hash of given capacityHash* createHash(int capacity){ // Allocate memory for hash Hash* hash = (Hash*)malloc(sizeof(Hash)); hash->capacity = capacity; // Create an array of pointers for referring queue nodes hash->array = (QNode**)malloc(hash->capacity * sizeof(QNode*)); // Initialize all hash entries as empty int i; for (i = 0; i < hash->capacity; ++i) hash->array[i] = NULL; return hash;} // A function to check if there is slot available in memoryint AreAllFramesFull(Queue* queue){ return queue->count == queue->numberOfFrames;} // A utility function to check if queue is emptyint isQueueEmpty(Queue* queue){ return queue->rear == NULL;} // A utility function to delete a frame from queuevoid deQueue(Queue* queue){ if (isQueueEmpty(queue)) return; // If this is the only node in list, then change front if (queue->front == queue->rear) queue->front = NULL; // Change rear and remove the previous rear QNode* temp = queue->rear; queue->rear = queue->rear->prev; if (queue->rear) queue->rear->next = NULL; free(temp); // decrement the number of full frames by 1 queue->count--;} // A function to add a page with given 'pageNumber' to both queue// and hashvoid Enqueue(Queue* queue, Hash* hash, unsigned pageNumber){ // If all frames are full, remove the page at the rear if (AreAllFramesFull(queue)) { // remove page from hash hash->array[queue->rear->pageNumber] = NULL; deQueue(queue); } // Create a new node with given page number, // And add the new node to the front of queue QNode* temp = newQNode(pageNumber); temp->next = queue->front; // If queue is empty, change both front and rear pointers if (isQueueEmpty(queue)) queue->rear = queue->front = temp; else // Else change the front { queue->front->prev = temp; queue->front = temp; } // Add page entry to hash also hash->array[pageNumber] = temp; // increment number of full frames queue->count++;} // This function is called when a page with given 'pageNumber' is referenced// from cache (or memory). There are two cases:// 1. Frame is not there in memory, we bring it in memory and add to the front// of queue// 2. Frame is there in memory, we move the frame to front of queuevoid ReferencePage(Queue* queue, Hash* hash, unsigned pageNumber){ QNode* reqPage = hash->array[pageNumber]; // the page is not in cache, bring it if (reqPage == NULL) Enqueue(queue, hash, pageNumber); // page is there and not at front, change pointer else if (reqPage != queue->front) { // Unlink rquested page from its current location // in queue. reqPage->prev->next = reqPage->next; if (reqPage->next) reqPage->next->prev = reqPage->prev; // If the requested page is rear, then change rear // as this node will be moved to front if (reqPage == queue->rear) { queue->rear = reqPage->prev; queue->rear->next = NULL; } // Put the requested page before current front reqPage->next = queue->front; reqPage->prev = NULL; // Change prev of current front reqPage->next->prev = reqPage; // Change front to the requested page queue->front = reqPage; }} // Driver program to test above functionsint main(){ // Let cache can hold 4 pages Queue* q = createQueue(4); // Let 10 different pages can be requested (pages to be // referenced are numbered from 0 to 9 Hash* hash = createHash(10); // Let us refer pages 1, 2, 3, 1, 4, 5 ReferencePage(q, hash, 1); ReferencePage(q, hash, 2); ReferencePage(q, hash, 3); ReferencePage(q, hash, 1); ReferencePage(q, hash, 4); ReferencePage(q, hash, 5); // Let us print cache frames after the above referenced pages printf("%d ", q->front->pageNumber); printf("%d ", q->front->next->pageNumber); printf("%d ", q->front->next->next->pageNumber); printf("%d ", q->front->next->next->next->pageNumber); return 0;} /* We can use Java inbuilt Deque as a double ended queue to store the cache keys, with the descending time of reference from front to back and a set container to check presence of a key. But remove a key from the Deque using remove(), it takes O(N) time. This can be optimized by storing a reference (iterator) to each key in a hash map. */import java.util.Deque;import java.util.HashSet; import java.util.LinkedList; import java.util.Iterator; public class LRUCache { // store keys of cache private Deque<Integer> doublyQueue; // store references of key in cache private HashSet<Integer> hashSet; // maximum capacity of cache private final int CACHE_SIZE; LRUCache(int capacity) { doublyQueue = new LinkedList<>(); hashSet = new HashSet<>(); CACHE_SIZE = capacity; } /* Refer the page within the LRU cache */ public void refer(int page) { if (!hashSet.contains(page)) { if (doublyQueue.size() == CACHE_SIZE) { int last = doublyQueue.removeLast(); hashSet.remove(last); } } else {/* The found page may not be always the last element, even if it's an intermediate element that needs to be removed and added to the start of the Queue */ doublyQueue.remove(page); } doublyQueue.push(page); hashSet.add(page); } // display contents of cache public void display() { Iterator<Integer> itr = doublyQueue.iterator(); while (itr.hasNext()) { System.out.print(itr.next() + " "); } } public static void main(String[] args) { LRUCache cache = new LRUCache(4); cache.refer(1); cache.refer(2); cache.refer(3); cache.refer(1); cache.refer(4); cache.refer(5); cache.display(); }} // This code is contributed by Niraj Kumar 5 4 1 3 Java Implementation using LinkedHashMap. The idea is to use a LinkedHashSet that maintains the insertion order of elements. This way implementation becomes short and easy. Java // Java program to implement LRU cache// using LinkedHashSetimport java.util.*; class LRUCache { Set<Integer> cache; int capacity; public LRUCache(int capacity) { this.cache = new LinkedHashSet<Integer>(capacity); this.capacity = capacity; } // This function returns false if key is not // present in cache. Else it moves the key to // front by first removing it and then adding // it, and returns true. public boolean get(int key) { if (!cache.contains(key)) return false; cache.remove(key); cache.add(key); return true; } /* Refers key x with in the LRU cache */ public void refer(int key) { if (get(key) == false) put(key); } // displays contents of cache in Reverse Order public void display() { LinkedList<Integer> list = new LinkedList<>(cache); // The descendingIterator() method of java.util.LinkedList // class is used to return an iterator over the elements // in this LinkedList in reverse sequential order Iterator<Integer> itr = list.descendingIterator(); while (itr.hasNext()) System.out.print(itr.next() + " "); } public void put(int key) { if (cache.size() == capacity) { int firstKey = cache.iterator().next(); cache.remove(firstKey); } cache.add(key); } public static void main(String[] args) { LRUCache ca = new LRUCache(4); ca.refer(1); ca.refer(2); ca.refer(3); ca.refer(1); ca.refer(4); ca.refer(5); ca.display(); }} 5 4 1 3 Python implementation using OrderedDictThis article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. _Gaurav_Tiwari spattk MadhaviVaddepalli Majorssn nirajtechi sudhanshublaze adnanirshad158 sumitgumber28 sharanaseem Amazon cpp-unordered_map MakeMyTrip Morgan Stanley Snapdeal STL Advanced Data Structure GATE CS Operating Systems Queue Morgan Stanley Amazon Snapdeal MakeMyTrip Operating Systems Queue STL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. AVL Tree | Set 1 (Insertion) Trie | (Insert and Search) Red-Black Tree | Set 1 (Introduction) Introduction of B-Tree Agents in Artificial Intelligence Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 419, "s": 0, "text": "CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses" }, { "code": null, "e": 600, "s": 419, "text": "For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More" }, { "code": null, "e": 685, "s": 600, "text": "LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More" }, { "code": null, "e": 702, "s": 685, "text": "DSA Live Classes" }, { "code": null, "e": 716, "s": 702, "text": "System Design" }, { "code": null, "e": 741, "s": 716, "text": "Java Backend Development" }, { "code": null, "e": 757, "s": 741, "text": "Full Stack LIVE" }, { "code": null, "e": 770, "s": 757, "text": "Explore More" }, { "code": null, "e": 842, "s": 770, "text": "Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More" }, { "code": null, "e": 858, "s": 842, "text": "DSA- Self Paced" }, { "code": null, "e": 869, "s": 858, "text": "SDE Theory" }, { "code": null, "e": 894, "s": 869, "text": "Must-Do Coding Questions" }, { "code": null, "e": 907, "s": 894, "text": "Explore More" }, { "code": null, "e": 1054, "s": 907, "text": "For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More" }, { "code": null, "e": 1130, "s": 1054, "text": "LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More" }, { "code": null, "e": 1154, "s": 1130, "text": "Competitive Programming" }, { "code": null, "e": 1179, "s": 1154, "text": "Data Structures with C++" }, { "code": null, "e": 1192, "s": 1179, "text": "Data Science" }, { "code": null, "e": 1205, "s": 1192, "text": "Explore More" }, { "code": null, "e": 1265, "s": 1205, "text": "Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More" }, { "code": null, "e": 1281, "s": 1265, "text": "DSA- Self Paced" }, { "code": null, "e": 1285, "s": 1281, "text": "CIP" }, { "code": null, "e": 1305, "s": 1285, "text": "JAVA / Python / C++" }, { "code": null, "e": 1318, "s": 1305, "text": "Explore More" }, { "code": null, "e": 1393, "s": 1318, "text": "School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more" }, { "code": null, "e": 1406, "s": 1393, "text": "School Guide" }, { "code": null, "e": 1425, "s": 1406, "text": "Python Programming" }, { "code": null, "e": 1444, "s": 1425, "text": "Learn To Make Apps" }, { "code": null, "e": 1457, "s": 1444, "text": "Explore more" }, { "code": null, "e": 1469, "s": 1457, "text": "All Courses" }, { "code": null, "e": 3985, "s": 1469, "text": "TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers" }, { "code": null, "e": 4566, "s": 3985, "text": "AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms" }, { "code": null, "e": 4899, "s": 4566, "text": "Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question" }, { "code": null, "e": 4919, "s": 4899, "text": "Asymptotic Analysis" }, { "code": null, "e": 4949, "s": 4919, "text": "Worst, Average and Best Cases" }, { "code": null, "e": 4970, "s": 4949, "text": "Asymptotic Notations" }, { "code": null, "e": 5006, "s": 4970, "text": "Little o and little omega notations" }, { "code": null, "e": 5035, "s": 5006, "text": "Lower and Upper Bound Theory" }, { "code": null, "e": 5053, "s": 5035, "text": "Analysis of Loops" }, { "code": null, "e": 5073, "s": 5053, "text": "Solving Recurrences" }, { "code": null, "e": 5092, "s": 5073, "text": "Amortized Analysis" }, { "code": null, "e": 5128, "s": 5092, "text": "What does 'Space Complexity' mean ?" }, { "code": null, "e": 5157, "s": 5128, "text": "Pseudo-polynomial Algorithms" }, { "code": null, "e": 5194, "s": 5157, "text": "Polynomial Time Approximation Scheme" }, { "code": null, "e": 5221, "s": 5194, "text": "A Time Complexity Question" }, { "code": null, "e": 5242, "s": 5221, "text": "Searching Algorithms" }, { "code": null, "e": 5261, "s": 5242, "text": "Sorting Algorithms" }, { "code": null, "e": 5278, "s": 5261, "text": "Graph Algorithms" }, { "code": null, "e": 5296, "s": 5278, "text": "Pattern Searching" }, { "code": null, "e": 5317, "s": 5296, "text": "Geometric Algorithms" }, { "code": null, "e": 5330, "s": 5317, "text": "Mathematical" }, { "code": null, "e": 5349, "s": 5330, "text": "Bitwise Algorithms" }, { "code": null, "e": 5371, "s": 5349, "text": "Randomized Algorithms" }, { "code": null, "e": 5389, "s": 5371, "text": "Greedy Algorithms" }, { "code": null, "e": 5409, "s": 5389, "text": "Dynamic Programming" }, { "code": null, "e": 5428, "s": 5409, "text": "Divide and Conquer" }, { "code": null, "e": 5441, "s": 5428, "text": "Backtracking" }, { "code": null, "e": 5458, "s": 5441, "text": "Branch and Bound" }, { "code": null, "e": 5473, "s": 5458, "text": "All Algorithms" }, { "code": null, "e": 5616, "s": 5473, "text": "Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures" }, { "code": null, "e": 5623, "s": 5616, "text": "Arrays" }, { "code": null, "e": 5635, "s": 5623, "text": "Linked List" }, { "code": null, "e": 5641, "s": 5635, "text": "Stack" }, { "code": null, "e": 5647, "s": 5641, "text": "Queue" }, { "code": null, "e": 5659, "s": 5647, "text": "Binary Tree" }, { "code": null, "e": 5678, "s": 5659, "text": "Binary Search Tree" }, { "code": null, "e": 5683, "s": 5678, "text": "Heap" }, { "code": null, "e": 5691, "s": 5683, "text": "Hashing" }, { "code": null, "e": 5697, "s": 5691, "text": "Graph" }, { "code": null, "e": 5721, "s": 5697, "text": "Advanced Data Structure" }, { "code": null, "e": 5728, "s": 5721, "text": "Matrix" }, { "code": null, "e": 5736, "s": 5728, "text": "Strings" }, { "code": null, "e": 5756, "s": 5736, "text": "All Data Structures" }, { "code": null, "e": 5976, "s": 5756, "text": "Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes" }, { "code": null, "e": 5996, "s": 5976, "text": "Company Preparation" }, { "code": null, "e": 6007, "s": 5996, "text": "Top Topics" }, { "code": null, "e": 6034, "s": 6007, "text": "Practice Company Questions" }, { "code": null, "e": 6056, "s": 6034, "text": "Interview Experiences" }, { "code": null, "e": 6079, "s": 6056, "text": "Experienced Interviews" }, { "code": null, "e": 6101, "s": 6079, "text": "Internship Interviews" }, { "code": null, "e": 6126, "s": 6101, "text": "Competititve Programming" }, { "code": null, "e": 6142, "s": 6126, "text": "Design Patterns" }, { "code": null, "e": 6165, "s": 6142, "text": "System Design Tutorial" }, { "code": null, "e": 6189, "s": 6165, "text": "Multiple Choice Quizzes" }, { "code": null, "e": 6270, "s": 6189, "text": "LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin" }, { "code": null, "e": 6272, "s": 6270, "text": "C" }, { "code": null, "e": 6276, "s": 6272, "text": "C++" }, { "code": null, "e": 6281, "s": 6276, "text": "Java" }, { "code": null, "e": 6288, "s": 6281, "text": "Python" }, { "code": null, "e": 6291, "s": 6288, "text": "C#" }, { "code": null, "e": 6302, "s": 6291, "text": "JavaScript" }, { "code": null, "e": 6309, "s": 6302, "text": "jQuery" }, { "code": null, "e": 6313, "s": 6309, "text": "SQL" }, { "code": null, "e": 6317, "s": 6313, "text": "PHP" }, { "code": null, "e": 6323, "s": 6317, "text": "Scala" }, { "code": null, "e": 6328, "s": 6323, "text": "Perl" }, { "code": null, "e": 6340, "s": 6328, "text": "Go Language" }, { "code": null, "e": 6345, "s": 6340, "text": "HTML" }, { "code": null, "e": 6349, "s": 6345, "text": "CSS" }, { "code": null, "e": 6356, "s": 6349, "text": "Kotlin" }, { "code": null, "e": 6402, "s": 6356, "text": "ML & Data ScienceMachine LearningData Science" }, { "code": null, "e": 6419, "s": 6402, "text": "Machine Learning" }, { "code": null, "e": 6432, "s": 6419, "text": "Data Science" }, { "code": null, "e": 6599, "s": 6432, "text": "CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering" }, { "code": null, "e": 6611, "s": 6599, "text": "Mathematics" }, { "code": null, "e": 6628, "s": 6611, "text": "Operating System" }, { "code": null, "e": 6633, "s": 6628, "text": "DBMS" }, { "code": null, "e": 6651, "s": 6633, "text": "Computer Networks" }, { "code": null, "e": 6690, "s": 6651, "text": "Computer Organization and Architecture" }, { "code": null, "e": 6712, "s": 6690, "text": "Theory of Computation" }, { "code": null, "e": 6728, "s": 6712, "text": "Compiler Design" }, { "code": null, "e": 6742, "s": 6728, "text": "Digital Logic" }, { "code": null, "e": 6763, "s": 6742, "text": "Software Engineering" }, { "code": null, "e": 6938, "s": 6763, "text": "GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS" }, { "code": null, "e": 6966, "s": 6938, "text": "GATE Computer Science Notes" }, { "code": null, "e": 6984, "s": 6966, "text": "Last Minute Notes" }, { "code": null, "e": 7006, "s": 6984, "text": "GATE CS Solved Papers" }, { "code": null, "e": 7048, "s": 7006, "text": "GATE CS Original Papers and Official Keys" }, { "code": null, "e": 7064, "s": 7048, "text": "GATE 2021 Dates" }, { "code": null, "e": 7086, "s": 7064, "text": "GATE CS 2021 Syllabus" }, { "code": null, "e": 7115, "s": 7086, "text": "Important Topics for GATE CS" }, { "code": null, "e": 7189, "s": 7115, "text": "Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP" }, { "code": null, "e": 7194, "s": 7189, "text": "HTML" }, { "code": null, "e": 7198, "s": 7194, "text": "CSS" }, { "code": null, "e": 7209, "s": 7198, "text": "JavaScript" }, { "code": null, "e": 7219, "s": 7209, "text": "AngularJS" }, { "code": null, "e": 7227, "s": 7219, "text": "ReactJS" }, { "code": null, "e": 7234, "s": 7227, "text": "NodeJS" }, { "code": null, "e": 7244, "s": 7234, "text": "Bootstrap" }, { "code": null, "e": 7251, "s": 7244, "text": "jQuery" }, { "code": null, "e": 7255, "s": 7251, "text": "PHP" }, { "code": null, "e": 7318, "s": 7255, "text": "Software DesignsSoftware Design PatternsSystem Design Tutorial" }, { "code": null, "e": 7343, "s": 7318, "text": "Software Design Patterns" }, { "code": null, "e": 7366, "s": 7343, "text": "System Design Tutorial" }, { "code": null, "e": 7923, "s": 7366, "text": "School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes" }, { "code": null, "e": 7942, "s": 7923, "text": "School Programming" }, { "code": null, "e": 8034, "s": 7942, "text": "MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus" }, { "code": null, "e": 8048, "s": 8034, "text": "Number System" }, { "code": null, "e": 8056, "s": 8048, "text": "Algebra" }, { "code": null, "e": 8069, "s": 8056, "text": "Trigonometry" }, { "code": null, "e": 8080, "s": 8069, "text": "Statistics" }, { "code": null, "e": 8092, "s": 8080, "text": "Probability" }, { "code": null, "e": 8101, "s": 8092, "text": "Geometry" }, { "code": null, "e": 8113, "s": 8101, "text": "Mensuration" }, { "code": null, "e": 8122, "s": 8113, "text": "Calculus" }, { "code": null, "e": 8215, "s": 8122, "text": "Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes" }, { "code": null, "e": 8229, "s": 8215, "text": "Class 8 Notes" }, { "code": null, "e": 8243, "s": 8229, "text": "Class 9 Notes" }, { "code": null, "e": 8258, "s": 8243, "text": "Class 10 Notes" }, { "code": null, "e": 8273, "s": 8258, "text": "Class 11 Notes" }, { "code": null, "e": 8288, "s": 8273, "text": "Class 12 Notes" }, { "code": null, "e": 8417, "s": 8288, "text": "NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution" }, { "code": null, "e": 8440, "s": 8417, "text": "Class 8 Maths Solution" }, { "code": null, "e": 8463, "s": 8440, "text": "Class 9 Maths Solution" }, { "code": null, "e": 8487, "s": 8463, "text": "Class 10 Maths Solution" }, { "code": null, "e": 8511, "s": 8487, "text": "Class 11 Maths Solution" }, { "code": null, "e": 8535, "s": 8511, "text": "Class 12 Maths Solution" }, { "code": null, "e": 8668, "s": 8535, "text": "RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution" }, { "code": null, "e": 8691, "s": 8668, "text": "Class 8 Maths Solution" }, { "code": null, "e": 8714, "s": 8691, "text": "Class 9 Maths Solution" }, { "code": null, "e": 8738, "s": 8714, "text": "Class 10 Maths Solution" }, { "code": null, "e": 8762, "s": 8738, "text": "Class 11 Maths Solution" }, { "code": null, "e": 8786, "s": 8762, "text": "Class 12 Maths Solution" }, { "code": null, "e": 8867, "s": 8786, "text": "Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes" }, { "code": null, "e": 8881, "s": 8867, "text": "Class 8 Notes" }, { "code": null, "e": 8895, "s": 8881, "text": "Class 9 Notes" }, { "code": null, "e": 8910, "s": 8895, "text": "Class 10 Notes" }, { "code": null, "e": 8925, "s": 8910, "text": "Class 11 Notes" }, { "code": null, "e": 9131, "s": 8925, "text": "CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers" }, { "code": null, "e": 9242, "s": 9131, "text": "ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam" }, { "code": null, "e": 9284, "s": 9242, "text": "ISRO CS Original Papers and Official Keys" }, { "code": null, "e": 9306, "s": 9284, "text": "ISRO CS Solved Papers" }, { "code": null, "e": 9351, "s": 9306, "text": "ISRO CS Syllabus for Scientist/Engineer Exam" }, { "code": null, "e": 9434, "s": 9351, "text": "UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers" }, { "code": null, "e": 9460, "s": 9434, "text": "UGC NET CS Notes Paper II" }, { "code": null, "e": 9487, "s": 9460, "text": "UGC NET CS Notes Paper III" }, { "code": null, "e": 9512, "s": 9487, "text": "UGC NET CS Solved Papers" }, { "code": null, "e": 9717, "s": 9512, "text": "StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers" }, { "code": null, "e": 9743, "s": 9717, "text": "Campus Ambassador Program" }, { "code": null, "e": 9769, "s": 9743, "text": "School Ambassador Program" }, { "code": null, "e": 9777, "s": 9769, "text": "Project" }, { "code": null, "e": 9795, "s": 9777, "text": "Geek of the Month" }, { "code": null, "e": 9820, "s": 9795, "text": "Campus Geek of the Month" }, { "code": null, "e": 9837, "s": 9820, "text": "Placement Course" }, { "code": null, "e": 9862, "s": 9837, "text": "Competititve Programming" }, { "code": null, "e": 9875, "s": 9862, "text": "Testimonials" }, { "code": null, "e": 9891, "s": 9875, "text": "Student Chapter" }, { "code": null, "e": 9907, "s": 9891, "text": "Geek on the Top" }, { "code": null, "e": 9918, "s": 9907, "text": "Internship" }, { "code": null, "e": 9926, "s": 9918, "text": "Careers" }, { "code": null, "e": 9965, "s": 9926, "text": "JobsApply for JobsPost a JobJOB-A-THON" }, { "code": null, "e": 9980, "s": 9965, "text": "Apply for Jobs" }, { "code": null, "e": 9991, "s": 9980, "text": "Post a Job" }, { "code": null, "e": 10002, "s": 9991, "text": "JOB-A-THON" }, { "code": null, "e": 10267, "s": 10002, "text": "PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems" }, { "code": null, "e": 10284, "s": 10267, "text": "All DSA Problems" }, { "code": null, "e": 10303, "s": 10284, "text": "Problem of the Day" }, { "code": null, "e": 10337, "s": 10303, "text": "Interview Series: Weekly Contests" }, { "code": null, "e": 10371, "s": 10337, "text": "Bi-Wizard Coding: School Contests" }, { "code": null, "e": 10391, "s": 10371, "text": "Contests and Events" }, { "code": null, "e": 10410, "s": 10391, "text": "Practice SDE Sheet" }, { "code": null, "e": 10530, "s": 10410, "text": "Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems" }, { "code": null, "e": 10552, "s": 10530, "text": "Top 50 Array Problems" }, { "code": null, "e": 10575, "s": 10552, "text": "Top 50 String Problems" }, { "code": null, "e": 10596, "s": 10575, "text": "Top 50 Tree Problems" }, { "code": null, "e": 10618, "s": 10596, "text": "Top 50 Graph Problems" }, { "code": null, "e": 10637, "s": 10618, "text": "Top 50 DP Problems" }, { "code": null, "e": 10908, "s": 10641, "text": "WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri" }, { "code": null, "e": 10921, "s": 10908, "text": "Geeks Digest" }, { "code": null, "e": 10929, "s": 10921, "text": "Quizzes" }, { "code": null, "e": 10942, "s": 10929, "text": "Geeks Campus" }, { "code": null, "e": 10957, "s": 10942, "text": "Gblog Articles" }, { "code": null, "e": 10961, "s": 10957, "text": "IDE" }, { "code": null, "e": 10975, "s": 10961, "text": "Campus Mantri" }, { "code": null, "e": 10983, "s": 10975, "text": "Sign In" }, { "code": null, "e": 10991, "s": 10983, "text": "Sign In" }, { "code": null, "e": 10996, "s": 10991, "text": "Home" }, { "code": null, "e": 11009, "s": 10996, "text": "Saved Videos" }, { "code": null, "e": 11017, "s": 11009, "text": "Courses" }, { "code": null, "e": 15482, "s": 11017, "text": "\n\nFor Working Professionals\n \n\n\n\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n\n\nFor Students\n \n\n\n\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n\n\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\nExplore more\n\n\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n\n\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n\n\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n\n\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n\n\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n\n\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n\n\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n\n\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n\n\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n\n\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n\n\nSchool Learning\n \n\n\nSchool Programming\n\n\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n\n\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n\n\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\n\nCS Exams/PSUs\n \n\n\n\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n\n\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n\n\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nStudent Chapter\n\nGeek on the Top\n\nInternship\n\nCareers\n\n\nCurated DSA Lists\n \n\n\nTop 50 Array Problems\n\nTop 50 String Problems\n\nTop 50 Tree Problems\n\nTop 50 Graph Problems\n\nTop 50 DP Problems\n\n\nTutorials\n \n\n\n\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n\n\nPractice\n \n\n\nAll DSA Problems\n\nProblem of the Day\n\nInterview Series: Weekly Contests\n\nBi-Wizard Coding: School Contests\n\nContests and Events\n\nPractice SDE Sheet\n" }, { "code": null, "e": 15536, "s": 15482, "text": "\nFor Working Professionals\n \n\n" }, { "code": null, "e": 15659, "s": 15536, "text": "\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n" }, { "code": null, "e": 15678, "s": 15659, "text": "\nDSA Live Classes\n" }, { "code": null, "e": 15694, "s": 15678, "text": "\nSystem Design\n" }, { "code": null, "e": 15721, "s": 15694, "text": "\nJava Backend Development\n" }, { "code": null, "e": 15739, "s": 15721, "text": "\nFull Stack LIVE\n" }, { "code": null, "e": 15754, "s": 15739, "text": "\nExplore More\n" }, { "code": null, "e": 15862, "s": 15754, "text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n" }, { "code": null, "e": 15880, "s": 15862, "text": "\nDSA- Self Paced\n" }, { "code": null, "e": 15893, "s": 15880, "text": "\nSDE Theory\n" }, { "code": null, "e": 15920, "s": 15893, "text": "\nMust-Do Coding Questions\n" }, { "code": null, "e": 15935, "s": 15920, "text": "\nExplore More\n" }, { "code": null, "e": 15976, "s": 15935, "text": "\nFor Students\n \n\n" }, { "code": null, "e": 16088, "s": 15976, "text": "\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n" }, { "code": null, "e": 16114, "s": 16088, "text": "\nCompetitive Programming\n" }, { "code": null, "e": 16141, "s": 16114, "text": "\nData Structures with C++\n" }, { "code": null, "e": 16156, "s": 16141, "text": "\nData Science\n" }, { "code": null, "e": 16171, "s": 16156, "text": "\nExplore More\n" }, { "code": null, "e": 16267, "s": 16171, "text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n" }, { "code": null, "e": 16285, "s": 16267, "text": "\nDSA- Self Paced\n" }, { "code": null, "e": 16291, "s": 16285, "text": "\nCIP\n" }, { "code": null, "e": 16313, "s": 16291, "text": "\nJAVA / Python / C++\n" }, { "code": null, "e": 16328, "s": 16313, "text": "\nExplore More\n" }, { "code": null, "e": 16439, "s": 16328, "text": "\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\nExplore more\n" }, { "code": null, "e": 16454, "s": 16439, "text": "\nSchool Guide\n" }, { "code": null, "e": 16475, "s": 16454, "text": "\nPython Programming\n" }, { "code": null, "e": 16496, "s": 16475, "text": "\nLearn To Make Apps\n" }, { "code": null, "e": 16511, "s": 16496, "text": "\nExplore more\n" }, { "code": null, "e": 16816, "s": 16511, "text": "\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n" }, { "code": null, "e": 16839, "s": 16816, "text": "\nSearching Algorithms\n" }, { "code": null, "e": 16860, "s": 16839, "text": "\nSorting Algorithms\n" }, { "code": null, "e": 16879, "s": 16860, "text": "\nGraph Algorithms\n" }, { "code": null, "e": 16899, "s": 16879, "text": "\nPattern Searching\n" }, { "code": null, "e": 16922, "s": 16899, "text": "\nGeometric Algorithms\n" }, { "code": null, "e": 16937, "s": 16922, "text": "\nMathematical\n" }, { "code": null, "e": 16958, "s": 16937, "text": "\nBitwise Algorithms\n" }, { "code": null, "e": 16982, "s": 16958, "text": "\nRandomized Algorithms\n" }, { "code": null, "e": 17002, "s": 16982, "text": "\nGreedy Algorithms\n" }, { "code": null, "e": 17024, "s": 17002, "text": "\nDynamic Programming\n" }, { "code": null, "e": 17045, "s": 17024, "text": "\nDivide and Conquer\n" }, { "code": null, "e": 17060, "s": 17045, "text": "\nBacktracking\n" }, { "code": null, "e": 17079, "s": 17060, "text": "\nBranch and Bound\n" }, { "code": null, "e": 17096, "s": 17079, "text": "\nAll Algorithms\n" }, { "code": null, "e": 17481, "s": 17096, "text": "\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n" }, { "code": null, "e": 17503, "s": 17481, "text": "\nAsymptotic Analysis\n" }, { "code": null, "e": 17535, "s": 17503, "text": "\nWorst, Average and Best Cases\n" }, { "code": null, "e": 17558, "s": 17535, "text": "\nAsymptotic Notations\n" }, { "code": null, "e": 17596, "s": 17558, "text": "\nLittle o and little omega notations\n" }, { "code": null, "e": 17627, "s": 17596, "text": "\nLower and Upper Bound Theory\n" }, { "code": null, "e": 17647, "s": 17627, "text": "\nAnalysis of Loops\n" }, { "code": null, "e": 17669, "s": 17647, "text": "\nSolving Recurrences\n" }, { "code": null, "e": 17690, "s": 17669, "text": "\nAmortized Analysis\n" }, { "code": null, "e": 17728, "s": 17690, "text": "\nWhat does 'Space Complexity' mean ?\n" }, { "code": null, "e": 17759, "s": 17728, "text": "\nPseudo-polynomial Algorithms\n" }, { "code": null, "e": 17798, "s": 17759, "text": "\nPolynomial Time Approximation Scheme\n" }, { "code": null, "e": 17827, "s": 17798, "text": "\nA Time Complexity Question\n" }, { "code": null, "e": 18024, "s": 17827, "text": "\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n" }, { "code": null, "e": 18033, "s": 18024, "text": "\nArrays\n" }, { "code": null, "e": 18047, "s": 18033, "text": "\nLinked List\n" }, { "code": null, "e": 18055, "s": 18047, "text": "\nStack\n" }, { "code": null, "e": 18063, "s": 18055, "text": "\nQueue\n" }, { "code": null, "e": 18077, "s": 18063, "text": "\nBinary Tree\n" }, { "code": null, "e": 18098, "s": 18077, "text": "\nBinary Search Tree\n" }, { "code": null, "e": 18105, "s": 18098, "text": "\nHeap\n" }, { "code": null, "e": 18115, "s": 18105, "text": "\nHashing\n" }, { "code": null, "e": 18123, "s": 18115, "text": "\nGraph\n" }, { "code": null, "e": 18149, "s": 18123, "text": "\nAdvanced Data Structure\n" }, { "code": null, "e": 18158, "s": 18149, "text": "\nMatrix\n" }, { "code": null, "e": 18168, "s": 18158, "text": "\nStrings\n" }, { "code": null, "e": 18190, "s": 18168, "text": "\nAll Data Structures\n" }, { "code": null, "e": 18458, "s": 18190, "text": "\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n" }, { "code": null, "e": 18480, "s": 18458, "text": "\nCompany Preparation\n" }, { "code": null, "e": 18493, "s": 18480, "text": "\nTop Topics\n" }, { "code": null, "e": 18522, "s": 18493, "text": "\nPractice Company Questions\n" }, { "code": null, "e": 18546, "s": 18522, "text": "\nInterview Experiences\n" }, { "code": null, "e": 18571, "s": 18546, "text": "\nExperienced Interviews\n" }, { "code": null, "e": 18595, "s": 18571, "text": "\nInternship Interviews\n" }, { "code": null, "e": 18622, "s": 18595, "text": "\nCompetititve Programming\n" }, { "code": null, "e": 18640, "s": 18622, "text": "\nDesign Patterns\n" }, { "code": null, "e": 18665, "s": 18640, "text": "\nSystem Design Tutorial\n" }, { "code": null, "e": 18691, "s": 18665, "text": "\nMultiple Choice Quizzes\n" }, { "code": null, "e": 18830, "s": 18691, "text": "\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n" }, { "code": null, "e": 18834, "s": 18830, "text": "\nC\n" }, { "code": null, "e": 18840, "s": 18834, "text": "\nC++\n" }, { "code": null, "e": 18847, "s": 18840, "text": "\nJava\n" }, { "code": null, "e": 18856, "s": 18847, "text": "\nPython\n" }, { "code": null, "e": 18861, "s": 18856, "text": "\nC#\n" }, { "code": null, "e": 18874, "s": 18861, "text": "\nJavaScript\n" }, { "code": null, "e": 18883, "s": 18874, "text": "\njQuery\n" }, { "code": null, "e": 18889, "s": 18883, "text": "\nSQL\n" }, { "code": null, "e": 18895, "s": 18889, "text": "\nPHP\n" }, { "code": null, "e": 18903, "s": 18895, "text": "\nScala\n" }, { "code": null, "e": 18910, "s": 18903, "text": "\nPerl\n" }, { "code": null, "e": 18924, "s": 18910, "text": "\nGo Language\n" }, { "code": null, "e": 18931, "s": 18924, "text": "\nHTML\n" }, { "code": null, "e": 18937, "s": 18931, "text": "\nCSS\n" }, { "code": null, "e": 18946, "s": 18937, "text": "\nKotlin\n" }, { "code": null, "e": 19024, "s": 18946, "text": "\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n" }, { "code": null, "e": 19043, "s": 19024, "text": "\nMachine Learning\n" }, { "code": null, "e": 19058, "s": 19043, "text": "\nData Science\n" }, { "code": null, "e": 19271, "s": 19058, "text": "\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n" }, { "code": null, "e": 19285, "s": 19271, "text": "\nMathematics\n" }, { "code": null, "e": 19304, "s": 19285, "text": "\nOperating System\n" }, { "code": null, "e": 19311, "s": 19304, "text": "\nDBMS\n" }, { "code": null, "e": 19331, "s": 19311, "text": "\nComputer Networks\n" }, { "code": null, "e": 19372, "s": 19331, "text": "\nComputer Organization and Architecture\n" }, { "code": null, "e": 19396, "s": 19372, "text": "\nTheory of Computation\n" }, { "code": null, "e": 19414, "s": 19396, "text": "\nCompiler Design\n" }, { "code": null, "e": 19430, "s": 19414, "text": "\nDigital Logic\n" }, { "code": null, "e": 19453, "s": 19430, "text": "\nSoftware Engineering\n" }, { "code": null, "e": 19670, "s": 19453, "text": "\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n" }, { "code": null, "e": 19700, "s": 19670, "text": "\nGATE Computer Science Notes\n" }, { "code": null, "e": 19720, "s": 19700, "text": "\nLast Minute Notes\n" }, { "code": null, "e": 19744, "s": 19720, "text": "\nGATE CS Solved Papers\n" }, { "code": null, "e": 19788, "s": 19744, "text": "\nGATE CS Original Papers and Official Keys\n" }, { "code": null, "e": 19806, "s": 19788, "text": "\nGATE 2021 Dates\n" }, { "code": null, "e": 19830, "s": 19806, "text": "\nGATE CS 2021 Syllabus\n" }, { "code": null, "e": 19861, "s": 19830, "text": "\nImportant Topics for GATE CS\n" }, { "code": null, "e": 19981, "s": 19861, "text": "\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n" }, { "code": null, "e": 19988, "s": 19981, "text": "\nHTML\n" }, { "code": null, "e": 19994, "s": 19988, "text": "\nCSS\n" }, { "code": null, "e": 20007, "s": 19994, "text": "\nJavaScript\n" }, { "code": null, "e": 20019, "s": 20007, "text": "\nAngularJS\n" }, { "code": null, "e": 20029, "s": 20019, "text": "\nReactJS\n" }, { "code": null, "e": 20038, "s": 20029, "text": "\nNodeJS\n" }, { "code": null, "e": 20050, "s": 20038, "text": "\nBootstrap\n" }, { "code": null, "e": 20059, "s": 20050, "text": "\njQuery\n" }, { "code": null, "e": 20065, "s": 20059, "text": "\nPHP\n" }, { "code": null, "e": 20160, "s": 20065, "text": "\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n" }, { "code": null, "e": 20187, "s": 20160, "text": "\nSoftware Design Patterns\n" }, { "code": null, "e": 20212, "s": 20187, "text": "\nSystem Design Tutorial\n" }, { "code": null, "e": 20276, "s": 20212, "text": "\nSchool Learning\n \n\n\nSchool Programming\n" }, { "code": null, "e": 20297, "s": 20276, "text": "\nSchool Programming\n" }, { "code": null, "e": 20433, "s": 20297, "text": "\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n" }, { "code": null, "e": 20449, "s": 20433, "text": "\nNumber System\n" }, { "code": null, "e": 20459, "s": 20449, "text": "\nAlgebra\n" }, { "code": null, "e": 20474, "s": 20459, "text": "\nTrigonometry\n" }, { "code": null, "e": 20487, "s": 20474, "text": "\nStatistics\n" }, { "code": null, "e": 20501, "s": 20487, "text": "\nProbability\n" }, { "code": null, "e": 20512, "s": 20501, "text": "\nGeometry\n" }, { "code": null, "e": 20526, "s": 20512, "text": "\nMensuration\n" }, { "code": null, "e": 20537, "s": 20526, "text": "\nCalculus\n" }, { "code": null, "e": 20668, "s": 20537, "text": "\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n" }, { "code": null, "e": 20684, "s": 20668, "text": "\nClass 8 Notes\n" }, { "code": null, "e": 20700, "s": 20684, "text": "\nClass 9 Notes\n" }, { "code": null, "e": 20717, "s": 20700, "text": "\nClass 10 Notes\n" }, { "code": null, "e": 20734, "s": 20717, "text": "\nClass 11 Notes\n" }, { "code": null, "e": 20751, "s": 20734, "text": "\nClass 12 Notes\n" }, { "code": null, "e": 20918, "s": 20751, "text": "\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n" }, { "code": null, "e": 20943, "s": 20918, "text": "\nClass 8 Maths Solution\n" }, { "code": null, "e": 20968, "s": 20943, "text": "\nClass 9 Maths Solution\n" }, { "code": null, "e": 20994, "s": 20968, "text": "\nClass 10 Maths Solution\n" }, { "code": null, "e": 21020, "s": 20994, "text": "\nClass 11 Maths Solution\n" }, { "code": null, "e": 21046, "s": 21020, "text": "\nClass 12 Maths Solution\n" }, { "code": null, "e": 21217, "s": 21046, "text": "\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n" }, { "code": null, "e": 21242, "s": 21217, "text": "\nClass 8 Maths Solution\n" }, { "code": null, "e": 21267, "s": 21242, "text": "\nClass 9 Maths Solution\n" }, { "code": null, "e": 21293, "s": 21267, "text": "\nClass 10 Maths Solution\n" }, { "code": null, "e": 21319, "s": 21293, "text": "\nClass 11 Maths Solution\n" }, { "code": null, "e": 21345, "s": 21319, "text": "\nClass 12 Maths Solution\n" }, { "code": null, "e": 21462, "s": 21345, "text": "\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n" }, { "code": null, "e": 21478, "s": 21462, "text": "\nClass 8 Notes\n" }, { "code": null, "e": 21494, "s": 21478, "text": "\nClass 9 Notes\n" }, { "code": null, "e": 21511, "s": 21494, "text": "\nClass 10 Notes\n" }, { "code": null, "e": 21528, "s": 21511, "text": "\nClass 11 Notes\n" }, { "code": null, "e": 21570, "s": 21528, "text": "\nCS Exams/PSUs\n \n\n" }, { "code": null, "e": 21715, "s": 21570, "text": "\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n" }, { "code": null, "e": 21759, "s": 21715, "text": "\nISRO CS Original Papers and Official Keys\n" }, { "code": null, "e": 21783, "s": 21759, "text": "\nISRO CS Solved Papers\n" }, { "code": null, "e": 21830, "s": 21783, "text": "\nISRO CS Syllabus for Scientist/Engineer Exam\n" }, { "code": null, "e": 21947, "s": 21830, "text": "\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n" }, { "code": null, "e": 21975, "s": 21947, "text": "\nUGC NET CS Notes Paper II\n" }, { "code": null, "e": 22004, "s": 21975, "text": "\nUGC NET CS Notes Paper III\n" }, { "code": null, "e": 22031, "s": 22004, "text": "\nUGC NET CS Solved Papers\n" }, { "code": null, "e": 22288, "s": 22031, "text": "\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nStudent Chapter\n\nGeek on the Top\n\nInternship\n\nCareers\n" }, { "code": null, "e": 22316, "s": 22288, "text": "\nCampus Ambassador Program\n" }, { "code": null, "e": 22344, "s": 22316, "text": "\nSchool Ambassador Program\n" }, { "code": null, "e": 22354, "s": 22344, "text": "\nProject\n" }, { "code": null, "e": 22374, "s": 22354, "text": "\nGeek of the Month\n" }, { "code": null, "e": 22401, "s": 22374, "text": "\nCampus Geek of the Month\n" }, { "code": null, "e": 22420, "s": 22401, "text": "\nPlacement Course\n" }, { "code": null, "e": 22447, "s": 22420, "text": "\nCompetititve Programming\n" }, { "code": null, "e": 22462, "s": 22447, "text": "\nTestimonials\n" }, { "code": null, "e": 22480, "s": 22462, "text": "\nStudent Chapter\n" }, { "code": null, "e": 22498, "s": 22480, "text": "\nGeek on the Top\n" }, { "code": null, "e": 22511, "s": 22498, "text": "\nInternship\n" }, { "code": null, "e": 22521, "s": 22511, "text": "\nCareers\n" }, { "code": null, "e": 22679, "s": 22521, "text": "\nCurated DSA Lists\n \n\n\nTop 50 Array Problems\n\nTop 50 String Problems\n\nTop 50 Tree Problems\n\nTop 50 Graph Problems\n\nTop 50 DP Problems\n" }, { "code": null, "e": 22703, "s": 22679, "text": "\nTop 50 Array Problems\n" }, { "code": null, "e": 22728, "s": 22703, "text": "\nTop 50 String Problems\n" }, { "code": null, "e": 22751, "s": 22728, "text": "\nTop 50 Tree Problems\n" }, { "code": null, "e": 22775, "s": 22751, "text": "\nTop 50 Graph Problems\n" }, { "code": null, "e": 22796, "s": 22775, "text": "\nTop 50 DP Problems\n" }, { "code": null, "e": 22834, "s": 22796, "text": "\nTutorials\n \n\n" }, { "code": null, "e": 22907, "s": 22834, "text": "\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n" }, { "code": null, "e": 22924, "s": 22907, "text": "\nApply for Jobs\n" }, { "code": null, "e": 22937, "s": 22924, "text": "\nPost a Job\n" }, { "code": null, "e": 22950, "s": 22937, "text": "\nJOB-A-THON\n" }, { "code": null, "e": 23136, "s": 22950, "text": "\nPractice\n \n\n\nAll DSA Problems\n\nProblem of the Day\n\nInterview Series: Weekly Contests\n\nBi-Wizard Coding: School Contests\n\nContests and Events\n\nPractice SDE Sheet\n" }, { "code": null, "e": 23155, "s": 23136, "text": "\nAll DSA Problems\n" }, { "code": null, "e": 23176, "s": 23155, "text": "\nProblem of the Day\n" }, { "code": null, "e": 23212, "s": 23176, "text": "\nInterview Series: Weekly Contests\n" }, { "code": null, "e": 23248, "s": 23212, "text": "\nBi-Wizard Coding: School Contests\n" }, { "code": null, "e": 23270, "s": 23248, "text": "\nContests and Events\n" }, { "code": null, "e": 23291, "s": 23270, "text": "\nPractice SDE Sheet\n" }, { "code": null, "e": 23297, "s": 23291, "text": "GBlog" }, { "code": null, "e": 23305, "s": 23297, "text": "Puzzles" }, { "code": null, "e": 23318, "s": 23305, "text": "What's New ?" }, { "code": null, "e": 23324, "s": 23318, "text": "Array" }, { "code": null, "e": 23331, "s": 23324, "text": "Matrix" }, { "code": null, "e": 23339, "s": 23331, "text": "Strings" }, { "code": null, "e": 23347, "s": 23339, "text": "Hashing" }, { "code": null, "e": 23359, "s": 23347, "text": "Linked List" }, { "code": null, "e": 23365, "s": 23359, "text": "Stack" }, { "code": null, "e": 23371, "s": 23365, "text": "Queue" }, { "code": null, "e": 23383, "s": 23371, "text": "Binary Tree" }, { "code": null, "e": 23402, "s": 23383, "text": "Binary Search Tree" }, { "code": null, "e": 23407, "s": 23402, "text": "Heap" }, { "code": null, "e": 23413, "s": 23407, "text": "Graph" }, { "code": null, "e": 23423, "s": 23413, "text": "Searching" }, { "code": null, "e": 23431, "s": 23423, "text": "Sorting" }, { "code": null, "e": 23448, "s": 23431, "text": "Divide & Conquer" }, { "code": null, "e": 23461, "s": 23448, "text": "Mathematical" }, { "code": null, "e": 23471, "s": 23461, "text": "Geometric" }, { "code": null, "e": 23479, "s": 23471, "text": "Bitwise" }, { "code": null, "e": 23486, "s": 23479, "text": "Greedy" }, { "code": null, "e": 23499, "s": 23486, "text": "Backtracking" }, { "code": null, "e": 23516, "s": 23499, "text": "Branch and Bound" }, { "code": null, "e": 23536, "s": 23516, "text": "Dynamic Programming" }, { "code": null, "e": 23554, "s": 23536, "text": "Pattern Searching" }, { "code": null, "e": 23565, "s": 23554, "text": "Randomized" }, { "code": null, "e": 27422, "s": 23565, "text": "Data StructuresArrayIntroduction to ArraysArrays in C/C++Arrays in JavaProgram for array rotationReversal algorithm for array rotationBlock swap algorithm for array rotationRearrange an array such that arr[i] = iWrite a program to reverse an array or stringRearrange array such that arr[i] >= arr[j] if i is even and arr[i]<=arr[j] if i is odd and j < iLinked ListLinked List | Set 1 (Introduction)Linked List vs ArrayLinked List | Set 2 (Inserting a node)Linked List | Set 3 (Deleting a node)Delete a Linked List node at a given positionCircular Linked List | Set 1 (Introduction and Applications)Circular Linked List | Set 2 (Traversal)Split a Circular Linked List into two halvesSorted insert for circular linked listStackStack Data Structure (Introduction and Program)Stack in C++ STLStack Class in JavaStack in PythonC# Stack with ExamplesQueue using StacksDesign and Implement Special Stack Data Structure | Added Space Optimized VersionImplement two stacks in an arrayImplement Stack using QueuesQueueQueue | Set 1 (Introduction and Array Implementation)Applications of Queue Data StructurePriority Queue | Set 1 (Introduction)Applications of Priority QueueDeque | Set 1 (Introduction and Applications)LRU Cache ImplementationQueue – Linked List ImplementationBinary TreeBinary Tree | Set 1 (Introduction)Binary Tree | Set 2 (Properties)Binary Tree | Set 3 (Types of Binary Tree)Tree Traversals (Inorder, Preorder and Postorder)Inorder Tree Traversal without RecursionInorder Tree Traversal without recursion and without stack!Construct Tree from given Inorder and Preorder traversalsConstruct a tree from Inorder and Level order traversals | Set 1Construct Complete Binary Tree from its Linked List RepresentationBinary Search TreeBinary Search Tree | Set 1 (Search and Insertion)Binary Search Tree | Set 2 (Delete)Advantages of BST over Hash TableConstruct BST from given preorder traversal | Set 1Construct BST from given preorder traversal | Set 2Binary Tree to Binary Search Tree ConversionSorted Linked List to Balanced BSTSorted Array to Balanced BSTFind the node with minimum value in a Binary Search TreeHeapBinary HeapTime Complexity of building a heapApplications of Heap Data StructureBinomial HeapFibonacci Heap | Set 1 (Introduction)Leftist Tree / Leftist HeapK-ary HeapHeapSortIterative HeapSortHashingHashing | Set 1 (Introduction)Index Mapping (or Trivial Hashing) with negatives allowedHashing | Set 2 (Separate Chaining)Hashing | Set 3 (Open Addressing)Double HashingPrint a Binary Tree in Vertical Order | Set 2 (Map based Method)Find whether an array is subset of another array | Added Method 5Union and Intersection of two linked lists | Set-3 (Hashing)Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)GraphGraph and its representationsBreadth First Search or BFS for a GraphDepth First Search or DFS for a GraphDetect Cycle in a Directed GraphDetect cycle in an undirected graphDetect Cycle in a directed graph using colorsTopological SortingAll Topological Sorts of a Directed Acyclic GraphKahn’s algorithm for Topological SortingMatrixRotate Matrix ElementsInplace rotate square matrix by 90 degrees | Set 1Rotate a matrix by 90 degree without using any extra space | Set 2Rotate a Matrix by 180 degreeRotate each ring of matrix anticlockwise by K elementsTurn an image by 90 degreeCheck if all rows of a matrix are circular rotations of each otherSort the given matrixFind the row with maximum number of 1sFind median in row wise sorted matrixAdvanced Data StructureMemory efficient doubly linked listXOR Linked List – A Memory Efficient Doubly Linked List | Set 1XOR Linked List – A Memory Efficient Doubly Linked List | Set 2Memory efficient doubly linked listXOR Linked List – A Memory Efficient Doubly Linked List | Set 1XOR Linked List – A Memory Efficient Doubly Linked List | Set 2" }, { "code": null, "e": 27445, "s": 27422, "text": "Introduction to Arrays" }, { "code": null, "e": 27461, "s": 27445, "text": "Arrays in C/C++" }, { "code": null, "e": 27476, "s": 27461, "text": "Arrays in Java" }, { "code": null, "e": 27503, "s": 27476, "text": "Program for array rotation" }, { "code": null, "e": 27541, "s": 27503, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 27581, "s": 27541, "text": "Block swap algorithm for array rotation" }, { "code": null, "e": 27621, "s": 27581, "text": "Rearrange an array such that arr[i] = i" }, { "code": null, "e": 27667, "s": 27621, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 27764, "s": 27667, "text": "Rearrange array such that arr[i] >= arr[j] if i is even and arr[i]<=arr[j] if i is odd and j < i" }, { "code": null, "e": 27799, "s": 27764, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 27820, "s": 27799, "text": "Linked List vs Array" }, { "code": null, "e": 27859, "s": 27820, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 27897, "s": 27859, "text": "Linked List | Set 3 (Deleting a node)" }, { "code": null, "e": 27943, "s": 27897, "text": "Delete a Linked List node at a given position" }, { "code": null, "e": 28004, "s": 27943, "text": "Circular Linked List | Set 1 (Introduction and Applications)" }, { "code": null, "e": 28045, "s": 28004, "text": "Circular Linked List | Set 2 (Traversal)" }, { "code": null, "e": 28090, "s": 28045, "text": "Split a Circular Linked List into two halves" }, { "code": null, "e": 28129, "s": 28090, "text": "Sorted insert for circular linked list" }, { "code": null, "e": 28177, "s": 28129, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 28194, "s": 28177, "text": "Stack in C++ STL" }, { "code": null, "e": 28214, "s": 28194, "text": "Stack Class in Java" }, { "code": null, "e": 28230, "s": 28214, "text": "Stack in Python" }, { "code": null, "e": 28253, "s": 28230, "text": "C# Stack with Examples" }, { "code": null, "e": 28272, "s": 28253, "text": "Queue using Stacks" }, { "code": null, "e": 28354, "s": 28272, "text": "Design and Implement Special Stack Data Structure | Added Space Optimized Version" }, { "code": null, "e": 28387, "s": 28354, "text": "Implement two stacks in an array" }, { "code": null, "e": 28416, "s": 28387, "text": "Implement Stack using Queues" }, { "code": null, "e": 28470, "s": 28416, "text": "Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 28507, "s": 28470, "text": "Applications of Queue Data Structure" }, { "code": null, "e": 28545, "s": 28507, "text": "Priority Queue | Set 1 (Introduction)" }, { "code": null, "e": 28576, "s": 28545, "text": "Applications of Priority Queue" }, { "code": null, "e": 28622, "s": 28576, "text": "Deque | Set 1 (Introduction and Applications)" }, { "code": null, "e": 28647, "s": 28622, "text": "LRU Cache Implementation" }, { "code": null, "e": 28682, "s": 28647, "text": "Queue – Linked List Implementation" }, { "code": null, "e": 28717, "s": 28682, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 28750, "s": 28717, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 28793, "s": 28750, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 28843, "s": 28793, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 28884, "s": 28843, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 28944, "s": 28884, "text": "Inorder Tree Traversal without recursion and without stack!" }, { "code": null, "e": 29002, "s": 28944, "text": "Construct Tree from given Inorder and Preorder traversals" }, { "code": null, "e": 29067, "s": 29002, "text": "Construct a tree from Inorder and Level order traversals | Set 1" }, { "code": null, "e": 29134, "s": 29067, "text": "Construct Complete Binary Tree from its Linked List Representation" }, { "code": null, "e": 29184, "s": 29134, "text": "Binary Search Tree | Set 1 (Search and Insertion)" }, { "code": null, "e": 29220, "s": 29184, "text": "Binary Search Tree | Set 2 (Delete)" }, { "code": null, "e": 29254, "s": 29220, "text": "Advantages of BST over Hash Table" }, { "code": null, "e": 29306, "s": 29254, "text": "Construct BST from given preorder traversal | Set 1" }, { "code": null, "e": 29358, "s": 29306, "text": "Construct BST from given preorder traversal | Set 2" }, { "code": null, "e": 29403, "s": 29358, "text": "Binary Tree to Binary Search Tree Conversion" }, { "code": null, "e": 29438, "s": 29403, "text": "Sorted Linked List to Balanced BST" }, { "code": null, "e": 29467, "s": 29438, "text": "Sorted Array to Balanced BST" }, { "code": null, "e": 29524, "s": 29467, "text": "Find the node with minimum value in a Binary Search Tree" }, { "code": null, "e": 29536, "s": 29524, "text": "Binary Heap" }, { "code": null, "e": 29571, "s": 29536, "text": "Time Complexity of building a heap" }, { "code": null, "e": 29607, "s": 29571, "text": "Applications of Heap Data Structure" }, { "code": null, "e": 29621, "s": 29607, "text": "Binomial Heap" }, { "code": null, "e": 29659, "s": 29621, "text": "Fibonacci Heap | Set 1 (Introduction)" }, { "code": null, "e": 29687, "s": 29659, "text": "Leftist Tree / Leftist Heap" }, { "code": null, "e": 29698, "s": 29687, "text": "K-ary Heap" }, { "code": null, "e": 29707, "s": 29698, "text": "HeapSort" }, { "code": null, "e": 29726, "s": 29707, "text": "Iterative HeapSort" }, { "code": null, "e": 29757, "s": 29726, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 29815, "s": 29757, "text": "Index Mapping (or Trivial Hashing) with negatives allowed" }, { "code": null, "e": 29851, "s": 29815, "text": "Hashing | Set 2 (Separate Chaining)" }, { "code": null, "e": 29885, "s": 29851, "text": "Hashing | Set 3 (Open Addressing)" }, { "code": null, "e": 29900, "s": 29885, "text": "Double Hashing" }, { "code": null, "e": 29965, "s": 29900, "text": "Print a Binary Tree in Vertical Order | Set 2 (Map based Method)" }, { "code": null, "e": 30031, "s": 29965, "text": "Find whether an array is subset of another array | Added Method 5" }, { "code": null, "e": 30092, "s": 30031, "text": "Union and Intersection of two linked lists | Set-3 (Hashing)" }, { "code": null, "e": 30177, "s": 30092, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 30207, "s": 30177, "text": "Graph and its representations" }, { "code": null, "e": 30247, "s": 30207, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 30285, "s": 30247, "text": "Depth First Search or DFS for a Graph" }, { "code": null, "e": 30318, "s": 30285, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 30354, "s": 30318, "text": "Detect cycle in an undirected graph" }, { "code": null, "e": 30400, "s": 30354, "text": "Detect Cycle in a directed graph using colors" }, { "code": null, "e": 30420, "s": 30400, "text": "Topological Sorting" }, { "code": null, "e": 30470, "s": 30420, "text": "All Topological Sorts of a Directed Acyclic Graph" }, { "code": null, "e": 30511, "s": 30470, "text": "Kahn’s algorithm for Topological Sorting" }, { "code": null, "e": 30534, "s": 30511, "text": "Rotate Matrix Elements" }, { "code": null, "e": 30585, "s": 30534, "text": "Inplace rotate square matrix by 90 degrees | Set 1" }, { "code": null, "e": 30652, "s": 30585, "text": "Rotate a matrix by 90 degree without using any extra space | Set 2" }, { "code": null, "e": 30682, "s": 30652, "text": "Rotate a Matrix by 180 degree" }, { "code": null, "e": 30737, "s": 30682, "text": "Rotate each ring of matrix anticlockwise by K elements" }, { "code": null, "e": 30764, "s": 30737, "text": "Turn an image by 90 degree" }, { "code": null, "e": 30831, "s": 30764, "text": "Check if all rows of a matrix are circular rotations of each other" }, { "code": null, "e": 30853, "s": 30831, "text": "Sort the given matrix" }, { "code": null, "e": 30892, "s": 30853, "text": "Find the row with maximum number of 1s" }, { "code": null, "e": 30930, "s": 30892, "text": "Find median in row wise sorted matrix" }, { "code": null, "e": 30966, "s": 30930, "text": "Memory efficient doubly linked list" }, { "code": null, "e": 31030, "s": 30966, "text": "XOR Linked List – A Memory Efficient Doubly Linked List | Set 1" }, { "code": null, "e": 31094, "s": 31030, "text": "XOR Linked List – A Memory Efficient Doubly Linked List | Set 2" }, { "code": null, "e": 31130, "s": 31094, "text": "Memory efficient doubly linked list" }, { "code": null, "e": 31194, "s": 31130, "text": "XOR Linked List – A Memory Efficient Doubly Linked List | Set 1" }, { "code": null, "e": 31258, "s": 31194, "text": "XOR Linked List – A Memory Efficient Doubly Linked List | Set 2" }, { "code": null, "e": 35115, "s": 31258, "text": "Data StructuresArrayIntroduction to ArraysArrays in C/C++Arrays in JavaProgram for array rotationReversal algorithm for array rotationBlock swap algorithm for array rotationRearrange an array such that arr[i] = iWrite a program to reverse an array or stringRearrange array such that arr[i] >= arr[j] if i is even and arr[i]<=arr[j] if i is odd and j < iLinked ListLinked List | Set 1 (Introduction)Linked List vs ArrayLinked List | Set 2 (Inserting a node)Linked List | Set 3 (Deleting a node)Delete a Linked List node at a given positionCircular Linked List | Set 1 (Introduction and Applications)Circular Linked List | Set 2 (Traversal)Split a Circular Linked List into two halvesSorted insert for circular linked listStackStack Data Structure (Introduction and Program)Stack in C++ STLStack Class in JavaStack in PythonC# Stack with ExamplesQueue using StacksDesign and Implement Special Stack Data Structure | Added Space Optimized VersionImplement two stacks in an arrayImplement Stack using QueuesQueueQueue | Set 1 (Introduction and Array Implementation)Applications of Queue Data StructurePriority Queue | Set 1 (Introduction)Applications of Priority QueueDeque | Set 1 (Introduction and Applications)LRU Cache ImplementationQueue – Linked List ImplementationBinary TreeBinary Tree | Set 1 (Introduction)Binary Tree | Set 2 (Properties)Binary Tree | Set 3 (Types of Binary Tree)Tree Traversals (Inorder, Preorder and Postorder)Inorder Tree Traversal without RecursionInorder Tree Traversal without recursion and without stack!Construct Tree from given Inorder and Preorder traversalsConstruct a tree from Inorder and Level order traversals | Set 1Construct Complete Binary Tree from its Linked List RepresentationBinary Search TreeBinary Search Tree | Set 1 (Search and Insertion)Binary Search Tree | Set 2 (Delete)Advantages of BST over Hash TableConstruct BST from given preorder traversal | Set 1Construct BST from given preorder traversal | Set 2Binary Tree to Binary Search Tree ConversionSorted Linked List to Balanced BSTSorted Array to Balanced BSTFind the node with minimum value in a Binary Search TreeHeapBinary HeapTime Complexity of building a heapApplications of Heap Data StructureBinomial HeapFibonacci Heap | Set 1 (Introduction)Leftist Tree / Leftist HeapK-ary HeapHeapSortIterative HeapSortHashingHashing | Set 1 (Introduction)Index Mapping (or Trivial Hashing) with negatives allowedHashing | Set 2 (Separate Chaining)Hashing | Set 3 (Open Addressing)Double HashingPrint a Binary Tree in Vertical Order | Set 2 (Map based Method)Find whether an array is subset of another array | Added Method 5Union and Intersection of two linked lists | Set-3 (Hashing)Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)GraphGraph and its representationsBreadth First Search or BFS for a GraphDepth First Search or DFS for a GraphDetect Cycle in a Directed GraphDetect cycle in an undirected graphDetect Cycle in a directed graph using colorsTopological SortingAll Topological Sorts of a Directed Acyclic GraphKahn’s algorithm for Topological SortingMatrixRotate Matrix ElementsInplace rotate square matrix by 90 degrees | Set 1Rotate a matrix by 90 degree without using any extra space | Set 2Rotate a Matrix by 180 degreeRotate each ring of matrix anticlockwise by K elementsTurn an image by 90 degreeCheck if all rows of a matrix are circular rotations of each otherSort the given matrixFind the row with maximum number of 1sFind median in row wise sorted matrixAdvanced Data StructureMemory efficient doubly linked listXOR Linked List – A Memory Efficient Doubly Linked List | Set 1XOR Linked List – A Memory Efficient Doubly Linked List | Set 2Memory efficient doubly linked listXOR Linked List – A Memory Efficient Doubly Linked List | Set 1XOR Linked List – A Memory Efficient Doubly Linked List | Set 2" }, { "code": null, "e": 35138, "s": 35115, "text": "Introduction to Arrays" }, { "code": null, "e": 35154, "s": 35138, "text": "Arrays in C/C++" }, { "code": null, "e": 35169, "s": 35154, "text": "Arrays in Java" }, { "code": null, "e": 35196, "s": 35169, "text": "Program for array rotation" }, { "code": null, "e": 35234, "s": 35196, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 35274, "s": 35234, "text": "Block swap algorithm for array rotation" }, { "code": null, "e": 35314, "s": 35274, "text": "Rearrange an array such that arr[i] = i" }, { "code": null, "e": 35360, "s": 35314, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 35457, "s": 35360, "text": "Rearrange array such that arr[i] >= arr[j] if i is even and arr[i]<=arr[j] if i is odd and j < i" }, { "code": null, "e": 35492, "s": 35457, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 35513, "s": 35492, "text": "Linked List vs Array" }, { "code": null, "e": 35552, "s": 35513, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 35590, "s": 35552, "text": "Linked List | Set 3 (Deleting a node)" }, { "code": null, "e": 35636, "s": 35590, "text": "Delete a Linked List node at a given position" }, { "code": null, "e": 35697, "s": 35636, "text": "Circular Linked List | Set 1 (Introduction and Applications)" }, { "code": null, "e": 35738, "s": 35697, "text": "Circular Linked List | Set 2 (Traversal)" }, { "code": null, "e": 35783, "s": 35738, "text": "Split a Circular Linked List into two halves" }, { "code": null, "e": 35822, "s": 35783, "text": "Sorted insert for circular linked list" }, { "code": null, "e": 35870, "s": 35822, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 35887, "s": 35870, "text": "Stack in C++ STL" }, { "code": null, "e": 35907, "s": 35887, "text": "Stack Class in Java" }, { "code": null, "e": 35923, "s": 35907, "text": "Stack in Python" }, { "code": null, "e": 35946, "s": 35923, "text": "C# Stack with Examples" }, { "code": null, "e": 35965, "s": 35946, "text": "Queue using Stacks" }, { "code": null, "e": 36047, "s": 35965, "text": "Design and Implement Special Stack Data Structure | Added Space Optimized Version" }, { "code": null, "e": 36080, "s": 36047, "text": "Implement two stacks in an array" }, { "code": null, "e": 36109, "s": 36080, "text": "Implement Stack using Queues" }, { "code": null, "e": 36163, "s": 36109, "text": "Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 36200, "s": 36163, "text": "Applications of Queue Data Structure" }, { "code": null, "e": 36238, "s": 36200, "text": "Priority Queue | Set 1 (Introduction)" }, { "code": null, "e": 36269, "s": 36238, "text": "Applications of Priority Queue" }, { "code": null, "e": 36315, "s": 36269, "text": "Deque | Set 1 (Introduction and Applications)" }, { "code": null, "e": 36340, "s": 36315, "text": "LRU Cache Implementation" }, { "code": null, "e": 36375, "s": 36340, "text": "Queue – Linked List Implementation" }, { "code": null, "e": 36410, "s": 36375, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 36443, "s": 36410, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 36486, "s": 36443, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 36536, "s": 36486, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 36577, "s": 36536, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 36637, "s": 36577, "text": "Inorder Tree Traversal without recursion and without stack!" }, { "code": null, "e": 36695, "s": 36637, "text": "Construct Tree from given Inorder and Preorder traversals" }, { "code": null, "e": 36760, "s": 36695, "text": "Construct a tree from Inorder and Level order traversals | Set 1" }, { "code": null, "e": 36827, "s": 36760, "text": "Construct Complete Binary Tree from its Linked List Representation" }, { "code": null, "e": 36877, "s": 36827, "text": "Binary Search Tree | Set 1 (Search and Insertion)" }, { "code": null, "e": 36913, "s": 36877, "text": "Binary Search Tree | Set 2 (Delete)" }, { "code": null, "e": 36947, "s": 36913, "text": "Advantages of BST over Hash Table" }, { "code": null, "e": 36999, "s": 36947, "text": "Construct BST from given preorder traversal | Set 1" }, { "code": null, "e": 37051, "s": 36999, "text": "Construct BST from given preorder traversal | Set 2" }, { "code": null, "e": 37096, "s": 37051, "text": "Binary Tree to Binary Search Tree Conversion" }, { "code": null, "e": 37131, "s": 37096, "text": "Sorted Linked List to Balanced BST" }, { "code": null, "e": 37160, "s": 37131, "text": "Sorted Array to Balanced BST" }, { "code": null, "e": 37217, "s": 37160, "text": "Find the node with minimum value in a Binary Search Tree" }, { "code": null, "e": 37229, "s": 37217, "text": "Binary Heap" }, { "code": null, "e": 37264, "s": 37229, "text": "Time Complexity of building a heap" }, { "code": null, "e": 37300, "s": 37264, "text": "Applications of Heap Data Structure" }, { "code": null, "e": 37314, "s": 37300, "text": "Binomial Heap" }, { "code": null, "e": 37352, "s": 37314, "text": "Fibonacci Heap | Set 1 (Introduction)" }, { "code": null, "e": 37380, "s": 37352, "text": "Leftist Tree / Leftist Heap" }, { "code": null, "e": 37391, "s": 37380, "text": "K-ary Heap" }, { "code": null, "e": 37400, "s": 37391, "text": "HeapSort" }, { "code": null, "e": 37419, "s": 37400, "text": "Iterative HeapSort" }, { "code": null, "e": 37450, "s": 37419, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 37508, "s": 37450, "text": "Index Mapping (or Trivial Hashing) with negatives allowed" }, { "code": null, "e": 37544, "s": 37508, "text": "Hashing | Set 2 (Separate Chaining)" }, { "code": null, "e": 37578, "s": 37544, "text": "Hashing | Set 3 (Open Addressing)" }, { "code": null, "e": 37593, "s": 37578, "text": "Double Hashing" }, { "code": null, "e": 37658, "s": 37593, "text": "Print a Binary Tree in Vertical Order | Set 2 (Map based Method)" }, { "code": null, "e": 37724, "s": 37658, "text": "Find whether an array is subset of another array | Added Method 5" }, { "code": null, "e": 37785, "s": 37724, "text": "Union and Intersection of two linked lists | Set-3 (Hashing)" }, { "code": null, "e": 37870, "s": 37785, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 37900, "s": 37870, "text": "Graph and its representations" }, { "code": null, "e": 37940, "s": 37900, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 37978, "s": 37940, "text": "Depth First Search or DFS for a Graph" }, { "code": null, "e": 38011, "s": 37978, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 38047, "s": 38011, "text": "Detect cycle in an undirected graph" }, { "code": null, "e": 38093, "s": 38047, "text": "Detect Cycle in a directed graph using colors" }, { "code": null, "e": 38113, "s": 38093, "text": "Topological Sorting" }, { "code": null, "e": 38163, "s": 38113, "text": "All Topological Sorts of a Directed Acyclic Graph" }, { "code": null, "e": 38204, "s": 38163, "text": "Kahn’s algorithm for Topological Sorting" }, { "code": null, "e": 38227, "s": 38204, "text": "Rotate Matrix Elements" }, { "code": null, "e": 38278, "s": 38227, "text": "Inplace rotate square matrix by 90 degrees | Set 1" }, { "code": null, "e": 38345, "s": 38278, "text": "Rotate a matrix by 90 degree without using any extra space | Set 2" }, { "code": null, "e": 38375, "s": 38345, "text": "Rotate a Matrix by 180 degree" }, { "code": null, "e": 38430, "s": 38375, "text": "Rotate each ring of matrix anticlockwise by K elements" }, { "code": null, "e": 38457, "s": 38430, "text": "Turn an image by 90 degree" }, { "code": null, "e": 38524, "s": 38457, "text": "Check if all rows of a matrix are circular rotations of each other" }, { "code": null, "e": 38546, "s": 38524, "text": "Sort the given matrix" }, { "code": null, "e": 38585, "s": 38546, "text": "Find the row with maximum number of 1s" }, { "code": null, "e": 38623, "s": 38585, "text": "Find median in row wise sorted matrix" }, { "code": null, "e": 38659, "s": 38623, "text": "Memory efficient doubly linked list" }, { "code": null, "e": 38723, "s": 38659, "text": "XOR Linked List – A Memory Efficient Doubly Linked List | Set 1" }, { "code": null, "e": 38787, "s": 38723, "text": "XOR Linked List – A Memory Efficient Doubly Linked List | Set 2" }, { "code": null, "e": 38823, "s": 38787, "text": "Memory efficient doubly linked list" }, { "code": null, "e": 38887, "s": 38823, "text": "XOR Linked List – A Memory Efficient Doubly Linked List | Set 1" }, { "code": null, "e": 38951, "s": 38887, "text": "XOR Linked List – A Memory Efficient Doubly Linked List | Set 2" }, { "code": null, "e": 38975, "s": 38951, "text": "Difficulty Level :\nHard" }, { "code": null, "e": 39458, "s": 38975, "text": "How to implement LRU caching scheme? What data structures should be used? We are given the total possible page numbers that can be referred. We are also given cache (or memory) size (The number of page frames that the cache can hold at a time). The LRU caching scheme is to remove the least recently used frame when the cache is full and a new page is referenced which is not there in the cache. Please see the Galvin book for more details (see the LRU page replacement slide here)." }, { "code": null, "e": 39514, "s": 39458, "text": "We use two data structures to implement an LRU Cache. " }, { "code": null, "e": 39857, "s": 39514, "text": "Queue is implemented using a doubly-linked list. The maximum size of the queue will be equal to the total number of frames available (cache size). The most recently used pages will be near the front end and the least recently pages will be near the rear end.A Hash with page number as key and address of the corresponding queue node as value." }, { "code": null, "e": 40116, "s": 39857, "text": "Queue is implemented using a doubly-linked list. The maximum size of the queue will be equal to the total number of frames available (cache size). The most recently used pages will be near the front end and the least recently pages will be near the rear end." }, { "code": null, "e": 40201, "s": 40116, "text": "A Hash with page number as key and address of the corresponding queue node as value." }, { "code": null, "e": 40696, "s": 40201, "text": "When a page is referenced, the required page may be in the memory. If it is in the memory, we need to detach the node of the list and bring it to the front of the queue. If the required page is not in memory, we bring that in memory. In simple words, we add a new node to the front of the queue and update the corresponding node address in the hash. If the queue is full, i.e. all the frames are full, we remove a node from the rear of the queue, and add the new node to the front of the queue." }, { "code": null, "e": 40750, "s": 40696, "text": "Example – Consider the following reference string : " }, { "code": null, "e": 40785, "s": 40750, "text": "1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5" }, { "code": null, "e": 40900, "s": 40785, "text": "Find the number of page faults using the least recently used (LRU) page replacement algorithm with 3-page frames. " }, { "code": null, "e": 40915, "s": 40900, "text": "Explanation – " }, { "code": null, "e": 40959, "s": 40917, "text": "Note: Initially no page is in the memory." }, { "code": null, "e": 40963, "s": 40959, "text": "C++" }, { "code": null, "e": 40965, "s": 40963, "text": "C" }, { "code": null, "e": 40970, "s": 40965, "text": "Java" }, { "code": "// We can use stl container list as a double// ended queue to store the cache keys, with// the descending time of reference from front// to back and a set container to check presence// of a key. But to fetch the address of the key// in the list using find(), it takes O(N) time.// This can be optimized by storing a reference// (iterator) to each key in a hash map.#include <bits/stdc++.h>using namespace std; class LRUCache { // store keys of cache list<int> dq; // store references of key in cache unordered_map<int, list<int>::iterator> ma; int csize; // maximum capacity of cache public: LRUCache(int); void refer(int); void display();}; // Declare the sizeLRUCache::LRUCache(int n){ csize = n;} // Refers key x with in the LRU cachevoid LRUCache::refer(int x){ // not present in cache if (ma.find(x) == ma.end()) { // cache is full if (dq.size() == csize) { // delete least recently used element int last = dq.back(); // Pops the last element dq.pop_back(); // Erase the last ma.erase(last); } } // present in cache else dq.erase(ma[x]); // update reference dq.push_front(x); ma[x] = dq.begin();} // Function to display contents of cachevoid LRUCache::display(){ // Iterate in the deque and print // all the elements in it for (auto it = dq.begin(); it != dq.end(); it++) cout << (*it) << \" \"; cout << endl;} // Driver Codeint main(){ LRUCache ca(4); ca.refer(1); ca.refer(2); ca.refer(3); ca.refer(1); ca.refer(4); ca.refer(5); ca.display(); return 0;}// This code is contributed by Satish Srinivas", "e": 42702, "s": 40970, "text": null }, { "code": "// A C program to show implementation of LRU cache#include <stdio.h>#include <stdlib.h> // A Queue Node (Queue is implemented using Doubly Linked List)typedef struct QNode { struct QNode *prev, *next; unsigned pageNumber; // the page number stored in this QNode} QNode; // A Queue (A FIFO collection of Queue Nodes)typedef struct Queue { unsigned count; // Number of filled frames unsigned numberOfFrames; // total number of frames QNode *front, *rear;} Queue; // A hash (Collection of pointers to Queue Nodes)typedef struct Hash { int capacity; // how many pages can be there QNode** array; // an array of queue nodes} Hash; // A utility function to create a new Queue Node. The queue Node// will store the given 'pageNumber'QNode* newQNode(unsigned pageNumber){ // Allocate memory and assign 'pageNumber' QNode* temp = (QNode*)malloc(sizeof(QNode)); temp->pageNumber = pageNumber; // Initialize prev and next as NULL temp->prev = temp->next = NULL; return temp;} // A utility function to create an empty Queue.// The queue can have at most 'numberOfFrames' nodesQueue* createQueue(int numberOfFrames){ Queue* queue = (Queue*)malloc(sizeof(Queue)); // The queue is empty queue->count = 0; queue->front = queue->rear = NULL; // Number of frames that can be stored in memory queue->numberOfFrames = numberOfFrames; return queue;} // A utility function to create an empty Hash of given capacityHash* createHash(int capacity){ // Allocate memory for hash Hash* hash = (Hash*)malloc(sizeof(Hash)); hash->capacity = capacity; // Create an array of pointers for referring queue nodes hash->array = (QNode**)malloc(hash->capacity * sizeof(QNode*)); // Initialize all hash entries as empty int i; for (i = 0; i < hash->capacity; ++i) hash->array[i] = NULL; return hash;} // A function to check if there is slot available in memoryint AreAllFramesFull(Queue* queue){ return queue->count == queue->numberOfFrames;} // A utility function to check if queue is emptyint isQueueEmpty(Queue* queue){ return queue->rear == NULL;} // A utility function to delete a frame from queuevoid deQueue(Queue* queue){ if (isQueueEmpty(queue)) return; // If this is the only node in list, then change front if (queue->front == queue->rear) queue->front = NULL; // Change rear and remove the previous rear QNode* temp = queue->rear; queue->rear = queue->rear->prev; if (queue->rear) queue->rear->next = NULL; free(temp); // decrement the number of full frames by 1 queue->count--;} // A function to add a page with given 'pageNumber' to both queue// and hashvoid Enqueue(Queue* queue, Hash* hash, unsigned pageNumber){ // If all frames are full, remove the page at the rear if (AreAllFramesFull(queue)) { // remove page from hash hash->array[queue->rear->pageNumber] = NULL; deQueue(queue); } // Create a new node with given page number, // And add the new node to the front of queue QNode* temp = newQNode(pageNumber); temp->next = queue->front; // If queue is empty, change both front and rear pointers if (isQueueEmpty(queue)) queue->rear = queue->front = temp; else // Else change the front { queue->front->prev = temp; queue->front = temp; } // Add page entry to hash also hash->array[pageNumber] = temp; // increment number of full frames queue->count++;} // This function is called when a page with given 'pageNumber' is referenced// from cache (or memory). There are two cases:// 1. Frame is not there in memory, we bring it in memory and add to the front// of queue// 2. Frame is there in memory, we move the frame to front of queuevoid ReferencePage(Queue* queue, Hash* hash, unsigned pageNumber){ QNode* reqPage = hash->array[pageNumber]; // the page is not in cache, bring it if (reqPage == NULL) Enqueue(queue, hash, pageNumber); // page is there and not at front, change pointer else if (reqPage != queue->front) { // Unlink rquested page from its current location // in queue. reqPage->prev->next = reqPage->next; if (reqPage->next) reqPage->next->prev = reqPage->prev; // If the requested page is rear, then change rear // as this node will be moved to front if (reqPage == queue->rear) { queue->rear = reqPage->prev; queue->rear->next = NULL; } // Put the requested page before current front reqPage->next = queue->front; reqPage->prev = NULL; // Change prev of current front reqPage->next->prev = reqPage; // Change front to the requested page queue->front = reqPage; }} // Driver program to test above functionsint main(){ // Let cache can hold 4 pages Queue* q = createQueue(4); // Let 10 different pages can be requested (pages to be // referenced are numbered from 0 to 9 Hash* hash = createHash(10); // Let us refer pages 1, 2, 3, 1, 4, 5 ReferencePage(q, hash, 1); ReferencePage(q, hash, 2); ReferencePage(q, hash, 3); ReferencePage(q, hash, 1); ReferencePage(q, hash, 4); ReferencePage(q, hash, 5); // Let us print cache frames after the above referenced pages printf(\"%d \", q->front->pageNumber); printf(\"%d \", q->front->next->pageNumber); printf(\"%d \", q->front->next->next->pageNumber); printf(\"%d \", q->front->next->next->next->pageNumber); return 0;}", "e": 48279, "s": 42702, "text": null }, { "code": "/* We can use Java inbuilt Deque as a double ended queue to store the cache keys, with the descending time of reference from front to back and a set container to check presence of a key. But remove a key from the Deque using remove(), it takes O(N) time. This can be optimized by storing a reference (iterator) to each key in a hash map. */import java.util.Deque;import java.util.HashSet; import java.util.LinkedList; import java.util.Iterator; public class LRUCache { // store keys of cache private Deque<Integer> doublyQueue; // store references of key in cache private HashSet<Integer> hashSet; // maximum capacity of cache private final int CACHE_SIZE; LRUCache(int capacity) { doublyQueue = new LinkedList<>(); hashSet = new HashSet<>(); CACHE_SIZE = capacity; } /* Refer the page within the LRU cache */ public void refer(int page) { if (!hashSet.contains(page)) { if (doublyQueue.size() == CACHE_SIZE) { int last = doublyQueue.removeLast(); hashSet.remove(last); } } else {/* The found page may not be always the last element, even if it's an intermediate element that needs to be removed and added to the start of the Queue */ doublyQueue.remove(page); } doublyQueue.push(page); hashSet.add(page); } // display contents of cache public void display() { Iterator<Integer> itr = doublyQueue.iterator(); while (itr.hasNext()) { System.out.print(itr.next() + \" \"); } } public static void main(String[] args) { LRUCache cache = new LRUCache(4); cache.refer(1); cache.refer(2); cache.refer(3); cache.refer(1); cache.refer(4); cache.refer(5); cache.display(); }} // This code is contributed by Niraj Kumar", "e": 50212, "s": 48279, "text": null }, { "code": null, "e": 50221, "s": 50212, "text": "5 4 1 3 " }, { "code": null, "e": 50393, "s": 50221, "text": "Java Implementation using LinkedHashMap. The idea is to use a LinkedHashSet that maintains the insertion order of elements. This way implementation becomes short and easy." }, { "code": null, "e": 50398, "s": 50393, "text": "Java" }, { "code": "// Java program to implement LRU cache// using LinkedHashSetimport java.util.*; class LRUCache { Set<Integer> cache; int capacity; public LRUCache(int capacity) { this.cache = new LinkedHashSet<Integer>(capacity); this.capacity = capacity; } // This function returns false if key is not // present in cache. Else it moves the key to // front by first removing it and then adding // it, and returns true. public boolean get(int key) { if (!cache.contains(key)) return false; cache.remove(key); cache.add(key); return true; } /* Refers key x with in the LRU cache */ public void refer(int key) { if (get(key) == false) put(key); } // displays contents of cache in Reverse Order public void display() { LinkedList<Integer> list = new LinkedList<>(cache); // The descendingIterator() method of java.util.LinkedList // class is used to return an iterator over the elements // in this LinkedList in reverse sequential order Iterator<Integer> itr = list.descendingIterator(); while (itr.hasNext()) System.out.print(itr.next() + \" \"); } public void put(int key) { if (cache.size() == capacity) { int firstKey = cache.iterator().next(); cache.remove(firstKey); } cache.add(key); } public static void main(String[] args) { LRUCache ca = new LRUCache(4); ca.refer(1); ca.refer(2); ca.refer(3); ca.refer(1); ca.refer(4); ca.refer(5); ca.display(); }}", "e": 52083, "s": 50398, "text": null }, { "code": null, "e": 52092, "s": 52083, "text": "5 4 1 3 " }, { "code": null, "e": 52337, "s": 52092, "text": "Python implementation using OrderedDictThis article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 52352, "s": 52337, "text": "_Gaurav_Tiwari" }, { "code": null, "e": 52359, "s": 52352, "text": "spattk" }, { "code": null, "e": 52377, "s": 52359, "text": "MadhaviVaddepalli" }, { "code": null, "e": 52386, "s": 52377, "text": "Majorssn" }, { "code": null, "e": 52397, "s": 52386, "text": "nirajtechi" }, { "code": null, "e": 52412, "s": 52397, "text": "sudhanshublaze" }, { "code": null, "e": 52427, "s": 52412, "text": "adnanirshad158" }, { "code": null, "e": 52441, "s": 52427, "text": "sumitgumber28" }, { "code": null, "e": 52453, "s": 52441, "text": "sharanaseem" }, { "code": null, "e": 52460, "s": 52453, "text": "Amazon" }, { "code": null, "e": 52478, "s": 52460, "text": "cpp-unordered_map" }, { "code": null, "e": 52489, "s": 52478, "text": "MakeMyTrip" }, { "code": null, "e": 52504, "s": 52489, "text": "Morgan Stanley" }, { "code": null, "e": 52513, "s": 52504, "text": "Snapdeal" }, { "code": null, "e": 52517, "s": 52513, "text": "STL" }, { "code": null, "e": 52541, "s": 52517, "text": "Advanced Data Structure" }, { "code": null, "e": 52549, "s": 52541, "text": "GATE CS" }, { "code": null, "e": 52567, "s": 52549, "text": "Operating Systems" }, { "code": null, "e": 52573, "s": 52567, "text": "Queue" }, { "code": null, "e": 52588, "s": 52573, "text": "Morgan Stanley" }, { "code": null, "e": 52595, "s": 52588, "text": "Amazon" }, { "code": null, "e": 52604, "s": 52595, "text": "Snapdeal" }, { "code": null, "e": 52615, "s": 52604, "text": "MakeMyTrip" }, { "code": null, "e": 52633, "s": 52615, "text": "Operating Systems" }, { "code": null, "e": 52639, "s": 52633, "text": "Queue" }, { "code": null, "e": 52643, "s": 52639, "text": "STL" }, { "code": null, "e": 52741, "s": 52643, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 52770, "s": 52741, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 52797, "s": 52770, "text": "Trie | (Insert and Search)" }, { "code": null, "e": 52835, "s": 52797, "text": "Red-Black Tree | Set 1 (Introduction)" }, { "code": null, "e": 52858, "s": 52835, "text": "Introduction of B-Tree" }, { "code": null, "e": 52892, "s": 52858, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 52912, "s": 52892, "text": "Layers of OSI Model" }, { "code": null, "e": 52936, "s": 52912, "text": "ACID Properties in DBMS" }, { "code": null, "e": 52949, "s": 52936, "text": "TCP/IP Model" }, { "code": null, "e": 52976, "s": 52949, "text": "Types of Operating Systems" } ]
MongoDB - Map Reduce - GeeksforGeeks
05 Feb, 2021 In MongoDB, map-reduce is a data processing programming model that helps to perform operations on large data sets and produce aggregated results. MongoDB provides the mapReduce() function to perform the map-reduce operations. This function has two main functions, i.e., map function and reduce function. The map function is used to group all the data based on the key-value and the reduce function is used to perform operations on the mapped data. So, the data is independently mapped and reduced in different spaces and then combined together in the function and the result will save to the specified new collection. This mapReduce() function generally operated on large data sets only. Using Map Reduce you can perform aggregation operations such as max, avg on the data using some key and it is similar to groupBy in SQL. It performs on data independently and parallel. Let’s try to understand the mapReduce() using the following example: In this example, we have five records from which we need to take out the maximum marks of each section and the keys are id, sec, marks. {"id":1, "sec":A, "marks":80} {"id":2, "sec":A, "marks":90} {"id":1, "sec":B, "marks":99} {"id":1, "sec":B, "marks":95} {"id":1, "sec":C, "marks":90} Here we need to find the maximum marks in each section. So, our key by which we will group documents is the sec key and the value will be marks. Inside the map function, we use emit(this.sec, this.marks) function, and we will return the sec and marks of each record(document) from the emit function. This is similar to group By MySQL. var map = function(){emit(this.sec, this.marks)}; After iterating over each document Emit function will give back the data like this: {“A”:[80, 90]}, {“B”:[99, 90]}, {“C”:[90] } and upto this point it is what map() function does. The data given by emit function is grouped by sec key, Now this data will be input to our reduce function. Reduce function is where actual aggregation of data takes place. In our example we will pick the Max of each section like for sec A:[80, 90] = 90 (Max) B:[99, 90] = 99 (max) , C:[90] = 90(max). var reduce = function(sec,marks){return Array.max(marks);}; Here in reduce() function, we have reduced the records now we will output them into a new collection.{out :”collectionName”} db.collectionName.mapReduce(map,reduce,{out :"collectionName"}); In the above query we have already defined the map, reduce. Then for checking we need to look into the newly created collection we can use the query db.collectionName.find() we get: {"id":"A", value:90} {"id":"B", value:99} {"id":"C", value:90} Syntax: db.collectionName.mapReduce( ... map(), ...reduce(), ...query{}, ...output{} ); Here, map() function: It uses emit() function in which it takes two parameters key and value key. Here the key is on which we make groups like groups by in MySQL. Example like group by ages or names and the second parameter is on which aggregation is performed like avg(), sum() is calculated on. reduce() function: It is the step in which we perform our aggregate function like avg(), sum(). query: Here we will pass the query to filter the resultset. output: In this, we will specify the collection name where the result will be stored. Example 1: In this example, we are working with: Database: geeksforgeeks2 Collection: employee Documents: Six documents that contains the details of the employees Find the sum of ranks grouped by ages: var map=function(){ emit(this.age,this.rank)}; var reduce=function(age,rank){ return Array.sum(rank);}; db.employee.mapReduce(map,reduce,{out :"resultCollection1"}); Here, we will calculate the sum of rank present inside the particular age group. Now age is our key on which we will perform group by (like in MySQL) and rank will be the key on which we will perform sum aggregation. Inside map() function, i.e., map() : function map(){ emit(this.age,this.rank);}; we will write the emit(this.age,this.rank) function. Here this represents the current collection being iterated and the first key is age using age we will group the result like having age 24 give the sum of all rank or having age 25 give the sum of all rank and the second argument is rank on which aggregation will be performed. Inside the reduce function, i.e., reduce(): function reduce(key,rank){ return Array.sum(rank); }; we will perform the aggregation function. Now the third parameter will be output where we will define the collection where the result will be saved, i.e., {out :”resultCollection1′′}. Here, out represents the key whose value is the collection name where the result will be saved. Performing avg() aggregation on rank grouped by ages: var map=function(){ emit(this.age,this.rank)}; var reduce=function(age,rank){ return Array.avg(rank);}; db.employee.mapReduce(map,reduce,{out :"resultCollection3"}); db.resultCollection3.find() In this example, we will calculate the average of the ranks grouped by age. So, map(): Function map(){ emit(this.age, this.rank)};. Here age is the key by which we will group and rank is the key on which avg() aggregation will be performed. reduce(): Function reduce (age,rank){ return Array.avg(rank)l}; output: {out:”resultCollection3′′} In MongoDB, you can use Map-reduce when your aggregation query is slow because data is present in a large amount and the aggregation query is taking more time to process. So using map-reduce you can perform action faster than aggregation query. MongoDB-method Picked MongoDB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to connect MongoDB with ReactJS ? MongoDB - limit() Method MongoDB - FindOne() Method Create user and add role in MongoDB MongoDB - sort() Method MongoDB updateOne() Method - db.Collection.updateOne() MongoDB insertMany() Method - db.Collection.insertMany() MongoDB Cursor MongoDB - Update() Method MongoDB updateMany() Method - db.Collection.updateMany()
[ { "code": null, "e": 25517, "s": 25489, "text": "\n05 Feb, 2021" }, { "code": null, "e": 26459, "s": 25517, "text": "In MongoDB, map-reduce is a data processing programming model that helps to perform operations on large data sets and produce aggregated results. MongoDB provides the mapReduce() function to perform the map-reduce operations. This function has two main functions, i.e., map function and reduce function. The map function is used to group all the data based on the key-value and the reduce function is used to perform operations on the mapped data. So, the data is independently mapped and reduced in different spaces and then combined together in the function and the result will save to the specified new collection. This mapReduce() function generally operated on large data sets only. Using Map Reduce you can perform aggregation operations such as max, avg on the data using some key and it is similar to groupBy in SQL. It performs on data independently and parallel. Let’s try to understand the mapReduce() using the following example:" }, { "code": null, "e": 26595, "s": 26459, "text": "In this example, we have five records from which we need to take out the maximum marks of each section and the keys are id, sec, marks." }, { "code": null, "e": 26745, "s": 26595, "text": "{\"id\":1, \"sec\":A, \"marks\":80}\n{\"id\":2, \"sec\":A, \"marks\":90}\n{\"id\":1, \"sec\":B, \"marks\":99}\n{\"id\":1, \"sec\":B, \"marks\":95}\n{\"id\":1, \"sec\":C, \"marks\":90}" }, { "code": null, "e": 27080, "s": 26745, "text": "Here we need to find the maximum marks in each section. So, our key by which we will group documents is the sec key and the value will be marks. Inside the map function, we use emit(this.sec, this.marks) function, and we will return the sec and marks of each record(document) from the emit function. This is similar to group By MySQL." }, { "code": null, "e": 27130, "s": 27080, "text": "var map = function(){emit(this.sec, this.marks)};" }, { "code": null, "e": 27214, "s": 27130, "text": "After iterating over each document Emit function will give back the data like this:" }, { "code": null, "e": 27261, "s": 27214, "text": "{“A”:[80, 90]}, {“B”:[99, 90]}, {“C”:[90] } " }, { "code": null, "e": 27615, "s": 27261, "text": "and upto this point it is what map() function does. The data given by emit function is grouped by sec key, Now this data will be input to our reduce function. Reduce function is where actual aggregation of data takes place. In our example we will pick the Max of each section like for sec A:[80, 90] = 90 (Max) B:[99, 90] = 99 (max) , C:[90] = 90(max)." }, { "code": null, "e": 27675, "s": 27615, "text": "var reduce = function(sec,marks){return Array.max(marks);};" }, { "code": null, "e": 27800, "s": 27675, "text": "Here in reduce() function, we have reduced the records now we will output them into a new collection.{out :”collectionName”}" }, { "code": null, "e": 27865, "s": 27800, "text": "db.collectionName.mapReduce(map,reduce,{out :\"collectionName\"});" }, { "code": null, "e": 28047, "s": 27865, "text": "In the above query we have already defined the map, reduce. Then for checking we need to look into the newly created collection we can use the query db.collectionName.find() we get:" }, { "code": null, "e": 28110, "s": 28047, "text": "{\"id\":\"A\", value:90}\n{\"id\":\"B\", value:99}\n{\"id\":\"C\", value:90}" }, { "code": null, "e": 28119, "s": 28110, "text": "Syntax: " }, { "code": null, "e": 28199, "s": 28119, "text": "db.collectionName.mapReduce(\n... map(),\n...reduce(),\n...query{},\n...output{}\n);" }, { "code": null, "e": 28205, "s": 28199, "text": "Here," }, { "code": null, "e": 28496, "s": 28205, "text": "map() function: It uses emit() function in which it takes two parameters key and value key. Here the key is on which we make groups like groups by in MySQL. Example like group by ages or names and the second parameter is on which aggregation is performed like avg(), sum() is calculated on." }, { "code": null, "e": 28593, "s": 28496, "text": "reduce() function: It is the step in which we perform our aggregate function like avg(), sum()." }, { "code": null, "e": 28653, "s": 28593, "text": "query: Here we will pass the query to filter the resultset." }, { "code": null, "e": 28739, "s": 28653, "text": "output: In this, we will specify the collection name where the result will be stored." }, { "code": null, "e": 28750, "s": 28739, "text": "Example 1:" }, { "code": null, "e": 28788, "s": 28750, "text": "In this example, we are working with:" }, { "code": null, "e": 28813, "s": 28788, "text": "Database: geeksforgeeks2" }, { "code": null, "e": 28834, "s": 28813, "text": "Collection: employee" }, { "code": null, "e": 28902, "s": 28834, "text": "Documents: Six documents that contains the details of the employees" }, { "code": null, "e": 28941, "s": 28902, "text": "Find the sum of ranks grouped by ages:" }, { "code": null, "e": 29107, "s": 28941, "text": "var map=function(){ emit(this.age,this.rank)};\nvar reduce=function(age,rank){ return Array.sum(rank);};\ndb.employee.mapReduce(map,reduce,{out :\"resultCollection1\"});" }, { "code": null, "e": 29324, "s": 29107, "text": "Here, we will calculate the sum of rank present inside the particular age group. Now age is our key on which we will perform group by (like in MySQL) and rank will be the key on which we will perform sum aggregation." }, { "code": null, "e": 29735, "s": 29324, "text": "Inside map() function, i.e., map() : function map(){ emit(this.age,this.rank);}; we will write the emit(this.age,this.rank) function. Here this represents the current collection being iterated and the first key is age using age we will group the result like having age 24 give the sum of all rank or having age 25 give the sum of all rank and the second argument is rank on which aggregation will be performed." }, { "code": null, "e": 29875, "s": 29735, "text": "Inside the reduce function, i.e., reduce(): function reduce(key,rank){ return Array.sum(rank); }; we will perform the aggregation function." }, { "code": null, "e": 30113, "s": 29875, "text": "Now the third parameter will be output where we will define the collection where the result will be saved, i.e., {out :”resultCollection1′′}. Here, out represents the key whose value is the collection name where the result will be saved." }, { "code": null, "e": 30167, "s": 30113, "text": "Performing avg() aggregation on rank grouped by ages:" }, { "code": null, "e": 30361, "s": 30167, "text": "var map=function(){ emit(this.age,this.rank)};\nvar reduce=function(age,rank){ return Array.avg(rank);};\ndb.employee.mapReduce(map,reduce,{out :\"resultCollection3\"});\ndb.resultCollection3.find()" }, { "code": null, "e": 30442, "s": 30361, "text": "In this example, we will calculate the average of the ranks grouped by age. So, " }, { "code": null, "e": 30603, "s": 30442, "text": "map(): Function map(){ emit(this.age, this.rank)};. Here age is the key by which we will group and rank is the key on which avg() aggregation will be performed." }, { "code": null, "e": 30667, "s": 30603, "text": "reduce(): Function reduce (age,rank){ return Array.avg(rank)l};" }, { "code": null, "e": 30702, "s": 30667, "text": "output: {out:”resultCollection3′′}" }, { "code": null, "e": 30948, "s": 30702, "text": "In MongoDB, you can use Map-reduce when your aggregation query is slow because data is present in a large amount and the aggregation query is taking more time to process. So using map-reduce you can perform action faster than aggregation query. " }, { "code": null, "e": 30963, "s": 30948, "text": "MongoDB-method" }, { "code": null, "e": 30970, "s": 30963, "text": "Picked" }, { "code": null, "e": 30978, "s": 30970, "text": "MongoDB" }, { "code": null, "e": 31076, "s": 30978, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31114, "s": 31076, "text": "How to connect MongoDB with ReactJS ?" }, { "code": null, "e": 31139, "s": 31114, "text": "MongoDB - limit() Method" }, { "code": null, "e": 31166, "s": 31139, "text": "MongoDB - FindOne() Method" }, { "code": null, "e": 31202, "s": 31166, "text": "Create user and add role in MongoDB" }, { "code": null, "e": 31226, "s": 31202, "text": "MongoDB - sort() Method" }, { "code": null, "e": 31281, "s": 31226, "text": "MongoDB updateOne() Method - db.Collection.updateOne()" }, { "code": null, "e": 31338, "s": 31281, "text": "MongoDB insertMany() Method - db.Collection.insertMany()" }, { "code": null, "e": 31353, "s": 31338, "text": "MongoDB Cursor" }, { "code": null, "e": 31379, "s": 31353, "text": "MongoDB - Update() Method" } ]
Projection Perspective in Machine Learning - GeeksforGeeks
30 May, 2021 Before getting into projection perspective, let us first understand a technique known as PCA, what is the need for it and where it is used. Principal Component Analysis: It is an adaptive data analysis technique used for reducing the dimensionality of large datasets, increasing interpretability while minimizing information and reconstruction losses. In machine learning terms, it is used to reduce the number of parameters (regressors) based on how much they contribute to predicting the output so that they can be represented graphically in a 2D/3D plot. Let us consider the following regression model with 5 input parameters. where, y -> output (dependent variable). x1, ..., x5 -> input parameters / regressors (independent variable). w1, ..., w5 -> weights assigned to the input parameters. It is not possible to represent this model graphically as there is 5 variable, but we can only plot data up to 3 dimensions. Therefore, we use PCA which takes in an input n where n represents the n most important regressors that contribute to finding the output y. Say n = 2, then we will get 2 new parameters that will best determine the output y is the equation now will be: It is really easy to represent data in 2 dimensions. Projection Perspective It is a technique used in PCA that further minimizes the data reconstruction cost. Data reconstruction simply means reducing the data point in higher dimensions to lower dimensions where it is easily interpretable. In this method, we will focus on the difference between the original data vector xi and the reconstructed data vector xi‘. For this, we find a subspace (line) that minimizes the difference vector between the original data point and its projection as shown in Fig 1. Fig 1: Illustration of the projection approach Linear Independence It states that there will always be a set of vectors with which we can represent every vector in the vector space by adding them together and scaling them. This set of vectors is called the basis. Generally, we can add vectors together and multiply them with scalars as shown in the equation given below: where, V -> vector space v -> formed vector x1...i -> original vector λ1...i -> scalar values Intuition Consider an orthogonal basis, B = (b1, . . . , bN). Orthogonal Basis implies biTbj = 1 iff (i = j) and 0 otherwise. As per the concept of linear independence, basis B can be defined as a linear combination of the basis vectors. (equation given below) where, v -> linear combination of basis vector existing in the higher dimension. x -> suitable coordinates for v. Now, we are interested in finding out a vector v’, that exists in the lower dimension U (called the principal subspace) where, dim(U) = I. We can find v’ by using the following equation: where, v' -> new vector existing in the lower dimensions. y -> suitable coordinates for v'. Assuming that coordinates yi and xi are not identical to each other. Based on the above 2 equations, we ensure that the vector v’ found in the lower dimension is as similar as possible to the vector v in the higher dimension. Now, the objective is to minimize the difference between the vector present in the higher and lower dimension (or minimizing the reconstruction error). To measure the similarity between vectors v and v’, we find the squared Euclidean distance (also known as Reconstruction error) between them using the following equation: Consider the image given below: On observing the graph on the left, we have mapped the projections of data points on the 3D plane. However, we cannot easily segregate the data into distinct clusters as they may overlap with each other. Using a projection perspective in PCA, we can project the 3D data points onto a 2D plane. This way it becomes easier to interpret the data into distinct clusters. This is the big advantage of using different perspective methods like projection perspective in the PCA algorithm. For any doubt/query comment below. Machine Learning 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 k-nearest neighbor algorithm in Python Markov Decision Process Singular Value Decomposition (SVD) Python | Decision Tree Regression using sklearn Q-Learning in Python
[ { "code": null, "e": 25589, "s": 25561, "text": "\n30 May, 2021" }, { "code": null, "e": 25730, "s": 25589, "text": "Before getting into projection perspective, let us first understand a technique known as PCA, what is the need for it and where it is used. " }, { "code": null, "e": 25761, "s": 25730, "text": "Principal Component Analysis: " }, { "code": null, "e": 26222, "s": 25761, "text": "It is an adaptive data analysis technique used for reducing the dimensionality of large datasets, increasing interpretability while minimizing information and reconstruction losses. In machine learning terms, it is used to reduce the number of parameters (regressors) based on how much they contribute to predicting the output so that they can be represented graphically in a 2D/3D plot. Let us consider the following regression model with 5 input parameters. " }, { "code": null, "e": 26391, "s": 26222, "text": "where, \ny -> output (dependent variable).\nx1, ..., x5 -> input parameters / regressors (independent variable).\nw1, ..., w5 -> weights assigned to the input parameters. " }, { "code": null, "e": 26768, "s": 26391, "text": "It is not possible to represent this model graphically as there is 5 variable, but we can only plot data up to 3 dimensions. Therefore, we use PCA which takes in an input n where n represents the n most important regressors that contribute to finding the output y. Say n = 2, then we will get 2 new parameters that will best determine the output y is the equation now will be:" }, { "code": null, "e": 26822, "s": 26768, "text": "It is really easy to represent data in 2 dimensions. " }, { "code": null, "e": 26845, "s": 26822, "text": "Projection Perspective" }, { "code": null, "e": 27327, "s": 26845, "text": "It is a technique used in PCA that further minimizes the data reconstruction cost. Data reconstruction simply means reducing the data point in higher dimensions to lower dimensions where it is easily interpretable. In this method, we will focus on the difference between the original data vector xi and the reconstructed data vector xi‘. For this, we find a subspace (line) that minimizes the difference vector between the original data point and its projection as shown in Fig 1. " }, { "code": null, "e": 27374, "s": 27327, "text": "Fig 1: Illustration of the projection approach" }, { "code": null, "e": 27395, "s": 27374, "text": "Linear Independence " }, { "code": null, "e": 27700, "s": 27395, "text": "It states that there will always be a set of vectors with which we can represent every vector in the vector space by adding them together and scaling them. This set of vectors is called the basis. Generally, we can add vectors together and multiply them with scalars as shown in the equation given below:" }, { "code": null, "e": 27795, "s": 27700, "text": "where, \nV -> vector space\nv -> formed vector\nx1...i -> original vector\nλ1...i -> scalar values" }, { "code": null, "e": 27805, "s": 27795, "text": "Intuition" }, { "code": null, "e": 27857, "s": 27805, "text": "Consider an orthogonal basis, B = (b1, . . . , bN)." }, { "code": null, "e": 27949, "s": 27857, "text": "Orthogonal Basis implies biTbj = 1 iff (i = j) and 0 otherwise. " }, { "code": null, "e": 28085, "s": 27949, "text": " As per the concept of linear independence, basis B can be defined as a linear combination of the basis vectors. (equation given below)" }, { "code": null, "e": 28199, "s": 28085, "text": "where,\nv -> linear combination of basis vector existing in the higher dimension.\nx -> suitable coordinates for v." }, { "code": null, "e": 28386, "s": 28199, "text": "Now, we are interested in finding out a vector v’, that exists in the lower dimension U (called the principal subspace) where, dim(U) = I. We can find v’ by using the following equation:" }, { "code": null, "e": 28479, "s": 28386, "text": "where, \nv' -> new vector existing in the lower dimensions.\ny -> suitable coordinates for v'." }, { "code": null, "e": 28549, "s": 28479, "text": "Assuming that coordinates yi and xi are not identical to each other. " }, { "code": null, "e": 28706, "s": 28549, "text": "Based on the above 2 equations, we ensure that the vector v’ found in the lower dimension is as similar as possible to the vector v in the higher dimension." }, { "code": null, "e": 29030, "s": 28706, "text": "Now, the objective is to minimize the difference between the vector present in the higher and lower dimension (or minimizing the reconstruction error). To measure the similarity between vectors v and v’, we find the squared Euclidean distance (also known as Reconstruction error) between them using the following equation: " }, { "code": null, "e": 29062, "s": 29030, "text": "Consider the image given below:" }, { "code": null, "e": 29580, "s": 29062, "text": "On observing the graph on the left, we have mapped the projections of data points on the 3D plane. However, we cannot easily segregate the data into distinct clusters as they may overlap with each other. Using a projection perspective in PCA, we can project the 3D data points onto a 2D plane. This way it becomes easier to interpret the data into distinct clusters. This is the big advantage of using different perspective methods like projection perspective in the PCA algorithm. For any doubt/query comment below. " }, { "code": null, "e": 29597, "s": 29580, "text": "Machine Learning" }, { "code": null, "e": 29614, "s": 29597, "text": "Machine Learning" }, { "code": null, "e": 29712, "s": 29614, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29753, "s": 29712, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 29786, "s": 29753, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 29814, "s": 29786, "text": "Intuition of Adam Optimizer" }, { "code": null, "e": 29850, "s": 29814, "text": "CNN | Introduction to Pooling Layer" }, { "code": null, "e": 29905, "s": 29850, "text": "Convolutional Neural Network (CNN) in Machine Learning" }, { "code": null, "e": 29944, "s": 29905, "text": "k-nearest neighbor algorithm in Python" }, { "code": null, "e": 29968, "s": 29944, "text": "Markov Decision Process" }, { "code": null, "e": 30003, "s": 29968, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 30051, "s": 30003, "text": "Python | Decision Tree Regression using sklearn" } ]
Flutter - Asset Image - GeeksforGeeks
08 Dec, 2020 Flutter is an open-source, cross-platform UI development kit developed by Google. It is gaining popularity these days, as the app made in flutter can run on various devices regardless of their platform. It is majorly used to develop applications for Android and iOS, as a single app made in flutter can work efficiently on both platforms. In this article, we will learn how to add images in the flutter app. A flutter app when built has both assets (resources) and code. Assets are available and deployed during runtime. The asset is a file that can include static data, configuration files, icons, and images. The Flutter app supports many image formats, such as JPEG, WebP, PNG, GIF, animated WebP/GIF, BMP, and WBMP. Syntax: Image.asset('image name') 1. Create a new folder It should be in the root of your flutter project. You can name it whatever you want, but assets are preferred. If you want to add other assets to your app, like fonts, it is preferred to make another subfolder named images. 2. Now you can copy your image to images sub-folder. The path should look like assets/images/yourImage. Before adding images also check the above-mentioned supported image formats. 3. Register the assets folder in pubspec.yaml file and update it. a) To add images, write the following code: flutter: assets: - assets/images/yourFirstImage.jpg - assets/image/yourSecondImage.jpg b) If you want to include all the images of the assets folder then add this: flutter: assets: - assets/images/ Note: Take care of the indentation, assets should be properly indented to avoid any error. 4. Insert the image code in the file, where you want to add the image. Image.asset('assets/images/GeeksforGeeks.jpg') Dart import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root // of your application @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Insert Image Demo'), ), body: Center( child: Column( children: <Widget>[ Image.asset('assets/images/GeeksforGeeks.jpg'), ], ), ), ), ); } } 5. Now you can save all the files and run the app, you will find the output as shown below. Output : Flutter Dart How To Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar Flutter - Checkbox Widget ListView Class in Flutter Flutter - Flexible Widget Flutter - BoxShadow Widget How to Install PIP on Windows ? How to Find the Wi-Fi Password Using CMD in Windows? How to install Jupyter Notebook on Windows? How to Align Text in HTML? How to Install OpenCV for Python on Windows?
[ { "code": null, "e": 25159, "s": 25131, "text": "\n08 Dec, 2020" }, { "code": null, "e": 25499, "s": 25159, "text": "Flutter is an open-source, cross-platform UI development kit developed by Google. It is gaining popularity these days, as the app made in flutter can run on various devices regardless of their platform. It is majorly used to develop applications for Android and iOS, as a single app made in flutter can work efficiently on both platforms. " }, { "code": null, "e": 25881, "s": 25499, "text": "In this article, we will learn how to add images in the flutter app. A flutter app when built has both assets (resources) and code. Assets are available and deployed during runtime. The asset is a file that can include static data, configuration files, icons, and images. The Flutter app supports many image formats, such as JPEG, WebP, PNG, GIF, animated WebP/GIF, BMP, and WBMP. " }, { "code": null, "e": 25889, "s": 25881, "text": "Syntax:" }, { "code": null, "e": 25916, "s": 25889, "text": "Image.asset('image name')\n" }, { "code": null, "e": 25940, "s": 25916, "text": "1. Create a new folder " }, { "code": null, "e": 26051, "s": 25940, "text": "It should be in the root of your flutter project. You can name it whatever you want, but assets are preferred." }, { "code": null, "e": 26164, "s": 26051, "text": "If you want to add other assets to your app, like fonts, it is preferred to make another subfolder named images." }, { "code": null, "e": 26347, "s": 26166, "text": "2. Now you can copy your image to images sub-folder. The path should look like assets/images/yourImage. Before adding images also check the above-mentioned supported image formats." }, { "code": null, "e": 26415, "s": 26347, "text": "3. Register the assets folder in pubspec.yaml file and update it. " }, { "code": null, "e": 26459, "s": 26415, "text": "a) To add images, write the following code:" }, { "code": null, "e": 26568, "s": 26459, "text": "flutter: \n assets:\n - assets/images/yourFirstImage.jpg\n - assets/image/yourSecondImage.jpg\n" }, { "code": null, "e": 26645, "s": 26568, "text": "b) If you want to include all the images of the assets folder then add this:" }, { "code": null, "e": 26711, "s": 26645, "text": "flutter: \n assets: \n - assets/images/\n" }, { "code": null, "e": 26804, "s": 26713, "text": "Note: Take care of the indentation, assets should be properly indented to avoid any error." }, { "code": null, "e": 26875, "s": 26804, "text": "4. Insert the image code in the file, where you want to add the image." }, { "code": null, "e": 26923, "s": 26875, "text": "Image.asset('assets/images/GeeksforGeeks.jpg')\n" }, { "code": null, "e": 26928, "s": 26923, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root // of your application @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Insert Image Demo'), ), body: Center( child: Column( children: <Widget>[ Image.asset('assets/images/GeeksforGeeks.jpg'), ], ), ), ), ); } } ", "e": 27536, "s": 26928, "text": null }, { "code": null, "e": 27632, "s": 27538, "text": "5. Now you can save all the files and run the app, you will find the output as shown below. " }, { "code": null, "e": 27642, "s": 27632, "text": "Output : " }, { "code": null, "e": 27652, "s": 27644, "text": "Flutter" }, { "code": null, "e": 27657, "s": 27652, "text": "Dart" }, { "code": null, "e": 27664, "s": 27657, "text": "How To" }, { "code": null, "e": 27762, "s": 27664, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27801, "s": 27762, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 27827, "s": 27801, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 27853, "s": 27827, "text": "ListView Class in Flutter" }, { "code": null, "e": 27879, "s": 27853, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 27906, "s": 27879, "text": "Flutter - BoxShadow Widget" }, { "code": null, "e": 27938, "s": 27906, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27991, "s": 27938, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 28035, "s": 27991, "text": "How to install Jupyter Notebook on Windows?" }, { "code": null, "e": 28062, "s": 28035, "text": "How to Align Text in HTML?" } ]
Python | simpy.nextprime() method - GeeksforGeeks
03 Aug, 2021 In simpy module, we can get the next prime number for a given number n using sympy.nextprime() function. For n < 2^64 the answer is definitive; larger n values have a small probability of actually being pseudoprimes. Syntax: sympy.nextprime() Parameter: n; number to be tested Return: next prime value Code #1: Python3 # Python program to get next prime number# using sympy.nextprime() method # importing sympy modulefrom sympy import * # calling nextprime function on different numbersnextprime(7)nextprime(13)nextprime(2) Output: 11 17 3 Code #2: Python3 # Python program to check prime number# using sympy.isprime() method # importing sympy moduleimport sympy.ntheory as nt # calling isprime function on different numbersnt.nextprime(30)nt.nextprime(13)nt.nextprime(2) Output: 31 17 3 gulshankumarar231 SymPy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Convert integer to string in Python Create a Pandas DataFrame from Lists Check if element exists in list in Python sum() function in Python
[ { "code": null, "e": 26311, "s": 26283, "text": "\n03 Aug, 2021" }, { "code": null, "e": 26530, "s": 26311, "text": "In simpy module, we can get the next prime number for a given number n using sympy.nextprime() function. For n < 2^64 the answer is definitive; larger n values have a small probability of actually being pseudoprimes. " }, { "code": null, "e": 26618, "s": 26530, "text": "Syntax: sympy.nextprime()\nParameter: n; number to be tested\nReturn: next prime value" }, { "code": null, "e": 26629, "s": 26618, "text": "Code #1: " }, { "code": null, "e": 26637, "s": 26629, "text": "Python3" }, { "code": "# Python program to get next prime number# using sympy.nextprime() method # importing sympy modulefrom sympy import * # calling nextprime function on different numbersnextprime(7)nextprime(13)nextprime(2)", "e": 26842, "s": 26637, "text": null }, { "code": null, "e": 26852, "s": 26842, "text": "Output: " }, { "code": null, "e": 26860, "s": 26852, "text": "11\n17\n3" }, { "code": null, "e": 26871, "s": 26860, "text": "Code #2: " }, { "code": null, "e": 26879, "s": 26871, "text": "Python3" }, { "code": "# Python program to check prime number# using sympy.isprime() method # importing sympy moduleimport sympy.ntheory as nt # calling isprime function on different numbersnt.nextprime(30)nt.nextprime(13)nt.nextprime(2)", "e": 27094, "s": 26879, "text": null }, { "code": null, "e": 27104, "s": 27094, "text": "Output: " }, { "code": null, "e": 27112, "s": 27104, "text": "31\n17\n3" }, { "code": null, "e": 27132, "s": 27114, "text": "gulshankumarar231" }, { "code": null, "e": 27138, "s": 27132, "text": "SymPy" }, { "code": null, "e": 27145, "s": 27138, "text": "Python" }, { "code": null, "e": 27243, "s": 27145, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27261, "s": 27243, "text": "Python Dictionary" }, { "code": null, "e": 27293, "s": 27261, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27315, "s": 27293, "text": "Enumerate() in Python" }, { "code": null, "e": 27357, "s": 27315, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27383, "s": 27357, "text": "Python String | replace()" }, { "code": null, "e": 27412, "s": 27383, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27448, "s": 27412, "text": "Convert integer to string in Python" }, { "code": null, "e": 27485, "s": 27448, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27527, "s": 27485, "text": "Check if element exists in list in Python" } ]
import command in Linux with Examples - GeeksforGeeks
22 May, 2019 import command in Linux system is used for capturing a screenshot for any of the active pages we have and it gives the output as an image file. You can capture a single window if you want or you can take the entire screen or you can take a screenshot of any rectangular portion of the screen. Syntax: import [options] output-file import command with help option: It will print the general syntax of the command along with the various options that can be used with the import command as well as gives a brief description about each option. Example: Options: -adjoin: With the help of this option you will be able to join images into a single multi-image file.import -adjoin sample.png import -adjoin sample.png -border: This option is used to include window border in the output image.import -border sample.png import -border sample.png -descend: This option obtain image by descending window hierarchy.import -descend sample.png import -descend sample.png -frame: This option will include window manager frame.import -frame sample.png import -frame sample.png -identify: This option is being used to identify the format and characteristics of the image.import -identify sample.png import -identify sample.png -quiet: This option will suppress all warning messages.import -quiet sample.png import -quiet sample.png -monitor: This option will monitor the progress.import -monitor sample.png import -monitor sample.png -screen: This option will select image from root window.import -screen sample.png import -screen sample.png Other available options in the import command are: linux-command Linux-misc-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ZIP command in Linux with examples TCP Server-Client implementation in C tar command in Linux with examples curl command in Linux with Examples Conditional Statements | Shell Script UDP Server-Client implementation in C Tail command in Linux with examples Cat command in Linux with examples touch command in Linux with Examples echo command in Linux with Examples
[ { "code": null, "e": 25329, "s": 25301, "text": "\n22 May, 2019" }, { "code": null, "e": 25622, "s": 25329, "text": "import command in Linux system is used for capturing a screenshot for any of the active pages we have and it gives the output as an image file. You can capture a single window if you want or you can take the entire screen or you can take a screenshot of any rectangular portion of the screen." }, { "code": null, "e": 25630, "s": 25622, "text": "Syntax:" }, { "code": null, "e": 25659, "s": 25630, "text": "import [options] output-file" }, { "code": null, "e": 25868, "s": 25659, "text": "import command with help option: It will print the general syntax of the command along with the various options that can be used with the import command as well as gives a brief description about each option." }, { "code": null, "e": 25877, "s": 25868, "text": "Example:" }, { "code": null, "e": 25886, "s": 25877, "text": "Options:" }, { "code": null, "e": 26013, "s": 25886, "text": "-adjoin: With the help of this option you will be able to join images into a single multi-image file.import -adjoin sample.png" }, { "code": null, "e": 26039, "s": 26013, "text": "import -adjoin sample.png" }, { "code": null, "e": 26139, "s": 26039, "text": "-border: This option is used to include window border in the output image.import -border sample.png" }, { "code": null, "e": 26165, "s": 26139, "text": "import -border sample.png" }, { "code": null, "e": 26258, "s": 26165, "text": "-descend: This option obtain image by descending window hierarchy.import -descend sample.png" }, { "code": null, "e": 26285, "s": 26258, "text": "import -descend sample.png" }, { "code": null, "e": 26364, "s": 26285, "text": "-frame: This option will include window manager frame.import -frame sample.png" }, { "code": null, "e": 26389, "s": 26364, "text": "import -frame sample.png" }, { "code": null, "e": 26510, "s": 26389, "text": "-identify: This option is being used to identify the format and characteristics of the image.import -identify sample.png" }, { "code": null, "e": 26538, "s": 26510, "text": "import -identify sample.png" }, { "code": null, "e": 26618, "s": 26538, "text": "-quiet: This option will suppress all warning messages.import -quiet sample.png" }, { "code": null, "e": 26643, "s": 26618, "text": "import -quiet sample.png" }, { "code": null, "e": 26718, "s": 26643, "text": "-monitor: This option will monitor the progress.import -monitor sample.png" }, { "code": null, "e": 26745, "s": 26718, "text": "import -monitor sample.png" }, { "code": null, "e": 26827, "s": 26745, "text": "-screen: This option will select image from root window.import -screen sample.png" }, { "code": null, "e": 26853, "s": 26827, "text": "import -screen sample.png" }, { "code": null, "e": 26904, "s": 26853, "text": "Other available options in the import command are:" }, { "code": null, "e": 26918, "s": 26904, "text": "linux-command" }, { "code": null, "e": 26938, "s": 26918, "text": "Linux-misc-commands" }, { "code": null, "e": 26945, "s": 26938, "text": "Picked" }, { "code": null, "e": 26956, "s": 26945, "text": "Linux-Unix" }, { "code": null, "e": 27054, "s": 26956, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27089, "s": 27054, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 27127, "s": 27089, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 27162, "s": 27127, "text": "tar command in Linux with examples" }, { "code": null, "e": 27198, "s": 27162, "text": "curl command in Linux with Examples" }, { "code": null, "e": 27236, "s": 27198, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 27274, "s": 27236, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 27310, "s": 27274, "text": "Tail command in Linux with examples" }, { "code": null, "e": 27345, "s": 27310, "text": "Cat command in Linux with examples" }, { "code": null, "e": 27382, "s": 27345, "text": "touch command in Linux with Examples" } ]
Python Program for Find sum of odd factors of a number - GeeksforGeeks
17 Feb, 2018 Given a number n, the task is to find the odd factor sum. Examples: Input : n = 30 Output : 24 Odd dividers sum 1 + 3 + 5 + 15 = 24 Input : 18 Output : 13 Odd dividers sum 1 + 3 + 9 = 13 Let p1, p2, ... pk be prime factors of n. Let a1, a2, .. ak be highest powers of p1, p2, .. pk respectively that divide n, i.e., we can write n as n = (p1a1)*(p2a2)* ... (pkak). Sum of divisors = (1 + p1 + p12 ... p1a1) * (1 + p2 + p22 ... p2a2) * ............................................. (1 + pk + pk2 ... pkak) To find sum of odd factors, we simply need to ignore even factors and their powers. For example, consider n = 18. It can be written as 2132 and sun of all factors is (1)*(1 + 2)*(1 + 3 + 32). Sum of odd factors (1)*(1+3+32) = 13. To remove all even factors, we repeatedly divide n while it is divisible by 2. After this step, we only get odd factors. Note that 2 is the only even prime. # Formula based Python3 program # to find sum of all divisors# of n.import math # Returns sum of all factors# of n.def sumofoddFactors( n ): # Traversing through all # prime factors. res = 1 # ignore even factors by # of 2 while n % 2 == 0: n = n // 2 for i in range(3, int(math.sqrt(n) + 1)): # While i divides n, print # i and divide n count = 0 curr_sum = 1 curr_term = 1 while n % i == 0: count+=1 n = n // i curr_term *= i curr_sum += curr_term res *= curr_sum # This condition is to # handle the case when # n is a prime number. if n >= 2: res *= (1 + n) return res # Driver coden = 30print(sumofoddFactors(n)) # This code is contributed by "Sharad_Bhardwaj". Output: 24 Please refer complete article on Find sum of odd factors of a number for more details! Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python | Convert string dictionary to dictionary Python Program for Binary Search (Recursive and Iterative) Iterate over characters of a string in Python Python Program for factorial of a number Python | Convert set into a list Python | Convert a list into a tuple Python | Check if a variable is string Python program to add two numbers Add a key:value pair to dictionary in Python Appending to list in Python dictionary
[ { "code": null, "e": 26027, "s": 25999, "text": "\n17 Feb, 2018" }, { "code": null, "e": 26085, "s": 26027, "text": "Given a number n, the task is to find the odd factor sum." }, { "code": null, "e": 26095, "s": 26085, "text": "Examples:" }, { "code": null, "e": 26217, "s": 26095, "text": "Input : n = 30\nOutput : 24\nOdd dividers sum 1 + 3 + 5 + 15 = 24 \n\nInput : 18\nOutput : 13\nOdd dividers sum 1 + 3 + 9 = 13\n" }, { "code": null, "e": 26395, "s": 26217, "text": "Let p1, p2, ... pk be prime factors of n. Let a1, a2, .. ak be highest powers of p1, p2, .. pk respectively that divide n, i.e., we can write n as n = (p1a1)*(p2a2)* ... (pkak)." }, { "code": null, "e": 26591, "s": 26395, "text": "Sum of divisors = (1 + p1 + p12 ... p1a1) * \n (1 + p2 + p22 ... p2a2) *\n .............................................\n (1 + pk + pk2 ... pkak) " }, { "code": null, "e": 26821, "s": 26591, "text": "To find sum of odd factors, we simply need to ignore even factors and their powers. For example, consider n = 18. It can be written as 2132 and sun of all factors is (1)*(1 + 2)*(1 + 3 + 32). Sum of odd factors (1)*(1+3+32) = 13." }, { "code": null, "e": 26978, "s": 26821, "text": "To remove all even factors, we repeatedly divide n while it is divisible by 2. After this step, we only get odd factors. Note that 2 is the only even prime." }, { "code": "# Formula based Python3 program # to find sum of all divisors# of n.import math # Returns sum of all factors# of n.def sumofoddFactors( n ): # Traversing through all # prime factors. res = 1 # ignore even factors by # of 2 while n % 2 == 0: n = n // 2 for i in range(3, int(math.sqrt(n) + 1)): # While i divides n, print # i and divide n count = 0 curr_sum = 1 curr_term = 1 while n % i == 0: count+=1 n = n // i curr_term *= i curr_sum += curr_term res *= curr_sum # This condition is to # handle the case when # n is a prime number. if n >= 2: res *= (1 + n) return res # Driver coden = 30print(sumofoddFactors(n)) # This code is contributed by \"Sharad_Bhardwaj\".", "e": 27856, "s": 26978, "text": null }, { "code": null, "e": 27864, "s": 27856, "text": "Output:" }, { "code": null, "e": 27868, "s": 27864, "text": "24\n" }, { "code": null, "e": 27955, "s": 27868, "text": "Please refer complete article on Find sum of odd factors of a number for more details!" }, { "code": null, "e": 27971, "s": 27955, "text": "Python Programs" }, { "code": null, "e": 28069, "s": 27971, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28118, "s": 28069, "text": "Python | Convert string dictionary to dictionary" }, { "code": null, "e": 28177, "s": 28118, "text": "Python Program for Binary Search (Recursive and Iterative)" }, { "code": null, "e": 28223, "s": 28177, "text": "Iterate over characters of a string in Python" }, { "code": null, "e": 28264, "s": 28223, "text": "Python Program for factorial of a number" }, { "code": null, "e": 28297, "s": 28264, "text": "Python | Convert set into a list" }, { "code": null, "e": 28334, "s": 28297, "text": "Python | Convert a list into a tuple" }, { "code": null, "e": 28373, "s": 28334, "text": "Python | Check if a variable is string" }, { "code": null, "e": 28407, "s": 28373, "text": "Python program to add two numbers" }, { "code": null, "e": 28452, "s": 28407, "text": "Add a key:value pair to dictionary in Python" } ]
finalize() Method in Java and How to Override it? - GeeksforGeeks
21 Dec, 2021 The Java finalize() method of Object class is a method that the Garbage Collector always calls just before the deletion/destroying the object which is eligible for Garbage Collection to perform clean-up activity. Clean-up activity means closing the resources associated with that object like Database Connection, Network Connection, or we can say resource de-allocation. Remember, it is not a reserved keyword. Once the finalize() method completes immediately, Garbage Collector destroys that object. Finalization: Just before destroying any object, the garbage collector always calls finalize() method to perform clean-up activities on that object. This process is known as Finalization in Java. Note: The Garbage collector calls the finalize() method only once on any object. Syntax: protected void finalize throws Throwable{} Since the Object class contains the finalize method hence finalize method is available for every java class since Object is the superclass of all java classes. Since it is available for every java class, Garbage Collector can call the finalize() method on any java object. Why finalize() method is used? finalize() method releases system resources before the garbage collector runs for a specific object. JVM allows finalize() to be invoked only once per object. How to override finalize() method? The finalize method, which is present in the Object class, has an empty implementation. In our class, clean-up activities are there. Then we have to override this method to define our clean-up activities. In order to Override this method, we have to define and call finalize within our code explicitly. Java // Java code to show the// overriding of finalize() method import java.lang.*; // Defining a class demo since every java class// is a subclass of predefined Object class// Therefore demo is a subclass of Object classpublic class demo { protected void finalize() throws Throwable { try { System.out.println("inside demo's finalize()"); } catch (Throwable e) { throw e; } finally { System.out.println("Calling finalize method" + " of the Object class"); // Calling finalize() of Object class super.finalize(); } } // Driver code public static void main(String[] args) throws Throwable { // Creating demo's object demo d = new demo(); // Calling finalize of demo d.finalize(); }} Output: inside demo's finalize() Calling finalize method of the Object class nishkarshgandhi Java-Functions java-overriding Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. HashMap in Java with Examples Stream In Java 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 Set in Java Multithreading in Java
[ { "code": null, "e": 25514, "s": 25486, "text": "\n21 Dec, 2021" }, { "code": null, "e": 26016, "s": 25514, "text": "The Java finalize() method of Object class is a method that the Garbage Collector always calls just before the deletion/destroying the object which is eligible for Garbage Collection to perform clean-up activity. Clean-up activity means closing the resources associated with that object like Database Connection, Network Connection, or we can say resource de-allocation. Remember, it is not a reserved keyword. Once the finalize() method completes immediately, Garbage Collector destroys that object. " }, { "code": null, "e": 26212, "s": 26016, "text": "Finalization: Just before destroying any object, the garbage collector always calls finalize() method to perform clean-up activities on that object. This process is known as Finalization in Java." }, { "code": null, "e": 26293, "s": 26212, "text": "Note: The Garbage collector calls the finalize() method only once on any object." }, { "code": null, "e": 26302, "s": 26293, "text": "Syntax: " }, { "code": null, "e": 26345, "s": 26302, "text": "protected void finalize throws Throwable{}" }, { "code": null, "e": 26618, "s": 26345, "text": "Since the Object class contains the finalize method hence finalize method is available for every java class since Object is the superclass of all java classes. Since it is available for every java class, Garbage Collector can call the finalize() method on any java object." }, { "code": null, "e": 26650, "s": 26618, "text": "Why finalize() method is used? " }, { "code": null, "e": 26809, "s": 26650, "text": "finalize() method releases system resources before the garbage collector runs for a specific object. JVM allows finalize() to be invoked only once per object." }, { "code": null, "e": 26845, "s": 26809, "text": "How to override finalize() method? " }, { "code": null, "e": 27050, "s": 26845, "text": "The finalize method, which is present in the Object class, has an empty implementation. In our class, clean-up activities are there. Then we have to override this method to define our clean-up activities." }, { "code": null, "e": 27148, "s": 27050, "text": "In order to Override this method, we have to define and call finalize within our code explicitly." }, { "code": null, "e": 27153, "s": 27148, "text": "Java" }, { "code": "// Java code to show the// overriding of finalize() method import java.lang.*; // Defining a class demo since every java class// is a subclass of predefined Object class// Therefore demo is a subclass of Object classpublic class demo { protected void finalize() throws Throwable { try { System.out.println(\"inside demo's finalize()\"); } catch (Throwable e) { throw e; } finally { System.out.println(\"Calling finalize method\" + \" of the Object class\"); // Calling finalize() of Object class super.finalize(); } } // Driver code public static void main(String[] args) throws Throwable { // Creating demo's object demo d = new demo(); // Calling finalize of demo d.finalize(); }}", "e": 28014, "s": 27153, "text": null }, { "code": null, "e": 28022, "s": 28014, "text": "Output:" }, { "code": null, "e": 28091, "s": 28022, "text": "inside demo's finalize()\nCalling finalize method of the Object class" }, { "code": null, "e": 28107, "s": 28091, "text": "nishkarshgandhi" }, { "code": null, "e": 28122, "s": 28107, "text": "Java-Functions" }, { "code": null, "e": 28138, "s": 28122, "text": "java-overriding" }, { "code": null, "e": 28143, "s": 28138, "text": "Java" }, { "code": null, "e": 28148, "s": 28143, "text": "Java" }, { "code": null, "e": 28246, "s": 28148, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28276, "s": 28246, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28291, "s": 28276, "text": "Stream In Java" }, { "code": null, "e": 28322, "s": 28291, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28340, "s": 28322, "text": "ArrayList in Java" }, { "code": null, "e": 28372, "s": 28340, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28392, "s": 28372, "text": "Stack Class in Java" }, { "code": null, "e": 28424, "s": 28392, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 28448, "s": 28424, "text": "Singleton Class in Java" }, { "code": null, "e": 28460, "s": 28448, "text": "Set in Java" } ]
Difference between JSON and XML - GeeksforGeeks
19 Feb, 2019 Prerequisite: JSON XML | Basics JSON (JavaScript Object Notation) is a lightweight data-interchange format and it completely language independent. It is based on the JavaScript programming language and easy to understand and generate.Example : {"Geeks":[ { "firstName":"Vivek", "lastName":"Kothari" }, { "firstName":"Suraj", "lastName":"Kumar" }, { "firstName":"John", "lastName":"Smith" }, { "firstName":"Peter", "lastName":"Gregory" }]} XML (Extensible markup language) was designed to carry data, not to display data. It is a W3C recommendation. Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. The design goals of XML focus on simplicity, generality, and usability across the Internet. It is a textual data format with strong support via Unicode for different human languages. Although the design of XML focuses on documents, the language is widely used for the representation of arbitrary data structures such as those used in web services.Example : <Geeks> <Geek> <firstName>Vivek</firstName> <lastName>Kothari</lastName> </Geek> <Geek> <firstName>Suraj</firstName> <lastName>Kumar</lastName> </Geek> <Geek> <firstName>John</firstName> <lastName>Smith</lastName> </Geek> <Geek> <firstName>Peter</firstName> <lastName>Gregory</lastName> </Geek></Geeks> Both of these are self-describing and can be parsed and used by lots of programming languages. Below are few differences between JSON and XML: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML and XML JavaScript-Misc JSON Difference Between 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 IPv4 and IPv6 Difference Between Method Overloading and Method Overriding in Java Difference between Process and Thread Difference between Clustered and Non-clustered index Difference between SQL and NoSQL Logical and Physical Address in Operating System Difference between DDL and DML in DBMS Difference between Prim's and Kruskal's algorithm for MST Difference between Primary Key and Foreign Key
[ { "code": null, "e": 25331, "s": 25303, "text": "\n19 Feb, 2019" }, { "code": null, "e": 25345, "s": 25331, "text": "Prerequisite:" }, { "code": null, "e": 25350, "s": 25345, "text": "JSON" }, { "code": null, "e": 25363, "s": 25350, "text": "XML | Basics" }, { "code": null, "e": 25575, "s": 25363, "text": "JSON (JavaScript Object Notation) is a lightweight data-interchange format and it completely language independent. It is based on the JavaScript programming language and easy to understand and generate.Example :" }, { "code": "{\"Geeks\":[ { \"firstName\":\"Vivek\", \"lastName\":\"Kothari\" }, { \"firstName\":\"Suraj\", \"lastName\":\"Kumar\" }, { \"firstName\":\"John\", \"lastName\":\"Smith\" }, { \"firstName\":\"Peter\", \"lastName\":\"Gregory\" }]}", "e": 25782, "s": 25575, "text": null }, { "code": null, "e": 26416, "s": 25782, "text": "XML (Extensible markup language) was designed to carry data, not to display data. It is a W3C recommendation. Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. The design goals of XML focus on simplicity, generality, and usability across the Internet. It is a textual data format with strong support via Unicode for different human languages. Although the design of XML focuses on documents, the language is widely used for the representation of arbitrary data structures such as those used in web services.Example :" }, { "code": "<Geeks> <Geek> <firstName>Vivek</firstName> <lastName>Kothari</lastName> </Geek> <Geek> <firstName>Suraj</firstName> <lastName>Kumar</lastName> </Geek> <Geek> <firstName>John</firstName> <lastName>Smith</lastName> </Geek> <Geek> <firstName>Peter</firstName> <lastName>Gregory</lastName> </Geek></Geeks>", "e": 26771, "s": 26416, "text": null }, { "code": null, "e": 26866, "s": 26771, "text": "Both of these are self-describing and can be parsed and used by lots of programming languages." }, { "code": null, "e": 26914, "s": 26866, "text": "Below are few differences between JSON and XML:" }, { "code": null, "e": 27051, "s": 26914, "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": 27064, "s": 27051, "text": "HTML and XML" }, { "code": null, "e": 27080, "s": 27064, "text": "JavaScript-Misc" }, { "code": null, "e": 27085, "s": 27080, "text": "JSON" }, { "code": null, "e": 27104, "s": 27085, "text": "Difference Between" }, { "code": null, "e": 27202, "s": 27104, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27263, "s": 27202, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27297, "s": 27263, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 27365, "s": 27297, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 27403, "s": 27365, "text": "Difference between Process and Thread" }, { "code": null, "e": 27456, "s": 27403, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 27489, "s": 27456, "text": "Difference between SQL and NoSQL" }, { "code": null, "e": 27538, "s": 27489, "text": "Logical and Physical Address in Operating System" }, { "code": null, "e": 27577, "s": 27538, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 27635, "s": 27577, "text": "Difference between Prim's and Kruskal's algorithm for MST" } ]
Building a Movie Recommender using Python | by Behic Guven | Towards Data Science
In this post, I will show you how to build a movie recommender program using Python. This will be a simple project where we will be able to see how machine learning can be used in our daily life. If you check my other articles, you will see that I like to demonstrate hands-on projects. I think this is the best way to practice our coding skills and improve ourselves. Building a movie recommender program is a great way to get started with machine recommenders. After sharing the contents table, I would like to introduce you to recommendation systems. Introduction The Movie Data Data Preparation Content-Based Recommender Show Time Video Demonstration Recommendation systems have been around with us for a while now, and they are so powerful. They do have a strong influence on our decisions these days. From movie streaming services to online shopping stores, they are almost everywhere we look. If you are wondering how do they know what you might buy after adding an “x” item to your cart, the answer is simple: Power of Data. We may look very different from each other, but our habits can be very similar. And the companies love to find similar habits of their customers. Since they know that many people who bought “x” item also bought “y” item, they recommend you to add “y” item to your cart. And guess what, you are training your own recommender the more you buy, which means the machine will know more about you. Recommendation systems are a very interesting field of machine learning, and the cool part about them is that they are all around us. There is a lot to learn about this topic, to keep things simple I will stop here. Let’s begin building our own movie recommender system! I’ve found great movie data on Kaggle. If you haven’t heard about Kaggle, Kaggle is the world’s largest data science community with powerful tools and resources to help you achieve your data science goals. Here is the link to download the dataset. The data folder contains the metadata for all 45,000 movies listed in the Full MovieLens Dataset. The dataset consists of movies released on or before July 2017. Data points include cast, crew, plot keywords, budget, revenue, posters, release dates, languages, production companies, countries, TMDB vote counts, and vote averages. This data folder also contains a rating file with 26 million ratings from 270,000 users for all 45,000 movies. First things first, let’s start by importing and exploring our data. After you download the data folder, you will multiple dataset files. For this project, we will be using the movies_metadata.csv dataset. This dataset has all we need to create a movie recommender. import pandas as pd#load the datamovie_data = pd.read_csv('data/movie_data/movies_metadata.csv', low_memory=False)movie_data.head() movie_data['overview'].head(10) Perfect! Our data is all set. Ready to be trained by our model. It’s time to move to the next step, where we will start building our content-based recommender. Content based recommender is a recommendation model that returns a list of items based on a specific item. A nice example of this recommenders are Netflix, YouTube, Disney+ and more. For example, Netflix recommends similar shows that you watched before and liked more. With this project, you will have a better understanding of how these online streaming services’ algorithms work. Back to the project, as an input to train our model we will use the overview of the movies that we checked earlier. And then we will use some sci-kit learn ready functions to build our model. Our recommender will be ready in four simple steps. Let’s begin! from sklearn.feature_extraction.text import TfidfVectorizertfidf_vector = TfidfVectorizer(stop_words='english')movie_data['overview'] = movie_data['overview'].fillna('')tfidf_matrix = tfidf_vector.fit_transform(movie_data['overview']) Understanding the above code Importing the vectorizer from sci-kit learn module. Learn more here. Tf-idf Vectorizer Object removes all English stop words such as ‘the’, ‘a’ etc. We are replacing the Null(empty) values with an empty string so that it doesn’t return an error message when training them. Lastly, we are constructing the required Tf-idf matrix by fitting and transforming the data We will start by importing the linear kernel function from sci-kit learn module. The linear kernel will help us to create a similarity matrix. These lines take a bit longer to execute, don’t worry it’s normal. Calculating the dot product of two huge matrixes is not easy, even for machines :) from sklearn.metrics.pairwise import linear_kernelsim_matrix = linear_kernel(tfidf_matrix, tfidf_matrix) Now, we have to construct a reverse map of the indices and movie titles. And in the second part of the Series function, we are cleaning the movie titles that are repeating with a simple function called drop_duplicates. indices = pd.Series(movie_data.index, index=movie_data['title']).drop_duplicates()indices[:10] def content_based_recommender(title, sim_scores=sim_matrix): idx = indices[title] sim_scores = list(enumerate(sim_matrix[idx])) sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True) sim_scores = sim_scores[1:11] movie_indices = [i[0] for i in sim_scores] return movie_data['title'].iloc[movie_indices] Well done! It’s time to test our recommender. Let’s see in action and how powerful it really is. We will run the function by adding the movie name as a string as a parameter. content_based_recommender('Toy Story') Congrats!! You have created a program that recommends movies to you. Now, you have a program to run when you want to choose your next Netflix show. Hoping that you enjoyed reading this hands-on project. I would be glad if you learned something new today. Working on hands-on programming projects like this one is the best way to sharpen your coding skills. Feel free to contact me if you have any questions while implementing the code. Follow my blog and youtube channel to stay inspired. Thank you,
[ { "code": null, "e": 726, "s": 172, "text": "In this post, I will show you how to build a movie recommender program using Python. This will be a simple project where we will be able to see how machine learning can be used in our daily life. If you check my other articles, you will see that I like to demonstrate hands-on projects. I think this is the best way to practice our coding skills and improve ourselves. Building a movie recommender program is a great way to get started with machine recommenders. After sharing the contents table, I would like to introduce you to recommendation systems." }, { "code": null, "e": 739, "s": 726, "text": "Introduction" }, { "code": null, "e": 754, "s": 739, "text": "The Movie Data" }, { "code": null, "e": 771, "s": 754, "text": "Data Preparation" }, { "code": null, "e": 797, "s": 771, "text": "Content-Based Recommender" }, { "code": null, "e": 807, "s": 797, "text": "Show Time" }, { "code": null, "e": 827, "s": 807, "text": "Video Demonstration" }, { "code": null, "e": 1205, "s": 827, "text": "Recommendation systems have been around with us for a while now, and they are so powerful. They do have a strong influence on our decisions these days. From movie streaming services to online shopping stores, they are almost everywhere we look. If you are wondering how do they know what you might buy after adding an “x” item to your cart, the answer is simple: Power of Data." }, { "code": null, "e": 1597, "s": 1205, "text": "We may look very different from each other, but our habits can be very similar. And the companies love to find similar habits of their customers. Since they know that many people who bought “x” item also bought “y” item, they recommend you to add “y” item to your cart. And guess what, you are training your own recommender the more you buy, which means the machine will know more about you." }, { "code": null, "e": 1868, "s": 1597, "text": "Recommendation systems are a very interesting field of machine learning, and the cool part about them is that they are all around us. There is a lot to learn about this topic, to keep things simple I will stop here. Let’s begin building our own movie recommender system!" }, { "code": null, "e": 2074, "s": 1868, "text": "I’ve found great movie data on Kaggle. If you haven’t heard about Kaggle, Kaggle is the world’s largest data science community with powerful tools and resources to help you achieve your data science goals." }, { "code": null, "e": 2116, "s": 2074, "text": "Here is the link to download the dataset." }, { "code": null, "e": 2214, "s": 2116, "text": "The data folder contains the metadata for all 45,000 movies listed in the Full MovieLens Dataset." }, { "code": null, "e": 2447, "s": 2214, "text": "The dataset consists of movies released on or before July 2017. Data points include cast, crew, plot keywords, budget, revenue, posters, release dates, languages, production companies, countries, TMDB vote counts, and vote averages." }, { "code": null, "e": 2558, "s": 2447, "text": "This data folder also contains a rating file with 26 million ratings from 270,000 users for all 45,000 movies." }, { "code": null, "e": 2824, "s": 2558, "text": "First things first, let’s start by importing and exploring our data. After you download the data folder, you will multiple dataset files. For this project, we will be using the movies_metadata.csv dataset. This dataset has all we need to create a movie recommender." }, { "code": null, "e": 2956, "s": 2824, "text": "import pandas as pd#load the datamovie_data = pd.read_csv('data/movie_data/movies_metadata.csv', low_memory=False)movie_data.head()" }, { "code": null, "e": 2988, "s": 2956, "text": "movie_data['overview'].head(10)" }, { "code": null, "e": 3148, "s": 2988, "text": "Perfect! Our data is all set. Ready to be trained by our model. It’s time to move to the next step, where we will start building our content-based recommender." }, { "code": null, "e": 3530, "s": 3148, "text": "Content based recommender is a recommendation model that returns a list of items based on a specific item. A nice example of this recommenders are Netflix, YouTube, Disney+ and more. For example, Netflix recommends similar shows that you watched before and liked more. With this project, you will have a better understanding of how these online streaming services’ algorithms work." }, { "code": null, "e": 3787, "s": 3530, "text": "Back to the project, as an input to train our model we will use the overview of the movies that we checked earlier. And then we will use some sci-kit learn ready functions to build our model. Our recommender will be ready in four simple steps. Let’s begin!" }, { "code": null, "e": 4022, "s": 3787, "text": "from sklearn.feature_extraction.text import TfidfVectorizertfidf_vector = TfidfVectorizer(stop_words='english')movie_data['overview'] = movie_data['overview'].fillna('')tfidf_matrix = tfidf_vector.fit_transform(movie_data['overview'])" }, { "code": null, "e": 4051, "s": 4022, "text": "Understanding the above code" }, { "code": null, "e": 4120, "s": 4051, "text": "Importing the vectorizer from sci-kit learn module. Learn more here." }, { "code": null, "e": 4200, "s": 4120, "text": "Tf-idf Vectorizer Object removes all English stop words such as ‘the’, ‘a’ etc." }, { "code": null, "e": 4324, "s": 4200, "text": "We are replacing the Null(empty) values with an empty string so that it doesn’t return an error message when training them." }, { "code": null, "e": 4416, "s": 4324, "text": "Lastly, we are constructing the required Tf-idf matrix by fitting and transforming the data" }, { "code": null, "e": 4709, "s": 4416, "text": "We will start by importing the linear kernel function from sci-kit learn module. The linear kernel will help us to create a similarity matrix. These lines take a bit longer to execute, don’t worry it’s normal. Calculating the dot product of two huge matrixes is not easy, even for machines :)" }, { "code": null, "e": 4814, "s": 4709, "text": "from sklearn.metrics.pairwise import linear_kernelsim_matrix = linear_kernel(tfidf_matrix, tfidf_matrix)" }, { "code": null, "e": 5033, "s": 4814, "text": "Now, we have to construct a reverse map of the indices and movie titles. And in the second part of the Series function, we are cleaning the movie titles that are repeating with a simple function called drop_duplicates." }, { "code": null, "e": 5128, "s": 5033, "text": "indices = pd.Series(movie_data.index, index=movie_data['title']).drop_duplicates()indices[:10]" }, { "code": null, "e": 5460, "s": 5128, "text": "def content_based_recommender(title, sim_scores=sim_matrix): idx = indices[title] sim_scores = list(enumerate(sim_matrix[idx])) sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True) sim_scores = sim_scores[1:11] movie_indices = [i[0] for i in sim_scores] return movie_data['title'].iloc[movie_indices]" }, { "code": null, "e": 5635, "s": 5460, "text": "Well done! It’s time to test our recommender. Let’s see in action and how powerful it really is. We will run the function by adding the movie name as a string as a parameter." }, { "code": null, "e": 5674, "s": 5635, "text": "content_based_recommender('Toy Story')" }, { "code": null, "e": 6031, "s": 5674, "text": "Congrats!! You have created a program that recommends movies to you. Now, you have a program to run when you want to choose your next Netflix show. Hoping that you enjoyed reading this hands-on project. I would be glad if you learned something new today. Working on hands-on programming projects like this one is the best way to sharpen your coding skills." }, { "code": null, "e": 6110, "s": 6031, "text": "Feel free to contact me if you have any questions while implementing the code." } ]
Convex Hull using Divide and Conquer Algorithm in C++
In this tutorial, we will be discussing a program to find the convex hull of a given set of points. Convex hull is the smallest polygon convex figure containing all the given points either on the boundary on inside the figure. In this program, we will use brute force to divide the given points into smaller segments and then finally merging the ones that follow on to construct the convex hull. Live Demo #include<bits/stdc++.h> using namespace std; //storing the center point of polygon pair<int, int> mid; //calculating the quadrant of //a particular point int quad(pair<int, int> p){ if (p.first >= 0 && p.second >= 0) return 1; if (p.first <= 0 && p.second >= 0) return 2; if (p.first <= 0 && p.second <= 0) return 3; return 4; } //if line is touching the polygon int calc_line(pair<int, int> a, pair<int, int> b, pair<int, int> c){ int res = (b.second-a.second)*(c.first-b.first) - (c.second-b.second)*(b.first-a.first); if (res == 0) return 0; if (res > 0) return 1; return -1; } //comparing functions for sorting bool compare(pair<int, int> p1, pair<int, int> q1){ pair<int, int> p = make_pair(p1.first - mid.first, p1.second - mid.second); pair<int, int> q = make_pair(q1.first - mid.first, q1.second - mid.second); int one = quad(p); int two = quad(q); if (one != two) return (one < two); return (p.second*q.first < q.second*p.first); } //finding the upper tangent for both polygons vector<pair<int, int>> merger(vector<pair<int, int> > a, vector<pair<int, int> > b){ int n1 = a.size(), n2 = b.size(); int ia = 0, ib = 0; for (int i=1; i<n1; i++) if (a[i].first > a[ia].first) ia = i; //calculating leftmost point of b for (int i=1; i<n2; i++) if (b[i].first < b[ib].first) ib=i; int inda = ia, indb = ib; bool done = 0; while (!done){ done = 1; while (calc_line(b[indb], a[inda], a[(inda+1)%n1]) >=0) inda = (inda + 1) % n1; while (calc_line(a[inda], b[indb], b[(n2+indb-1)%n2]) <=0){ indb = (n2+indb-1)%n2; done = 0; } } int uppera = inda, upperb = indb; inda = ia, indb=ib; done = 0; int g = 0; //calculating the lower tangent while (!done){ done = 1; while (calc_line(a[inda], b[indb], b[(indb+1)%n2])>=0) indb=(indb+1)%n2; while (calc_line(b[indb], a[inda], a[(n1+inda-1)%n1])<=0){ inda=(n1+inda-1)%n1; done=0; } } int lowera = inda, lowerb = indb; vector<pair<int, int>> ret; //merging the two polygons to get convex hull int ind = uppera; ret.push_back(a[uppera]); while (ind != lowera){ ind = (ind+1)%n1; ret.push_back(a[ind]); } ind = lowerb; ret.push_back(b[lowerb]); while (ind != upperb){ ind = (ind+1)%n2; ret.push_back(b[ind]); } return ret; } //brute force algo to find convex hull vector<pair<int, int>> bruteHull(vector<pair<int, int>> a){ set<pair<int, int> >s; for (int i=0; i<a.size(); i++){ for (int j=i+1; j<a.size(); j++){ int x1 = a[i].first, x2 = a[j].first; int y1 = a[i].second, y2 = a[j].second; int a1 = y1-y2; int b1 = x2-x1; int c1 = x1*y2-y1*x2; int pos = 0, neg = 0; for (int k=0; k<a.size(); k++){ if (a1*a[k].first+b1*a[k].second+c1 <= 0) neg++; if (a1*a[k].first+b1*a[k].second+c1 >= 0) pos++; } if (pos == a.size() || neg == a.size()){ s.insert(a[i]); s.insert(a[j]); } } } vector<pair<int, int>>ret; for (auto e:s) ret.push_back(e); //moving through anti clockwise direction mid = {0, 0}; int n = ret.size(); for (int i=0; i<n; i++){ mid.first += ret[i].first; mid.second += ret[i].second; ret[i].first *= n; ret[i].second *= n; } sort(ret.begin(), ret.end(), compare); for (int i=0; i<n; i++) ret[i] = make_pair(ret[i].first/n, ret[i].second/n); return ret; } //returning the value of convex hull vector<pair<int, int>> divide(vector<pair<int, int>> a){ if (a.size() <= 5) return bruteHull(a); // left contains the left half points // right contains the right half points vector<pair<int, int>>left, right; for (int i=0; i<a.size()/2; i++) left.push_back(a[i]); for (int i=a.size()/2; i<a.size(); i++) right.push_back(a[i]); vector<pair<int, int>>left_hull = divide(left); vector<pair<int, int>>right_hull = divide(right); //merging the convex hulls return merger(left_hull, right_hull); } int main(){ vector<pair<int, int> > a; a.push_back(make_pair(0, 0)); a.push_back(make_pair(1, -4)); a.push_back(make_pair(-1, -5)); a.push_back(make_pair(-5, -3)); a.push_back(make_pair(-3, -1)); a.push_back(make_pair(-1, -3)); a.push_back(make_pair(-2, -2)); a.push_back(make_pair(-1, -1)); a.push_back(make_pair(-2, -1)); a.push_back(make_pair(-1, 1)); int n = a.size(); sort(a.begin(), a.end()); vector<pair<int, int> >ans = divide(a); cout << "Convex Hull:\n"; for (auto e:ans) cout << e.first << " "<< e.second << endl; return 0; } Convex Hull: -5 -3 -1 -5 1 -4 0 0 -1 1
[ { "code": null, "e": 1162, "s": 1062, "text": "In this tutorial, we will be discussing a program to find the convex hull of a given set of points." }, { "code": null, "e": 1289, "s": 1162, "text": "Convex hull is the smallest polygon convex figure containing all the given points either on the boundary on inside the figure." }, { "code": null, "e": 1458, "s": 1289, "text": "In this program, we will use brute force to divide the given points into smaller segments and then finally merging the ones that follow on to construct the convex hull." }, { "code": null, "e": 1469, "s": 1458, "text": " Live Demo" }, { "code": null, "e": 6200, "s": 1469, "text": "#include<bits/stdc++.h>\nusing namespace std;\n//storing the center point of polygon\npair<int, int> mid;\n//calculating the quadrant of\n//a particular point\nint quad(pair<int, int> p){\n if (p.first >= 0 && p.second >= 0)\n return 1;\n if (p.first <= 0 && p.second >= 0)\n return 2;\n if (p.first <= 0 && p.second <= 0)\n return 3;\n return 4;\n}\n//if line is touching the polygon\nint calc_line(pair<int, int> a, pair<int, int> b,\npair<int, int> c){\n int res = (b.second-a.second)*(c.first-b.first) -\n (c.second-b.second)*(b.first-a.first);\n if (res == 0)\n return 0;\n if (res > 0)\n return 1;\n return -1;\n}\n//comparing functions for sorting\nbool compare(pair<int, int> p1, pair<int, int> q1){\n pair<int, int> p = make_pair(p1.first - mid.first,\n p1.second - mid.second);\n pair<int, int> q = make_pair(q1.first - mid.first,\n q1.second - mid.second);\n int one = quad(p);\n int two = quad(q);\n if (one != two)\n return (one < two);\n return (p.second*q.first < q.second*p.first);\n}\n//finding the upper tangent for both polygons\nvector<pair<int, int>> merger(vector<pair<int, int> > a,\nvector<pair<int, int> > b){\n int n1 = a.size(), n2 = b.size();\n int ia = 0, ib = 0;\n for (int i=1; i<n1; i++)\n if (a[i].first > a[ia].first)\n ia = i;\n //calculating leftmost point of b\n for (int i=1; i<n2; i++)\n if (b[i].first < b[ib].first)\n ib=i;\n int inda = ia, indb = ib;\n bool done = 0;\n while (!done){\n done = 1;\n while (calc_line(b[indb], a[inda], a[(inda+1)%n1]) >=0)\n inda = (inda + 1) % n1;\n while (calc_line(a[inda], b[indb], b[(n2+indb-1)%n2]) <=0){\n indb = (n2+indb-1)%n2;\n done = 0;\n }\n }\n int uppera = inda, upperb = indb;\n inda = ia, indb=ib;\n done = 0;\n int g = 0;\n //calculating the lower tangent\n while (!done){\n done = 1;\n while (calc_line(a[inda], b[indb], b[(indb+1)%n2])>=0)\n indb=(indb+1)%n2;\n while (calc_line(b[indb], a[inda], a[(n1+inda-1)%n1])<=0){\n inda=(n1+inda-1)%n1;\n done=0;\n }\n}\nint lowera = inda, lowerb = indb;\nvector<pair<int, int>> ret;\n//merging the two polygons to get convex hull\nint ind = uppera;\nret.push_back(a[uppera]);\nwhile (ind != lowera){\n ind = (ind+1)%n1;\n ret.push_back(a[ind]);\n}\nind = lowerb;\nret.push_back(b[lowerb]);\nwhile (ind != upperb){\n ind = (ind+1)%n2;\n ret.push_back(b[ind]);\n}\nreturn ret;\n}\n//brute force algo to find convex hull\nvector<pair<int, int>> bruteHull(vector<pair<int, int>> a){\n set<pair<int, int> >s;\n for (int i=0; i<a.size(); i++){\n for (int j=i+1; j<a.size(); j++){\n int x1 = a[i].first, x2 = a[j].first;\n int y1 = a[i].second, y2 = a[j].second;\n int a1 = y1-y2;\n int b1 = x2-x1;\n int c1 = x1*y2-y1*x2;\n int pos = 0, neg = 0;\n for (int k=0; k<a.size(); k++){\n if (a1*a[k].first+b1*a[k].second+c1 <= 0)\n neg++;\n if (a1*a[k].first+b1*a[k].second+c1 >= 0)\n pos++;\n }\n if (pos == a.size() || neg == a.size()){\n s.insert(a[i]);\n s.insert(a[j]);\n }\n }\n }\n vector<pair<int, int>>ret;\n for (auto e:s)\n ret.push_back(e);\n //moving through anti clockwise direction\n mid = {0, 0};\n int n = ret.size();\n for (int i=0; i<n; i++){\n mid.first += ret[i].first;\n mid.second += ret[i].second;\n ret[i].first *= n;\n ret[i].second *= n;\n }\n sort(ret.begin(), ret.end(), compare);\n for (int i=0; i<n; i++)\n ret[i] = make_pair(ret[i].first/n, ret[i].second/n);\n return ret;\n}\n//returning the value of convex hull\nvector<pair<int, int>> divide(vector<pair<int, int>> a){\n if (a.size() <= 5)\n return bruteHull(a);\n // left contains the left half points\n // right contains the right half points\n vector<pair<int, int>>left, right;\n for (int i=0; i<a.size()/2; i++)\n left.push_back(a[i]);\n for (int i=a.size()/2; i<a.size(); i++)\n right.push_back(a[i]);\n vector<pair<int, int>>left_hull = divide(left);\n vector<pair<int, int>>right_hull = divide(right);\n //merging the convex hulls\n return merger(left_hull, right_hull);\n}\nint main(){\n vector<pair<int, int> > a;\n a.push_back(make_pair(0, 0));\n a.push_back(make_pair(1, -4));\n a.push_back(make_pair(-1, -5));\n a.push_back(make_pair(-5, -3));\n a.push_back(make_pair(-3, -1));\n a.push_back(make_pair(-1, -3));\n a.push_back(make_pair(-2, -2));\n a.push_back(make_pair(-1, -1));\n a.push_back(make_pair(-2, -1));\n a.push_back(make_pair(-1, 1));\n int n = a.size();\n sort(a.begin(), a.end());\n vector<pair<int, int> >ans = divide(a);\n cout << \"Convex Hull:\\n\";\n for (auto e:ans)\n cout << e.first << \" \"<< e.second << endl;\n return 0;\n}" }, { "code": null, "e": 6239, "s": 6200, "text": "Convex Hull:\n-5 -3\n-1 -5\n1 -4\n0 0\n-1 1" } ]
What are Assignment Operators in JavaScript?
Using Assignment Operators, you can assign a value to a variable. JavaScript supports the following assignment operators − Try the following code to implement assignment operator in JavaScript − Live Demo <html> <body> <script> <!-- var a = 33; var b = 10; var linebreak = "<br />"; document.write("Value of a => (a = b) => "); result = (a = b); document.write(result); document.write(linebreak); document.write("Value of a => (a += b) => "); result = (a += b); document.write(result); document.write(linebreak); document.write("Value of a => (a -= b) => "); result = (a -= b); document.write(result); document.write(linebreak); document.write("Value of a => (a *= b) => "); result = (a *= b); document.write(result); document.write(linebreak); document.write("Value of a => (a /= b) => "); result = (a /= b); document.write(result); document.write(linebreak); document.write("Value of a => (a %= b) => "); result = (a %= b); document.write(result); document.write(linebreak); //--> </script> <p>Set the variables to different values and different operators and then try...</p> </body> </html>
[ { "code": null, "e": 1185, "s": 1062, "text": "Using Assignment Operators, you can assign a value to a variable. JavaScript supports the following assignment operators −" }, { "code": null, "e": 1257, "s": 1185, "text": "Try the following code to implement assignment operator in JavaScript −" }, { "code": null, "e": 1267, "s": 1257, "text": "Live Demo" }, { "code": null, "e": 2519, "s": 1267, "text": "<html>\n <body>\n <script>\n <!--\n var a = 33;\n var b = 10;\n var linebreak = \"<br />\";\n document.write(\"Value of a => (a = b) => \");\n result = (a = b);\n document.write(result);\n document.write(linebreak);\n document.write(\"Value of a => (a += b) => \");\n result = (a += b);\n document.write(result);\n document.write(linebreak);\n document.write(\"Value of a => (a -= b) => \");\n result = (a -= b);\n document.write(result);\n document.write(linebreak);\n document.write(\"Value of a => (a *= b) => \");\n result = (a *= b);\n document.write(result);\n document.write(linebreak);\n document.write(\"Value of a => (a /= b) => \");\n result = (a /= b);\n document.write(result);\n document.write(linebreak);\n document.write(\"Value of a => (a %= b) => \");\n result = (a %= b);\n document.write(result);\n document.write(linebreak);\n //-->\n </script>\n <p>Set the variables to different values and different operators and then try...</p>\n</body>\n</html>" } ]
PHP - Form Introduction
The Websites provide the functionalities that can use to store, update, retrieve, and delete the data in a database. A Document that containing black fields, that the user can fill the data or user can select the data.Casually the data will store in the data base Below example shows the form with some specific actions by using post method. <html> <head> <title>PHP Form Validation</title> </head> <body> <?php // define variables and set to empty values $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = test_input($_POST["name"]); $email = test_input($_POST["email"]); $website = test_input($_POST["website"]); $comment = test_input($_POST["comment"]); $gender = test_input($_POST["gender"]); } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <h2>Tutorials Point Absolute classes registration</h2> <form method = "post" action = "/php/php_form_introduction.htm"> <table> <tr> <td>Name:</td> <td><input type = "text" name = "name"></td> </tr> <tr> <td>E-mail:</td> <td><input type = "text" name = "email"></td> </tr> <tr> <td>Specific Time:</td> <td><input type = "text" name = "website"></td> </tr> <tr> <td>Class details:</td> <td><textarea name = "comment" rows = "5" cols = "40"></textarea></td> </tr> <tr> <td>Gender:</td> <td> <input type = "radio" name = "gender" value = "female">Female <input type = "radio" name = "gender" value = "male">Male </td> </tr> <tr> <td> <input type = "submit" name = "submit" value = "Submit"> </td> </tr> </table> </form> <?php echo "<h2>Your Given details are as :</h2>"; echo $name; echo "<br>"; echo $email; echo "<br>"; echo $website; echo "<br>"; echo $comment; echo "<br>"; echo $gender; ?> </body> </html> It will produce the following result − 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2874, "s": 2757, "text": "The Websites provide the functionalities that can use to store, update, retrieve, and delete the data in a database." }, { "code": null, "e": 3021, "s": 2874, "text": "A Document that containing black fields, that the user can fill the data or user can select the data.Casually the data will store in the data base" }, { "code": null, "e": 3099, "s": 3021, "text": "Below example shows the form with some specific actions by using post method." }, { "code": null, "e": 5442, "s": 3099, "text": "<html>\n \n <head>\n <title>PHP Form Validation</title>\n </head>\n \n <body>\n <?php\n \n // define variables and set to empty values\n $name = $email = $gender = $comment = $website = \"\";\n \n if ($_SERVER[\"REQUEST_METHOD\"] == \"POST\") {\n $name = test_input($_POST[\"name\"]);\n $email = test_input($_POST[\"email\"]);\n $website = test_input($_POST[\"website\"]);\n $comment = test_input($_POST[\"comment\"]);\n $gender = test_input($_POST[\"gender\"]);\n }\n \n function test_input($data) {\n $data = trim($data);\n $data = stripslashes($data);\n $data = htmlspecialchars($data);\n return $data;\n }\n ?>\n \n <h2>Tutorials Point Absolute classes registration</h2>\n \n <form method = \"post\" action = \"/php/php_form_introduction.htm\">\n <table>\n <tr>\n <td>Name:</td> \n <td><input type = \"text\" name = \"name\"></td>\n </tr>\n \n <tr>\n <td>E-mail:</td>\n <td><input type = \"text\" name = \"email\"></td>\n </tr>\n \n <tr>\n <td>Specific Time:</td>\n <td><input type = \"text\" name = \"website\"></td>\n </tr>\n \n <tr>\n <td>Class details:</td>\n <td><textarea name = \"comment\" rows = \"5\" cols = \"40\"></textarea></td>\n </tr>\n \n <tr>\n <td>Gender:</td>\n <td>\n <input type = \"radio\" name = \"gender\" value = \"female\">Female\n <input type = \"radio\" name = \"gender\" value = \"male\">Male\n </td>\n </tr>\n \n <tr>\n <td>\n <input type = \"submit\" name = \"submit\" value = \"Submit\"> \n </td>\n </tr>\n </table>\n </form>\n \n <?php\n echo \"<h2>Your Given details are as :</h2>\";\n echo $name;\n echo \"<br>\";\n \n echo $email;\n echo \"<br>\";\n \n echo $website;\n echo \"<br>\";\n \n echo $comment;\n echo \"<br>\";\n \n echo $gender;\n ?>\n \n </body>\n</html>" }, { "code": null, "e": 5481, "s": 5442, "text": "It will produce the following result −" }, { "code": null, "e": 5514, "s": 5481, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 5530, "s": 5514, "text": " Malhar Lathkar" }, { "code": null, "e": 5563, "s": 5530, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 5574, "s": 5563, "text": " Syed Raza" }, { "code": null, "e": 5609, "s": 5574, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5626, "s": 5609, "text": " Frahaan Hussain" }, { "code": null, "e": 5659, "s": 5626, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 5674, "s": 5659, "text": " Nivedita Jain" }, { "code": null, "e": 5709, "s": 5674, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 5721, "s": 5709, "text": " Azaz Patel" }, { "code": null, "e": 5756, "s": 5721, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5784, "s": 5756, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 5791, "s": 5784, "text": " Print" }, { "code": null, "e": 5802, "s": 5791, "text": " Add Notes" } ]
Building Blog CMS (Content Management System) with Django - GeeksforGeeks
06 Aug, 2021 Django is a python based web application framework which is helpful for building a variety of web application. Django also includes an extensible Django-Admin interface, Default SQLIte3 database, which is also extensible to PostgreSQL, MySQL databases, and few other components to build efficient web apps. Create a directory for our blog, install and activate the virtual environment. Then install Django using the below commands # creating directory for our project mkdir gfgblog && cd gfgblog # installing virtual environment pip install virtualenv python3 -m venv env # activating virtual environment source env/bin/activate # installing django pip install django As now we have installed Django we will now create a Django project which will set up a basic Django app django-admin startproject gfgblog cd gfgblog In our gfgblog Django app, we will have these files __init__.py – empty file urls.py – for routing our Django project settings.py – has all settings for our Django project asgi.py, wsgi – helpful while deploying our app We are in the Django web app directory. Now we will make some migrations for our database which will be SQLite3 which will set up some default tables to run our app in our database. Then we will create a superuser for our app. # migrating tables python3 manage.py makemigrations python3 manage.py migrate # create and enter the details for superuser python3 manage.py createsuperuser creating, migrating django-app Now run the Django development server and open port 8000 in your localhost # running python development server python3 manage.py runserver default django page Now stop the server and go into gfgblog directory in our gfgblog Django app directory and open urls.py file using your code editor. You can look tree of our gfgblog directory from the below picture django app directory tree structure Now we will create our actual blog app and database for it. Go to the gfgblog project directory. You can see our SQLite3 database, gfgblog Django app. now in this directory create a new app named blog. The below command will create a new app for us. # creating an app named blog python3 manage.py startapp blog The new app directory has 5 default files __init__.py – an empty file admin.py – for managing admin interface apps.py – for managing app configuration models.py – for managing database models of the app tests.py – for testing the app views.py – for managing behavior and logic of the app As we have created the app now we have to tell the django app that there is a new app in our project. For that go to settings.py in gfgblog directory and open settings.py file. Go to installed apps section of the settings file add the name of the app we created in our case its blog Python3 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog',] Now we will create Django models for the app. You can learn more about Django Models from this tutorial – Django Models To create Django Models open in your editor and add the below code Python3 # importing django models and usersfrom django.db import modelsfrom django.contrib.auth.models import User STATUS = ( (0,"Draft"), (1,"Publish"), (2, "Delete")) # creating an django model classclass posts(models.Model): # title field using charfield constraint with unique constraint title = models.CharField(max_length=200, unique=True) # slug field auto populated using title with unique constraint slug = models.SlugField(max_length=200, unique=True) # author field populated using users database author = models.ForeignKey(User, on_delete= models.CASCADE) # and date time fields automatically populated using system time updated_on = models.DateTimeField(auto_now= True) created_on = models.DateTimeField() # content field to store our post content = models.TextField() # meta description for SEO benifits metades = models.CharField(max_length=300, default="new post") # status of post status = models.IntegerField(choices=STATUS, default=0) # meta for the class class Meta: ordering = ['-created_on'] # used while managing models from terminal def __str__(self): return self.title Save the file and make migration so that the fields will be created in our database using the below commands # creates migrations for the blog app python3 manage.py makemigrations blog # migrates the blog app python3 manage.py migrate blog So far we are good with creating models and setting our database for storing our posts, but we should present them to users. Luckily Django comes with its own templating language with which we can build dynamic HTML pages to serve our users. We can also add styling using CSS and JavaScript. You can learn more about Django templates this tutorial – Django Templates To create templates first create a template directory in the blog app (You can also create it outside the blog app but in this way, it would be easy to manage). To manage templates in an easy way for each app in the project we have to do some changes in the settings. Go to the project settings file and replace template settings with the code below Python3 TEMPLATES_DIR = os.path.join(BASE_DIR,'templates') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },] Now we will create templates for our blog. As Django can build pages dynamically we will build our templates according to it. Now we will create a base template that servers as a base for all the pages in our blog. HTML <!DOCTYPE html><html lang="en"><head> <!-- will be replaced with meta content --> {% block metatags %}{% endblock %} <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <style>html, body { height: 100%;} body { font-family: sans-serif; font-size: 18px; background-color: #fdfdfd;display: flex; flex-direction: column; } #nofooter {flex: 1 0 auto;}darkbtn {color: #66ff99; } .dark-mode { background-color: black; color: white; } #foot { flex-shrink: 0; font-family: sans-serif;background-color: #BDFFD3; color: #00308F; bottom: 0px; width: 100%;}.card-group,.card,.card-footer,.card-body {border: none;}</style></head><body><div id="bodydiv"><div id="nofooter"> <nav class="navbar navbar-expand-lg navbar-light bg-light shadow" id="topnav"> <div class="container-fluid"> <a class="navbar-brand" href="{% url 'home' %}"> <img src="/static/icons/logo.png" width="30" height="30" class="d-inline-block rounded align-top" alt="logo" loading="lazy"> GeeksForGeeks</a> <div class="nav justify-content-end"> <div class="d-inline"><a class="nav-link text-black font-weight-bold" href="{% url 'posts'%}">Posts</a></div> </div></div></nav> <!-- will be replaced with post content -->{% block content %}{% endblock content %}</div><footer class="footer" id="foot"><div class="container"><h5 style="text-align:center;">Enjoy the Blog and Stay Updated</h5><nav class="navbar navbar-expand-lg"><div class="container-fluid"> <p>Copyright © GeeksForGeeks</p> <div class="nav justify-content-center" id="navfooter"><span><a class="nav-link text-black font-weight-bold" href="{% url 'about' %}">About</a></span><span><a class="nav-link text-black font-weight-bold" href="{% url 'privacy' %}">Privacy</a></span><span><a class="nav-link text-black font-weight-bold" href="{% url 'tos' %}">Terms</a></span><span><a class="nav-link text-black font-weight-bold" href="#">Feed</a></span></div></div> </nav> </div></footer></div></body></html> This will be our base template, You can block like {% block name %}{% endblock %} which will be replaced with the content assigned to them, Now we will create a home template that would be the homepage for our blog which will have the latest posts. HTML {% extends "base.html" %}{% block metatags %}<title>Home | GeeksForGeeks</title><meta name="description" content="A destination for Learning"><meta property="og:title" content="GeeksForGeeks"><meta property="og:site_name" content="GeeksForGeeks"><meta property="og:url" content="https://GeeksForGeeks.org"><meta property="og:description" content="A destination for Learning"><meta property="og:type" content="website">{% endblock %}{% block content %}<style type="text/css"> body { font-family: 'Raleway', sans-serif;} .head_text { color: white; }.h1, h4 {font-family: 'Raleway', sans-serif;}#mainhome {text-align: center; }</style><header class="jumbotron" style="background-color: #BDFFD3; color: #00308F;"> <div class="container"> <p class="h1"> Welcome to <strong>GeeksForGeeks</strong></p> </div></header><div class="container"> <div class="row"> <div class="col-md-8 mt-3 left"> {% for post in posts_list %} <div class="shadow-none card mb-4" id="newsfeed"> <div class="card-body"> <h3 class="card-title">{{ post.title }}</h3> <p class="card-text text-muted h6"><span>{{ post.author.first_name }} {{ post.author.last_name }}</span> | {{ post.created_on}} </p> <p class="card-text">{{post.metades }}</p> <span><a href="{% url 'post_detail' post.slug %}" class="btn btn-outline-primary">Read More →</a></span><span><a href="{% url 'post_detail_amp' post.slug %}" class="btn btn-outline-success">AMP page</a></span> </div> </div> {% endfor %} </div></div></div>{% if is_paginated %} <nav aria-label="Page navigation container"></nav> <ul class="pagination justify-content-center"> {% if page_obj.has_previous %} <li><a href="?page={{ page_obj.previous_page_number }}" class="btn btn-outline-info" style="font-family: sans-serif;">« PREV </a></li> {% endif %} {% if page_obj.has_next %} <li><a href="?page={{ page_obj.next_page_number }}" class="btn btn-outline-info" style="font-family: sans-serif;"> NEXT »</a></li> {% endif %} </ul>{% endif %}{%endblock%} We have created our homepage with pagination. Posts will be displayed using the for a loop. Now we will add our last template to display posts individually. HTML {% extends 'base.html' %}{% block metatags %}<title>{{ object.title }}</title><meta name="description" content="{{ object.metades}}" /><meta property="og:title" content="{{ object.title }}"><meta property="og:site_name" content="GeeksForGeeks"><meta property="og:url" content="{% url 'post_detail' object.slug %}"><meta property="og:description" content="{{ object.metades }}"><meta property="og:type" content="article">{% endblock %}{% block content %}<style type="text/css">#container img {border-radius: 29px;width: 100%;height: 360px;opacity: 0.7;align-content: center;}#container img {opacity: 1.0; }a {text-align: center; text-decoration: none;}</style><script type="application/ld+json">{ "@context": "https://schema.org/", "@type": "Post", "headline": "{{ object.title }}", "description": "{{ object.metades }}", "mainEntityOfPage": { "@type": "WebPage", "@id": "{% url 'post_detail' object.slug %}"}, "author": { "@type": "Person", "name": "{{ post.author.first_name }} {{ post.author.last_name " }, "publisher": { "@type": "Organization", "name": "GeeksForGeeks", }, "datePublished": "{{ news.created_on }}", "dateModified": "{{ news.created_on }}", "mentions": "{{ object.source }}"}</script><div class="container"> <div class="row"> <div class="col-md-6 left"> <h1 class="card-title">{% block title %} {{ object.title }} {% endblock title %}</h1> <p class=" text-muted">{{ object.author.first_name }} {{ object.author.last_name }} |{{ object.created_on }}</p> <p class="card-text">{{ object.content | safe }}</p> </div> </div> </div>{% endblock content %} Both homepage and post page will be built by extending base template and replacing blocks with the data stored in our database. Both also have a Facebook open graphs for better sharing and social network and the post page has a structured schema for better SEO additionally. We will build AMP template incoming tutorial. Now open views.py file in the blog directory. This file has the logic to run the blog app. We will be using class-based views for the blog app. Class Based Generic Views are an advanced set of Built-in views which are used for the implementation of selective view strategies such as Create, Retrieve, Update, Delete. Python3 # importing models and librariesfrom django.shortcuts import renderfrom .models import postsfrom django.views import genericfrom django.views.decorators.http import require_GETfrom django.http import HttpResponse # class based views for postsclass postslist(generic.ListView): queryset = posts.objects.filter(status=1).order_by('-created_on') template_name = 'home.html' paginate_by = 4 # class based view for each postclass postdetail(generic.DetailView): model = posts template_name = "post.html" For Routing our blog app just go into the blog app directory and create a file urls.py to route our app. see the code below Python3 # importing django routing librariesfrom . import viewsfrom django.urls import path, includefrom .views import *from .feeds import blogFeed urlpatterns = [ # home page path('', views.postslist.as_view(), name='posts'), # route for posts path('<slug:slug>/', views.postdetail.as_view(), name='post_detail'),] Go to urls.py file in gfgblog directory and route our blog app. See the code below for reference Python3 from django.contrib import adminfrom django.urls import path, include, re_pathfrom django.conf import settingsfrom django.conf.urls.static import static urlpatterns = [ # urls handling admin route path('admin/', admin.site.urls), # urls handling blog routes path('', include('blog.urls')),] Done, Let’s Now run the server using Python manage.py runserver homepage with latest’s posts sample post page posts management User management kushwanthreddy kalrap615 sagartomar9927 surindertarika1234 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Box Plot in Python using Matplotlib Python | Get dictionary keys as a list Bar Plot in Matplotlib Multithreading in Python | Set 2 (Synchronization) Python Dictionary keys() method loops in python Python - Call function from another file Ways to filter Pandas DataFrame by column values Python | Convert set into a list Python program to find number of days between two given dates
[ { "code": null, "e": 23901, "s": 23873, "text": "\n06 Aug, 2021" }, { "code": null, "e": 24208, "s": 23901, "text": "Django is a python based web application framework which is helpful for building a variety of web application. Django also includes an extensible Django-Admin interface, Default SQLIte3 database, which is also extensible to PostgreSQL, MySQL databases, and few other components to build efficient web apps." }, { "code": null, "e": 24332, "s": 24208, "text": "Create a directory for our blog, install and activate the virtual environment. Then install Django using the below commands" }, { "code": null, "e": 24572, "s": 24332, "text": "# creating directory for our project\nmkdir gfgblog && cd gfgblog\n\n# installing virtual environment\npip install virtualenv\npython3 -m venv env\n\n# activating virtual environment\nsource env/bin/activate\n\n# installing django\npip install django" }, { "code": null, "e": 24677, "s": 24572, "text": "As now we have installed Django we will now create a Django project which will set up a basic Django app" }, { "code": null, "e": 24722, "s": 24677, "text": "django-admin startproject gfgblog\ncd gfgblog" }, { "code": null, "e": 24774, "s": 24722, "text": "In our gfgblog Django app, we will have these files" }, { "code": null, "e": 24802, "s": 24774, "text": "__init__.py – empty file" }, { "code": null, "e": 24845, "s": 24802, "text": "urls.py – for routing our Django project" }, { "code": null, "e": 24901, "s": 24845, "text": "settings.py – has all settings for our Django project" }, { "code": null, "e": 24949, "s": 24901, "text": "asgi.py, wsgi – helpful while deploying our app" }, { "code": null, "e": 25176, "s": 24949, "text": "We are in the Django web app directory. Now we will make some migrations for our database which will be SQLite3 which will set up some default tables to run our app in our database. Then we will create a superuser for our app." }, { "code": null, "e": 25334, "s": 25176, "text": "# migrating tables\npython3 manage.py makemigrations\npython3 manage.py migrate\n\n# create and enter the details for superuser\npython3 manage.py createsuperuser" }, { "code": null, "e": 25365, "s": 25334, "text": "creating, migrating django-app" }, { "code": null, "e": 25440, "s": 25365, "text": "Now run the Django development server and open port 8000 in your localhost" }, { "code": null, "e": 25504, "s": 25440, "text": "# running python development server\npython3 manage.py runserver" }, { "code": null, "e": 25524, "s": 25504, "text": "default django page" }, { "code": null, "e": 25722, "s": 25524, "text": "Now stop the server and go into gfgblog directory in our gfgblog Django app directory and open urls.py file using your code editor. You can look tree of our gfgblog directory from the below picture" }, { "code": null, "e": 25758, "s": 25722, "text": "django app directory tree structure" }, { "code": null, "e": 26008, "s": 25758, "text": "Now we will create our actual blog app and database for it. Go to the gfgblog project directory. You can see our SQLite3 database, gfgblog Django app. now in this directory create a new app named blog. The below command will create a new app for us." }, { "code": null, "e": 26069, "s": 26008, "text": "# creating an app named blog\npython3 manage.py startapp blog" }, { "code": null, "e": 26111, "s": 26069, "text": "The new app directory has 5 default files" }, { "code": null, "e": 26140, "s": 26111, "text": "__init__.py – an empty file" }, { "code": null, "e": 26181, "s": 26140, "text": "admin.py – for managing admin interface" }, { "code": null, "e": 26223, "s": 26181, "text": "apps.py – for managing app configuration" }, { "code": null, "e": 26276, "s": 26223, "text": "models.py – for managing database models of the app" }, { "code": null, "e": 26308, "s": 26276, "text": "tests.py – for testing the app" }, { "code": null, "e": 26363, "s": 26308, "text": "views.py – for managing behavior and logic of the app" }, { "code": null, "e": 26646, "s": 26363, "text": "As we have created the app now we have to tell the django app that there is a new app in our project. For that go to settings.py in gfgblog directory and open settings.py file. Go to installed apps section of the settings file add the name of the app we created in our case its blog" }, { "code": null, "e": 26654, "s": 26646, "text": "Python3" }, { "code": "INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog',]", "e": 26867, "s": 26654, "text": null }, { "code": null, "e": 26990, "s": 26870, "text": "Now we will create Django models for the app. You can learn more about Django Models from this tutorial – Django Models" }, { "code": null, "e": 27057, "s": 26990, "text": "To create Django Models open in your editor and add the below code" }, { "code": null, "e": 27065, "s": 27057, "text": "Python3" }, { "code": "# importing django models and usersfrom django.db import modelsfrom django.contrib.auth.models import User STATUS = ( (0,\"Draft\"), (1,\"Publish\"), (2, \"Delete\")) # creating an django model classclass posts(models.Model): # title field using charfield constraint with unique constraint title = models.CharField(max_length=200, unique=True) # slug field auto populated using title with unique constraint slug = models.SlugField(max_length=200, unique=True) # author field populated using users database author = models.ForeignKey(User, on_delete= models.CASCADE) # and date time fields automatically populated using system time updated_on = models.DateTimeField(auto_now= True) created_on = models.DateTimeField() # content field to store our post content = models.TextField() # meta description for SEO benifits metades = models.CharField(max_length=300, default=\"new post\") # status of post status = models.IntegerField(choices=STATUS, default=0) # meta for the class class Meta: ordering = ['-created_on'] # used while managing models from terminal def __str__(self): return self.title", "e": 28232, "s": 27065, "text": null }, { "code": null, "e": 28341, "s": 28232, "text": "Save the file and make migration so that the fields will be created in our database using the below commands" }, { "code": null, "e": 28473, "s": 28341, "text": "# creates migrations for the blog app\npython3 manage.py makemigrations blog\n\n# migrates the blog app\npython3 manage.py migrate blog" }, { "code": null, "e": 28840, "s": 28473, "text": "So far we are good with creating models and setting our database for storing our posts, but we should present them to users. Luckily Django comes with its own templating language with which we can build dynamic HTML pages to serve our users. We can also add styling using CSS and JavaScript. You can learn more about Django templates this tutorial – Django Templates" }, { "code": null, "e": 29190, "s": 28840, "text": "To create templates first create a template directory in the blog app (You can also create it outside the blog app but in this way, it would be easy to manage). To manage templates in an easy way for each app in the project we have to do some changes in the settings. Go to the project settings file and replace template settings with the code below" }, { "code": null, "e": 29198, "s": 29190, "text": "Python3" }, { "code": "TEMPLATES_DIR = os.path.join(BASE_DIR,'templates') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },]", "e": 29732, "s": 29198, "text": null }, { "code": null, "e": 29947, "s": 29732, "text": "Now we will create templates for our blog. As Django can build pages dynamically we will build our templates according to it. Now we will create a base template that servers as a base for all the pages in our blog." }, { "code": null, "e": 29952, "s": 29947, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <!-- will be replaced with meta content --> {% block metatags %}{% endblock %} <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css\" integrity=\"sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z\" crossorigin=\"anonymous\"> <style>html, body { height: 100%;} body { font-family: sans-serif; font-size: 18px; background-color: #fdfdfd;display: flex; flex-direction: column; } #nofooter {flex: 1 0 auto;}darkbtn {color: #66ff99; } .dark-mode { background-color: black; color: white; } #foot { flex-shrink: 0; font-family: sans-serif;background-color: #BDFFD3; color: #00308F; bottom: 0px; width: 100%;}.card-group,.card,.card-footer,.card-body {border: none;}</style></head><body><div id=\"bodydiv\"><div id=\"nofooter\"> <nav class=\"navbar navbar-expand-lg navbar-light bg-light shadow\" id=\"topnav\"> <div class=\"container-fluid\"> <a class=\"navbar-brand\" href=\"{% url 'home' %}\"> <img src=\"/static/icons/logo.png\" width=\"30\" height=\"30\" class=\"d-inline-block rounded align-top\" alt=\"logo\" loading=\"lazy\"> GeeksForGeeks</a> <div class=\"nav justify-content-end\"> <div class=\"d-inline\"><a class=\"nav-link text-black font-weight-bold\" href=\"{% url 'posts'%}\">Posts</a></div> </div></div></nav> <!-- will be replaced with post content -->{% block content %}{% endblock content %}</div><footer class=\"footer\" id=\"foot\"><div class=\"container\"><h5 style=\"text-align:center;\">Enjoy the Blog and Stay Updated</h5><nav class=\"navbar navbar-expand-lg\"><div class=\"container-fluid\"> <p>Copyright © GeeksForGeeks</p> <div class=\"nav justify-content-center\" id=\"navfooter\"><span><a class=\"nav-link text-black font-weight-bold\" href=\"{% url 'about' %}\">About</a></span><span><a class=\"nav-link text-black font-weight-bold\" href=\"{% url 'privacy' %}\">Privacy</a></span><span><a class=\"nav-link text-black font-weight-bold\" href=\"{% url 'tos' %}\">Terms</a></span><span><a class=\"nav-link text-black font-weight-bold\" href=\"#\">Feed</a></span></div></div> </nav> </div></footer></div></body></html>", "e": 32214, "s": 29952, "text": null }, { "code": null, "e": 32463, "s": 32214, "text": "This will be our base template, You can block like {% block name %}{% endblock %} which will be replaced with the content assigned to them, Now we will create a home template that would be the homepage for our blog which will have the latest posts." }, { "code": null, "e": 32468, "s": 32463, "text": "HTML" }, { "code": "{% extends \"base.html\" %}{% block metatags %}<title>Home | GeeksForGeeks</title><meta name=\"description\" content=\"A destination for Learning\"><meta property=\"og:title\" content=\"GeeksForGeeks\"><meta property=\"og:site_name\" content=\"GeeksForGeeks\"><meta property=\"og:url\" content=\"https://GeeksForGeeks.org\"><meta property=\"og:description\" content=\"A destination for Learning\"><meta property=\"og:type\" content=\"website\">{% endblock %}{% block content %}<style type=\"text/css\"> body { font-family: 'Raleway', sans-serif;} .head_text { color: white; }.h1, h4 {font-family: 'Raleway', sans-serif;}#mainhome {text-align: center; }</style><header class=\"jumbotron\" style=\"background-color: #BDFFD3; color: #00308F;\"> <div class=\"container\"> <p class=\"h1\"> Welcome to <strong>GeeksForGeeks</strong></p> </div></header><div class=\"container\"> <div class=\"row\"> <div class=\"col-md-8 mt-3 left\"> {% for post in posts_list %} <div class=\"shadow-none card mb-4\" id=\"newsfeed\"> <div class=\"card-body\"> <h3 class=\"card-title\">{{ post.title }}</h3> <p class=\"card-text text-muted h6\"><span>{{ post.author.first_name }} {{ post.author.last_name }}</span> | {{ post.created_on}} </p> <p class=\"card-text\">{{post.metades }}</p> <span><a href=\"{% url 'post_detail' post.slug %}\" class=\"btn btn-outline-primary\">Read More →</a></span><span><a href=\"{% url 'post_detail_amp' post.slug %}\" class=\"btn btn-outline-success\">AMP page</a></span> </div> </div> {% endfor %} </div></div></div>{% if is_paginated %} <nav aria-label=\"Page navigation container\"></nav> <ul class=\"pagination justify-content-center\"> {% if page_obj.has_previous %} <li><a href=\"?page={{ page_obj.previous_page_number }}\" class=\"btn btn-outline-info\" style=\"font-family: sans-serif;\">« PREV </a></li> {% endif %} {% if page_obj.has_next %} <li><a href=\"?page={{ page_obj.next_page_number }}\" class=\"btn btn-outline-info\" style=\"font-family: sans-serif;\"> NEXT »</a></li> {% endif %} </ul>{% endif %}{%endblock%}", "e": 34677, "s": 32468, "text": null }, { "code": null, "e": 34835, "s": 34677, "text": "We have created our homepage with pagination. Posts will be displayed using the for a loop. Now we will add our last template to display posts individually. " }, { "code": null, "e": 34840, "s": 34835, "text": "HTML" }, { "code": "{% extends 'base.html' %}{% block metatags %}<title>{{ object.title }}</title><meta name=\"description\" content=\"{{ object.metades}}\" /><meta property=\"og:title\" content=\"{{ object.title }}\"><meta property=\"og:site_name\" content=\"GeeksForGeeks\"><meta property=\"og:url\" content=\"{% url 'post_detail' object.slug %}\"><meta property=\"og:description\" content=\"{{ object.metades }}\"><meta property=\"og:type\" content=\"article\">{% endblock %}{% block content %}<style type=\"text/css\">#container img {border-radius: 29px;width: 100%;height: 360px;opacity: 0.7;align-content: center;}#container img {opacity: 1.0; }a {text-align: center; text-decoration: none;}</style><script type=\"application/ld+json\">{ \"@context\": \"https://schema.org/\", \"@type\": \"Post\", \"headline\": \"{{ object.title }}\", \"description\": \"{{ object.metades }}\", \"mainEntityOfPage\": { \"@type\": \"WebPage\", \"@id\": \"{% url 'post_detail' object.slug %}\"}, \"author\": { \"@type\": \"Person\", \"name\": \"{{ post.author.first_name }} {{ post.author.last_name \" }, \"publisher\": { \"@type\": \"Organization\", \"name\": \"GeeksForGeeks\", }, \"datePublished\": \"{{ news.created_on }}\", \"dateModified\": \"{{ news.created_on }}\", \"mentions\": \"{{ object.source }}\"}</script><div class=\"container\"> <div class=\"row\"> <div class=\"col-md-6 left\"> <h1 class=\"card-title\">{% block title %} {{ object.title }} {% endblock title %}</h1> <p class=\" text-muted\">{{ object.author.first_name }} {{ object.author.last_name }} |{{ object.created_on }}</p> <p class=\"card-text\">{{ object.content | safe }}</p> </div> </div> </div>{% endblock content %}", "e": 36485, "s": 34840, "text": null }, { "code": null, "e": 36806, "s": 36485, "text": "Both homepage and post page will be built by extending base template and replacing blocks with the data stored in our database. Both also have a Facebook open graphs for better sharing and social network and the post page has a structured schema for better SEO additionally. We will build AMP template incoming tutorial." }, { "code": null, "e": 37124, "s": 36806, "text": "Now open views.py file in the blog directory. This file has the logic to run the blog app. We will be using class-based views for the blog app. Class Based Generic Views are an advanced set of Built-in views which are used for the implementation of selective view strategies such as Create, Retrieve, Update, Delete. " }, { "code": null, "e": 37132, "s": 37124, "text": "Python3" }, { "code": "# importing models and librariesfrom django.shortcuts import renderfrom .models import postsfrom django.views import genericfrom django.views.decorators.http import require_GETfrom django.http import HttpResponse # class based views for postsclass postslist(generic.ListView): queryset = posts.objects.filter(status=1).order_by('-created_on') template_name = 'home.html' paginate_by = 4 # class based view for each postclass postdetail(generic.DetailView): model = posts template_name = \"post.html\"", "e": 37646, "s": 37132, "text": null }, { "code": null, "e": 37774, "s": 37649, "text": "For Routing our blog app just go into the blog app directory and create a file urls.py to route our app. see the code below " }, { "code": null, "e": 37782, "s": 37774, "text": "Python3" }, { "code": "# importing django routing librariesfrom . import viewsfrom django.urls import path, includefrom .views import *from .feeds import blogFeed urlpatterns = [ # home page path('', views.postslist.as_view(), name='posts'), # route for posts path('<slug:slug>/', views.postdetail.as_view(), name='post_detail'),]", "e": 38102, "s": 37782, "text": null }, { "code": null, "e": 38200, "s": 38102, "text": " Go to urls.py file in gfgblog directory and route our blog app. See the code below for reference" }, { "code": null, "e": 38208, "s": 38200, "text": "Python3" }, { "code": "from django.contrib import adminfrom django.urls import path, include, re_pathfrom django.conf import settingsfrom django.conf.urls.static import static urlpatterns = [ # urls handling admin route path('admin/', admin.site.urls), # urls handling blog routes path('', include('blog.urls')),]", "e": 38511, "s": 38208, "text": null }, { "code": null, "e": 38549, "s": 38511, "text": "Done, Let’s Now run the server using " }, { "code": null, "e": 38576, "s": 38549, "text": "Python manage.py runserver" }, { "code": null, "e": 38605, "s": 38576, "text": "homepage with latest’s posts" }, { "code": null, "e": 38622, "s": 38605, "text": "sample post page" }, { "code": null, "e": 38639, "s": 38622, "text": "posts management" }, { "code": null, "e": 38655, "s": 38639, "text": "User management" }, { "code": null, "e": 38670, "s": 38655, "text": "kushwanthreddy" }, { "code": null, "e": 38680, "s": 38670, "text": "kalrap615" }, { "code": null, "e": 38695, "s": 38680, "text": "sagartomar9927" }, { "code": null, "e": 38714, "s": 38695, "text": "surindertarika1234" }, { "code": null, "e": 38721, "s": 38714, "text": "Python" }, { "code": null, "e": 38740, "s": 38721, "text": "Technical Scripter" }, { "code": null, "e": 38838, "s": 38740, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38847, "s": 38838, "text": "Comments" }, { "code": null, "e": 38860, "s": 38847, "text": "Old Comments" }, { "code": null, "e": 38896, "s": 38860, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 38935, "s": 38896, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 38958, "s": 38935, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 39009, "s": 38958, "text": "Multithreading in Python | Set 2 (Synchronization)" }, { "code": null, "e": 39041, "s": 39009, "text": "Python Dictionary keys() method" }, { "code": null, "e": 39057, "s": 39041, "text": "loops in python" }, { "code": null, "e": 39098, "s": 39057, "text": "Python - Call function from another file" }, { "code": null, "e": 39147, "s": 39098, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 39180, "s": 39147, "text": "Python | Convert set into a list" } ]
VBA - Events
VBA, an event-driven programming can be triggered when you change a cell or range of cell values manually. Change event may make things easier, but you can very quickly end a page full of formatting. There are two kinds of events. Worksheet Events Workbook Events Worksheet Events are triggered when there is a change in the worksheet. It is created by performing a right-click on the sheet tab and choosing 'view code', and later pasting the code. The user can select each one of those worksheets and choose "WorkSheet" from the drop down to get the list of all supported Worksheet events. Following are the supported worksheet events that can be added by the user. Private Sub Worksheet_Activate() Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean) Private Sub Worksheet_Calculate() Private Sub Worksheet_Change(ByVal Target As Range) Private Sub Worksheet_Deactivate() Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink) Private Sub Worksheet_SelectionChange(ByVal Target As Range) Let us say, we just need to display a message before double click. Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) MsgBox "Before Double Click" End Sub Upon double-clicking on any cell, the message box is displayed to the user as shown in the following screenshot. Workbook events are triggered when there is a change in the workbook on the whole. We can add the code for workbook events by selecting the 'ThisWorkbook' and selecting 'workbook' from the dropdown as shown in the following screenshot. Immediately Workbook_open sub procedure is displayed to the user as seen in the following screenshot. Following are the supported Workbook events that can be added by the user. Private Sub Workbook_AddinUninstall() Private Sub Workbook_BeforeClose(Cancel As Boolean) Private Sub Workbook_BeforePrint(Cancel As Boolean) Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) Private Sub Workbook_Deactivate() Private Sub Workbook_NewSheet(ByVal Sh As Object) Private Sub Workbook_Open() Private Sub Workbook_SheetActivate(ByVal Sh As Object) Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) Private Sub Workbook_SheetBeforeRightClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) Private Sub Workbook_SheetCalculate(ByVal Sh As Object) Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) Private Sub Workbook_SheetDeactivate(ByVal Sh As Object) Private Sub Workbook_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As Hyperlink) Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range) Private Sub Workbook_WindowActivate(ByVal Wn As Window) Private Sub Workbook_WindowDeactivate(ByVal Wn As Window) Private Sub Workbook_WindowResize(ByVal Wn As Window) Let us say, we just need to display a message to the user that a new sheet is created successfully, whenever a new sheet is created. Private Sub Workbook_NewSheet(ByVal Sh As Object) MsgBox "New Sheet Created Successfully" End Sub Upon creating a new excel sheet, a message is displayed to the user as shown in the following screenshot. 101 Lectures 6 hours Pavan Lalwani 41 Lectures 3 hours Arnold Higuit 80 Lectures 5.5 hours Prashant Panchal 25 Lectures 2 hours Prashant Panchal 26 Lectures 2 hours Arnold Higuit 92 Lectures 10.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2166, "s": 1935, "text": "VBA, an event-driven programming can be triggered when you change a cell or range of cell values manually. Change event may make things easier, but you can very quickly end a page full of formatting. There are two kinds of events." }, { "code": null, "e": 2183, "s": 2166, "text": "Worksheet Events" }, { "code": null, "e": 2199, "s": 2183, "text": "Workbook Events" }, { "code": null, "e": 2384, "s": 2199, "text": "Worksheet Events are triggered when there is a change in the worksheet. It is created by performing a right-click on the sheet tab and choosing 'view code', and later pasting the code." }, { "code": null, "e": 2526, "s": 2384, "text": "The user can select each one of those worksheets and choose \"WorkSheet\" from the drop down to get the list of all supported Worksheet events." }, { "code": null, "e": 2602, "s": 2526, "text": "Following are the supported worksheet events that can be added by the user." }, { "code": null, "e": 3055, "s": 2602, "text": "Private Sub Worksheet_Activate() \nPrivate Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) \nPrivate Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean) \nPrivate Sub Worksheet_Calculate() \nPrivate Sub Worksheet_Change(ByVal Target As Range) \nPrivate Sub Worksheet_Deactivate() \nPrivate Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink) \nPrivate Sub Worksheet_SelectionChange(ByVal Target As Range)" }, { "code": null, "e": 3122, "s": 3055, "text": "Let us say, we just need to display a message before double click." }, { "code": null, "e": 3244, "s": 3122, "text": "Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)\n MsgBox \"Before Double Click\"\nEnd Sub" }, { "code": null, "e": 3357, "s": 3244, "text": "Upon double-clicking on any cell, the message box is displayed to the user as shown in the following screenshot." }, { "code": null, "e": 3695, "s": 3357, "text": "Workbook events are triggered when there is a change in the workbook on the whole. We can add the code for workbook events by selecting the 'ThisWorkbook' and selecting 'workbook' from the dropdown as shown in the following screenshot. Immediately Workbook_open sub procedure is displayed to the user as seen in the following screenshot." }, { "code": null, "e": 3770, "s": 3695, "text": "Following are the supported Workbook events that can be added by the user." }, { "code": null, "e": 4916, "s": 3770, "text": "Private Sub Workbook_AddinUninstall() \nPrivate Sub Workbook_BeforeClose(Cancel As Boolean) \nPrivate Sub Workbook_BeforePrint(Cancel As Boolean) \nPrivate Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) \nPrivate Sub Workbook_Deactivate() \nPrivate Sub Workbook_NewSheet(ByVal Sh As Object) \nPrivate Sub Workbook_Open() \nPrivate Sub Workbook_SheetActivate(ByVal Sh As Object) \nPrivate Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) \nPrivate Sub Workbook_SheetBeforeRightClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) \nPrivate Sub Workbook_SheetCalculate(ByVal Sh As Object) \nPrivate Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) \nPrivate Sub Workbook_SheetDeactivate(ByVal Sh As Object) \nPrivate Sub Workbook_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As Hyperlink) \nPrivate Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range) \nPrivate Sub Workbook_WindowActivate(ByVal Wn As Window) \nPrivate Sub Workbook_WindowDeactivate(ByVal Wn As Window) \nPrivate Sub Workbook_WindowResize(ByVal Wn As Window)" }, { "code": null, "e": 5049, "s": 4916, "text": "Let us say, we just need to display a message to the user that a new sheet is created successfully, whenever a new sheet is created." }, { "code": null, "e": 5150, "s": 5049, "text": "Private Sub Workbook_NewSheet(ByVal Sh As Object)\n MsgBox \"New Sheet Created Successfully\"\nEnd Sub" }, { "code": null, "e": 5256, "s": 5150, "text": "Upon creating a new excel sheet, a message is displayed to the user as shown in the following screenshot." }, { "code": null, "e": 5290, "s": 5256, "text": "\n 101 Lectures \n 6 hours \n" }, { "code": null, "e": 5305, "s": 5290, "text": " Pavan Lalwani" }, { "code": null, "e": 5338, "s": 5305, "text": "\n 41 Lectures \n 3 hours \n" }, { "code": null, "e": 5353, "s": 5338, "text": " Arnold Higuit" }, { "code": null, "e": 5388, "s": 5353, "text": "\n 80 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5406, "s": 5388, "text": " Prashant Panchal" }, { "code": null, "e": 5439, "s": 5406, "text": "\n 25 Lectures \n 2 hours \n" }, { "code": null, "e": 5457, "s": 5439, "text": " Prashant Panchal" }, { "code": null, "e": 5490, "s": 5457, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 5505, "s": 5490, "text": " Arnold Higuit" }, { "code": null, "e": 5541, "s": 5505, "text": "\n 92 Lectures \n 10.5 hours \n" }, { "code": null, "e": 5569, "s": 5541, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 5576, "s": 5569, "text": " Print" }, { "code": null, "e": 5587, "s": 5576, "text": " Add Notes" } ]
DOM - XMLHttpRequest Object
XMLHttpRequest object establishes a medium between a web page's client-side and server-side that can be used by the many scripting languages like JavaScript, JScript, VBScript and other web browser to transfer and manipulate the XML data. With the XMLHttpRequest object it is possible to update the part of a web page without reloading the whole page, request and receive the data from a server after the page has been loaded and send the data to the server. An XMLHttpRequest object can be instatiated as follows − xmlhttp = new XMLHttpRequest(); To handle all browsers, including IE5 and IE6, check if the browser supports the XMLHttpRequest object as below − if(window.XMLHttpRequest) // for Firefox, IE7+, Opera, Safari, ... { xmlHttp = new XMLHttpRequest(); } else if(window.ActiveXObject) // for Internet Explorer 5 or 6 { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } Examples to load an XML file using the XMLHttpRequest object can be referred here The following table lists the methods of the XMLHttpRequest object − abort() Terminates the current request made. getAllResponseHeaders() Returns all the response headers as a string, or null if no response has been received. getResponseHeader() Returns the string containing the text of the specified header, or null if either the response has not yet been received or the header doesn't exist in the response. open(method,url,async,uname,pswd) It is used in conjugation with the Send method to send the request to the server. The open method specifies the following parameters − method − specifies the type of request i.e. Get or Post. method − specifies the type of request i.e. Get or Post. url − it is the location of the file. url − it is the location of the file. async − indicates how the request should be handled. It is boolean value. where, 'true' means the request is processed asynchronously without waiting for a Http response. 'false' means the request is processed synchronously after receiving the Http response. async − indicates how the request should be handled. It is boolean value. where, 'true' means the request is processed asynchronously without waiting for a Http response. 'true' means the request is processed asynchronously without waiting for a Http response. 'false' means the request is processed synchronously after receiving the Http response. 'false' means the request is processed synchronously after receiving the Http response. uname − is the username. uname − is the username. pswd − is the password. pswd − is the password. send(string) It is used to send the request working in conjugation with the Open method. setRequestHeader() Header contains the label/value pair to which the request is sent. The following table lists the attributes of the XMLHttpRequest object − onreadystatechange It is an event based property which is set on at every state change. readyState This describes the present state of the XMLHttpRequest object. There are five possible states of the readyState property − readyState = 0 − means request is yet to initialize. readyState = 0 − means request is yet to initialize. readyState = 1 − request is set. readyState = 1 − request is set. readyState = 2 − request is sent. readyState = 2 − request is sent. readyState = 3 − request is processing. readyState = 3 − request is processing. readyState = 4 − request is completed. readyState = 4 − request is completed. responseText This property is used when the response from the server is a text file. responseXML This property is used when the response from the server is an XML file. status statusText Gives the status of the Http request object as a string. For example, "Not Found" or "OK". node.xml contents are as below − <?xml version = "1.0"?> <Company> <Employee category = "Technical"> <FirstName>Tanmay</FirstName> <LastName>Patil</LastName> <ContactNo>1234567890</ContactNo> <Email>[email protected]</Email> </Employee> <Employee category = "Non-Technical"> <FirstName>Taniya</FirstName> <LastName>Mishra</LastName> <ContactNo>1234667898</ContactNo> <Email>[email protected]</Email> </Employee> <Employee category = "Management"> <FirstName>Tanisha</FirstName> <LastName>Sharma</LastName> <ContactNo>1234562350</ContactNo> <Email>[email protected]</Email> </Employee> </Company> Following example demonstrates how to retrive specific information of a resource file using the method getResponseHeader() and the property readState. <!DOCTYPE html> <html> <head> <meta http-equiv = "content-type" content = "text/html; charset = iso-8859-2" /> <script> function loadXMLDoc() { var xmlHttp = null; if(window.XMLHttpRequest) // for Firefox, IE7+, Opera, Safari, ... { xmlHttp = new XMLHttpRequest(); } else if(window.ActiveXObject) // for Internet Explorer 5 or 6 { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } return xmlHttp; } function makerequest(serverPage, myDiv) { var request = loadXMLDoc(); request.open("GET", serverPage); request.send(null); request.onreadystatechange = function() { if (request.readyState == 4) { document.getElementById(myDiv).innerHTML = request.getResponseHeader("Content-length"); } } } </script> </head> <body> <button type = "button" onclick="makerequest('/dom/node.xml', 'ID')">Click me to get the specific ResponseHeader</button> <div id = "ID">Specific header information is returned.</div> </body> </html> Save this file as elementattribute_removeAttributeNS.htm on the server path (this file and node_ns.xml should be on the same path in your server). We will get the output as shown below − Before removing the attributeNS: en After removing the attributeNS: null Following example demonstrates how to retrieve the header information of a resource file, using the method getAllResponseHeaders() using the property readyState. <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-2" /> <script> function loadXMLDoc() { var xmlHttp = null; if(window.XMLHttpRequest) // for Firefox, IE7+, Opera, Safari, ... { xmlHttp = new XMLHttpRequest(); } else if(window.ActiveXObject) // for Internet Explorer 5 or 6 { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } return xmlHttp; } function makerequest(serverPage, myDiv) { var request = loadXMLDoc(); request.open("GET", serverPage); request.send(null); request.onreadystatechange = function() { if (request.readyState == 4) { document.getElementById(myDiv).innerHTML = request.getAllResponseHeaders(); } } } </script> </head> <body> <button type = "button" onclick = "makerequest('/dom/node.xml', 'ID')"> Click me to load the AllResponseHeaders</button> <div id = "ID"></div> </body> </html> Save this file as http_allheader.html on the server path (this file and node.xml should be on the same path in your server). We will get the output as shown below (depends on the browser) − Date: Sat, 27 Sep 2014 07:48:07 GMT Server: Apache Last-Modified: Wed, 03 Sep 2014 06:35:30 GMT Etag: "464bf9-2af-50223713b8a60" Accept-Ranges: bytes Vary: Accept-Encoding,User-Agent Content-Encoding: gzip Content-Length: 256 Content-Type: text/xml 41 Lectures 5 hours Abhishek And Pukhraj 33 Lectures 3.5 hours Abhishek And Pukhraj 15 Lectures 1 hours Zach Miller 15 Lectures 4 hours Prof. Paul Cline, Ed.D 13 Lectures 4 hours Prof. Paul Cline, Ed.D 17 Lectures 2 hours Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2527, "s": 2288, "text": "XMLHttpRequest object establishes a medium between a web page's client-side and server-side that can be used by the many scripting languages like JavaScript, JScript, VBScript and other web browser to transfer and manipulate the XML data." }, { "code": null, "e": 2747, "s": 2527, "text": "With the XMLHttpRequest object it is possible to update the part of a web page without reloading the whole page, request and receive the data from a server after the page has been loaded and send the data to the server." }, { "code": null, "e": 2804, "s": 2747, "text": "An XMLHttpRequest object can be instatiated as follows −" }, { "code": null, "e": 2837, "s": 2804, "text": "xmlhttp = new XMLHttpRequest();\n" }, { "code": null, "e": 2951, "s": 2837, "text": "To handle all browsers, including IE5 and IE6, check if the browser supports the XMLHttpRequest object as below −" }, { "code": null, "e": 3176, "s": 2951, "text": "if(window.XMLHttpRequest) // for Firefox, IE7+, Opera, Safari, ... {\n xmlHttp = new XMLHttpRequest();\n} else if(window.ActiveXObject) // for Internet Explorer 5 or 6 {\n xmlHttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n}" }, { "code": null, "e": 3258, "s": 3176, "text": "Examples to load an XML file using the XMLHttpRequest object can be referred here" }, { "code": null, "e": 3327, "s": 3258, "text": "The following table lists the methods of the XMLHttpRequest object −" }, { "code": null, "e": 3335, "s": 3327, "text": "abort()" }, { "code": null, "e": 3372, "s": 3335, "text": "Terminates the current request made." }, { "code": null, "e": 3396, "s": 3372, "text": "getAllResponseHeaders()" }, { "code": null, "e": 3484, "s": 3396, "text": "Returns all the response headers as a string, or null if no response has been received." }, { "code": null, "e": 3504, "s": 3484, "text": "getResponseHeader()" }, { "code": null, "e": 3670, "s": 3504, "text": "Returns the string containing the text of the specified header, or null if either the response has not yet been received or the header doesn't exist in the response." }, { "code": null, "e": 3704, "s": 3670, "text": "open(method,url,async,uname,pswd)" }, { "code": null, "e": 3839, "s": 3704, "text": "It is used in conjugation with the Send method to send the request to the server. The open method specifies the following parameters −" }, { "code": null, "e": 3896, "s": 3839, "text": "method − specifies the type of request i.e. Get or Post." }, { "code": null, "e": 3953, "s": 3896, "text": "method − specifies the type of request i.e. Get or Post." }, { "code": null, "e": 3991, "s": 3953, "text": "url − it is the location of the file." }, { "code": null, "e": 4029, "s": 3991, "text": "url − it is the location of the file." }, { "code": null, "e": 4291, "s": 4029, "text": "async − indicates how the request should be handled. It is boolean value. where,\n\n'true' means the request is processed asynchronously without waiting for a Http response.\n'false' means the request is processed synchronously after receiving the Http response.\n\n" }, { "code": null, "e": 4372, "s": 4291, "text": "async − indicates how the request should be handled. It is boolean value. where," }, { "code": null, "e": 4462, "s": 4372, "text": "'true' means the request is processed asynchronously without waiting for a Http response." }, { "code": null, "e": 4552, "s": 4462, "text": "'true' means the request is processed asynchronously without waiting for a Http response." }, { "code": null, "e": 4640, "s": 4552, "text": "'false' means the request is processed synchronously after receiving the Http response." }, { "code": null, "e": 4728, "s": 4640, "text": "'false' means the request is processed synchronously after receiving the Http response." }, { "code": null, "e": 4753, "s": 4728, "text": "uname − is the username." }, { "code": null, "e": 4778, "s": 4753, "text": "uname − is the username." }, { "code": null, "e": 4802, "s": 4778, "text": "pswd − is the password." }, { "code": null, "e": 4826, "s": 4802, "text": "pswd − is the password." }, { "code": null, "e": 4839, "s": 4826, "text": "send(string)" }, { "code": null, "e": 4915, "s": 4839, "text": "It is used to send the request working in conjugation with the Open method." }, { "code": null, "e": 4934, "s": 4915, "text": "setRequestHeader()" }, { "code": null, "e": 5001, "s": 4934, "text": "Header contains the label/value pair to which the request is sent." }, { "code": null, "e": 5073, "s": 5001, "text": "The following table lists the attributes of the XMLHttpRequest object −" }, { "code": null, "e": 5092, "s": 5073, "text": "onreadystatechange" }, { "code": null, "e": 5161, "s": 5092, "text": "It is an event based property which is set on at every state change." }, { "code": null, "e": 5172, "s": 5161, "text": "readyState" }, { "code": null, "e": 5295, "s": 5172, "text": "This describes the present state of the XMLHttpRequest object. There are five possible states of the readyState property −" }, { "code": null, "e": 5348, "s": 5295, "text": "readyState = 0 − means request is yet to initialize." }, { "code": null, "e": 5401, "s": 5348, "text": "readyState = 0 − means request is yet to initialize." }, { "code": null, "e": 5434, "s": 5401, "text": "readyState = 1 − request is set." }, { "code": null, "e": 5467, "s": 5434, "text": "readyState = 1 − request is set." }, { "code": null, "e": 5501, "s": 5467, "text": "readyState = 2 − request is sent." }, { "code": null, "e": 5535, "s": 5501, "text": "readyState = 2 − request is sent." }, { "code": null, "e": 5575, "s": 5535, "text": "readyState = 3 − request is processing." }, { "code": null, "e": 5615, "s": 5575, "text": "readyState = 3 − request is processing." }, { "code": null, "e": 5654, "s": 5615, "text": "readyState = 4 − request is completed." }, { "code": null, "e": 5693, "s": 5654, "text": "readyState = 4 − request is completed." }, { "code": null, "e": 5706, "s": 5693, "text": "responseText" }, { "code": null, "e": 5778, "s": 5706, "text": "This property is used when the response from the server is a text file." }, { "code": null, "e": 5790, "s": 5778, "text": "responseXML" }, { "code": null, "e": 5862, "s": 5790, "text": "This property is used when the response from the server is an XML file." }, { "code": null, "e": 5869, "s": 5862, "text": "status" }, { "code": null, "e": 5880, "s": 5869, "text": "statusText" }, { "code": null, "e": 5971, "s": 5880, "text": "Gives the status of the Http request object as a string. For example, \"Not Found\" or \"OK\"." }, { "code": null, "e": 6004, "s": 5971, "text": "node.xml contents are as below −" }, { "code": null, "e": 6674, "s": 6004, "text": "<?xml version = \"1.0\"?>\n<Company>\n <Employee category = \"Technical\">\n <FirstName>Tanmay</FirstName>\n <LastName>Patil</LastName>\n <ContactNo>1234567890</ContactNo>\n <Email>[email protected]</Email>\n </Employee>\n \n <Employee category = \"Non-Technical\">\n <FirstName>Taniya</FirstName>\n <LastName>Mishra</LastName>\n <ContactNo>1234667898</ContactNo>\n <Email>[email protected]</Email>\n </Employee>\n \n <Employee category = \"Management\">\n <FirstName>Tanisha</FirstName>\n <LastName>Sharma</LastName>\n <ContactNo>1234562350</ContactNo>\n <Email>[email protected]</Email>\n </Employee>\n</Company>" }, { "code": null, "e": 6825, "s": 6674, "text": "Following example demonstrates how to retrive specific information of a resource file using the method getResponseHeader() and the property readState." }, { "code": null, "e": 8096, "s": 6825, "text": "<!DOCTYPE html>\n<html>\n <head>\n <meta http-equiv = \"content-type\" content = \"text/html; charset = iso-8859-2\" />\n <script>\n function loadXMLDoc() {\n var xmlHttp = null;\n if(window.XMLHttpRequest) // for Firefox, IE7+, Opera, Safari, ... {\n xmlHttp = new XMLHttpRequest();\n }\n else if(window.ActiveXObject) // for Internet Explorer 5 or 6 {\n xmlHttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n\n return xmlHttp;\n }\n\n function makerequest(serverPage, myDiv) {\n var request = loadXMLDoc();\n request.open(\"GET\", serverPage);\n request.send(null);\n\n request.onreadystatechange = function() {\n if (request.readyState == 4) {\n document.getElementById(myDiv).innerHTML = request.getResponseHeader(\"Content-length\");\n }\n }\n }\n </script>\n </head>\n <body>\n <button type = \"button\" onclick=\"makerequest('/dom/node.xml', 'ID')\">Click me to get the specific ResponseHeader</button>\n <div id = \"ID\">Specific header information is returned.</div>\n </body>\n</html>" }, { "code": null, "e": 8283, "s": 8096, "text": "Save this file as elementattribute_removeAttributeNS.htm on the server path (this file and node_ns.xml should be on the same path in your server). We will get the output as shown below −" }, { "code": null, "e": 8357, "s": 8283, "text": "Before removing the attributeNS: en\nAfter removing the attributeNS: null\n" }, { "code": null, "e": 8519, "s": 8357, "text": "Following example demonstrates how to retrieve the header information of a resource file, using the method getAllResponseHeaders() using the property readyState." }, { "code": null, "e": 9666, "s": 8519, "text": "<!DOCTYPE html>\n<html>\n <head>\n <meta http-equiv=\"content-type\" content=\"text/html; charset=iso-8859-2\" />\n <script>\n function loadXMLDoc() {\n var xmlHttp = null;\n\n if(window.XMLHttpRequest) // for Firefox, IE7+, Opera, Safari, ... {\n xmlHttp = new XMLHttpRequest();\n } else if(window.ActiveXObject) // for Internet Explorer 5 or 6 {\n xmlHttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n\n return xmlHttp;\n }\n\n function makerequest(serverPage, myDiv) {\n var request = loadXMLDoc();\n request.open(\"GET\", serverPage);\n request.send(null);\n request.onreadystatechange = function() {\n if (request.readyState == 4) {\n document.getElementById(myDiv).innerHTML = request.getAllResponseHeaders();\n }\n }\n }\n </script>\n </head>\n <body>\n <button type = \"button\" onclick = \"makerequest('/dom/node.xml', 'ID')\">\n Click me to load the AllResponseHeaders</button>\n <div id = \"ID\"></div>\n </body>\n</html>" }, { "code": null, "e": 9856, "s": 9666, "text": "Save this file as http_allheader.html on the server path (this file and node.xml should be on the same path in your server). We will get the output as shown below (depends on the browser) −" }, { "code": null, "e": 10121, "s": 9856, "text": "Date: Sat, 27 Sep 2014 07:48:07 GMT Server: Apache Last-Modified: \n Wed, 03 Sep 2014 06:35:30 GMT Etag: \"464bf9-2af-50223713b8a60\" Accept-Ranges: bytes Vary: Accept-Encoding,User-Agent \n Content-Encoding: gzip Content-Length: 256 Content-Type: text/xml \n" }, { "code": null, "e": 10154, "s": 10121, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 10176, "s": 10154, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 10211, "s": 10176, "text": "\n 33 Lectures \n 3.5 hours \n" }, { "code": null, "e": 10233, "s": 10211, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 10266, "s": 10233, "text": "\n 15 Lectures \n 1 hours \n" }, { "code": null, "e": 10279, "s": 10266, "text": " Zach Miller" }, { "code": null, "e": 10312, "s": 10279, "text": "\n 15 Lectures \n 4 hours \n" }, { "code": null, "e": 10336, "s": 10312, "text": " Prof. Paul Cline, Ed.D" }, { "code": null, "e": 10369, "s": 10336, "text": "\n 13 Lectures \n 4 hours \n" }, { "code": null, "e": 10393, "s": 10369, "text": " Prof. Paul Cline, Ed.D" }, { "code": null, "e": 10426, "s": 10393, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 10443, "s": 10426, "text": " Laurence Svekis" }, { "code": null, "e": 10450, "s": 10443, "text": " Print" }, { "code": null, "e": 10461, "s": 10450, "text": " Add Notes" } ]
How to insert a record into a table in a database using JDBC API?
A. You can insert records in to a table using the INSERT query. INSERT INTO TABLE_NAME (column1, column2, column3,...columnN) VALUES (value1, value2, value3,...valueN); Or, INSERT INTO TABLE_NAME VALUES (value1, value2, value3,...valueN); To insert a record into a table in a database using JDBC API you need to: Register the driver: Register the driver class using the registerDriver() method of the DriverManager class. Pass the driver class name to it, as parameter. Register the driver: Register the driver class using the registerDriver() method of the DriverManager class. Pass the driver class name to it, as parameter. Establish a connection: Connect ot the database using the getConnection() method of the DriverManager class. Passing URL (String), username (String), password (String) as parameters to it. Establish a connection: Connect ot the database using the getConnection() method of the DriverManager class. Passing URL (String), username (String), password (String) as parameters to it. Create Statement: Create a Statement object using the createStatement() method of the Connection interface. Create Statement: Create a Statement object using the createStatement() method of the Connection interface. Execute the Query: Execute the query using the executeUpdate() method of the Statement interface. Execute the Query: Execute the query using the executeUpdate() method of the Statement interface. Assume we have a table named customers in the database with description as shown below: +---------+---------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+---------------+------+-----+---------+-------+ | ID | int(11) | NO | PRI | NULL | | | NAME | varchar(20) | NO | | NULL | | | AGE | int(11) | NO | | NULL | | | SALARY | decimal(18,2) | YES | | NULL | | | ADDRESS | char(25) | YES | | NULL | | +---------+---------------+------+-----+---------+-------+ Following JDBC program establishes connection with MySQL and inserts 12 records in the customers table: import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class InsertRecordsExample { public static void main(String args[]) throws SQLException { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Creating the Statement Statement stmt = con.createStatement(); //Query to insert records String query = "INSERT INTO CUSTOMERS(" + "ID, Name, AGE, SALARY, ADDRESS) VALUES " + "(1, 'Amit', 25, 3000, 'Hyderabad'), " + "(2, 'Kalyan', 27, 4000, 'Vishakhapatnam'), " + "(3, 'Renuka', 30, 5000, 'Delhi'), " + "(4, 'Archana', 24, 1500, 'Mumbai')," + "(5, 'Koushik', 30, 9000, 'Kota')," + "(6, 'Hardik', 45, 6400, 'Bhopal')," + "(7, 'Trupthi', 33, 4360, 'Ahmedabad')," + "(8, 'Mithili', 26, 4100, 'Vijayawada')," + "(9, 'Maneesh', 39, 4000, 'Hyderabad')," + "(10, 'Rajaneesh', 30, 6400, 'Delhi')," + "(11, 'Komal', 29, 8000, 'Ahmedabad')," + "(12, 'Manyata', 25, 5000, 'Vijayawada')"; int i = stmt.executeUpdate(query); System.out.println("Rows inserted: "+i); } } Connection established...... Rows inserted: 12 If you verify the contents of the customers table using select statement, you can find the inserted records in it as: mysql> select * from customers; +----+-----------+------+---------+----------------+ | ID | NAME | AGE | SALARY | ADDRESS | +----+-----------+------+---------+----------------+ | 1 | Amit | 25 | 3000.00 | Hyderabad | | 2 | Kalyan | 27 | 4000.00 | Vishakhapatnam | | 3 | Renuka | 30 | 5000.00 | Delhi | | 4 | Archana | 24 | 1500.00 | Mumbai | | 5 | Koushik | 30 | 9000.00 | Kota | | 6 | Hardik | 45 | 6400.00 | Bhopal | | 7 | Trupthi | 33 | 4360.00 | Ahmedabad | | 8 | Mithili | 26 | 4100.00 | Vijayawada | | 9 | Maneesh | 39 | 4000.00 | Hyderabad | | 10 | Rajaneesh | 30 | 6400.00 | Delhi | | 11 | Komal | 29 | 8000.00 | Ahmedabad | | 12 | Manyata | 25 | 5000.00 | Vijayawada | +----+-----------+------+---------+----------------+ 12 rows in set (0.06 sec)
[ { "code": null, "e": 1126, "s": 1062, "text": "A. You can insert records in to a table using the INSERT query." }, { "code": null, "e": 1301, "s": 1126, "text": "INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)\nVALUES (value1, value2, value3,...valueN);\nOr,\nINSERT INTO TABLE_NAME VALUES (value1, value2, value3,...valueN);" }, { "code": null, "e": 1375, "s": 1301, "text": "To insert a record into a table in a database using JDBC API you need to:" }, { "code": null, "e": 1532, "s": 1375, "text": "Register the driver: Register the driver class using the registerDriver() method of the DriverManager class. Pass the driver class name to it, as parameter." }, { "code": null, "e": 1689, "s": 1532, "text": "Register the driver: Register the driver class using the registerDriver() method of the DriverManager class. Pass the driver class name to it, as parameter." }, { "code": null, "e": 1878, "s": 1689, "text": "Establish a connection: Connect ot the database using the getConnection() method of the DriverManager class. Passing URL (String), username (String), password (String) as parameters to it." }, { "code": null, "e": 2067, "s": 1878, "text": "Establish a connection: Connect ot the database using the getConnection() method of the DriverManager class. Passing URL (String), username (String), password (String) as parameters to it." }, { "code": null, "e": 2175, "s": 2067, "text": "Create Statement: Create a Statement object using the createStatement() method of the Connection interface." }, { "code": null, "e": 2283, "s": 2175, "text": "Create Statement: Create a Statement object using the createStatement() method of the Connection interface." }, { "code": null, "e": 2381, "s": 2283, "text": "Execute the Query: Execute the query using the executeUpdate() method of the Statement interface." }, { "code": null, "e": 2479, "s": 2381, "text": "Execute the Query: Execute the query using the executeUpdate() method of the Statement interface." }, { "code": null, "e": 2567, "s": 2479, "text": "Assume we have a table named customers in the database with description as shown below:" }, { "code": null, "e": 3098, "s": 2567, "text": "+---------+---------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+---------+---------------+------+-----+---------+-------+\n| ID | int(11) | NO | PRI | NULL | |\n| NAME | varchar(20) | NO | | NULL | |\n| AGE | int(11) | NO | | NULL | |\n| SALARY | decimal(18,2) | YES | | NULL | |\n| ADDRESS | char(25) | YES | | NULL | |\n+---------+---------------+------+-----+---------+-------+" }, { "code": null, "e": 3202, "s": 3098, "text": "Following JDBC program establishes connection with MySQL and inserts 12 records in the customers table:" }, { "code": null, "e": 4652, "s": 3202, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\nimport java.sql.Statement;\npublic class InsertRecordsExample {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating the Statement\n Statement stmt = con.createStatement();\n //Query to insert records\n String query = \"INSERT INTO CUSTOMERS(\" + \"ID, Name, AGE, SALARY, ADDRESS) VALUES \"\n + \"(1, 'Amit', 25, 3000, 'Hyderabad'), \"\n + \"(2, 'Kalyan', 27, 4000, 'Vishakhapatnam'), \"\n + \"(3, 'Renuka', 30, 5000, 'Delhi'), \"\n + \"(4, 'Archana', 24, 1500, 'Mumbai'),\"\n + \"(5, 'Koushik', 30, 9000, 'Kota'),\"\n + \"(6, 'Hardik', 45, 6400, 'Bhopal'),\"\n + \"(7, 'Trupthi', 33, 4360, 'Ahmedabad'),\"\n + \"(8, 'Mithili', 26, 4100, 'Vijayawada'),\"\n + \"(9, 'Maneesh', 39, 4000, 'Hyderabad'),\"\n + \"(10, 'Rajaneesh', 30, 6400, 'Delhi'),\"\n + \"(11, 'Komal', 29, 8000, 'Ahmedabad'),\"\n + \"(12, 'Manyata', 25, 5000, 'Vijayawada')\";\n int i = stmt.executeUpdate(query);\n System.out.println(\"Rows inserted: \"+i);\n }\n}" }, { "code": null, "e": 4699, "s": 4652, "text": "Connection established......\nRows inserted: 12" }, { "code": null, "e": 4817, "s": 4699, "text": "If you verify the contents of the customers table using select statement, you can find the inserted records in it as:" }, { "code": null, "e": 5723, "s": 4817, "text": "mysql> select * from customers;\n+----+-----------+------+---------+----------------+\n| ID | NAME | AGE | SALARY | ADDRESS |\n+----+-----------+------+---------+----------------+\n| 1 | Amit | 25 | 3000.00 | Hyderabad |\n| 2 | Kalyan | 27 | 4000.00 | Vishakhapatnam |\n| 3 | Renuka | 30 | 5000.00 | Delhi |\n| 4 | Archana | 24 | 1500.00 | Mumbai |\n| 5 | Koushik | 30 | 9000.00 | Kota |\n| 6 | Hardik | 45 | 6400.00 | Bhopal |\n| 7 | Trupthi | 33 | 4360.00 | Ahmedabad |\n| 8 | Mithili | 26 | 4100.00 | Vijayawada |\n| 9 | Maneesh | 39 | 4000.00 | Hyderabad |\n| 10 | Rajaneesh | 30 | 6400.00 | Delhi |\n| 11 | Komal | 29 | 8000.00 | Ahmedabad |\n| 12 | Manyata | 25 | 5000.00 | Vijayawada |\n+----+-----------+------+---------+----------------+\n12 rows in set (0.06 sec)" } ]
Using mlr for Machine Learning in R: A Step By Step Approach for Decision Trees | by Asel Mendis | Towards Data Science
I personally like to use mlr to conduct my machine learning tasks but you could just as well use any other library to your liking. First let’s load the relevant libraries: mlr for the machine learning algorithms FSelector for Feature Selection. (Again you can use any Feature Selection library you wish) rpart.plot because I want to visualize the tree and I will be using the rpart decision tree algorithm. library(mlr) library(FSelector) library(rpart.plot)glimpse(Diabetes)Observations: 768 Variables: 6 $ Pregnancies <fct> Yes, Yes, Yes, Yes, No, Yes, Yes... $ Glucose <fct> Hyperglycemia, Normal, Hyperglyc... $ BMI <fct> Obese, Overweight, Normal, Overw... $ DiabetesPedigreeFunction <dbl> 0.627, 0.351, 0.672, 0.167, 2.28... $ Age <int> 50, 31, 32, 21, 33, 30, 26, 29, ... $ Outcome <fct> Positive, Negative, Positive, Ne... A look at the dataset I worked on in my previous post shows the variables we will be working with. I am going to work with a 80/20 train/test dataset. set.seed(1000) train_index <- sample(1:nrow(Diabetes), 0.8 * nrow(Diabetes)) test_index <- setdiff(1:nrow(Diabetes), train_index) train <- Diabetes[train_index,] test <- Diabetes[test_index,]list( train = summary(train), test = summary(test) ) The training set shows our target variable having 212 positive outcomes and 402 negative outcomes. The test set shows that we have 56 positive outcomes and 98 negative outcomes. There is an obvious class imbalance here with our target variable and because it is skewed towards ‘Negative’ (No Diabetes) we will find in harder to build a predictive model for a ‘Positive’ Outcome. You can solve this issue with re-balancing the classes which will involve re-sampling. But, I will resort adjusting the probability threshold in the prediction stage. I do not know if this would solve any underlying issues but threshold adjustment allows you to alter a prediction to give a completely different outcome. (dt_task <- makeClassifTask(data=train, target="Outcome"))Supervised task: train Type: classif Target: Outcome Observations: 614 Features: numerics factors ordered functionals 2 3 0 0 Missings: FALSE Has weights: FALSE Has blocking: FALSE Has coordinates: FALSE Classes: 2 Positive Negative 212 402 Positive class: Positive First we have to make a classification task with our training set. This is where we can define which type of machine learning problem we’re trying to solve and define the target variable. As we can see, the Positive level of Outcome has defaulted to the Positive class in the machine learning task. This is not always the case. You can change it by specifying Positive=x (where ‘x’ is the target level of the variable you want to predict). In this case we want to predict the people that have diabetes (namely, the Positive level of the Outcome variable). (dt_prob <- makeLearner('classif.rpart', predict.type="prob"))Learner classif.rpart from package rpart Type: classif Name: Decision Tree; Short name: rpart Class: classif.rpart Properties: twoclass,multiclass,missings,numerics,factors,ordered,prob,weights,featimp Predict-Type: prob Hyperparameters: xval=0 After creating a classification task we need to make a learner that will later take our task to learn the data. I have chosen the rpart decision tree algorithm. This is the Recursive Partitioning Decision Tree. In order to select which features provide the best chance to predict Positive, the generateFilterValuesData gives us a score for each feature. This can then be plotted with PlotFilterValues. The score for each variable is dependent upon which criteria you choose. Here I choose Information Gain, Chi-squared and Gain Ratio as my criteria. generateFilterValuesData(dt_task, method = c("information.gain","chi.squared", "gain.ratio")) %>% plotFilterValues() The generateFeatureImportanceData function also works in a similar fashion. Except it will show us the importance of each feature according to a given performance criteria. I have chosen True Positive Rate and Area Under the Curve. generateFeatureImportanceData(task=dt_task, learner = dt_prob,measure = tpr, interaction = FALSE)FeatureImportance: Task: train Interaction: FALSE Learner: classif.rpart Measure: tpr Contrast: function (x, y) x - y Aggregation: function (x, ...) UseMethod("mean") Replace: TRUE Number of Monte-Carlo iterations: 50 Local: FALSE tprPregnancies 0Glucose -0.1869811BMI -0.1443396DiabetesPedigreeFunction -0.06339623Age -0.06896226generateFeatureImportanceData(task=dt_task, learner = dt_prob,measure = auc, interaction = FALSE)FeatureImportance: Task: train Interaction: FALSE Learner: classif.rpart Measure: auc Contrast: function (x, y) x - y Aggregation: function (x, ...) UseMethod("mean") Replace: TRUE Number of Monte-Carlo iterations: 50 Local: FALSE aucPregnancies 0Glucose -0.1336535BMI -0.07317023DiabetesPedigreeFunction -0.01907362Age -0.08251478 As we can see with the above output: The information gain and gain ratio show a score of zero or a low score for Pregnancies. generateFeatureImportanceData shows a score of zero for Pregnancies when looking at the TPR and AUC as a performance measure. Looking at all the evidence, Pregnancies will be the only variable I discard. The other variables still show predictive capabilities across certain criteria. Seeing as how we are only left with 4 features, there can be a risk of underfitting my model. The other argument for this would be that I do not have many rows of data to deal with in the first place. This is ongoing discussion on what is the right amount of data and features (Curse of Dimensionality). Looking below I have taken Pregnancies out of our train and test sets and made a new classification task with our new training set. set.seed(1000) train <- select(train, -Pregnancies) test <- select(test, -Pregnancies)list( train = summary(train), test = summary(test) ) Another problem is that in the Glucose category, ‘Hypoglycemia’ has only 5 representations in the whole dataset. When we go for cross validation this will be an issue because almost definitely this level will absent in any of the folds. This will disallow the model to be properly trained later. Therefore we need to remove Hypoglycemia from both datasets: train <- filter(train, Glucose!='Hypoglycemia') %>% droplevels() test <- filter(test, Glucose!='Hypoglycemia') %>% droplevels()list( train = summary(train), test = summary(test) ) As we now have new datasets we need to make a new classification task based on the new training set. (dt_task <- makeClassifTask(data=train, target="Outcome"))Supervised task: train Type: classif Target: Outcome Observations: 609 Features: numerics factors ordered functionals 2 2 0 0 Missings: FALSE Has weights: FALSE Has blocking: FALSE Has coordinates: FALSE Classes: 2 Positive Negative 210 399 Positive class: Positive Now any machine learning algorithm will require us to tune the hyperparameters at our own discretion. Tuning hyperparameters is the process of selecting a value for machine learning parameter with the target of obtaining your desired level of performance. Tuning a machine learning algorithm in mlr involves the following procedures: Define a search space. Define the optimization algorithm (aka tuning method). Define an evaluation method (i.e. re-sampling strategy and a performance measure). So defining a search space is when specify parameters for a given feature/variable. As we are focusing on decision trees in this post, using the getParamSet(learner) function, we can obtain the hyperparameters for the algorithm we want. We need the parameters for the rpart learner. getParamSet("classif.rpart") We can see that there are 10 hyperparameters for rpart and only xval is untunable (i.e it cannot be changed). Here is an explanation of the above parameters: minsplit The minimum number of observations in a node for which the routine will even try to compute a split. The default is 20. Tuning this parameter can save computation time since smaller nodes are almost always pruned away by cross-validation. minbucket Minimum number of observations in a terminal node. The default is minspit/3 (although I do not know if this is the optimal choice). maxcompete This will show you the the variable that gave the best split at a node if set at 1. If set larger than 1, then it will give you the second, third etc.. best. It has no effect on computation time and minimal effect on memory used. maxdepth This controls how deep the tree can be built. cp This is the complexity parameter. The lower it is the larger the tree will grow. A cp=1 will result in no tree at all. This also helps in pruning the tree. Whatever the value of cp we need to be cautious about overpruning the tree. Higher complexity parameters can lead to an overpruned tree. I personally find that a very high complexity parameter value (in my case above 0.3) leads to underfitting the tree due to overpruning but this also depends on the number of features you have. I have not used surrogate variables before so I will omit them in this case. I just do not want to proceed with them at this point without an adequate understanding to explain myself. So now we need to set the hyperparameters to what we want. Remember there is no one right answer exactly. We need to define the space and run the search to automatically find which values of the hyperparameters will give us the best result ACCORDING TO THE SPACE WE DEFINED. This means the performance may or may not be affected with a change (big or small) in the hyperparameters. So either go with your gut if you’re pressed for time or define a large space for the hyperparameters and if you have a powerful machine and outstanding patience, let mlr do the heavy lifting. dt_param <- makeParamSet( makeDiscreteParam("minsplit", values=seq(5,10,1)), makeDiscreteParam("minbucket", values=seq(round(5/3,0), round(10/3,0), 1)), makeNumericParam("cp", lower = 0.01, upper = 0.05), makeDiscreteParam("maxcompete", values=6), makeDiscreteParam("usesurrogate", values=0), makeDiscreteParam("maxdepth", values=10) ) For the model I am using I will set: minsplit = [5,6,7,8,9,10] minbucket = [5/3, 10/3] cp = [0.01, 0.05] maxcompete = 6 usesurrogate = 0 maxdepth = 10 The main reason I am not defining huge spaces is that I did before and it took about 4 hours for it to run and had 100,000 combinations of the hyperparameters. That is too much time for me personally unless I am doing a project that will hugely benefit from it. One of the standard but slow algorithms available to us is Grid Search to choose an appropriate set of parameters. ctrl = makeTuneControlGrid() This is how we specify that we would like to run a grid search. With the space that we specified above, we get 120 possible combinations in the case of dt_param. After specifying the above, we can now conduct the tuning process. We define a resample strategy and make note of the performance. We set the resampling strategy to a 3-fold Cross-Validation with stratified sampling. Stratified Sampling is useful if you have class imbalances in the target variable. It will try to have the same number of classes in each fold. Usually for a good outcome from k-fold cross validation, 3–5 fold cross validation will work well. How many folds will also depend on how much data you have (i.e. number of levels for factors/categories, number of rows). rdesc = makeResampleDesc("CV", iters = 3L, stratify=TRUE) We can now use tuneParams to show us what combination of hyperparameter values as specified by us will give us the optimal result. In measures you can define which performance criteria you would like to see. I also want to get the standard deviation of the True Positive Rate from the test set during the cross validation. This added measure should give us an indication of how large the spread is between each fold for this measure. set.seed(1000) (dt_tuneparam <- tuneParams(learner=dt_prob, resampling=rdesc, measures=list(tpr,auc, fnr, mmce, tnr, setAggregation(tpr, test.sd)), par.set=dt_param, control=ctrl, task=dt_task, show.info = TRUE) )Tune result: Op. pars: minsplit=9; minbucket=2; cp=0.0144; maxcompete=6; usesurrogate=0; maxdepth=10 tpr.test.mean=0.6095238,auc.test.mean=0.7807376,fnr.test.mean=0.3904762,mmce.test.mean=0.2725780,tnr.test.mean=0.7894737,tpr.test.sd=0.0704698 Upon running the tuner, we see the 120 possible combinations of the hyparameters we set. The final result at the bottom of the output (i.e [Tune] Result:...) gives us our optimal combination. This will change every-time you run it. As long as you can see similar performance results there should be no danger in going ahead with the current dataset. If the performance results begin to diverge too much, the data may be inadequate. In the optimal hyperparameters, the standard deviation of the True Positive Rate in the test set is 0.0704698, which is relatively low and can give us an idea of the True Positive Rate we will obtain later when predicting. If the TPR from the prediction is close or in-between 1 standard deviation from the one obtained during cross validation, it is another indication that our model works well (this is just my view, others may require less spread) NOTE tuneParams knows which performance measure to minimize and maximize. So for example, it knows to maximize accuracy and minimize error rate (mmce). On a side not as I mentioned earlier, I defined a large search space and it took about 4 hours to finish and ended up with 100,000 combnations. This was the result: [Tune] Result: minsplit=17; minbucket=7; cp=0.0433; maxcompete=4; usesurrogate=0; maxdepth=7 : tpr.test.mean=0.6904762,auc.test.mean=0.7277720,f1.test.mean=0.6156823,acc.test.mean=0.7283265, mmce.test.mean=0.2716735,timepredict.test.mean=0.0000000,tnr.test.mean=0.7460928 Although the TPR is higher, I am going to use my previous hyperparameters because it is less computationally expensive. list( `Optimal HyperParameters` = dt_tuneparam$x, `Optimal Metrics` = dt_tuneparam$y )$`Optimal HyperParameters` $`Optimal HyperParameters`$minsplit [1] 9 $`Optimal HyperParameters`$minbucket [1] 2 $`Optimal HyperParameters`$cp [1] 0.01444444 $`Optimal HyperParameters`$maxcompete [1] 6 $`Optimal HyperParameters`$usesurrogate [1] 0 $`Optimal HyperParameters`$maxdepth [1] 10 $`Optimal Metrics` tpr.test.mean auc.test.mean fnr.test.mean mmce.test.mean 0.60952381 0.78073756 0.39047619 0.27257800 tnr.test.mean tpr.test.sd 0.78947368 0.07046976 Using dt_tuneparam$x we can extract the optimal values and dt_tuneparam$y gives us the corresponding performance measures. setHyperPars will tune the learner with its optimal values. dtree <- setHyperPars(dt_prob, par.vals = dt_tuneparam$x) set.seed(1000) dtree_train <- train(learner=dtree, task=dt_task) getLearnerModel(dtree_train)n= 609 node), split, n, loss, yval, (yprob) * denotes terminal node 1) root 609 210 Negative (0.34482759 0.65517241) 2) Glucose=Hyperglycemia 149 46 Positive (0.69127517 0.30872483) 4) BMI=Obese 117 28 Positive (0.76068376 0.23931624) * 5) BMI=Normal,Overweight 32 14 Negative (0.43750000 0.56250000) * 3) Glucose=Normal 460 107 Negative (0.23260870 0.76739130) 6) Age>=28.5 215 78 Negative (0.36279070 0.63720930) 12) BMI=Underweight,Overweight,Obese 184 77 Negative (0.41847826 0.58152174) 24) DiabetesPedigreeFunction>=0.5275 61 23 Positive (0.62295082 0.37704918) * 25) DiabetesPedigreeFunction< 0.5275 123 39 Negative (0.31707317 0.68292683) * 13) BMI=Normal 31 1 Negative (0.03225806 0.96774194) * 7) Age< 28.5 245 29 Negative (0.11836735 0.88163265) *rpart.plot(dtree_train$learner.model, roundint=FALSE, varlen=3, type = 3, clip.right.labs = FALSE, yesno = 2) rpart.rules(dtree_train$learner.model, roundint = FALSE)Outcome 0.24 when Glucose is Hyperglycemia & BMI is Obese 0.38 when Glucose is Normal & BMI is Underweight or Overweight or Obese & Age >= 29 & DiabetesPedigreeFunction >= 0.53 0.56 when Glucose is Hyperglycemia & BMI is Normal or Overweight 0.68 when Glucose is Normal & BMI is Underweight or Overweight or Obese & Age >= 29 & DiabetesPedigreeFunction < 0.53 0.88 when Glucose is Normal & Age < 29 0.97 when Glucose is Normal & BMI is Normal & Age >= 29 After training the decision tree I was able to plot it with the rpart.plot function and I can easily see the rules of the tree with rpart.rules. Since mlr is a wrapper for machine learning algorithms I can customize to my liking and this is just one example. We now pass the trained learner to be used to make predictions with our test data. set.seed(1000) (dtree_predict <- predict(dtree_train, newdata = test))Prediction: 154 observations predict.type: prob threshold: Positive=0.50,Negative=0.50 time: 0.00 truth prob.Positive prob.Negative response 1 Negative 0.3170732 0.6829268 Negative 2 Positive 0.6229508 0.3770492 Positive 3 Negative 0.4375000 0.5625000 Negative 4 Negative 0.3170732 0.6829268 Negative 5 Positive 0.7606838 0.2393162 Positive 6 Negative 0.1183673 0.8816327 Negative ... (#rows: 154, #cols: 4) The threshold for classifying each row is 50/50. This is by default but can be changed later (which I will do). dtree_predict %>% calculateROCMeasures() So now we have the confusion matrix for our model. We see that it does an excellent job in predicting a Negative Outcome but does poorly with a Positive Outcome. This is inherently due to the class imbalance in our dataset. This is why thresholding is an easier tactic to get our preferred model. Of course it would be better if we had balanced classes and more rows of observations in our data but this is not always a choice or reality. To see the performance of our model more coherently, we can use the following code I wrote to see it in a presentable manner. Performance <- performance(dtree_predict, measures = list(tpr,auc,mmce, acc,tnr)) %>% as.data.frame(row.names = c("True Positive","Area Under Curve", "Mean Misclassification Error","Accuracy","True Negative")) Performance %>% kable(caption="Performance of Decision Tree",digits = 2, format = 'html', col.names = "Result") These metrics are quite satisfactory. But we can still achieve a higher TPR as I describe below. In certain cases including this, the TPR will be the most important and not the TNR. But in my view, I need to achieve a satisfactory TNR because if not, my misclassification (error) rate will be high. (dtree_threshold <- generateThreshVsPerfData(dtree_predict, measures = list(tpr,auc, mmce,tnr)) %>% plotThreshVsPerf() + geom_point() ) My personal goal for this model will be to obtain an acceptable and satisfactory True Positive Rate and True Negative Rate. Since the AUC remains the same across all thresholds we need not concern ourselves with it. By changing the threshold I am deliberately creating a biased model but this is a normal machine learning problem. The Bias-Variance Tradeoff is so common and we need to learn to navigate throught it. It is a whole other topic and anyone doing machine learning will need some knowledge of it. Below you will see 3 different thresholds: The maximum threshold in which our TPR is below 100%. The minimum threshold in which our TPR is above 80%. The average of the two thresholds. The maximum threshold in which our TNR is above 70%. list( `TPR Threshold for 100%` = tpr_threshold100 <- dtree_threshold$data$threshold[ which.max(dtree_threshold$data$performance[ dtree_threshold$data$measure=="True positive rate"]<1)], `TPR Threshold for 80%` = tpr_threshold80 <- dtree_threshold$data$threshold[ which.min(dtree_threshold$data$performance[ dtree_threshold$data$measure=="True positive rate"]>0.80)], `Average Threshold` = avg_threshold <- mean(c(tpr_threshold100,tpr_threshold80)), `TNR Threshold for 80%` = tnr_threshold80 <- dtree_threshold$data$threshold[ which.max(dtree_threshold$data$performance[ dtree_threshold$data$measure=="True negative rate"]>0.70)] ) $TPR Threshold for 100% [1] 0.1212121 $TPR Threshold for 80% [1] 0.3232323 $Average Threshold [1] 0.2222222 $TNR Threshold for 80% [1] 0.3232323 Using avg_threhsold to predict on our model one more time we can get the following performance metrics. However looking at the thresholds from the plot and the ones I defined above, our True Negative Rate is going to take a big hit. DecisionTree <- dtree_predict %>% setThreshold(avg_threshold) (dt_performance <- DecisionTree %>% performance(measures = list(tpr,auc, mmce,tnr)) )tpr auc mmce tnr 0.8214286 0.7693149 0.3376623 0.5714286 Our TPR is now 82.14 %. This is a huge difference from a 50/50 threshold. Our TNR has reduced to 57.14 % but this is a consequence of biasing our model towards the TPR. I explain below looking at the new confusion matrix. (dt_cm <- DecisionTree %>% calculateROCMeasures() ) We notice the other following changes: The TNR has reduced to 57 % due to the threshold difference. The FPR has increased to 43 %. This means that the model has an increased likelihood of a Type 1 Error in which it will detect diabetes when it is actually absent. This is a sacrifice we needed to make to get a higher TPR. The Accuracy has reduced to 66 %. This is another consequence of changing the threshold. This is not a cause for concern because our model does what I intended for it to do — Have a high True Positive Rate. Accuracy is not an adequate measure of model performance if we only care about the accurate prediction of a certain outcome. This is the case most of the time but even then you still need to dig deep into the model performance. Performance_threshold <- performance(DecisionTree, measures = list(tpr,auc, mmce, acc, tnr)) %>% as.data.frame(row.names = c("True Positive","Area Under Curve", "Mean Misclassification Error","Accuracy","True Negative")) Performance_threshold %>% kable(caption=paste("Performance of Decision Tree\n\nAfter Thresholding to",(avg_threshold*100) %>% round(0),'%'), digits = 2, format = 'html', col.names = 'RESULT') We can see our new performance metrics after changing the classification threshold. Thresholding is very subjective to the user and the domain of the problem. Sometimes it will be necessary to skew the model’s performance in one direction depending on the cost of misclassification for you. In this scenario, there will be many false positives for patients but if the cost of misclassifying these patients is not too high, it is worthy of obtaining higher likelihoods of a correct diagnosis (i.e. True Positives). In an ending note, thresholding becomes a necessity especially when you have an imbalanced dataset (i.e. imbalanced number of target levels). In this dataset there are many more Negative’s than Positives’s. If it were more balanced there may not be a need for thresholding depending on how well the model classifies each target. If you have any questions or concerns please comment for a discussion and I invite anyone who finds this interesting to join. Thank you Originally published at Easy Data Science with R and Python.
[ { "code": null, "e": 302, "s": 171, "text": "I personally like to use mlr to conduct my machine learning tasks but you could just as well use any other library to your liking." }, { "code": null, "e": 343, "s": 302, "text": "First let’s load the relevant libraries:" }, { "code": null, "e": 383, "s": 343, "text": "mlr for the machine learning algorithms" }, { "code": null, "e": 475, "s": 383, "text": "FSelector for Feature Selection. (Again you can use any Feature Selection library you wish)" }, { "code": null, "e": 578, "s": 475, "text": "rpart.plot because I want to visualize the tree and I will be using the rpart decision tree algorithm." }, { "code": null, "e": 1002, "s": 578, "text": "library(mlr) library(FSelector) library(rpart.plot)glimpse(Diabetes)Observations: 768 Variables: 6 $ Pregnancies <fct> Yes, Yes, Yes, Yes, No, Yes, Yes... $ Glucose <fct> Hyperglycemia, Normal, Hyperglyc... $ BMI <fct> Obese, Overweight, Normal, Overw... $ DiabetesPedigreeFunction <dbl> 0.627, 0.351, 0.672, 0.167, 2.28... $ Age <int> 50, 31, 32, 21, 33, 30, 26, 29, ... $ Outcome <fct> Positive, Negative, Positive, Ne..." }, { "code": null, "e": 1101, "s": 1002, "text": "A look at the dataset I worked on in my previous post shows the variables we will be working with." }, { "code": null, "e": 1153, "s": 1101, "text": "I am going to work with a 80/20 train/test dataset." }, { "code": null, "e": 1397, "s": 1153, "text": "set.seed(1000) train_index <- sample(1:nrow(Diabetes), 0.8 * nrow(Diabetes)) test_index <- setdiff(1:nrow(Diabetes), train_index) train <- Diabetes[train_index,] test <- Diabetes[test_index,]list( train = summary(train), test = summary(test) )" }, { "code": null, "e": 1496, "s": 1397, "text": "The training set shows our target variable having 212 positive outcomes and 402 negative outcomes." }, { "code": null, "e": 1575, "s": 1496, "text": "The test set shows that we have 56 positive outcomes and 98 negative outcomes." }, { "code": null, "e": 1776, "s": 1575, "text": "There is an obvious class imbalance here with our target variable and because it is skewed towards ‘Negative’ (No Diabetes) we will find in harder to build a predictive model for a ‘Positive’ Outcome." }, { "code": null, "e": 2097, "s": 1776, "text": "You can solve this issue with re-balancing the classes which will involve re-sampling. But, I will resort adjusting the probability threshold in the prediction stage. I do not know if this would solve any underlying issues but threshold adjustment allows you to alter a prediction to give a completely different outcome." }, { "code": null, "e": 2471, "s": 2097, "text": "(dt_task <- makeClassifTask(data=train, target=\"Outcome\"))Supervised task: train Type: classif Target: Outcome Observations: 614 Features: numerics factors ordered functionals 2 3 0 0 Missings: FALSE Has weights: FALSE Has blocking: FALSE Has coordinates: FALSE Classes: 2 Positive Negative 212 402 Positive class: Positive" }, { "code": null, "e": 2659, "s": 2471, "text": "First we have to make a classification task with our training set. This is where we can define which type of machine learning problem we’re trying to solve and define the target variable." }, { "code": null, "e": 3027, "s": 2659, "text": "As we can see, the Positive level of Outcome has defaulted to the Positive class in the machine learning task. This is not always the case. You can change it by specifying Positive=x (where ‘x’ is the target level of the variable you want to predict). In this case we want to predict the people that have diabetes (namely, the Positive level of the Outcome variable)." }, { "code": null, "e": 3334, "s": 3027, "text": "(dt_prob <- makeLearner('classif.rpart', predict.type=\"prob\"))Learner classif.rpart from package rpart Type: classif Name: Decision Tree; Short name: rpart Class: classif.rpart Properties: twoclass,multiclass,missings,numerics,factors,ordered,prob,weights,featimp Predict-Type: prob Hyperparameters: xval=0" }, { "code": null, "e": 3545, "s": 3334, "text": "After creating a classification task we need to make a learner that will later take our task to learn the data. I have chosen the rpart decision tree algorithm. This is the Recursive Partitioning Decision Tree." }, { "code": null, "e": 3884, "s": 3545, "text": "In order to select which features provide the best chance to predict Positive, the generateFilterValuesData gives us a score for each feature. This can then be plotted with PlotFilterValues. The score for each variable is dependent upon which criteria you choose. Here I choose Information Gain, Chi-squared and Gain Ratio as my criteria." }, { "code": null, "e": 4001, "s": 3884, "text": "generateFilterValuesData(dt_task, method = c(\"information.gain\",\"chi.squared\", \"gain.ratio\")) %>% plotFilterValues()" }, { "code": null, "e": 4233, "s": 4001, "text": "The generateFeatureImportanceData function also works in a similar fashion. Except it will show us the importance of each feature according to a given performance criteria. I have chosen True Positive Rate and Area Under the Curve." }, { "code": null, "e": 5089, "s": 4233, "text": "generateFeatureImportanceData(task=dt_task, learner = dt_prob,measure = tpr, interaction = FALSE)FeatureImportance: Task: train Interaction: FALSE Learner: classif.rpart Measure: tpr Contrast: function (x, y) x - y Aggregation: function (x, ...) UseMethod(\"mean\") Replace: TRUE Number of Monte-Carlo iterations: 50 Local: FALSE tprPregnancies 0Glucose -0.1869811BMI -0.1443396DiabetesPedigreeFunction -0.06339623Age -0.06896226generateFeatureImportanceData(task=dt_task, learner = dt_prob,measure = auc, interaction = FALSE)FeatureImportance: Task: train Interaction: FALSE Learner: classif.rpart Measure: auc Contrast: function (x, y) x - y Aggregation: function (x, ...) UseMethod(\"mean\") Replace: TRUE Number of Monte-Carlo iterations: 50 Local: FALSE aucPregnancies 0Glucose -0.1336535BMI -0.07317023DiabetesPedigreeFunction -0.01907362Age -0.08251478" }, { "code": null, "e": 5126, "s": 5089, "text": "As we can see with the above output:" }, { "code": null, "e": 5215, "s": 5126, "text": "The information gain and gain ratio show a score of zero or a low score for Pregnancies." }, { "code": null, "e": 5341, "s": 5215, "text": "generateFeatureImportanceData shows a score of zero for Pregnancies when looking at the TPR and AUC as a performance measure." }, { "code": null, "e": 5499, "s": 5341, "text": "Looking at all the evidence, Pregnancies will be the only variable I discard. The other variables still show predictive capabilities across certain criteria." }, { "code": null, "e": 5803, "s": 5499, "text": "Seeing as how we are only left with 4 features, there can be a risk of underfitting my model. The other argument for this would be that I do not have many rows of data to deal with in the first place. This is ongoing discussion on what is the right amount of data and features (Curse of Dimensionality)." }, { "code": null, "e": 5935, "s": 5803, "text": "Looking below I have taken Pregnancies out of our train and test sets and made a new classification task with our new training set." }, { "code": null, "e": 6074, "s": 5935, "text": "set.seed(1000) train <- select(train, -Pregnancies) test <- select(test, -Pregnancies)list( train = summary(train), test = summary(test) )" }, { "code": null, "e": 6431, "s": 6074, "text": "Another problem is that in the Glucose category, ‘Hypoglycemia’ has only 5 representations in the whole dataset. When we go for cross validation this will be an issue because almost definitely this level will absent in any of the folds. This will disallow the model to be properly trained later. Therefore we need to remove Hypoglycemia from both datasets:" }, { "code": null, "e": 6611, "s": 6431, "text": "train <- filter(train, Glucose!='Hypoglycemia') %>% droplevels() test <- filter(test, Glucose!='Hypoglycemia') %>% droplevels()list( train = summary(train), test = summary(test) )" }, { "code": null, "e": 6712, "s": 6611, "text": "As we now have new datasets we need to make a new classification task based on the new training set." }, { "code": null, "e": 7076, "s": 6712, "text": "(dt_task <- makeClassifTask(data=train, target=\"Outcome\"))Supervised task: train Type: classif Target: Outcome Observations: 609 Features: numerics factors ordered functionals 2 2 0 0 Missings: FALSE Has weights: FALSE Has blocking: FALSE Has coordinates: FALSE Classes: 2 Positive Negative 210 399 Positive class: Positive" }, { "code": null, "e": 7332, "s": 7076, "text": "Now any machine learning algorithm will require us to tune the hyperparameters at our own discretion. Tuning hyperparameters is the process of selecting a value for machine learning parameter with the target of obtaining your desired level of performance." }, { "code": null, "e": 7410, "s": 7332, "text": "Tuning a machine learning algorithm in mlr involves the following procedures:" }, { "code": null, "e": 7433, "s": 7410, "text": "Define a search space." }, { "code": null, "e": 7488, "s": 7433, "text": "Define the optimization algorithm (aka tuning method)." }, { "code": null, "e": 7571, "s": 7488, "text": "Define an evaluation method (i.e. re-sampling strategy and a performance measure)." }, { "code": null, "e": 7808, "s": 7571, "text": "So defining a search space is when specify parameters for a given feature/variable. As we are focusing on decision trees in this post, using the getParamSet(learner) function, we can obtain the hyperparameters for the algorithm we want." }, { "code": null, "e": 7854, "s": 7808, "text": "We need the parameters for the rpart learner." }, { "code": null, "e": 7883, "s": 7854, "text": "getParamSet(\"classif.rpart\")" }, { "code": null, "e": 7993, "s": 7883, "text": "We can see that there are 10 hyperparameters for rpart and only xval is untunable (i.e it cannot be changed)." }, { "code": null, "e": 8041, "s": 7993, "text": "Here is an explanation of the above parameters:" }, { "code": null, "e": 8050, "s": 8041, "text": "minsplit" }, { "code": null, "e": 8289, "s": 8050, "text": "The minimum number of observations in a node for which the routine will even try to compute a split. The default is 20. Tuning this parameter can save computation time since smaller nodes are almost always pruned away by cross-validation." }, { "code": null, "e": 8299, "s": 8289, "text": "minbucket" }, { "code": null, "e": 8431, "s": 8299, "text": "Minimum number of observations in a terminal node. The default is minspit/3 (although I do not know if this is the optimal choice)." }, { "code": null, "e": 8442, "s": 8431, "text": "maxcompete" }, { "code": null, "e": 8672, "s": 8442, "text": "This will show you the the variable that gave the best split at a node if set at 1. If set larger than 1, then it will give you the second, third etc.. best. It has no effect on computation time and minimal effect on memory used." }, { "code": null, "e": 8681, "s": 8672, "text": "maxdepth" }, { "code": null, "e": 8727, "s": 8681, "text": "This controls how deep the tree can be built." }, { "code": null, "e": 8730, "s": 8727, "text": "cp" }, { "code": null, "e": 9216, "s": 8730, "text": "This is the complexity parameter. The lower it is the larger the tree will grow. A cp=1 will result in no tree at all. This also helps in pruning the tree. Whatever the value of cp we need to be cautious about overpruning the tree. Higher complexity parameters can lead to an overpruned tree. I personally find that a very high complexity parameter value (in my case above 0.3) leads to underfitting the tree due to overpruning but this also depends on the number of features you have." }, { "code": null, "e": 9400, "s": 9216, "text": "I have not used surrogate variables before so I will omit them in this case. I just do not want to proceed with them at this point without an adequate understanding to explain myself." }, { "code": null, "e": 9782, "s": 9400, "text": "So now we need to set the hyperparameters to what we want. Remember there is no one right answer exactly. We need to define the space and run the search to automatically find which values of the hyperparameters will give us the best result ACCORDING TO THE SPACE WE DEFINED. This means the performance may or may not be affected with a change (big or small) in the hyperparameters." }, { "code": null, "e": 9975, "s": 9782, "text": "So either go with your gut if you’re pressed for time or define a large space for the hyperparameters and if you have a powerful machine and outstanding patience, let mlr do the heavy lifting." }, { "code": null, "e": 10311, "s": 9975, "text": "dt_param <- makeParamSet( makeDiscreteParam(\"minsplit\", values=seq(5,10,1)), makeDiscreteParam(\"minbucket\", values=seq(round(5/3,0), round(10/3,0), 1)), makeNumericParam(\"cp\", lower = 0.01, upper = 0.05), makeDiscreteParam(\"maxcompete\", values=6), makeDiscreteParam(\"usesurrogate\", values=0), makeDiscreteParam(\"maxdepth\", values=10) )" }, { "code": null, "e": 10348, "s": 10311, "text": "For the model I am using I will set:" }, { "code": null, "e": 10374, "s": 10348, "text": "minsplit = [5,6,7,8,9,10]" }, { "code": null, "e": 10398, "s": 10374, "text": "minbucket = [5/3, 10/3]" }, { "code": null, "e": 10416, "s": 10398, "text": "cp = [0.01, 0.05]" }, { "code": null, "e": 10431, "s": 10416, "text": "maxcompete = 6" }, { "code": null, "e": 10448, "s": 10431, "text": "usesurrogate = 0" }, { "code": null, "e": 10462, "s": 10448, "text": "maxdepth = 10" }, { "code": null, "e": 10724, "s": 10462, "text": "The main reason I am not defining huge spaces is that I did before and it took about 4 hours for it to run and had 100,000 combinations of the hyperparameters. That is too much time for me personally unless I am doing a project that will hugely benefit from it." }, { "code": null, "e": 10839, "s": 10724, "text": "One of the standard but slow algorithms available to us is Grid Search to choose an appropriate set of parameters." }, { "code": null, "e": 10868, "s": 10839, "text": "ctrl = makeTuneControlGrid()" }, { "code": null, "e": 11030, "s": 10868, "text": "This is how we specify that we would like to run a grid search. With the space that we specified above, we get 120 possible combinations in the case of dt_param." }, { "code": null, "e": 11161, "s": 11030, "text": "After specifying the above, we can now conduct the tuning process. We define a resample strategy and make note of the performance." }, { "code": null, "e": 11612, "s": 11161, "text": "We set the resampling strategy to a 3-fold Cross-Validation with stratified sampling. Stratified Sampling is useful if you have class imbalances in the target variable. It will try to have the same number of classes in each fold. Usually for a good outcome from k-fold cross validation, 3–5 fold cross validation will work well. How many folds will also depend on how much data you have (i.e. number of levels for factors/categories, number of rows)." }, { "code": null, "e": 11670, "s": 11612, "text": "rdesc = makeResampleDesc(\"CV\", iters = 3L, stratify=TRUE)" }, { "code": null, "e": 11801, "s": 11670, "text": "We can now use tuneParams to show us what combination of hyperparameter values as specified by us will give us the optimal result." }, { "code": null, "e": 12104, "s": 11801, "text": "In measures you can define which performance criteria you would like to see. I also want to get the standard deviation of the True Positive Rate from the test set during the cross validation. This added measure should give us an indication of how large the spread is between each fold for this measure." }, { "code": null, "e": 12663, "s": 12104, "text": "set.seed(1000) (dt_tuneparam <- tuneParams(learner=dt_prob, resampling=rdesc, measures=list(tpr,auc, fnr, mmce, tnr, setAggregation(tpr, test.sd)), par.set=dt_param, control=ctrl, task=dt_task, show.info = TRUE) )Tune result: Op. pars: minsplit=9; minbucket=2; cp=0.0144; maxcompete=6; usesurrogate=0; maxdepth=10 tpr.test.mean=0.6095238,auc.test.mean=0.7807376,fnr.test.mean=0.3904762,mmce.test.mean=0.2725780,tnr.test.mean=0.7894737,tpr.test.sd=0.0704698" }, { "code": null, "e": 13095, "s": 12663, "text": "Upon running the tuner, we see the 120 possible combinations of the hyparameters we set. The final result at the bottom of the output (i.e [Tune] Result:...) gives us our optimal combination. This will change every-time you run it. As long as you can see similar performance results there should be no danger in going ahead with the current dataset. If the performance results begin to diverge too much, the data may be inadequate." }, { "code": null, "e": 13546, "s": 13095, "text": "In the optimal hyperparameters, the standard deviation of the True Positive Rate in the test set is 0.0704698, which is relatively low and can give us an idea of the True Positive Rate we will obtain later when predicting. If the TPR from the prediction is close or in-between 1 standard deviation from the one obtained during cross validation, it is another indication that our model works well (this is just my view, others may require less spread)" }, { "code": null, "e": 13698, "s": 13546, "text": "NOTE tuneParams knows which performance measure to minimize and maximize. So for example, it knows to maximize accuracy and minimize error rate (mmce)." }, { "code": null, "e": 13863, "s": 13698, "text": "On a side not as I mentioned earlier, I defined a large search space and it took about 4 hours to finish and ended up with 100,000 combnations. This was the result:" }, { "code": null, "e": 14135, "s": 13863, "text": "[Tune] Result: minsplit=17; minbucket=7; cp=0.0433; maxcompete=4; usesurrogate=0; maxdepth=7 : tpr.test.mean=0.6904762,auc.test.mean=0.7277720,f1.test.mean=0.6156823,acc.test.mean=0.7283265, mmce.test.mean=0.2716735,timepredict.test.mean=0.0000000,tnr.test.mean=0.7460928" }, { "code": null, "e": 14255, "s": 14135, "text": "Although the TPR is higher, I am going to use my previous hyperparameters because it is less computationally expensive." }, { "code": null, "e": 14820, "s": 14255, "text": "list( `Optimal HyperParameters` = dt_tuneparam$x, `Optimal Metrics` = dt_tuneparam$y )$`Optimal HyperParameters` $`Optimal HyperParameters`$minsplit [1] 9 $`Optimal HyperParameters`$minbucket [1] 2 $`Optimal HyperParameters`$cp [1] 0.01444444 $`Optimal HyperParameters`$maxcompete [1] 6 $`Optimal HyperParameters`$usesurrogate [1] 0 $`Optimal HyperParameters`$maxdepth [1] 10 $`Optimal Metrics` tpr.test.mean auc.test.mean fnr.test.mean mmce.test.mean 0.60952381 0.78073756 0.39047619 0.27257800 tnr.test.mean tpr.test.sd 0.78947368 0.07046976" }, { "code": null, "e": 14943, "s": 14820, "text": "Using dt_tuneparam$x we can extract the optimal values and dt_tuneparam$y gives us the corresponding performance measures." }, { "code": null, "e": 15003, "s": 14943, "text": "setHyperPars will tune the learner with its optimal values." }, { "code": null, "e": 15061, "s": 15003, "text": "dtree <- setHyperPars(dt_prob, par.vals = dt_tuneparam$x)" }, { "code": null, "e": 16022, "s": 15061, "text": "set.seed(1000) dtree_train <- train(learner=dtree, task=dt_task) getLearnerModel(dtree_train)n= 609 node), split, n, loss, yval, (yprob) * denotes terminal node 1) root 609 210 Negative (0.34482759 0.65517241) 2) Glucose=Hyperglycemia 149 46 Positive (0.69127517 0.30872483) 4) BMI=Obese 117 28 Positive (0.76068376 0.23931624) * 5) BMI=Normal,Overweight 32 14 Negative (0.43750000 0.56250000) * 3) Glucose=Normal 460 107 Negative (0.23260870 0.76739130) 6) Age>=28.5 215 78 Negative (0.36279070 0.63720930) 12) BMI=Underweight,Overweight,Obese 184 77 Negative (0.41847826 0.58152174) 24) DiabetesPedigreeFunction>=0.5275 61 23 Positive (0.62295082 0.37704918) * 25) DiabetesPedigreeFunction< 0.5275 123 39 Negative (0.31707317 0.68292683) * 13) BMI=Normal 31 1 Negative (0.03225806 0.96774194) * 7) Age< 28.5 245 29 Negative (0.11836735 0.88163265) *rpart.plot(dtree_train$learner.model, roundint=FALSE, varlen=3, type = 3, clip.right.labs = FALSE, yesno = 2)" }, { "code": null, "e": 16533, "s": 16022, "text": "rpart.rules(dtree_train$learner.model, roundint = FALSE)Outcome 0.24 when Glucose is Hyperglycemia & BMI is Obese 0.38 when Glucose is Normal & BMI is Underweight or Overweight or Obese & Age >= 29 & DiabetesPedigreeFunction >= 0.53 0.56 when Glucose is Hyperglycemia & BMI is Normal or Overweight 0.68 when Glucose is Normal & BMI is Underweight or Overweight or Obese & Age >= 29 & DiabetesPedigreeFunction < 0.53 0.88 when Glucose is Normal & Age < 29 0.97 when Glucose is Normal & BMI is Normal & Age >= 29" }, { "code": null, "e": 16792, "s": 16533, "text": "After training the decision tree I was able to plot it with the rpart.plot function and I can easily see the rules of the tree with rpart.rules. Since mlr is a wrapper for machine learning algorithms I can customize to my liking and this is just one example." }, { "code": null, "e": 16875, "s": 16792, "text": "We now pass the trained learner to be used to make predictions with our test data." }, { "code": null, "e": 17353, "s": 16875, "text": "set.seed(1000) (dtree_predict <- predict(dtree_train, newdata = test))Prediction: 154 observations predict.type: prob threshold: Positive=0.50,Negative=0.50 time: 0.00 truth prob.Positive prob.Negative response 1 Negative 0.3170732 0.6829268 Negative 2 Positive 0.6229508 0.3770492 Positive 3 Negative 0.4375000 0.5625000 Negative 4 Negative 0.3170732 0.6829268 Negative 5 Positive 0.7606838 0.2393162 Positive 6 Negative 0.1183673 0.8816327 Negative ... (#rows: 154, #cols: 4)" }, { "code": null, "e": 17465, "s": 17353, "text": "The threshold for classifying each row is 50/50. This is by default but can be changed later (which I will do)." }, { "code": null, "e": 17506, "s": 17465, "text": "dtree_predict %>% calculateROCMeasures()" }, { "code": null, "e": 17945, "s": 17506, "text": "So now we have the confusion matrix for our model. We see that it does an excellent job in predicting a Negative Outcome but does poorly with a Positive Outcome. This is inherently due to the class imbalance in our dataset. This is why thresholding is an easier tactic to get our preferred model. Of course it would be better if we had balanced classes and more rows of observations in our data but this is not always a choice or reality." }, { "code": null, "e": 18071, "s": 17945, "text": "To see the performance of our model more coherently, we can use the following code I wrote to see it in a presentable manner." }, { "code": null, "e": 18393, "s": 18071, "text": "Performance <- performance(dtree_predict, measures = list(tpr,auc,mmce, acc,tnr)) %>% as.data.frame(row.names = c(\"True Positive\",\"Area Under Curve\", \"Mean Misclassification Error\",\"Accuracy\",\"True Negative\")) Performance %>% kable(caption=\"Performance of Decision Tree\",digits = 2, format = 'html', col.names = \"Result\")" }, { "code": null, "e": 18692, "s": 18393, "text": "These metrics are quite satisfactory. But we can still achieve a higher TPR as I describe below. In certain cases including this, the TPR will be the most important and not the TNR. But in my view, I need to achieve a satisfactory TNR because if not, my misclassification (error) rate will be high." }, { "code": null, "e": 18828, "s": 18692, "text": "(dtree_threshold <- generateThreshVsPerfData(dtree_predict, measures = list(tpr,auc, mmce,tnr)) %>% plotThreshVsPerf() + geom_point() )" }, { "code": null, "e": 19337, "s": 18828, "text": "My personal goal for this model will be to obtain an acceptable and satisfactory True Positive Rate and True Negative Rate. Since the AUC remains the same across all thresholds we need not concern ourselves with it. By changing the threshold I am deliberately creating a biased model but this is a normal machine learning problem. The Bias-Variance Tradeoff is so common and we need to learn to navigate throught it. It is a whole other topic and anyone doing machine learning will need some knowledge of it." }, { "code": null, "e": 19380, "s": 19337, "text": "Below you will see 3 different thresholds:" }, { "code": null, "e": 19434, "s": 19380, "text": "The maximum threshold in which our TPR is below 100%." }, { "code": null, "e": 19487, "s": 19434, "text": "The minimum threshold in which our TPR is above 80%." }, { "code": null, "e": 19522, "s": 19487, "text": "The average of the two thresholds." }, { "code": null, "e": 19575, "s": 19522, "text": "The maximum threshold in which our TNR is above 70%." }, { "code": null, "e": 20206, "s": 19575, "text": "list( `TPR Threshold for 100%` = tpr_threshold100 <- dtree_threshold$data$threshold[ which.max(dtree_threshold$data$performance[ dtree_threshold$data$measure==\"True positive rate\"]<1)], `TPR Threshold for 80%` = tpr_threshold80 <- dtree_threshold$data$threshold[ which.min(dtree_threshold$data$performance[ dtree_threshold$data$measure==\"True positive rate\"]>0.80)], `Average Threshold` = avg_threshold <- mean(c(tpr_threshold100,tpr_threshold80)), `TNR Threshold for 80%` = tnr_threshold80 <- dtree_threshold$data$threshold[ which.max(dtree_threshold$data$performance[ dtree_threshold$data$measure==\"True negative rate\"]>0.70)] )" }, { "code": null, "e": 20244, "s": 20206, "text": "$TPR Threshold for 100% [1] 0.1212121" }, { "code": null, "e": 20281, "s": 20244, "text": "$TPR Threshold for 80% [1] 0.3232323" }, { "code": null, "e": 20314, "s": 20281, "text": "$Average Threshold [1] 0.2222222" }, { "code": null, "e": 20351, "s": 20314, "text": "$TNR Threshold for 80% [1] 0.3232323" }, { "code": null, "e": 20584, "s": 20351, "text": "Using avg_threhsold to predict on our model one more time we can get the following performance metrics. However looking at the thresholds from the plot and the ones I defined above, our True Negative Rate is going to take a big hit." }, { "code": null, "e": 20807, "s": 20584, "text": "DecisionTree <- dtree_predict %>% setThreshold(avg_threshold) (dt_performance <- DecisionTree %>% performance(measures = list(tpr,auc, mmce,tnr)) )tpr auc mmce tnr 0.8214286 0.7693149 0.3376623 0.5714286" }, { "code": null, "e": 21029, "s": 20807, "text": "Our TPR is now 82.14 %. This is a huge difference from a 50/50 threshold. Our TNR has reduced to 57.14 % but this is a consequence of biasing our model towards the TPR. I explain below looking at the new confusion matrix." }, { "code": null, "e": 21081, "s": 21029, "text": "(dt_cm <- DecisionTree %>% calculateROCMeasures() )" }, { "code": null, "e": 21120, "s": 21081, "text": "We notice the other following changes:" }, { "code": null, "e": 21181, "s": 21120, "text": "The TNR has reduced to 57 % due to the threshold difference." }, { "code": null, "e": 21404, "s": 21181, "text": "The FPR has increased to 43 %. This means that the model has an increased likelihood of a Type 1 Error in which it will detect diabetes when it is actually absent. This is a sacrifice we needed to make to get a higher TPR." }, { "code": null, "e": 21839, "s": 21404, "text": "The Accuracy has reduced to 66 %. This is another consequence of changing the threshold. This is not a cause for concern because our model does what I intended for it to do — Have a high True Positive Rate. Accuracy is not an adequate measure of model performance if we only care about the accurate prediction of a certain outcome. This is the case most of the time but even then you still need to dig deep into the model performance." }, { "code": null, "e": 22252, "s": 21839, "text": "Performance_threshold <- performance(DecisionTree, measures = list(tpr,auc, mmce, acc, tnr)) %>% as.data.frame(row.names = c(\"True Positive\",\"Area Under Curve\", \"Mean Misclassification Error\",\"Accuracy\",\"True Negative\")) Performance_threshold %>% kable(caption=paste(\"Performance of Decision Tree\\n\\nAfter Thresholding to\",(avg_threshold*100) %>% round(0),'%'), digits = 2, format = 'html', col.names = 'RESULT')" }, { "code": null, "e": 22766, "s": 22252, "text": "We can see our new performance metrics after changing the classification threshold. Thresholding is very subjective to the user and the domain of the problem. Sometimes it will be necessary to skew the model’s performance in one direction depending on the cost of misclassification for you. In this scenario, there will be many false positives for patients but if the cost of misclassifying these patients is not too high, it is worthy of obtaining higher likelihoods of a correct diagnosis (i.e. True Positives)." }, { "code": null, "e": 23095, "s": 22766, "text": "In an ending note, thresholding becomes a necessity especially when you have an imbalanced dataset (i.e. imbalanced number of target levels). In this dataset there are many more Negative’s than Positives’s. If it were more balanced there may not be a need for thresholding depending on how well the model classifies each target." }, { "code": null, "e": 23231, "s": 23095, "text": "If you have any questions or concerns please comment for a discussion and I invite anyone who finds this interesting to join. Thank you" } ]
Matplotlib.axis.Axis.set_minor_formatter() function in Python - GeeksforGeeks
03 Jun, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. The Axis.set_minor_formatter() function in axis module of matplotlib library is used to set the formatter of the minor ticker. Syntax: Axis.set_minor_formatter(self, formatter) Parameters: This method accepts the following parameters. formatter: This parameter is the Formatter. Return value: This method does not returns any value. Below examples illustrate the matplotlib.axis.Axis.set_minor_formatter() function in matplotlib.axis:Example 1: Python3 # Implementation of matplotlib function from matplotlib.axis import Axisimport matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator, ScalarFormatter fig, ax = plt.subplots() ax.plot([0, 5, 10, 15, 20], [3, 2, 1, 2, 4]) Axis.set_minor_locator(ax.xaxis, MultipleLocator(1)) Axis.set_minor_formatter(ax.xaxis, ScalarFormatter()) ax.tick_params(axis ='both', which ='major', labelsize = 14, pad = 12, colors ='g') ax.tick_params(axis ='both', which ='minor', labelsize = 8, colors ='b') plt.title("Matplotlib.axis.Axis.set_minor_formatter()\n\Function Example", fontsize = 12, fontweight ='bold') plt.show() Output: Example 2: Python3 # Implementation of matplotlib function from matplotlib.axis import Axisimport matplotlib.pyplot as plt from matplotlib.ticker import LogFormatter import numpy as np fig, axes = plt.subplots(2) dt = 0.01t = np.arange(dt, 20.0, dt) # first plot doesn't use a formatter axes[0].semilogx(t, np.exp(-t / 5.0)) axes[0].grid() xlims = [[0, 25], [0.2, 8], [0.6, 0.9]] for ax, xlim in zip(axes[1:], xlims): ax.semilogx(t, np.exp(-t / 5.0)) formatter = LogFormatter(labelOnlyBase = False, minor_thresholds = (2, 0.4)) Axis.set_minor_formatter(ax.xaxis, formatter) ax.grid() fig.suptitle("Matplotlib.axis.Axis.set_minor_formatter()\n\Function Example", fontsize = 12, fontweight ='bold') plt.show() Output: Matplotlib-Axis Class Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python OOPs Concepts How to Install PIP on Windows ? Bar Plot in Matplotlib Defaultdict in Python Python Classes and Objects Deque in Python Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python - Ways to remove duplicates from list Class method vs Static method in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n03 Jun, 2020" }, { "code": null, "e": 24123, "s": 23901, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. " }, { "code": null, "e": 24251, "s": 24123, "text": "The Axis.set_minor_formatter() function in axis module of matplotlib library is used to set the formatter of the minor ticker. " }, { "code": null, "e": 24301, "s": 24251, "text": "Syntax: Axis.set_minor_formatter(self, formatter)" }, { "code": null, "e": 24360, "s": 24301, "text": "Parameters: This method accepts the following parameters. " }, { "code": null, "e": 24404, "s": 24360, "text": "formatter: This parameter is the Formatter." }, { "code": null, "e": 24459, "s": 24404, "text": "Return value: This method does not returns any value. " }, { "code": null, "e": 24572, "s": 24459, "text": "Below examples illustrate the matplotlib.axis.Axis.set_minor_formatter() function in matplotlib.axis:Example 1: " }, { "code": null, "e": 24580, "s": 24572, "text": "Python3" }, { "code": "# Implementation of matplotlib function from matplotlib.axis import Axisimport matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator, ScalarFormatter fig, ax = plt.subplots() ax.plot([0, 5, 10, 15, 20], [3, 2, 1, 2, 4]) Axis.set_minor_locator(ax.xaxis, MultipleLocator(1)) Axis.set_minor_formatter(ax.xaxis, ScalarFormatter()) ax.tick_params(axis ='both', which ='major', labelsize = 14, pad = 12, colors ='g') ax.tick_params(axis ='both', which ='minor', labelsize = 8, colors ='b') plt.title(\"Matplotlib.axis.Axis.set_minor_formatter()\\n\\Function Example\", fontsize = 12, fontweight ='bold') plt.show()", "e": 25270, "s": 24580, "text": null }, { "code": null, "e": 25280, "s": 25270, "text": "Output: " }, { "code": null, "e": 25292, "s": 25280, "text": "Example 2: " }, { "code": null, "e": 25300, "s": 25292, "text": "Python3" }, { "code": "# Implementation of matplotlib function from matplotlib.axis import Axisimport matplotlib.pyplot as plt from matplotlib.ticker import LogFormatter import numpy as np fig, axes = plt.subplots(2) dt = 0.01t = np.arange(dt, 20.0, dt) # first plot doesn't use a formatter axes[0].semilogx(t, np.exp(-t / 5.0)) axes[0].grid() xlims = [[0, 25], [0.2, 8], [0.6, 0.9]] for ax, xlim in zip(axes[1:], xlims): ax.semilogx(t, np.exp(-t / 5.0)) formatter = LogFormatter(labelOnlyBase = False, minor_thresholds = (2, 0.4)) Axis.set_minor_formatter(ax.xaxis, formatter) ax.grid() fig.suptitle(\"Matplotlib.axis.Axis.set_minor_formatter()\\n\\Function Example\", fontsize = 12, fontweight ='bold') plt.show()", "e": 26069, "s": 25300, "text": null }, { "code": null, "e": 26079, "s": 26069, "text": "Output: " }, { "code": null, "e": 26103, "s": 26081, "text": "Matplotlib-Axis Class" }, { "code": null, "e": 26121, "s": 26103, "text": "Python-matplotlib" }, { "code": null, "e": 26128, "s": 26121, "text": "Python" }, { "code": null, "e": 26226, "s": 26128, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26235, "s": 26226, "text": "Comments" }, { "code": null, "e": 26248, "s": 26235, "text": "Old Comments" }, { "code": null, "e": 26269, "s": 26248, "text": "Python OOPs Concepts" }, { "code": null, "e": 26301, "s": 26269, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26324, "s": 26301, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 26346, "s": 26324, "text": "Defaultdict in Python" }, { "code": null, "e": 26373, "s": 26346, "text": "Python Classes and Objects" }, { "code": null, "e": 26389, "s": 26373, "text": "Deque in Python" }, { "code": null, "e": 26431, "s": 26389, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26487, "s": 26431, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26532, "s": 26487, "text": "Python - Ways to remove duplicates from list" } ]
How to get the entire document HTML as a string in JavaScript?
To get the entire document HTML as a string, use the concept of innerHTML, like − document.documentElement.innerHTML; Following is the code − <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <body> <h1> Hello World </h1> <p>This is the javascript program..</p> </body> <script> var entireDocumentHTMLAsAString = document.documentElement.innerHTML; console.log(entireDocumentHTMLAsAString); </script> </html> To run the above program, save the file name anyName.html(index.html). Right click on the file and select the option “Open with live server” in VS Code editor. This will produce the following output − Following is the output on console −
[ { "code": null, "e": 1144, "s": 1062, "text": "To get the entire document HTML as a string, use the concept of innerHTML, like −" }, { "code": null, "e": 1180, "s": 1144, "text": "document.documentElement.innerHTML;" }, { "code": null, "e": 1204, "s": 1180, "text": "Following is the code −" }, { "code": null, "e": 1823, "s": 1204, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n</head>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n<body>\n<h1> Hello World </h1>\n<p>This is the javascript program..</p>\n</body>\n<script>\n var entireDocumentHTMLAsAString = document.documentElement.innerHTML;\n console.log(entireDocumentHTMLAsAString);\n</script>\n</html>" }, { "code": null, "e": 1983, "s": 1823, "text": "To run the above program, save the file name anyName.html(index.html). Right click on the file\nand select the option “Open with live server” in VS Code editor." }, { "code": null, "e": 2024, "s": 1983, "text": "This will produce the following output −" }, { "code": null, "e": 2061, "s": 2024, "text": "Following is the output on console −" } ]
Using useContext in React.js
useContext hook allows passing data to children elements without using redux. useContext is a named export in react so we can importin functional components like below − import {useContext} from ‘react’; It’s an easy alternative to Redux if we just need to pass the data to the children elements. import React, { createContext } from ‘react’; import ReactDOM from ‘react-dom’; const MessageContext = createContext(); myApp=()=>{ return ( <MessageContext.Provider value=”hello”> <div> <Test/> </div> </MessageContext.Provider> ); } In child component Test we can access the message value as below − Test =()=>{ return ( <MessageContext.Consumer > {value=><div> message : {value} </div> } </MessageContext.Consumer> ); } Note that we have not passed props here in child component. The createContext hooks gives us provider and consumer. Provider is used to pass the values to child components and child components access the value using consumer as shown above. This a simple example of consumer but in real life scenarios we may need to have nested consumers. Here we can use useContext to write it in a simple way. Import { useContext } from ‘react’; Test =()=>{ const messageValue=useContext(MessageContext); return ( <div>Message: {messageValue} </div> ); } We eliminated the consumer code and used only useContext which has simplified the code and we can get the values from multiple parents having provider context values. Now, we don’t need to nest the multiple consumers. useMemo helps in performance optimization. It can execute on every render but only if one of the dependency changes. Similar to useEffect we provide the second argument to useMemo method which we can call as dependency. useMemo( ()=>{}, [dependency input array]); the computations in the first function is remembered till the provided dependency are not changed. If we have lot of heavy computation which should be executed once or executes if one of the input changes, we can use useMemo. If no input array is provided it will execute on every render. It optimizes the heavy computations in simple words. In the future the advanced compilers will decide the dependency array by itself. We can replace the useCallback and use only useMemo which works in a similar way. useCallback(function, []); useMemo(()=>function body, []); it caches the function value and returns the same value until one of the dependency changes. useReducer as name suggest is similar to concept with reducer function in Redux. It receives a input and based on dispatch action and value it will give us the modified updated state. const [ state, dispatch]= useReducer((state, action)={ switch(action.type){ //calculation based on action type and value } },[]); We have passed the second argument to useReducer which can be used to set some initial values to state. import React, { useReducer } from 'react'; function TestNumber() { const [total, dispatch] = useReducer((state, action) => { return state + action; }, 0); return ( <> {total} <button onClick={() => dispatch(1)}> Add 1 </button> </> ); } Here we have initialized state with 0 and incrementing on each click of button. We have used react fragment <> also in above example.
[ { "code": null, "e": 1140, "s": 1062, "text": "useContext hook allows passing data to children elements without using redux." }, { "code": null, "e": 1232, "s": 1140, "text": "useContext is a named export in react so we can importin functional components like below −" }, { "code": null, "e": 1266, "s": 1232, "text": "import {useContext} from ‘react’;" }, { "code": null, "e": 1359, "s": 1266, "text": "It’s an easy alternative to Redux if we just need to pass the data to the children elements." }, { "code": null, "e": 1641, "s": 1359, "text": "import React, { createContext } from ‘react’;\nimport ReactDOM from ‘react-dom’;\nconst MessageContext = createContext();\nmyApp=()=>{\n return (\n <MessageContext.Provider value=”hello”>\n <div>\n <Test/>\n </div>\n </MessageContext.Provider>\n );\n}" }, { "code": null, "e": 1708, "s": 1641, "text": "In child component Test we can access the message value as below −" }, { "code": null, "e": 1856, "s": 1708, "text": "Test =()=>{\n return (\n <MessageContext.Consumer >\n {value=><div> message : {value} </div> }\n </MessageContext.Consumer>\n );\n}" }, { "code": null, "e": 1972, "s": 1856, "text": "Note that we have not passed props here in child component. The createContext hooks gives us provider and consumer." }, { "code": null, "e": 2097, "s": 1972, "text": "Provider is used to pass the values to child components and child components access the value using consumer as shown above." }, { "code": null, "e": 2252, "s": 2097, "text": "This a simple example of consumer but in real life scenarios we may need to have nested consumers. Here we can use useContext to write it in a simple way." }, { "code": null, "e": 2412, "s": 2252, "text": "Import { useContext } from ‘react’;\nTest =()=>{\n const messageValue=useContext(MessageContext);\n return (\n <div>Message: {messageValue} </div>\n );\n}" }, { "code": null, "e": 2630, "s": 2412, "text": "We eliminated the consumer code and used only useContext which has simplified the code and we can get the values from multiple parents having provider context values. Now, we don’t need to nest the multiple consumers." }, { "code": null, "e": 2850, "s": 2630, "text": "useMemo helps in performance optimization. It can execute on every render but only if one of the dependency changes. Similar to useEffect we provide the second argument to useMemo method which we can call as dependency." }, { "code": null, "e": 2894, "s": 2850, "text": "useMemo( ()=>{}, [dependency input array]);" }, { "code": null, "e": 2993, "s": 2894, "text": "the computations in the first function is remembered till the provided dependency are not changed." }, { "code": null, "e": 3120, "s": 2993, "text": "If we have lot of heavy computation which should be executed once or executes if one of the input changes, we can use useMemo." }, { "code": null, "e": 3317, "s": 3120, "text": "If no input array is provided it will execute on every render. It optimizes the heavy computations in simple words. In the future the advanced compilers will decide the dependency array by itself." }, { "code": null, "e": 3399, "s": 3317, "text": "We can replace the useCallback and use only useMemo which works in a similar way." }, { "code": null, "e": 3458, "s": 3399, "text": "useCallback(function, []);\nuseMemo(()=>function body, []);" }, { "code": null, "e": 3551, "s": 3458, "text": "it caches the function value and returns the same value until one of the dependency changes." }, { "code": null, "e": 3632, "s": 3551, "text": "useReducer as name suggest is similar to concept with reducer function in Redux." }, { "code": null, "e": 3735, "s": 3632, "text": "It receives a input and based on dispatch action and value it will give us the modified updated state." }, { "code": null, "e": 3877, "s": 3735, "text": "const [ state, dispatch]= useReducer((state, action)={\n switch(action.type){\n //calculation based on action type and value\n }\n},[]);" }, { "code": null, "e": 3981, "s": 3877, "text": "We have passed the second argument to useReducer which can be used to set some initial values to state." }, { "code": null, "e": 4287, "s": 3981, "text": "import React, { useReducer } from 'react';\nfunction TestNumber() {\n const [total, dispatch] = useReducer((state, action) => {\n return state + action;\n }, 0);\n return (\n <>\n {total}\n <button onClick={() => dispatch(1)}>\n Add 1\n </button>\n </>\n );\n}" }, { "code": null, "e": 4367, "s": 4287, "text": "Here we have initialized state with 0 and incrementing on each click of button." }, { "code": null, "e": 4421, "s": 4367, "text": "We have used react fragment <> also in above example." } ]
MathML - Fractions
<mfrac> tag is used to draw fractions. Here is the simple syntax to use this tag − <mfrac> numerator denominator </mfrac> Here is the description of all the parameters of this tag − numerator − numerator of the fraction. numerator − numerator of the fraction. denominator − denominator of the fraction. denominator − denominator of the fraction. Here is the description of all the attributes of this tag − linethickness − to specify the stroke width of the fraction bar. values are measured in px, pt, em etc. linethickness − to specify the stroke width of the fraction bar. values are measured in px, pt, em etc. numalign − to specify alignment of numerator. values are left, right or center. numalign − to specify alignment of numerator. values are left, right or center. denomalign − to specify alignment of denominator. values are left, right or center. denomalign − to specify alignment of denominator. values are left, right or center. bevelled − to specify whether the fraction should be displayed vertically or inline. values are true or false. bevelled − to specify whether the fraction should be displayed vertically or inline. values are true or false. Let's draw a simple fraction for 1/x. <math xmlns = "http://www.w3.org/1998/Math/MathML"> <mfrac> <mn>1</mn> <mi>x</mi> </mfrac> </math> Let's build a complex fraction. <math xmlns = "http://www.w3.org/1998/Math/MathML"> <mfrac linethickness = '3px'> <mfrac bevelled = 'true'> <mn>1</mn> <mi>x</mi> </mfrac> <mrow> <mi>y</mi> <mo>-</mo> <mn>2</mn> </mrow> </mfrac> </math> Print Add Notes Bookmark this page
[ { "code": null, "e": 2296, "s": 2257, "text": "<mfrac> tag is used to draw fractions." }, { "code": null, "e": 2340, "s": 2296, "text": "Here is the simple syntax to use this tag −" }, { "code": null, "e": 2380, "s": 2340, "text": "<mfrac> numerator denominator </mfrac>\n" }, { "code": null, "e": 2440, "s": 2380, "text": "Here is the description of all the parameters of this tag −" }, { "code": null, "e": 2479, "s": 2440, "text": "numerator − numerator of the fraction." }, { "code": null, "e": 2518, "s": 2479, "text": "numerator − numerator of the fraction." }, { "code": null, "e": 2561, "s": 2518, "text": "denominator − denominator of the fraction." }, { "code": null, "e": 2604, "s": 2561, "text": "denominator − denominator of the fraction." }, { "code": null, "e": 2664, "s": 2604, "text": "Here is the description of all the attributes of this tag −" }, { "code": null, "e": 2768, "s": 2664, "text": "linethickness − to specify the stroke width of the fraction bar. values are measured in px, pt, em etc." }, { "code": null, "e": 2872, "s": 2768, "text": "linethickness − to specify the stroke width of the fraction bar. values are measured in px, pt, em etc." }, { "code": null, "e": 2952, "s": 2872, "text": "numalign − to specify alignment of numerator. values are left, right or center." }, { "code": null, "e": 3032, "s": 2952, "text": "numalign − to specify alignment of numerator. values are left, right or center." }, { "code": null, "e": 3116, "s": 3032, "text": "denomalign − to specify alignment of denominator. values are left, right or center." }, { "code": null, "e": 3200, "s": 3116, "text": "denomalign − to specify alignment of denominator. values are left, right or center." }, { "code": null, "e": 3311, "s": 3200, "text": "bevelled − to specify whether the fraction should be displayed vertically or inline. values are true or false." }, { "code": null, "e": 3422, "s": 3311, "text": "bevelled − to specify whether the fraction should be displayed vertically or inline. values are true or false." }, { "code": null, "e": 3460, "s": 3422, "text": "Let's draw a simple fraction for 1/x." }, { "code": null, "e": 3577, "s": 3460, "text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mfrac>\n <mn>1</mn>\n <mi>x</mi>\n </mfrac>\n</math>" }, { "code": null, "e": 3609, "s": 3577, "text": "Let's build a complex fraction." }, { "code": null, "e": 3895, "s": 3609, "text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mfrac linethickness = '3px'>\n <mfrac bevelled = 'true'>\n <mn>1</mn>\n <mi>x</mi>\n </mfrac>\n \n <mrow>\n <mi>y</mi>\n <mo>-</mo>\n <mn>2</mn>\n </mrow>\n </mfrac>\n</math>" }, { "code": null, "e": 3902, "s": 3895, "text": " Print" }, { "code": null, "e": 3913, "s": 3902, "text": " Add Notes" } ]
Ask a user to select a folder to read the files in Python
If you have ever wondered how the dialogboxes work in a Python application, then you probably end up hearing the filedialog module in Tkinter. The filedialog module contains a number of built-in functions which can be used to display various types of dialogs for dealing with files in the system. In most cases, we use the filedialog.askopenfilename() function to ask the user to browse and open a file from the system. Based on the selection of the filetype, the script is programmed to perform write or read operation. Once a file is opened, you can use the open(file, 'mode') function to open and perform operations in any mode. To demonstrate this, let's take an example where we will create an application that will ask the user to open a text file. Once a file is selected and opened, we can read this file using the "read" mode of operation. # Import the library from tkinter import * from tkinter import filedialog # Create an instance of window win=Tk() # Set the geometry of the window win.geometry("700x300") # Create a label Label(win, text="Click the button to open a dialog", font='Arial 16 bold').pack(pady=15) # Function to open a file in the system def open_file(): filepath = filedialog.askopenfilename(title="Open a Text File", filetypes=(("text files","*.txt"), ("all files","*.*"))) file = open(filepath,'r') print(file.read()) file.close() # Create a button to trigger the dialog button = Button(win, text="Open", command=open_file) button.pack() win.mainloop() Running the above code will display a window with a button to open a dialog. Select and open a text file and the console will display all the content of the file. Centralized Database Vs Blockchain A blockchain can be both permissionless (like Bitcoin or Ethereum) or permissioned (like the different Hyperledger blockchain frameworks). A permissionless blockchain is also known as a public blockchain, because anyone can join the network. A permissioned blockchain, or private blockchain, requires pre-verification of the participating parties within the network, and these parties are usually known to each other. Types of Blockchains The choice between permissionless versus permissioned blockchains should be driven by the particular application at hand (or use case). Most enterprise use cases involve extensive vetting before parties agree to do business with each other. An example where a number of businesses exchange information is supply chain management. The supply chain management is an ideal use case for permissioned blockchains. You would only want trusted parties participating in the network. Each participant that is involved in the supply chain would require permissions to execute transactions on the blockchain. These transactions would allow other companies to understand where in the supply chain a particular item is.
[ { "code": null, "e": 1359, "s": 1062, "text": "If you have ever wondered how the dialogboxes work in a Python application, then you probably end up hearing the filedialog module in Tkinter. The filedialog module contains a number of built-in functions which can be used to display various types of dialogs for dealing with files in the system." }, { "code": null, "e": 1583, "s": 1359, "text": "In most cases, we use the filedialog.askopenfilename() function to ask the user to browse and open a file from the system. Based on the selection of the filetype, the script is programmed to perform write or read operation." }, { "code": null, "e": 1911, "s": 1583, "text": "Once a file is opened, you can use the open(file, 'mode') function to open and perform operations in any mode. To demonstrate this, let's take an example where we will create an application that will ask the user to open a text file. Once a file is selected and opened, we can read this file using the \"read\" mode of operation." }, { "code": null, "e": 2567, "s": 1911, "text": "# Import the library\nfrom tkinter import *\nfrom tkinter import filedialog\n\n# Create an instance of window\nwin=Tk()\n\n# Set the geometry of the window\nwin.geometry(\"700x300\")\n\n# Create a label\nLabel(win, text=\"Click the button to open a dialog\", font='Arial 16 bold').pack(pady=15)\n\n# Function to open a file in the system\ndef open_file():\n filepath = filedialog.askopenfilename(title=\"Open a Text File\", filetypes=((\"text files\",\"*.txt\"), (\"all files\",\"*.*\")))\n file = open(filepath,'r')\n print(file.read())\n file.close()\n\n# Create a button to trigger the dialog\nbutton = Button(win, text=\"Open\", command=open_file)\nbutton.pack()\n\nwin.mainloop()" }, { "code": null, "e": 2644, "s": 2567, "text": "Running the above code will display a window with a button to open a dialog." }, { "code": null, "e": 2730, "s": 2644, "text": "Select and open a text file and the console will display all the content of the file." }, { "code": null, "e": 3914, "s": 2730, "text": "Centralized Database Vs Blockchain\n\nA blockchain can be both permissionless (like Bitcoin or Ethereum) or permissioned (like the different Hyperledger blockchain frameworks). A permissionless blockchain is also known as a public blockchain, because anyone can join the network. A permissioned blockchain, or private blockchain, requires pre-verification of the participating parties within the network, and these parties are usually known to each other.\n\nTypes of Blockchains\nThe choice between permissionless versus permissioned blockchains should be driven by the particular application at hand (or use case). Most enterprise use cases involve extensive vetting before parties agree to do business with each other. An example where a number of businesses exchange information is supply chain management. The supply chain management is an ideal use case for permissioned blockchains.\n\nYou would only want trusted parties participating in the network. Each participant that is involved in the supply chain would require permissions to execute transactions on the blockchain. These transactions would allow other companies to understand where in the supply chain a particular item is." } ]
Elasticsearch - Cat APIs
Usually the results from various Elasticsearch APIs are displayed in JSON format. But JSON is not easy to read always. So cat APIs feature is available in Elasticsearch helps in taking care of giving an easier to read and comprehend printing format of the results. There are various parameters used in cat API which server different purpose, for example - the term V makes the output verbose. Let us learn about cat APIs more in detail in this chapter. The verbose output gives a nice display of results of a cat command. In the example given below, we get the details of various indices present in the cluster. GET /_cat/indices?v On running the above code, we get the response as shown below − health status index uuid pri rep docs.count docs.deleted store.size pri.store.size yellow open schools RkMyEn2SQ4yUgzT6EQYuAA 1 1 2 1 21.6kb 21.6kb yellow open index_4_analysis zVmZdM1sTV61YJYrNXf1gg 1 1 0 0 283b 283b yellow open sensor-2018-01-01 KIrrHwABRB-ilGqTu3OaVQ 1 1 1 0 4.2kb 4.2kb yellow open colleges 3ExJbdl2R1qDLssIkwDAug 1 1 0 0 283b 283b The h parameter, also called header, is used to display only those columns mentioned in the command. GET /_cat/nodes?h=ip,port On running the above code, we get the response as shown below − 127.0.0.1 9300 The sort command accepts query string which can sort the table by specified column in the query. The default sort is ascending but this can be changed by adding :desc to a column. The below example, gives a result of templates arranged in descending order of the filed index patterns. GET _cat/templates?v&s=order:desc,index_patterns On running the above code, we get the response as shown below − name index_patterns order version .triggered_watches [.triggered_watches*] 2147483647 .watch-history-9 [.watcher-history-9*] 2147483647 .watches [.watches*] 2147483647 .kibana_task_manager [.kibana_task_manager] 0 7000099 The count parameter provides the count of total number of documents in the entire cluster. GET /_cat/count?v On running the above code, we get the response as shown below − epoch timestamp count 1557633536 03:58:56 17809 14 Lectures 5 hours Manuj Aggarwal 20 Lectures 1 hours Faizan Tayyab Print Add Notes Bookmark this page
[ { "code": null, "e": 2974, "s": 2581, "text": "Usually the results from various Elasticsearch APIs are displayed in JSON format. But JSON is not easy to read always. So cat APIs feature is available in Elasticsearch helps in taking\ncare of giving an easier to read and comprehend printing format of the results. There are various parameters used in cat API which server different purpose, for example - the term V makes the output verbose." }, { "code": null, "e": 3034, "s": 2974, "text": "Let us learn about cat APIs more in detail in this chapter." }, { "code": null, "e": 3193, "s": 3034, "text": "The verbose output gives a nice display of results of a cat command. In the example given\nbelow, we get the details of various indices present in the cluster." }, { "code": null, "e": 3214, "s": 3193, "text": "GET /_cat/indices?v\n" }, { "code": null, "e": 3278, "s": 3214, "text": "On running the above code, we get the response as shown below −" }, { "code": null, "e": 3632, "s": 3278, "text": "health status index uuid pri rep docs.count docs.deleted store.size pri.store.size\nyellow open schools RkMyEn2SQ4yUgzT6EQYuAA 1 1 2 1 21.6kb 21.6kb\nyellow open index_4_analysis zVmZdM1sTV61YJYrNXf1gg 1 1 0 0 283b 283b\nyellow open sensor-2018-01-01 KIrrHwABRB-ilGqTu3OaVQ 1 1 1 0 4.2kb 4.2kb\nyellow open colleges 3ExJbdl2R1qDLssIkwDAug 1 1 0 0 283b 283b\n" }, { "code": null, "e": 3733, "s": 3632, "text": "The h parameter, also called header, is used to display only those columns mentioned in\nthe command." }, { "code": null, "e": 3760, "s": 3733, "text": "GET /_cat/nodes?h=ip,port\n" }, { "code": null, "e": 3824, "s": 3760, "text": "On running the above code, we get the response as shown below −" }, { "code": null, "e": 3840, "s": 3824, "text": "127.0.0.1 9300\n" }, { "code": null, "e": 4020, "s": 3840, "text": "The sort command accepts query string which can sort the table by specified column in the query. The default sort is ascending but this can be changed by adding :desc to a column." }, { "code": null, "e": 4125, "s": 4020, "text": "The below example, gives a result of templates arranged in descending order of the filed\nindex patterns." }, { "code": null, "e": 4175, "s": 4125, "text": "GET _cat/templates?v&s=order:desc,index_patterns\n" }, { "code": null, "e": 4239, "s": 4175, "text": "On running the above code, we get the response as shown below −" }, { "code": null, "e": 4462, "s": 4239, "text": "name index_patterns order version\n.triggered_watches [.triggered_watches*] 2147483647\n.watch-history-9 [.watcher-history-9*] 2147483647\n.watches [.watches*] 2147483647\n.kibana_task_manager [.kibana_task_manager] 0 7000099\n" }, { "code": null, "e": 4553, "s": 4462, "text": "The count parameter provides the count of total number of documents in the entire cluster." }, { "code": null, "e": 4572, "s": 4553, "text": "GET /_cat/count?v\n" }, { "code": null, "e": 4636, "s": 4572, "text": "On running the above code, we get the response as shown below −" }, { "code": null, "e": 4685, "s": 4636, "text": "epoch timestamp count\n1557633536 03:58:56 17809\n" }, { "code": null, "e": 4718, "s": 4685, "text": "\n 14 Lectures \n 5 hours \n" }, { "code": null, "e": 4734, "s": 4718, "text": " Manuj Aggarwal" }, { "code": null, "e": 4767, "s": 4734, "text": "\n 20 Lectures \n 1 hours \n" }, { "code": null, "e": 4782, "s": 4767, "text": " Faizan Tayyab" }, { "code": null, "e": 4789, "s": 4782, "text": " Print" }, { "code": null, "e": 4800, "s": 4789, "text": " Add Notes" } ]
How to make use of Join with LINQ and Lambda in C#?
Inner join returns only those records or rows that match or exists in both the tables. We can also apply to join on multiple tables based on conditions as shown below. Make use of anonymous types if we need to apply to join on multiple conditions. In the below example we have written 2 ways that can be used to join in Linq Here the Department and the Employee are joined class Program{ static void Main(string[] args){ var result = Employee.GetAllEmployees().Join(Department.GetAllDepartments(), e => e.DepartmentID, d => d.ID, (employee, department) => new{ EmployeeName = employee.Name, DepartmentName = department.Name }); foreach (var employee in result){ Console.WriteLine(employee.EmployeeName + "\t" + employee.DepartmentName); } var result1 = from e in Employee.GetAllEmployees() join d in Department.GetAllDepartments() on e.DepartmentID equals d.ID select new{ EmployeeName = e.Name, DepartmentName = d.Name }; foreach (var employee in result1){ Console.WriteLine(employee.EmployeeName + "\t" + employee.DepartmentName); } Console.ReadLine(); } } public class Employee{ public int ID { get; set; } public string Name { get; set; } public int DepartmentID { get; set; } public static List<Employee> GetAllEmployees(){ return new List<Employee>(){ new Employee { ID = 1, Name = "A", DepartmentID = 1 }, new Employee { ID = 2, Name = "B", DepartmentID = 2 }, new Employee { ID = 3, Name = "B", DepartmentID = 1 }, new Employee { ID = 4, Name = "V", DepartmentID = 1 }, new Employee { ID = 5, Name = "F", DepartmentID = 2 }, new Employee { ID = 6, Name = "R", DepartmentID = 2 }, new Employee { ID = 7, Name = "TT", DepartmentID = 1 }, new Employee { ID = 8, Name = "YY", DepartmentID = 1 }, new Employee { ID = 9, Name = "WW", DepartmentID = 2 }, new Employee { ID = 10, Name = "QQ"} }; } } public class Department{ public int ID { get; set; } public string Name { get; set; } public static List<Department> GetAllDepartments(){ return new List<Department>(){ new Department { ID = 1, Name = "IT"}, new Department { ID = 2, Name = "HR"}, new Department { ID = 3, Name = "Contract"}, }; } } A IT B HR B IT V IT F HR R HR TT IT YY IT WW HR A IT B HR B IT V IT F HR R HR TT IT YY IT WW HR
[ { "code": null, "e": 1310, "s": 1062, "text": "Inner join returns only those records or rows that match or exists in both the tables. We can also apply to join on multiple tables based on conditions as shown below.\nMake use of anonymous types if we need to apply to join on multiple conditions." }, { "code": null, "e": 1435, "s": 1310, "text": "In the below example we have written 2 ways that can be used to join in Linq\nHere the Department and the Employee are joined" }, { "code": null, "e": 3497, "s": 1435, "text": "class Program{\n static void Main(string[] args){\n var result =\n Employee.GetAllEmployees().Join(Department.GetAllDepartments(),\n e => e.DepartmentID,\n d => d.ID, (employee, department) => new{\n EmployeeName = employee.Name,\n DepartmentName = department.Name\n });\n foreach (var employee in result){\n Console.WriteLine(employee.EmployeeName + \"\\t\" +\n employee.DepartmentName);\n }\n var result1 = from e in Employee.GetAllEmployees()\n join d in Department.GetAllDepartments()\n on e.DepartmentID equals d.ID\n select new{\n EmployeeName = e.Name,\n DepartmentName = d.Name\n };\n foreach (var employee in result1){\n Console.WriteLine(employee.EmployeeName + \"\\t\" +\n employee.DepartmentName);\n }\n Console.ReadLine();\n }\n}\npublic class Employee{\n public int ID { get; set; }\n public string Name { get; set; }\n public int DepartmentID { get; set; }\n public static List<Employee> GetAllEmployees(){\n return new List<Employee>(){\n new Employee { ID = 1, Name = \"A\", DepartmentID = 1 },\n new Employee { ID = 2, Name = \"B\", DepartmentID = 2 },\n new Employee { ID = 3, Name = \"B\", DepartmentID = 1 },\n new Employee { ID = 4, Name = \"V\", DepartmentID = 1 },\n new Employee { ID = 5, Name = \"F\", DepartmentID = 2 },\n new Employee { ID = 6, Name = \"R\", DepartmentID = 2 },\n new Employee { ID = 7, Name = \"TT\", DepartmentID = 1 },\n new Employee { ID = 8, Name = \"YY\", DepartmentID = 1 },\n new Employee { ID = 9, Name = \"WW\", DepartmentID = 2 },\n new Employee { ID = 10, Name = \"QQ\"}\n };\n }\n}\npublic class Department{\n public int ID { get; set; }\n public string Name { get; set; }\n public static List<Department> GetAllDepartments(){\n return new List<Department>(){\n new Department { ID = 1, Name = \"IT\"},\n new Department { ID = 2, Name = \"HR\"},\n new Department { ID = 3, Name = \"Contract\"},\n };\n }\n}" }, { "code": null, "e": 3593, "s": 3497, "text": "A IT\nB HR\nB IT\nV IT\nF HR\nR HR\nTT IT\nYY IT\nWW HR\nA IT\nB HR\nB IT\nV IT\nF HR\nR HR\nTT IT\nYY IT\nWW HR" } ]
Functional Components Vs. Class Components in ReactJS
Functional Components or stateless components are the most widely used type of components with a basic syntax of JavaScript Functions that return the JSX code or the HTML code. They are called as stateless components because they accept the data and display it accordingly and are mainly responsible for the rendering of the UI. import React from ‘react’; const App=()=>{ return ( <div> <h1>TutorialsPoint</h1> </div> ) } export default App Class based or stateful Components are the ES6 classes that extend the component class of the react library. They are known as stateful components because they are responsible for the implementation of the logic. It has different phases of the React lifecycle including rendering, mounting, updating and unmounting stage. import React from 'react'; class App extends React.Component{ render() { return ( <div> <h1>TutorialsPoint</h1> </div> ) } } export default App
[ { "code": null, "e": 1239, "s": 1062, "text": "Functional Components or stateless components are the most widely used type of components with a basic syntax of JavaScript Functions that return the JSX code or the HTML code." }, { "code": null, "e": 1391, "s": 1239, "text": "They are called as stateless components because they accept the data and display it accordingly and are mainly responsible for the rendering of the UI." }, { "code": null, "e": 1531, "s": 1391, "text": "import React from ‘react’;\n\nconst App=()=>{\n return (\n <div>\n <h1>TutorialsPoint</h1>\n </div>\n )\n}\nexport default App" }, { "code": null, "e": 1853, "s": 1531, "text": "Class based or stateful Components are the ES6 classes that extend the component class of the react library. They are known as stateful components because they are responsible for the implementation of the logic. It has different phases of the React lifecycle including rendering, mounting, updating and unmounting stage." }, { "code": null, "e": 2046, "s": 1853, "text": "import React from 'react';\n\nclass App extends React.Component{\n render() {\n return (\n <div>\n <h1>TutorialsPoint</h1>\n </div>\n )\n }\n}\nexport default App" } ]
What does parenthesis mean in MySQL SELECT (COLNAME)?
The SELECT(COLNAME) means, we are creating an alias for that column. Let us see an example and create a table − mysql> create table DemoTable865( FirstName varchar(100), LastName varchar(100) ); Query OK, 0 rows affected (0.77 sec) Insert some records in the table using insert command − mysql> insert into DemoTable865 values('Chris','Brown'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable865 values('Adam','Smith'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable865 values('David','Miller'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable865 values('Carol','Taylor'); Query OK, 1 row affected (0.15 sec) Display all records from the table using select statement − mysql> select *from DemoTable865; This will produce the following output − +-----------+----------+ | FirstName | LastName | +-----------+----------+ | Chris | Brown | | Adam | Smith | | David | Miller | | Carol | Taylor | +-----------+----------+ 4 rows in set (0.00 sec) Here, we are creating an alias for the column with SELECT (COLNAME) MySQL − mysql> select (FirstName) StudentFirstName,(LastName) StudentLastName from DemoTable865; This will produce the following output − +------------------+-----------------+ | StudentFirstName | StudentLastName | +------------------+-----------------+ | Chris | Brown | | Adam | Smith | | David | Miller | | Carol | Taylor | +------------------+-----------------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1174, "s": 1062, "text": "The SELECT(COLNAME) means, we are creating an alias for that column. Let us see an example and create a table −" }, { "code": null, "e": 1300, "s": 1174, "text": "mysql> create table DemoTable865(\n FirstName varchar(100),\n LastName varchar(100)\n);\nQuery OK, 0 rows affected (0.77 sec)" }, { "code": null, "e": 1356, "s": 1300, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1729, "s": 1356, "text": "mysql> insert into DemoTable865 values('Chris','Brown');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable865 values('Adam','Smith');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable865 values('David','Miller');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable865 values('Carol','Taylor');\nQuery OK, 1 row affected (0.15 sec)" }, { "code": null, "e": 1789, "s": 1729, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1823, "s": 1789, "text": "mysql> select *from DemoTable865;" }, { "code": null, "e": 1864, "s": 1823, "text": "This will produce the following output −" }, { "code": null, "e": 2089, "s": 1864, "text": "+-----------+----------+\n| FirstName | LastName |\n+-----------+----------+\n| Chris | Brown |\n| Adam | Smith |\n| David | Miller |\n| Carol | Taylor |\n+-----------+----------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2165, "s": 2089, "text": "Here, we are creating an alias for the column with SELECT (COLNAME) MySQL −" }, { "code": null, "e": 2254, "s": 2165, "text": "mysql> select (FirstName) StudentFirstName,(LastName) StudentLastName from DemoTable865;" }, { "code": null, "e": 2295, "s": 2254, "text": "This will produce the following output −" }, { "code": null, "e": 2632, "s": 2295, "text": "+------------------+-----------------+\n| StudentFirstName | StudentLastName |\n+------------------+-----------------+\n| Chris | Brown |\n| Adam | Smith |\n| David | Miller |\n| Carol | Taylor |\n+------------------+-----------------+\n4 rows in set (0.00 sec)" } ]
MySQL Error - #1046 - No database selected
The error-#1046 can occur when we are creating a table, but forget to select the database. Let us say we have started MySQL as shown below − After giving the correct password, the above window will open. Now create a table without choosing any database. This will show an error − mysql> CREATE table TblUni -> ( -> id int, -> Name varchar(100) -> ); ERROR 1046 (3D000): No database selected The following screenshot is showing the same error − Now, choose any database to get rid of the above error. Firstly, let us check how many databases are present in MySQL with the help of SHOW command − mysql> SHOW databases; The following is the output − +--------------------+ | Database | +--------------------+ | business | | hello | | information_schema | | mybusiness | | mysql | | performance_schema | | sample | | sys | | test | +--------------------+ 9 rows in set (0.00 sec) Now, we can choose any database. Suppose I am using the database ‘business’, therefore we can choose with the help of ‘use’ command. mysql> use business; Database changed After using database ‘business’, we can create the above table and we will not get any error. mysql> CREATE table TblUni -> ( -> id int, -> Name varchar(100) -> ); Query OK, 0 rows affected (0.50 sec)
[ { "code": null, "e": 1203, "s": 1062, "text": "The error-#1046 can occur when we are creating a table, but forget to select the database. Let\nus say we have started MySQL as shown below −" }, { "code": null, "e": 1342, "s": 1203, "text": "After giving the correct password, the above window will open. Now create a table without\nchoosing any database. This will show an error −" }, { "code": null, "e": 1412, "s": 1342, "text": "mysql> CREATE table TblUni\n-> (\n-> id int,\n-> Name varchar(100)\n-> );" }, { "code": null, "e": 1453, "s": 1412, "text": "ERROR 1046 (3D000): No database selected" }, { "code": null, "e": 1506, "s": 1453, "text": "The following screenshot is showing the same error −" }, { "code": null, "e": 1656, "s": 1506, "text": "Now, choose any database to get rid of the above error. Firstly, let us check how many\ndatabases are present in MySQL with the help of SHOW command −" }, { "code": null, "e": 1680, "s": 1656, "text": "mysql> SHOW databases;\n" }, { "code": null, "e": 1710, "s": 1680, "text": "The following is the output −" }, { "code": null, "e": 2035, "s": 1710, "text": "+--------------------+\n| Database |\n+--------------------+\n| business |\n| hello |\n| information_schema |\n| mybusiness |\n| mysql |\n| performance_schema |\n| sample |\n| sys | \n| test |\n+--------------------+\n9 rows in set (0.00 sec)" }, { "code": null, "e": 2168, "s": 2035, "text": "Now, we can choose any database. Suppose I am using the database ‘business’, therefore we\ncan choose with the help of ‘use’ command." }, { "code": null, "e": 2206, "s": 2168, "text": "mysql> use business;\nDatabase changed" }, { "code": null, "e": 2300, "s": 2206, "text": "After using database ‘business’, we can create the above table and we will not get any error." }, { "code": null, "e": 2407, "s": 2300, "text": "mysql> CREATE table TblUni\n-> (\n-> id int,\n-> Name varchar(100)\n-> );\nQuery OK, 0 rows affected (0.50 sec)" } ]