title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
SQL - Expressions
An expression is a combination of one or more values, operators and SQL functions that evaluate to a value. These SQL EXPRESSIONs are like formulae and they are written in query language. You can also use them to query the database for a specific set of data. Consider the basic syntax of the SELECT statement as follows − SELECT column1, column2, columnN FROM table_name WHERE [CONDITION|EXPRESSION]; There are different types of SQL expressions, which are mentioned below − Boolean Numeric Date Let us now discuss each of these in detail. SQL Boolean Expressions fetch the data based on matching a single value. Following is the syntax − SELECT column1, column2, columnN FROM table_name WHERE SINGLE VALUE MATCHING EXPRESSION; Consider the CUSTOMERS table having the following records − SQL> SELECT * FROM CUSTOMERS; +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ 7 rows in set (0.00 sec) The following table is a simple example showing the usage of various SQL Boolean Expressions − SQL> SELECT * FROM CUSTOMERS WHERE SALARY = 10000; +----+-------+-----+---------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+-------+-----+---------+----------+ | 7 | Muffy | 24 | Indore | 10000.00 | +----+-------+-----+---------+----------+ 1 row in set (0.00 sec) These expressions are used to perform any mathematical operation in any query. Following is the syntax − SELECT numerical_expression as OPERATION_NAME [FROM table_name WHERE CONDITION] ; Here, the numerical_expression is used for a mathematical expression or any formula. Following is a simple example showing the usage of SQL Numeric Expressions − SQL> SELECT (15 + 6) AS ADDITION +----------+ | ADDITION | +----------+ | 21 | +----------+ 1 row in set (0.00 sec) There are several built-in functions like avg(), sum(), count(), etc., to perform what is known as the aggregate data calculations against a table or a specific table column. SQL> SELECT COUNT(*) AS "RECORDS" FROM CUSTOMERS; +---------+ | RECORDS | +---------+ | 7 | +---------+ 1 row in set (0.00 sec) Date Expressions return current system date and time values − SQL> SELECT CURRENT_TIMESTAMP; +---------------------+ | Current_Timestamp | +---------------------+ | 2009-11-12 06:40:23 | +---------------------+ 1 row in set (0.00 sec) Another date expression is as shown below − SQL> SELECT GETDATE();; +-------------------------+ | GETDATE | +-------------------------+ | 2009-10-22 12:07:18.140 | +-------------------------+ 1 row in set (0.00 sec) 42 Lectures 5 hours Anadi Sharma 14 Lectures 2 hours Anadi Sharma 44 Lectures 4.5 hours Anadi Sharma 94 Lectures 7 hours Abhishek And Pukhraj 80 Lectures 6.5 hours Oracle Master Training | 150,000+ Students Worldwide 31 Lectures 6 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2713, "s": 2453, "text": "An expression is a combination of one or more values, operators and SQL functions that evaluate to a value. These SQL EXPRESSIONs are like formulae and they are written in query language. You can also use them to query the database for a specific set of data." }, { "code": null, "e": 2776, "s": 2713, "text": "Consider the basic syntax of the SELECT statement as follows −" }, { "code": null, "e": 2858, "s": 2776, "text": "SELECT column1, column2, columnN \nFROM table_name \nWHERE [CONDITION|EXPRESSION];\n" }, { "code": null, "e": 2932, "s": 2858, "text": "There are different types of SQL expressions, which are mentioned below −" }, { "code": null, "e": 2940, "s": 2932, "text": "Boolean" }, { "code": null, "e": 2948, "s": 2940, "text": "Numeric" }, { "code": null, "e": 2953, "s": 2948, "text": "Date" }, { "code": null, "e": 2997, "s": 2953, "text": "Let us now discuss each of these in detail." }, { "code": null, "e": 3096, "s": 2997, "text": "SQL Boolean Expressions fetch the data based on matching a single value. Following is the syntax −" }, { "code": null, "e": 3188, "s": 3096, "text": "SELECT column1, column2, columnN \nFROM table_name \nWHERE SINGLE VALUE MATCHING EXPRESSION;\n" }, { "code": null, "e": 3248, "s": 3188, "text": "Consider the CUSTOMERS table having the following records −" }, { "code": null, "e": 3820, "s": 3248, "text": "SQL> SELECT * FROM CUSTOMERS;\n+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n7 rows in set (0.00 sec)" }, { "code": null, "e": 3915, "s": 3820, "text": "The following table is a simple example showing the usage of various SQL Boolean Expressions −" }, { "code": null, "e": 4200, "s": 3915, "text": "SQL> SELECT * FROM CUSTOMERS WHERE SALARY = 10000;\n+----+-------+-----+---------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+-------+-----+---------+----------+\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+-------+-----+---------+----------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 4305, "s": 4200, "text": "These expressions are used to perform any mathematical operation in any query. Following is the syntax −" }, { "code": null, "e": 4389, "s": 4305, "text": "SELECT numerical_expression as OPERATION_NAME\n[FROM table_name\nWHERE CONDITION] ;\n" }, { "code": null, "e": 4551, "s": 4389, "text": "Here, the numerical_expression is used for a mathematical expression or any formula. Following is a simple example showing the usage of SQL Numeric Expressions −" }, { "code": null, "e": 4673, "s": 4551, "text": "SQL> SELECT (15 + 6) AS ADDITION\n+----------+\n| ADDITION |\n+----------+\n| 21 |\n+----------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 4848, "s": 4673, "text": "There are several built-in functions like avg(), sum(), count(), etc., to perform what is known as the aggregate data calculations against a table or a specific table column." }, { "code": null, "e": 4983, "s": 4848, "text": "SQL> SELECT COUNT(*) AS \"RECORDS\" FROM CUSTOMERS; \n+---------+\n| RECORDS |\n+---------+\n| 7 |\n+---------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 5045, "s": 4983, "text": "Date Expressions return current system date and time values −" }, { "code": null, "e": 5221, "s": 5045, "text": "SQL> SELECT CURRENT_TIMESTAMP;\n+---------------------+\n| Current_Timestamp |\n+---------------------+\n| 2009-11-12 06:40:23 |\n+---------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 5265, "s": 5221, "text": "Another date expression is as shown below −" }, { "code": null, "e": 5455, "s": 5265, "text": "SQL> SELECT GETDATE();;\n+-------------------------+\n| GETDATE |\n+-------------------------+\n| 2009-10-22 12:07:18.140 |\n+-------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 5488, "s": 5455, "text": "\n 42 Lectures \n 5 hours \n" }, { "code": null, "e": 5502, "s": 5488, "text": " Anadi Sharma" }, { "code": null, "e": 5535, "s": 5502, "text": "\n 14 Lectures \n 2 hours \n" }, { "code": null, "e": 5549, "s": 5535, "text": " Anadi Sharma" }, { "code": null, "e": 5584, "s": 5549, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5598, "s": 5584, "text": " Anadi Sharma" }, { "code": null, "e": 5631, "s": 5598, "text": "\n 94 Lectures \n 7 hours \n" }, { "code": null, "e": 5653, "s": 5631, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 5688, "s": 5653, "text": "\n 80 Lectures \n 6.5 hours \n" }, { "code": null, "e": 5742, "s": 5688, "text": " Oracle Master Training | 150,000+ Students Worldwide" }, { "code": null, "e": 5775, "s": 5742, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 5803, "s": 5775, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5810, "s": 5803, "text": " Print" }, { "code": null, "e": 5821, "s": 5810, "text": " Add Notes" } ]
Why static methods of parent class gets hidden in child class in java?
When we have two classes where, one extends another and if, these two classes have same method including parameters and return type (say, sample) the method in the sub class overrides the method in the super class. i.e. Since it is inheritance. If we instantiate the subclass a copy of superclass’s members is created in the subclass object and, thus both methods are available to the object of the subclass. But if you call the method (sample), the sample method of the subclass will be executed overriding the super class’s method. class Super{ public static void sample(){ System.out.println("Method of the superclass"); } } public class OverridingExample extends Super { public static void sample(){ System.out.println("Method of the subclass"); } public static void main(String args[]){ Super obj1 = (Super) new OverridingExample(); OverridingExample obj2 = new OverridingExample(); obj1.sample(); obj2.sample(); } } Method of the superclass Method of the subclass When superclass and subclass contains same method including parameters and if they are static. The method in the superclass will be hidden by the one that is in the subclass. This mechanism is known as method hiding in short, though super and subclasses have methods with same signature it they are static, it is not considered as overriding. class Super{ public static void demo() { System.out.println("This is the main method of the superclass"); } } class Sub extends Super{ public static void demo() { System.out.println("This is the main method of the subclass"); } } public class MethodHiding{ public static void main(String args[]) { MethodHiding obj = new MethodHiding(); Sub.demo(); } } This is the main method of the subclass The key in method overloading is, if the super class and sub class have method with same signature, to the object of the sub class both of them are available. Based on the object type (reference) you used to hold the object, the respective method will be executed. SuperClass obj1 = (Super) new SubClass(); obj1.demo() // invokes the demo method of the super class SubClass obj2 = new SubClass (); obj2.demo() //invokes the demo method of the sub class But, in case of static methods, since they don’t belong to any instance, you need to access them using the class name. SuperClass.demo(); SubClass.Demo(); Therefore, if a super class and sub class have static methods with same signature, though a copy of the super class method is available to the sub class object. Since they are static the method calls resolve at the compile time itself, overriding is not possible with static methods. But, since a copy of static method is available, if you call the sub class method the method of the super class will be redefined/hidden.
[ { "code": null, "e": 1277, "s": 1062, "text": "When we have two classes where, one extends another and if, these two classes have same method including parameters and return type (say, sample) the method in the sub class overrides the method in the super class." }, { "code": null, "e": 1471, "s": 1277, "text": "i.e. Since it is inheritance. If we instantiate the subclass a copy of superclass’s members is created in the subclass object and, thus both methods are available to the object of the subclass." }, { "code": null, "e": 1596, "s": 1471, "text": "But if you call the method (sample), the sample method of the subclass will be executed overriding the super class’s method." }, { "code": null, "e": 2038, "s": 1596, "text": "class Super{\n public static void sample(){\n System.out.println(\"Method of the superclass\");\n }\n}\npublic class OverridingExample extends Super {\n public static void sample(){\n System.out.println(\"Method of the subclass\");\n }\n public static void main(String args[]){\n Super obj1 = (Super) new OverridingExample();\n OverridingExample obj2 = new OverridingExample();\n obj1.sample();\n obj2.sample();\n }\n}" }, { "code": null, "e": 2086, "s": 2038, "text": "Method of the superclass\nMethod of the subclass" }, { "code": null, "e": 2261, "s": 2086, "text": "When superclass and subclass contains same method including parameters and if they are static. The method in the superclass will be hidden by the one that is in the subclass." }, { "code": null, "e": 2429, "s": 2261, "text": "This mechanism is known as method hiding in short, though super and subclasses have methods with same signature it they are static, it is not considered as overriding." }, { "code": null, "e": 2824, "s": 2429, "text": "class Super{\n public static void demo() {\n System.out.println(\"This is the main method of the superclass\");\n }\n}\nclass Sub extends Super{\n public static void demo() {\n System.out.println(\"This is the main method of the subclass\");\n }\n}\npublic class MethodHiding{\n public static void main(String args[]) {\n MethodHiding obj = new MethodHiding();\n Sub.demo();\n }\n}" }, { "code": null, "e": 2864, "s": 2824, "text": "This is the main method of the subclass" }, { "code": null, "e": 3129, "s": 2864, "text": "The key in method overloading is, if the super class and sub class have method with same signature, to the object of the sub class both of them are available. Based on the object type (reference) you used to hold the object, the respective method will be executed." }, { "code": null, "e": 3317, "s": 3129, "text": "SuperClass obj1 = (Super) new SubClass();\nobj1.demo() // invokes the demo method of the super class\nSubClass obj2 = new SubClass ();\nobj2.demo() //invokes the demo method of the sub class" }, { "code": null, "e": 3436, "s": 3317, "text": "But, in case of static methods, since they don’t belong to any instance, you need to access them using the class name." }, { "code": null, "e": 3472, "s": 3436, "text": "SuperClass.demo();\nSubClass.Demo();" }, { "code": null, "e": 3756, "s": 3472, "text": "Therefore, if a super class and sub class have static methods with same signature, though a copy of the super class method is available to the sub class object. Since they are static the method calls resolve at the compile time itself, overriding is not possible with static methods." }, { "code": null, "e": 3894, "s": 3756, "text": "But, since a copy of static method is available, if you call the sub class method the method of the super class will be redefined/hidden." } ]
attributes in C++ - GeeksforGeeks
05 Dec, 2018 Attributes are one of the key features of modern C++ which allows the programmer to specify additional information to the compiler to enforce constraints(conditions), optimise certain pieces of code or do some specific code generation. In simple terms, an attribute acts as an annotation or a note to the compiler which provides additional information about the code for optimization purposes and enforcing certain conditions on it. Introduced in C++11, they have remained one of the best features of C++ and are constantly being evolved with each new version of C++. Syntax: // C++11[[attribute-list]] // C++17[[using attribute-namespace:attribute-list]] // Upcoming C++20[[contract-attribute-token contract-level identifier : expression]] Except for some specific ones, most of the attributescan be applied with variables, functions, classes,structures etc. To enforce constraints on the code:Here constraint refers to a condition, that the arguments of a particular function must meet for its execution (precondition). In previous versions of C++, the code for specifying constraints was written in this mannerint f(int i){ if (i > 0) return i; else return -1; // Code}It increases the readability of your code and avoids the clutter that is written inside the function for argument checking.int f(int i)[[expects:i > 0]]{ // Code} Here constraint refers to a condition, that the arguments of a particular function must meet for its execution (precondition). In previous versions of C++, the code for specifying constraints was written in this manner int f(int i){ if (i > 0) return i; else return -1; // Code} It increases the readability of your code and avoids the clutter that is written inside the function for argument checking. int f(int i)[[expects:i > 0]]{ // Code} To give additional information to the compiler for optimisation purposes:Compilers are very good at optimization but compared to humans they still lag at some places and propose generalized code which is not very efficient. This mainly happens due to the lack of additional information about the “problem” which humans have. To reduce this problem to an extent C++ standard has introduced some new attributes that allow specifying a little more to the compiler rather than the code statement itself. Once such example is that of likely.int f(int i){ switch (i) { case 1: [[fallthrough]]; [[likely]] case 2 : return 1; } return -1;}When the statement is preceded by likely compiler makes special optimizations with respect to that statement which improves the overall performance of the code. Some examples of such attributes are [carries_dependency], [likely], [unlikely] Compilers are very good at optimization but compared to humans they still lag at some places and propose generalized code which is not very efficient. This mainly happens due to the lack of additional information about the “problem” which humans have. To reduce this problem to an extent C++ standard has introduced some new attributes that allow specifying a little more to the compiler rather than the code statement itself. Once such example is that of likely. int f(int i){ switch (i) { case 1: [[fallthrough]]; [[likely]] case 2 : return 1; } return -1;} When the statement is preceded by likely compiler makes special optimizations with respect to that statement which improves the overall performance of the code. Some examples of such attributes are [carries_dependency], [likely], [unlikely] Suppressing certain warnings and errors that programmer intended to have in his code:It happens rarely but sometimes the programmer intentionally tries to write a faulty code which gets detected by the compiler and is reported as an error or a warning. One such example is that of an unused variable which has been left in that state for a specific reason or of a switch statement where the break statements are not put after some cases to give rise to fall-through conditions. In order to circumvent errors and warnings on such conditions, C++ provides attributes such as [maybe_unused] and [fallthrough] that prevent the compiler from generating warnings or errors.#include <iostream>#include <string> int main(){ // Set debug mode in compiler or 'R' [[maybe_unused]] char mg_brk = 'D'; // Compiler does not emit any warnings // or error on this unused variable} It happens rarely but sometimes the programmer intentionally tries to write a faulty code which gets detected by the compiler and is reported as an error or a warning. One such example is that of an unused variable which has been left in that state for a specific reason or of a switch statement where the break statements are not put after some cases to give rise to fall-through conditions. In order to circumvent errors and warnings on such conditions, C++ provides attributes such as [maybe_unused] and [fallthrough] that prevent the compiler from generating warnings or errors. #include <iostream>#include <string> int main(){ // Set debug mode in compiler or 'R' [[maybe_unused]] char mg_brk = 'D'; // Compiler does not emit any warnings // or error on this unused variable} C++11noreturn: indicates that the function does not return a valueUsage:[[noreturn]] void f(); While looking at the code above, the question arises what is the point of having noreturn when the return type is actually void? If a function has a void type, then it actually returns to the caller without a value but if the case is such that the function never returns back to the caller (for example an infinite loop) then adding a noreturn attribute gives hints to the compiler to optimise the code or generate better warnings.Example:#include <iostream>#include <string> [[noreturn]] void f(){ // Some code that does not return // back the control to the caller // In this case the function returns // back to the caller without a value // This is the reason why the // warning "noreturn' function does return' arises} void g(){ std::cout << "Code is intented to reach here";} int main(){ f(); g();}Warning:main.cpp: In function 'void f()': main.cpp:8:1: warning: 'noreturn' function does return } ^ C++14deprecated: Indicates that the name or entity declared with this attribute has become obsolete and must not be used for some specific reason. This attribute can be applied to namespaces, functions, classes structures or variables.Usage:[[deprecated("Reason for deprecation")]] // For Class/Struct/Union struct [[deprecated]] S; // For Functions [[deprecated]] void f(); // For namespaces namespace [[deprecated]] ns{} // For variables (including static data members) [[deprecated]] int x; Example:#include <iostream>#include <string> [[deprecated("Susceptible to buffer overflow")]] void gets(char* str){ // Code for gets dummy // (Although original function has // char* as return type)} void gets_n(std::string& str){ // Dummy code char st[100]; std::cout << "Successfully Executed"; std::cin.getline(st, 100); str = std::string(st); // Code for new gets} int main(){ char a[100]; gets(a); // std::string str; // gets_n(str);}Warning:main.cpp: In function 'int main()': main.cpp:26:9: warning: 'void gets(char*)' is deprecated: Susceptible to buffer overflow [-Wdeprecated-declarations] gets(a); ^ C++17nodiscard: The entities declared with nodiscard should not have their return values ignored by the caller. Simply saying if a function returns a value and is marked nodiscard then the return value must be utilized by the caller and not discarded.Usage :// Functions [[nodiscard]] void f(); // Class/Struct declaration struct [[nodiscard]] my_struct{}; The main difference between nodiscard with functions and nodiscard with struct/class declaration is that in case of function, nodiscard applies to that particular function only which is declared no discard, whereas in case of class/struct declaration nodiscard applies to every single function that returns the nodiscard marked object by value.Example:#include <iostream>#include <string> // Return value must be utilized by the caller[[nodiscard]] int f(){ return 0;} class[[nodiscard]] my_class{}; // Automatically becomes nodiscard markedmy_class fun(){ return my_class();} int main(){ int x{ 1 }; // No error as value is utilised // x= f(); // Error : Value is not utilised f(); // Value not utilised error // fun() ; return x;}Warning:prog.cpp:5:21: warning: 'nodiscard' attribute directive ignored [-Wattributes] [[nodiscard]] int f() ^ prog.cpp:10:20: warning: 'nodiscard' attribute directive ignored [-Wattributes] class[[nodiscard]] my_class{}; ^ maybe_unused: Used to suppress warnings on any unused entities (For eg: An unused variable or an unused argument to a function).Usage://Variables [[maybe_used]] bool log_var = true; //Functions [[maybe_unused]] void log_without_warning(); //Function arguments void f([[maybe_unused]] int a, int b); Example:#include <iostream>#include <string> int main(){ // Set debug mode in compiler or 'R' [[maybe_unused]] char mg_brk = 'D'; // Compiler does not emit any warnings // or error on this unused variable}fallthrough:[[fallthrough]] indicates that a fallthrough in a switch statement is intentional. Missing a break or return in a switch statement is usually considered a programmer’s error but in some cases fallthrough can result in some very terse code and hence it is used.Note: Unlike other attributes a fallthrough requires a semicolon after it is declared.Example:void process_alert(Alert alert){ switch (alert) { case Alert::Red: evacuate(); // Compiler emits a warning here // thinking it is done by mistake case Alert::Orange: trigger_alarm(); // this attribute needs semicolon [[fallthrough]]; // Warning suppressed by [[fallthrough]] case Alert::Yellow: record_alert(); return; case Alert::Green: return; }}Upcoming C++20 attributeslikely: For optimisation of certain statements that have more probability to execute than others. Likely is now available in latest version of GCC compiler for experimentation purposes.Exampleint f(int i){ switch (i) { case 1: [[fallthrough]]; [[likely]] case 2 : return 1; } return 2;}no_unique_address: Indicates that this data member need not have an address distinct from all other non-static data members of its class. This means that if the class consist of an empty type then the compiler can perform empty base optimisation on it.Example:// empty class ( No state!)struct Empty {}; struct X { int i; Empty e;}; struct Y { int i; [[no_unique_address]] Empty e;}; int main(){ // the size of any object of // empty class type is at least 1 static_assert(sizeof(Empty) >= 1); // at least one more byte is needed // to give e a unique address static_assert(sizeof(X) >= sizeof(int) + 1); // empty base optimization applied static_assert(sizeof(Y) == sizeof(int));}expects: It specifies the conditions (in form of contract) that the arguments must meet for a particular function to be executed.Usage:return_type func ( args...) [[expects : precondition]] Example:void list(node* n)[[expects:n != nullptr]]Violation of the contract results in invocation of violation handler or if not specified then std::terminate() noreturn: indicates that the function does not return a valueUsage:[[noreturn]] void f(); While looking at the code above, the question arises what is the point of having noreturn when the return type is actually void? If a function has a void type, then it actually returns to the caller without a value but if the case is such that the function never returns back to the caller (for example an infinite loop) then adding a noreturn attribute gives hints to the compiler to optimise the code or generate better warnings.Example:#include <iostream>#include <string> [[noreturn]] void f(){ // Some code that does not return // back the control to the caller // In this case the function returns // back to the caller without a value // This is the reason why the // warning "noreturn' function does return' arises} void g(){ std::cout << "Code is intented to reach here";} int main(){ f(); g();}Warning:main.cpp: In function 'void f()': main.cpp:8:1: warning: 'noreturn' function does return } ^ C++14 Usage: [[noreturn]] void f(); While looking at the code above, the question arises what is the point of having noreturn when the return type is actually void? If a function has a void type, then it actually returns to the caller without a value but if the case is such that the function never returns back to the caller (for example an infinite loop) then adding a noreturn attribute gives hints to the compiler to optimise the code or generate better warnings. Example: #include <iostream>#include <string> [[noreturn]] void f(){ // Some code that does not return // back the control to the caller // In this case the function returns // back to the caller without a value // This is the reason why the // warning "noreturn' function does return' arises} void g(){ std::cout << "Code is intented to reach here";} int main(){ f(); g();} Warning: main.cpp: In function 'void f()': main.cpp:8:1: warning: 'noreturn' function does return } ^ C++14 deprecated: Indicates that the name or entity declared with this attribute has become obsolete and must not be used for some specific reason. This attribute can be applied to namespaces, functions, classes structures or variables.Usage:[[deprecated("Reason for deprecation")]] // For Class/Struct/Union struct [[deprecated]] S; // For Functions [[deprecated]] void f(); // For namespaces namespace [[deprecated]] ns{} // For variables (including static data members) [[deprecated]] int x; Example:#include <iostream>#include <string> [[deprecated("Susceptible to buffer overflow")]] void gets(char* str){ // Code for gets dummy // (Although original function has // char* as return type)} void gets_n(std::string& str){ // Dummy code char st[100]; std::cout << "Successfully Executed"; std::cin.getline(st, 100); str = std::string(st); // Code for new gets} int main(){ char a[100]; gets(a); // std::string str; // gets_n(str);}Warning:main.cpp: In function 'int main()': main.cpp:26:9: warning: 'void gets(char*)' is deprecated: Susceptible to buffer overflow [-Wdeprecated-declarations] gets(a); ^ C++17 Usage: [[deprecated("Reason for deprecation")]] // For Class/Struct/Union struct [[deprecated]] S; // For Functions [[deprecated]] void f(); // For namespaces namespace [[deprecated]] ns{} // For variables (including static data members) [[deprecated]] int x; Example: #include <iostream>#include <string> [[deprecated("Susceptible to buffer overflow")]] void gets(char* str){ // Code for gets dummy // (Although original function has // char* as return type)} void gets_n(std::string& str){ // Dummy code char st[100]; std::cout << "Successfully Executed"; std::cin.getline(st, 100); str = std::string(st); // Code for new gets} int main(){ char a[100]; gets(a); // std::string str; // gets_n(str);} Warning: main.cpp: In function 'int main()': main.cpp:26:9: warning: 'void gets(char*)' is deprecated: Susceptible to buffer overflow [-Wdeprecated-declarations] gets(a); ^ C++17 nodiscard: The entities declared with nodiscard should not have their return values ignored by the caller. Simply saying if a function returns a value and is marked nodiscard then the return value must be utilized by the caller and not discarded.Usage :// Functions [[nodiscard]] void f(); // Class/Struct declaration struct [[nodiscard]] my_struct{}; The main difference between nodiscard with functions and nodiscard with struct/class declaration is that in case of function, nodiscard applies to that particular function only which is declared no discard, whereas in case of class/struct declaration nodiscard applies to every single function that returns the nodiscard marked object by value.Example:#include <iostream>#include <string> // Return value must be utilized by the caller[[nodiscard]] int f(){ return 0;} class[[nodiscard]] my_class{}; // Automatically becomes nodiscard markedmy_class fun(){ return my_class();} int main(){ int x{ 1 }; // No error as value is utilised // x= f(); // Error : Value is not utilised f(); // Value not utilised error // fun() ; return x;}Warning:prog.cpp:5:21: warning: 'nodiscard' attribute directive ignored [-Wattributes] [[nodiscard]] int f() ^ prog.cpp:10:20: warning: 'nodiscard' attribute directive ignored [-Wattributes] class[[nodiscard]] my_class{}; ^ Usage : // Functions [[nodiscard]] void f(); // Class/Struct declaration struct [[nodiscard]] my_struct{}; The main difference between nodiscard with functions and nodiscard with struct/class declaration is that in case of function, nodiscard applies to that particular function only which is declared no discard, whereas in case of class/struct declaration nodiscard applies to every single function that returns the nodiscard marked object by value. Example: #include <iostream>#include <string> // Return value must be utilized by the caller[[nodiscard]] int f(){ return 0;} class[[nodiscard]] my_class{}; // Automatically becomes nodiscard markedmy_class fun(){ return my_class();} int main(){ int x{ 1 }; // No error as value is utilised // x= f(); // Error : Value is not utilised f(); // Value not utilised error // fun() ; return x;} Warning: prog.cpp:5:21: warning: 'nodiscard' attribute directive ignored [-Wattributes] [[nodiscard]] int f() ^ prog.cpp:10:20: warning: 'nodiscard' attribute directive ignored [-Wattributes] class[[nodiscard]] my_class{}; ^ maybe_unused: Used to suppress warnings on any unused entities (For eg: An unused variable or an unused argument to a function).Usage://Variables [[maybe_used]] bool log_var = true; //Functions [[maybe_unused]] void log_without_warning(); //Function arguments void f([[maybe_unused]] int a, int b); Example:#include <iostream>#include <string> int main(){ // Set debug mode in compiler or 'R' [[maybe_unused]] char mg_brk = 'D'; // Compiler does not emit any warnings // or error on this unused variable} Usage: //Variables [[maybe_used]] bool log_var = true; //Functions [[maybe_unused]] void log_without_warning(); //Function arguments void f([[maybe_unused]] int a, int b); Example: #include <iostream>#include <string> int main(){ // Set debug mode in compiler or 'R' [[maybe_unused]] char mg_brk = 'D'; // Compiler does not emit any warnings // or error on this unused variable} fallthrough:[[fallthrough]] indicates that a fallthrough in a switch statement is intentional. Missing a break or return in a switch statement is usually considered a programmer’s error but in some cases fallthrough can result in some very terse code and hence it is used.Note: Unlike other attributes a fallthrough requires a semicolon after it is declared.Example:void process_alert(Alert alert){ switch (alert) { case Alert::Red: evacuate(); // Compiler emits a warning here // thinking it is done by mistake case Alert::Orange: trigger_alarm(); // this attribute needs semicolon [[fallthrough]]; // Warning suppressed by [[fallthrough]] case Alert::Yellow: record_alert(); return; case Alert::Green: return; }}Upcoming C++20 attributes Note: Unlike other attributes a fallthrough requires a semicolon after it is declared. Example: void process_alert(Alert alert){ switch (alert) { case Alert::Red: evacuate(); // Compiler emits a warning here // thinking it is done by mistake case Alert::Orange: trigger_alarm(); // this attribute needs semicolon [[fallthrough]]; // Warning suppressed by [[fallthrough]] case Alert::Yellow: record_alert(); return; case Alert::Green: return; }} Upcoming C++20 attributes likely: For optimisation of certain statements that have more probability to execute than others. Likely is now available in latest version of GCC compiler for experimentation purposes.Exampleint f(int i){ switch (i) { case 1: [[fallthrough]]; [[likely]] case 2 : return 1; } return 2;} Example int f(int i){ switch (i) { case 1: [[fallthrough]]; [[likely]] case 2 : return 1; } return 2;} no_unique_address: Indicates that this data member need not have an address distinct from all other non-static data members of its class. This means that if the class consist of an empty type then the compiler can perform empty base optimisation on it.Example:// empty class ( No state!)struct Empty {}; struct X { int i; Empty e;}; struct Y { int i; [[no_unique_address]] Empty e;}; int main(){ // the size of any object of // empty class type is at least 1 static_assert(sizeof(Empty) >= 1); // at least one more byte is needed // to give e a unique address static_assert(sizeof(X) >= sizeof(int) + 1); // empty base optimization applied static_assert(sizeof(Y) == sizeof(int));} Example: // empty class ( No state!)struct Empty {}; struct X { int i; Empty e;}; struct Y { int i; [[no_unique_address]] Empty e;}; int main(){ // the size of any object of // empty class type is at least 1 static_assert(sizeof(Empty) >= 1); // at least one more byte is needed // to give e a unique address static_assert(sizeof(X) >= sizeof(int) + 1); // empty base optimization applied static_assert(sizeof(Y) == sizeof(int));} expects: It specifies the conditions (in form of contract) that the arguments must meet for a particular function to be executed.Usage:return_type func ( args...) [[expects : precondition]] Example:void list(node* n)[[expects:n != nullptr]]Violation of the contract results in invocation of violation handler or if not specified then std::terminate() Usage: return_type func ( args...) [[expects : precondition]] Example: void list(node* n)[[expects:n != nullptr]] Violation of the contract results in invocation of violation handler or if not specified then std::terminate() Ignoring unknown attributes:Since C++17, one of the major changes introduced for the attribute feature in C++ were regarding the clarification of unknown attributes by the compiler. In C++11 or 14, if an attribute was not recognized by the compiler, then it would produce an error and prevent the code from getting compiled. As a workaround, the programmer had to remove the attribute from the code to make it work. This introduced a major issue for portability. Apart from the standard attributes none of the vendor-specific attributes could be used, as the code would break. This prevented the actual use of this feature.As a solution, the standard made it compulsory for all the compilers to ignore the attributes that were not defined by them. This allowed the programmers to use vendor-specific attributes freely in their code and ensure that the code was still portable. Most of the compilers supporting C++17 now ignore the undefined attributes and produce a warning on when encountered. This allows the programmers to make the code more flexible as now, they can specify multiple attributes for the same operation under different vendor’s namespaces. (Support: MSVC(NOT YET), GCC, CLANG (YES))Example:// Here the attributes will work on their respective[[msvc::deprecated]][[gnu::deprecated]] char* gets(char* str) compilers Since C++17, one of the major changes introduced for the attribute feature in C++ were regarding the clarification of unknown attributes by the compiler. In C++11 or 14, if an attribute was not recognized by the compiler, then it would produce an error and prevent the code from getting compiled. As a workaround, the programmer had to remove the attribute from the code to make it work. This introduced a major issue for portability. Apart from the standard attributes none of the vendor-specific attributes could be used, as the code would break. This prevented the actual use of this feature. As a solution, the standard made it compulsory for all the compilers to ignore the attributes that were not defined by them. This allowed the programmers to use vendor-specific attributes freely in their code and ensure that the code was still portable. Most of the compilers supporting C++17 now ignore the undefined attributes and produce a warning on when encountered. This allows the programmers to make the code more flexible as now, they can specify multiple attributes for the same operation under different vendor’s namespaces. (Support: MSVC(NOT YET), GCC, CLANG (YES)) Example: // Here the attributes will work on their respective[[msvc::deprecated]][[gnu::deprecated]] char* gets(char* str) compilers Use of attribute namespaces without repetition:In C++17 some of the rules regarding the use of “non-standard” attributes were relaxed. One such case is that of prefixing namespaces with a subsequent non-standard attribute. In C++11 or 14 when multiple attributes were written together each one of them had to be prefixed with their enclosing namespaces which gave rise to the pattern of code as shown below.[[ gnu::always_inline, gnu::const, gnu::hot, nodiscard ]] int f();Looking at the code above, it can be seen that it seems bloated and cluttered. So the committee decided to “simplify the case when using multiple attributes” together. As of now, it is not mandatory for the programmer to prefix the namespace again and again with subsequent attributes being used together. This gives rise to the pattern of code shown below which looks clean and understandable.[[using gnu:const, always_inline]] int f() { return 0; } In C++17 some of the rules regarding the use of “non-standard” attributes were relaxed. One such case is that of prefixing namespaces with a subsequent non-standard attribute. In C++11 or 14 when multiple attributes were written together each one of them had to be prefixed with their enclosing namespaces which gave rise to the pattern of code as shown below. [[ gnu::always_inline, gnu::const, gnu::hot, nodiscard ]] int f(); Looking at the code above, it can be seen that it seems bloated and cluttered. So the committee decided to “simplify the case when using multiple attributes” together. As of now, it is not mandatory for the programmer to prefix the namespace again and again with subsequent attributes being used together. This gives rise to the pattern of code shown below which looks clean and understandable. [[using gnu:const, always_inline]] int f() { return 0; } Multiple attributes over a particular piece of code:Several attributes can now be applied to a certain piece of code in C++. The compiler, in that case, evaluates each of the attributes in the order they are written. This allows the programmers to write pieces of code that can contain multiple constraints.Example:#include <iostream> // Not implemented by compilers as of now// but will be implemented in the future[[nodiscard]] int f(int i)[[expects:i > 0]]{ std::cout << " Always greater than 0!" << " and return val must " << "always be utilized";} Several attributes can now be applied to a certain piece of code in C++. The compiler, in that case, evaluates each of the attributes in the order they are written. This allows the programmers to write pieces of code that can contain multiple constraints. Example: #include <iostream> // Not implemented by compilers as of now// but will be implemented in the future[[nodiscard]] int f(int i)[[expects:i > 0]]{ std::cout << " Always greater than 0!" << " and return val must " << "always be utilized";} There is a notable difference between attributes in C# and C++. In the case of C#, the programmer can define new attributes by deriving from System.Attribute; whereas in C++, the meta information is fixed by the compiler and cannot be used to define new user-defined attributes. This restriction is placed to prevent the language from evolving into a new form which could have made the language more complicated. CPP-Basics Technical Scripter 2018 C++ Technical Scripter CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Sorting a vector in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) Convert string to char array in C++ Iterators in C++ STL Inline Functions in C++ List in C++ Standard Template Library (STL) Multithreading in C++
[ { "code": null, "e": 24124, "s": 24096, "text": "\n05 Dec, 2018" }, { "code": null, "e": 24692, "s": 24124, "text": "Attributes are one of the key features of modern C++ which allows the programmer to specify additional information to the compiler to enforce constraints(conditions), optimise certain pieces of code or do some specific code generation. In simple terms, an attribute acts as an annotation or a note to the compiler which provides additional information about the code for optimization purposes and enforcing certain conditions on it. Introduced in C++11, they have remained one of the best features of C++ and are constantly being evolved with each new version of C++." }, { "code": null, "e": 24700, "s": 24692, "text": "Syntax:" }, { "code": null, "e": 24727, "s": 24700, "text": "// C++11[[attribute-list]]" }, { "code": null, "e": 24780, "s": 24727, "text": "// C++17[[using attribute-namespace:attribute-list]]" }, { "code": null, "e": 24865, "s": 24780, "text": "// Upcoming C++20[[contract-attribute-token contract-level identifier : expression]]" }, { "code": null, "e": 24984, "s": 24865, "text": "Except for some specific ones, most of the attributescan be applied with variables, functions, classes,structures etc." }, { "code": null, "e": 25487, "s": 24984, "text": "To enforce constraints on the code:Here constraint refers to a condition, that the arguments of a particular function must meet for its execution (precondition). In previous versions of C++, the code for specifying constraints was written in this mannerint f(int i){ if (i > 0) return i; else return -1; // Code}It increases the readability of your code and avoids the clutter that is written inside the function for argument checking.int f(int i)[[expects:i > 0]]{ // Code}" }, { "code": null, "e": 25706, "s": 25487, "text": "Here constraint refers to a condition, that the arguments of a particular function must meet for its execution (precondition). In previous versions of C++, the code for specifying constraints was written in this manner" }, { "code": "int f(int i){ if (i > 0) return i; else return -1; // Code}", "e": 25791, "s": 25706, "text": null }, { "code": null, "e": 25915, "s": 25791, "text": "It increases the readability of your code and avoids the clutter that is written inside the function for argument checking." }, { "code": "int f(int i)[[expects:i > 0]]{ // Code}", "e": 25958, "s": 25915, "text": null }, { "code": null, "e": 26856, "s": 25958, "text": "To give additional information to the compiler for optimisation purposes:Compilers are very good at optimization but compared to humans they still lag at some places and propose generalized code which is not very efficient. This mainly happens due to the lack of additional information about the “problem” which humans have. To reduce this problem to an extent C++ standard has introduced some new attributes that allow specifying a little more to the compiler rather than the code statement itself. Once such example is that of likely.int f(int i){ switch (i) { case 1: [[fallthrough]]; [[likely]] case 2 : return 1; } return -1;}When the statement is preceded by likely compiler makes special optimizations with respect to that statement which improves the overall performance of the code. Some examples of such attributes are [carries_dependency], [likely], [unlikely]" }, { "code": null, "e": 27320, "s": 26856, "text": "Compilers are very good at optimization but compared to humans they still lag at some places and propose generalized code which is not very efficient. This mainly happens due to the lack of additional information about the “problem” which humans have. To reduce this problem to an extent C++ standard has introduced some new attributes that allow specifying a little more to the compiler rather than the code statement itself. Once such example is that of likely." }, { "code": "int f(int i){ switch (i) { case 1: [[fallthrough]]; [[likely]] case 2 : return 1; } return -1;}", "e": 27442, "s": 27320, "text": null }, { "code": null, "e": 27683, "s": 27442, "text": "When the statement is preceded by likely compiler makes special optimizations with respect to that statement which improves the overall performance of the code. Some examples of such attributes are [carries_dependency], [likely], [unlikely]" }, { "code": null, "e": 28565, "s": 27683, "text": "Suppressing certain warnings and errors that programmer intended to have in his code:It happens rarely but sometimes the programmer intentionally tries to write a faulty code which gets detected by the compiler and is reported as an error or a warning. One such example is that of an unused variable which has been left in that state for a specific reason or of a switch statement where the break statements are not put after some cases to give rise to fall-through conditions. In order to circumvent errors and warnings on such conditions, C++ provides attributes such as [maybe_unused] and [fallthrough] that prevent the compiler from generating warnings or errors.#include <iostream>#include <string> int main(){ // Set debug mode in compiler or 'R' [[maybe_unused]] char mg_brk = 'D'; // Compiler does not emit any warnings // or error on this unused variable}" }, { "code": null, "e": 29148, "s": 28565, "text": "It happens rarely but sometimes the programmer intentionally tries to write a faulty code which gets detected by the compiler and is reported as an error or a warning. One such example is that of an unused variable which has been left in that state for a specific reason or of a switch statement where the break statements are not put after some cases to give rise to fall-through conditions. In order to circumvent errors and warnings on such conditions, C++ provides attributes such as [maybe_unused] and [fallthrough] that prevent the compiler from generating warnings or errors." }, { "code": "#include <iostream>#include <string> int main(){ // Set debug mode in compiler or 'R' [[maybe_unused]] char mg_brk = 'D'; // Compiler does not emit any warnings // or error on this unused variable}", "e": 29363, "s": 29148, "text": null }, { "code": null, "e": 35696, "s": 29363, "text": "C++11noreturn: indicates that the function does not return a valueUsage:[[noreturn]] void f();\nWhile looking at the code above, the question arises what is the point of having noreturn when the return type is actually void? If a function has a void type, then it actually returns to the caller without a value but if the case is such that the function never returns back to the caller (for example an infinite loop) then adding a noreturn attribute gives hints to the compiler to optimise the code or generate better warnings.Example:#include <iostream>#include <string> [[noreturn]] void f(){ // Some code that does not return // back the control to the caller // In this case the function returns // back to the caller without a value // This is the reason why the // warning \"noreturn' function does return' arises} void g(){ std::cout << \"Code is intented to reach here\";} int main(){ f(); g();}Warning:main.cpp: In function 'void f()':\nmain.cpp:8:1: warning: 'noreturn' function does return\n }\n ^\nC++14deprecated: Indicates that the name or entity declared with this attribute has become obsolete and must not be used for some specific reason. This attribute can be applied to namespaces, functions, classes structures or variables.Usage:[[deprecated(\"Reason for deprecation\")]]\n\n// For Class/Struct/Union\nstruct [[deprecated]] S;\n\n// For Functions\n[[deprecated]] void f();\n\n// For namespaces\nnamespace [[deprecated]] ns{}\n\n// For variables (including static data members)\n[[deprecated]] int x;\n\nExample:#include <iostream>#include <string> [[deprecated(\"Susceptible to buffer overflow\")]] void gets(char* str){ // Code for gets dummy // (Although original function has // char* as return type)} void gets_n(std::string& str){ // Dummy code char st[100]; std::cout << \"Successfully Executed\"; std::cin.getline(st, 100); str = std::string(st); // Code for new gets} int main(){ char a[100]; gets(a); // std::string str; // gets_n(str);}Warning:main.cpp: In function 'int main()':\nmain.cpp:26:9: warning: 'void gets(char*)' is deprecated:\n Susceptible to buffer overflow [-Wdeprecated-declarations]\n gets(a);\n ^\nC++17nodiscard: The entities declared with nodiscard should not have their return values ignored by the caller. Simply saying if a function returns a value and is marked nodiscard then the return value must be utilized by the caller and not discarded.Usage :// Functions\n[[nodiscard]] void f();\n\n// Class/Struct declaration \nstruct [[nodiscard]] my_struct{};\nThe main difference between nodiscard with functions and nodiscard with struct/class declaration is that in case of function, nodiscard applies to that particular function only which is declared no discard, whereas in case of class/struct declaration nodiscard applies to every single function that returns the nodiscard marked object by value.Example:#include <iostream>#include <string> // Return value must be utilized by the caller[[nodiscard]] int f(){ return 0;} class[[nodiscard]] my_class{}; // Automatically becomes nodiscard markedmy_class fun(){ return my_class();} int main(){ int x{ 1 }; // No error as value is utilised // x= f(); // Error : Value is not utilised f(); // Value not utilised error // fun() ; return x;}Warning:prog.cpp:5:21: warning: 'nodiscard' attribute directive ignored [-Wattributes]\n [[nodiscard]] int f()\n ^\nprog.cpp:10:20: warning: 'nodiscard' attribute directive ignored [-Wattributes]\n class[[nodiscard]] my_class{};\n ^\nmaybe_unused: Used to suppress warnings on any unused entities (For eg: An unused variable or an unused argument to a function).Usage://Variables\n[[maybe_used]] bool log_var = true;\n\n//Functions\n[[maybe_unused]] void log_without_warning();\n\n//Function arguments \nvoid f([[maybe_unused]] int a, int b);\nExample:#include <iostream>#include <string> int main(){ // Set debug mode in compiler or 'R' [[maybe_unused]] char mg_brk = 'D'; // Compiler does not emit any warnings // or error on this unused variable}fallthrough:[[fallthrough]] indicates that a fallthrough in a switch statement is intentional. Missing a break or return in a switch statement is usually considered a programmer’s error but in some cases fallthrough can result in some very terse code and hence it is used.Note: Unlike other attributes a fallthrough requires a semicolon after it is declared.Example:void process_alert(Alert alert){ switch (alert) { case Alert::Red: evacuate(); // Compiler emits a warning here // thinking it is done by mistake case Alert::Orange: trigger_alarm(); // this attribute needs semicolon [[fallthrough]]; // Warning suppressed by [[fallthrough]] case Alert::Yellow: record_alert(); return; case Alert::Green: return; }}Upcoming C++20 attributeslikely: For optimisation of certain statements that have more probability to execute than others. Likely is now available in latest version of GCC compiler for experimentation purposes.Exampleint f(int i){ switch (i) { case 1: [[fallthrough]]; [[likely]] case 2 : return 1; } return 2;}no_unique_address: Indicates that this data member need not have an address distinct from all other non-static data members of its class. This means that if the class consist of an empty type then the compiler can perform empty base optimisation on it.Example:// empty class ( No state!)struct Empty {}; struct X { int i; Empty e;}; struct Y { int i; [[no_unique_address]] Empty e;}; int main(){ // the size of any object of // empty class type is at least 1 static_assert(sizeof(Empty) >= 1); // at least one more byte is needed // to give e a unique address static_assert(sizeof(X) >= sizeof(int) + 1); // empty base optimization applied static_assert(sizeof(Y) == sizeof(int));}expects: It specifies the conditions (in form of contract) that the arguments must meet for a particular function to be executed.Usage:return_type func ( args...) [[expects : precondition]]\nExample:void list(node* n)[[expects:n != nullptr]]Violation of the contract results in invocation of violation handler or if not specified then std::terminate()" }, { "code": null, "e": 36729, "s": 35696, "text": "noreturn: indicates that the function does not return a valueUsage:[[noreturn]] void f();\nWhile looking at the code above, the question arises what is the point of having noreturn when the return type is actually void? If a function has a void type, then it actually returns to the caller without a value but if the case is such that the function never returns back to the caller (for example an infinite loop) then adding a noreturn attribute gives hints to the compiler to optimise the code or generate better warnings.Example:#include <iostream>#include <string> [[noreturn]] void f(){ // Some code that does not return // back the control to the caller // In this case the function returns // back to the caller without a value // This is the reason why the // warning \"noreturn' function does return' arises} void g(){ std::cout << \"Code is intented to reach here\";} int main(){ f(); g();}Warning:main.cpp: In function 'void f()':\nmain.cpp:8:1: warning: 'noreturn' function does return\n }\n ^\nC++14" }, { "code": null, "e": 36736, "s": 36729, "text": "Usage:" }, { "code": null, "e": 36760, "s": 36736, "text": "[[noreturn]] void f();\n" }, { "code": null, "e": 37192, "s": 36760, "text": "While looking at the code above, the question arises what is the point of having noreturn when the return type is actually void? If a function has a void type, then it actually returns to the caller without a value but if the case is such that the function never returns back to the caller (for example an infinite loop) then adding a noreturn attribute gives hints to the compiler to optimise the code or generate better warnings." }, { "code": null, "e": 37201, "s": 37192, "text": "Example:" }, { "code": "#include <iostream>#include <string> [[noreturn]] void f(){ // Some code that does not return // back the control to the caller // In this case the function returns // back to the caller without a value // This is the reason why the // warning \"noreturn' function does return' arises} void g(){ std::cout << \"Code is intented to reach here\";} int main(){ f(); g();}", "e": 37597, "s": 37201, "text": null }, { "code": null, "e": 37606, "s": 37597, "text": "Warning:" }, { "code": null, "e": 37702, "s": 37606, "text": "main.cpp: In function 'void f()':\nmain.cpp:8:1: warning: 'noreturn' function does return\n }\n ^\n" }, { "code": null, "e": 37708, "s": 37702, "text": "C++14" }, { "code": null, "e": 38878, "s": 37708, "text": "deprecated: Indicates that the name or entity declared with this attribute has become obsolete and must not be used for some specific reason. This attribute can be applied to namespaces, functions, classes structures or variables.Usage:[[deprecated(\"Reason for deprecation\")]]\n\n// For Class/Struct/Union\nstruct [[deprecated]] S;\n\n// For Functions\n[[deprecated]] void f();\n\n// For namespaces\nnamespace [[deprecated]] ns{}\n\n// For variables (including static data members)\n[[deprecated]] int x;\n\nExample:#include <iostream>#include <string> [[deprecated(\"Susceptible to buffer overflow\")]] void gets(char* str){ // Code for gets dummy // (Although original function has // char* as return type)} void gets_n(std::string& str){ // Dummy code char st[100]; std::cout << \"Successfully Executed\"; std::cin.getline(st, 100); str = std::string(st); // Code for new gets} int main(){ char a[100]; gets(a); // std::string str; // gets_n(str);}Warning:main.cpp: In function 'int main()':\nmain.cpp:26:9: warning: 'void gets(char*)' is deprecated:\n Susceptible to buffer overflow [-Wdeprecated-declarations]\n gets(a);\n ^\nC++17" }, { "code": null, "e": 38885, "s": 38878, "text": "Usage:" }, { "code": null, "e": 39144, "s": 38885, "text": "[[deprecated(\"Reason for deprecation\")]]\n\n// For Class/Struct/Union\nstruct [[deprecated]] S;\n\n// For Functions\n[[deprecated]] void f();\n\n// For namespaces\nnamespace [[deprecated]] ns{}\n\n// For variables (including static data members)\n[[deprecated]] int x;\n\n" }, { "code": null, "e": 39153, "s": 39144, "text": "Example:" }, { "code": "#include <iostream>#include <string> [[deprecated(\"Susceptible to buffer overflow\")]] void gets(char* str){ // Code for gets dummy // (Although original function has // char* as return type)} void gets_n(std::string& str){ // Dummy code char st[100]; std::cout << \"Successfully Executed\"; std::cin.getline(st, 100); str = std::string(st); // Code for new gets} int main(){ char a[100]; gets(a); // std::string str; // gets_n(str);}", "e": 39631, "s": 39153, "text": null }, { "code": null, "e": 39640, "s": 39631, "text": "Warning:" }, { "code": null, "e": 39818, "s": 39640, "text": "main.cpp: In function 'int main()':\nmain.cpp:26:9: warning: 'void gets(char*)' is deprecated:\n Susceptible to buffer overflow [-Wdeprecated-declarations]\n gets(a);\n ^\n" }, { "code": null, "e": 39824, "s": 39818, "text": "C++17" }, { "code": null, "e": 41218, "s": 39824, "text": "nodiscard: The entities declared with nodiscard should not have their return values ignored by the caller. Simply saying if a function returns a value and is marked nodiscard then the return value must be utilized by the caller and not discarded.Usage :// Functions\n[[nodiscard]] void f();\n\n// Class/Struct declaration \nstruct [[nodiscard]] my_struct{};\nThe main difference between nodiscard with functions and nodiscard with struct/class declaration is that in case of function, nodiscard applies to that particular function only which is declared no discard, whereas in case of class/struct declaration nodiscard applies to every single function that returns the nodiscard marked object by value.Example:#include <iostream>#include <string> // Return value must be utilized by the caller[[nodiscard]] int f(){ return 0;} class[[nodiscard]] my_class{}; // Automatically becomes nodiscard markedmy_class fun(){ return my_class();} int main(){ int x{ 1 }; // No error as value is utilised // x= f(); // Error : Value is not utilised f(); // Value not utilised error // fun() ; return x;}Warning:prog.cpp:5:21: warning: 'nodiscard' attribute directive ignored [-Wattributes]\n [[nodiscard]] int f()\n ^\nprog.cpp:10:20: warning: 'nodiscard' attribute directive ignored [-Wattributes]\n class[[nodiscard]] my_class{};\n ^\n" }, { "code": null, "e": 41226, "s": 41218, "text": "Usage :" }, { "code": null, "e": 41328, "s": 41226, "text": "// Functions\n[[nodiscard]] void f();\n\n// Class/Struct declaration \nstruct [[nodiscard]] my_struct{};\n" }, { "code": null, "e": 41673, "s": 41328, "text": "The main difference between nodiscard with functions and nodiscard with struct/class declaration is that in case of function, nodiscard applies to that particular function only which is declared no discard, whereas in case of class/struct declaration nodiscard applies to every single function that returns the nodiscard marked object by value." }, { "code": null, "e": 41682, "s": 41673, "text": "Example:" }, { "code": "#include <iostream>#include <string> // Return value must be utilized by the caller[[nodiscard]] int f(){ return 0;} class[[nodiscard]] my_class{}; // Automatically becomes nodiscard markedmy_class fun(){ return my_class();} int main(){ int x{ 1 }; // No error as value is utilised // x= f(); // Error : Value is not utilised f(); // Value not utilised error // fun() ; return x;}", "e": 42103, "s": 41682, "text": null }, { "code": null, "e": 42112, "s": 42103, "text": "Warning:" }, { "code": null, "e": 42372, "s": 42112, "text": "prog.cpp:5:21: warning: 'nodiscard' attribute directive ignored [-Wattributes]\n [[nodiscard]] int f()\n ^\nprog.cpp:10:20: warning: 'nodiscard' attribute directive ignored [-Wattributes]\n class[[nodiscard]] my_class{};\n ^\n" }, { "code": null, "e": 42897, "s": 42372, "text": "maybe_unused: Used to suppress warnings on any unused entities (For eg: An unused variable or an unused argument to a function).Usage://Variables\n[[maybe_used]] bool log_var = true;\n\n//Functions\n[[maybe_unused]] void log_without_warning();\n\n//Function arguments \nvoid f([[maybe_unused]] int a, int b);\nExample:#include <iostream>#include <string> int main(){ // Set debug mode in compiler or 'R' [[maybe_unused]] char mg_brk = 'D'; // Compiler does not emit any warnings // or error on this unused variable}" }, { "code": null, "e": 42904, "s": 42897, "text": "Usage:" }, { "code": null, "e": 43073, "s": 42904, "text": "//Variables\n[[maybe_used]] bool log_var = true;\n\n//Functions\n[[maybe_unused]] void log_without_warning();\n\n//Function arguments \nvoid f([[maybe_unused]] int a, int b);\n" }, { "code": null, "e": 43082, "s": 43073, "text": "Example:" }, { "code": "#include <iostream>#include <string> int main(){ // Set debug mode in compiler or 'R' [[maybe_unused]] char mg_brk = 'D'; // Compiler does not emit any warnings // or error on this unused variable}", "e": 43297, "s": 43082, "text": null }, { "code": null, "e": 44121, "s": 43297, "text": "fallthrough:[[fallthrough]] indicates that a fallthrough in a switch statement is intentional. Missing a break or return in a switch statement is usually considered a programmer’s error but in some cases fallthrough can result in some very terse code and hence it is used.Note: Unlike other attributes a fallthrough requires a semicolon after it is declared.Example:void process_alert(Alert alert){ switch (alert) { case Alert::Red: evacuate(); // Compiler emits a warning here // thinking it is done by mistake case Alert::Orange: trigger_alarm(); // this attribute needs semicolon [[fallthrough]]; // Warning suppressed by [[fallthrough]] case Alert::Yellow: record_alert(); return; case Alert::Green: return; }}Upcoming C++20 attributes" }, { "code": null, "e": 44208, "s": 44121, "text": "Note: Unlike other attributes a fallthrough requires a semicolon after it is declared." }, { "code": null, "e": 44217, "s": 44208, "text": "Example:" }, { "code": "void process_alert(Alert alert){ switch (alert) { case Alert::Red: evacuate(); // Compiler emits a warning here // thinking it is done by mistake case Alert::Orange: trigger_alarm(); // this attribute needs semicolon [[fallthrough]]; // Warning suppressed by [[fallthrough]] case Alert::Yellow: record_alert(); return; case Alert::Green: return; }}", "e": 44650, "s": 44217, "text": null }, { "code": null, "e": 44676, "s": 44650, "text": "Upcoming C++20 attributes" }, { "code": null, "e": 44989, "s": 44676, "text": "likely: For optimisation of certain statements that have more probability to execute than others. Likely is now available in latest version of GCC compiler for experimentation purposes.Exampleint f(int i){ switch (i) { case 1: [[fallthrough]]; [[likely]] case 2 : return 1; } return 2;}" }, { "code": null, "e": 44997, "s": 44989, "text": "Example" }, { "code": "int f(int i){ switch (i) { case 1: [[fallthrough]]; [[likely]] case 2 : return 1; } return 2;}", "e": 45118, "s": 44997, "text": null }, { "code": null, "e": 45843, "s": 45118, "text": "no_unique_address: Indicates that this data member need not have an address distinct from all other non-static data members of its class. This means that if the class consist of an empty type then the compiler can perform empty base optimisation on it.Example:// empty class ( No state!)struct Empty {}; struct X { int i; Empty e;}; struct Y { int i; [[no_unique_address]] Empty e;}; int main(){ // the size of any object of // empty class type is at least 1 static_assert(sizeof(Empty) >= 1); // at least one more byte is needed // to give e a unique address static_assert(sizeof(X) >= sizeof(int) + 1); // empty base optimization applied static_assert(sizeof(Y) == sizeof(int));}" }, { "code": null, "e": 45852, "s": 45843, "text": "Example:" }, { "code": "// empty class ( No state!)struct Empty {}; struct X { int i; Empty e;}; struct Y { int i; [[no_unique_address]] Empty e;}; int main(){ // the size of any object of // empty class type is at least 1 static_assert(sizeof(Empty) >= 1); // at least one more byte is needed // to give e a unique address static_assert(sizeof(X) >= sizeof(int) + 1); // empty base optimization applied static_assert(sizeof(Y) == sizeof(int));}", "e": 46317, "s": 45852, "text": null }, { "code": null, "e": 46668, "s": 46317, "text": "expects: It specifies the conditions (in form of contract) that the arguments must meet for a particular function to be executed.Usage:return_type func ( args...) [[expects : precondition]]\nExample:void list(node* n)[[expects:n != nullptr]]Violation of the contract results in invocation of violation handler or if not specified then std::terminate()" }, { "code": null, "e": 46675, "s": 46668, "text": "Usage:" }, { "code": null, "e": 46731, "s": 46675, "text": "return_type func ( args...) [[expects : precondition]]\n" }, { "code": null, "e": 46740, "s": 46731, "text": "Example:" }, { "code": "void list(node* n)[[expects:n != nullptr]]", "e": 46783, "s": 46740, "text": null }, { "code": null, "e": 46894, "s": 46783, "text": "Violation of the contract results in invocation of violation handler or if not specified then std::terminate()" }, { "code": null, "e": 48227, "s": 46894, "text": "Ignoring unknown attributes:Since C++17, one of the major changes introduced for the attribute feature in C++ were regarding the clarification of unknown attributes by the compiler. In C++11 or 14, if an attribute was not recognized by the compiler, then it would produce an error and prevent the code from getting compiled. As a workaround, the programmer had to remove the attribute from the code to make it work. This introduced a major issue for portability. Apart from the standard attributes none of the vendor-specific attributes could be used, as the code would break. This prevented the actual use of this feature.As a solution, the standard made it compulsory for all the compilers to ignore the attributes that were not defined by them. This allowed the programmers to use vendor-specific attributes freely in their code and ensure that the code was still portable. Most of the compilers supporting C++17 now ignore the undefined attributes and produce a warning on when encountered. This allows the programmers to make the code more flexible as now, they can specify multiple attributes for the same operation under different vendor’s namespaces. (Support: MSVC(NOT YET), GCC, CLANG (YES))Example:// Here the attributes will work on their respective[[msvc::deprecated]][[gnu::deprecated]] char* gets(char* str) compilers" }, { "code": null, "e": 48823, "s": 48227, "text": "Since C++17, one of the major changes introduced for the attribute feature in C++ were regarding the clarification of unknown attributes by the compiler. In C++11 or 14, if an attribute was not recognized by the compiler, then it would produce an error and prevent the code from getting compiled. As a workaround, the programmer had to remove the attribute from the code to make it work. This introduced a major issue for portability. Apart from the standard attributes none of the vendor-specific attributes could be used, as the code would break. This prevented the actual use of this feature." }, { "code": null, "e": 49402, "s": 48823, "text": "As a solution, the standard made it compulsory for all the compilers to ignore the attributes that were not defined by them. This allowed the programmers to use vendor-specific attributes freely in their code and ensure that the code was still portable. Most of the compilers supporting C++17 now ignore the undefined attributes and produce a warning on when encountered. This allows the programmers to make the code more flexible as now, they can specify multiple attributes for the same operation under different vendor’s namespaces. (Support: MSVC(NOT YET), GCC, CLANG (YES))" }, { "code": null, "e": 49411, "s": 49402, "text": "Example:" }, { "code": "// Here the attributes will work on their respective[[msvc::deprecated]][[gnu::deprecated]] char* gets(char* str) compilers", "e": 49535, "s": 49411, "text": null }, { "code": null, "e": 50459, "s": 49535, "text": "Use of attribute namespaces without repetition:In C++17 some of the rules regarding the use of “non-standard” attributes were relaxed. One such case is that of prefixing namespaces with a subsequent non-standard attribute. In C++11 or 14 when multiple attributes were written together each one of them had to be prefixed with their enclosing namespaces which gave rise to the pattern of code as shown below.[[ gnu::always_inline, gnu::const, gnu::hot, nodiscard ]] int f();Looking at the code above, it can be seen that it seems bloated and cluttered. So the committee decided to “simplify the case when using multiple attributes” together. As of now, it is not mandatory for the programmer to prefix the namespace again and again with subsequent attributes being used together. This gives rise to the pattern of code shown below which looks clean and understandable.[[using gnu:const, always_inline]] int f() { return 0; }" }, { "code": null, "e": 50820, "s": 50459, "text": "In C++17 some of the rules regarding the use of “non-standard” attributes were relaxed. One such case is that of prefixing namespaces with a subsequent non-standard attribute. In C++11 or 14 when multiple attributes were written together each one of them had to be prefixed with their enclosing namespaces which gave rise to the pattern of code as shown below." }, { "code": "[[ gnu::always_inline, gnu::const, gnu::hot, nodiscard ]] int f();", "e": 50887, "s": 50820, "text": null }, { "code": null, "e": 51282, "s": 50887, "text": "Looking at the code above, it can be seen that it seems bloated and cluttered. So the committee decided to “simplify the case when using multiple attributes” together. As of now, it is not mandatory for the programmer to prefix the namespace again and again with subsequent attributes being used together. This gives rise to the pattern of code shown below which looks clean and understandable." }, { "code": "[[using gnu:const, always_inline]] int f() { return 0; }", "e": 51339, "s": 51282, "text": null }, { "code": null, "e": 51922, "s": 51339, "text": "Multiple attributes over a particular piece of code:Several attributes can now be applied to a certain piece of code in C++. The compiler, in that case, evaluates each of the attributes in the order they are written. This allows the programmers to write pieces of code that can contain multiple constraints.Example:#include <iostream> // Not implemented by compilers as of now// but will be implemented in the future[[nodiscard]] int f(int i)[[expects:i > 0]]{ std::cout << \" Always greater than 0!\" << \" and return val must \" << \"always be utilized\";}" }, { "code": null, "e": 52178, "s": 51922, "text": "Several attributes can now be applied to a certain piece of code in C++. The compiler, in that case, evaluates each of the attributes in the order they are written. This allows the programmers to write pieces of code that can contain multiple constraints." }, { "code": null, "e": 52187, "s": 52178, "text": "Example:" }, { "code": "#include <iostream> // Not implemented by compilers as of now// but will be implemented in the future[[nodiscard]] int f(int i)[[expects:i > 0]]{ std::cout << \" Always greater than 0!\" << \" and return val must \" << \"always be utilized\";}", "e": 52455, "s": 52187, "text": null }, { "code": null, "e": 52868, "s": 52455, "text": "There is a notable difference between attributes in C# and C++. In the case of C#, the programmer can define new attributes by deriving from System.Attribute; whereas in C++, the meta information is fixed by the compiler and cannot be used to define new user-defined attributes. This restriction is placed to prevent the language from evolving into a new form which could have made the language more complicated." }, { "code": null, "e": 52879, "s": 52868, "text": "CPP-Basics" }, { "code": null, "e": 52903, "s": 52879, "text": "Technical Scripter 2018" }, { "code": null, "e": 52907, "s": 52903, "text": "C++" }, { "code": null, "e": 52926, "s": 52907, "text": "Technical Scripter" }, { "code": null, "e": 52930, "s": 52926, "text": "CPP" }, { "code": null, "e": 53028, "s": 52930, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 53056, "s": 53028, "text": "Operator Overloading in C++" }, { "code": null, "e": 53076, "s": 53056, "text": "Polymorphism in C++" }, { "code": null, "e": 53100, "s": 53076, "text": "Sorting a vector in C++" }, { "code": null, "e": 53133, "s": 53100, "text": "Friend class and function in C++" }, { "code": null, "e": 53177, "s": 53133, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 53213, "s": 53177, "text": "Convert string to char array in C++" }, { "code": null, "e": 53234, "s": 53213, "text": "Iterators in C++ STL" }, { "code": null, "e": 53258, "s": 53234, "text": "Inline Functions in C++" }, { "code": null, "e": 53302, "s": 53258, "text": "List in C++ Standard Template Library (STL)" } ]
Check if concatenation of two strings is balanced or not in Python
Suppose we have two bracket sequences s and t with only these characters '(' and ')'. We have to check whether the concatenated string of s and t is balanced or not. The concatenation can be done by s | t or t | s. So, if the input is like s = "()()))", t = "()(()(", then the output will be True because if we concatenate t | s, then we will get "()(()(()()))", which is balanced. To solve this, we will follow these steps − Define a function is_balanced_parenthesis() . This will take string stack := a new list for i in range 0 to size of string, doif string[i] is same as '(', thenpush string[i] into stackotherwise,if stack is empty, thenreturn Falseotherwise,pop from stack if string[i] is same as '(', thenpush string[i] into stack push string[i] into stack otherwise,if stack is empty, thenreturn Falseotherwise,pop from stack if stack is empty, thenreturn False return False otherwise,pop from stack pop from stack if stack is not empty, thenreturn False return False return True From the main method do the following − if is_balanced_parenthesis(s + t) is true, thenreturn True return True return is_balanced_parenthesis(t + s) Let us see the following implementation to get better understanding − Live Demo def is_balanced_parenthesis(string): stack = [] for i in range(len(string)): if string[i] == '(': stack.append(string[i]) else: if len(stack) == 0: return False else: stack.pop() if len(stack) > 0: return False return True def solve(s, t): if is_balanced_parenthesis(s + t): return True return is_balanced_parenthesis(t + s) s = "()()))" t = "()(()(" print(solve(s, t)) "()()))", "()(()(" True
[ { "code": null, "e": 1277, "s": 1062, "text": "Suppose we have two bracket sequences s and t with only these characters '(' and ')'. We have to check whether the concatenated string of s and t is balanced or not. The concatenation can be done by s | t or t | s." }, { "code": null, "e": 1444, "s": 1277, "text": "So, if the input is like s = \"()()))\", t = \"()(()(\", then the output will be True because if we concatenate t | s, then we will get \"()(()(()()))\", which is balanced." }, { "code": null, "e": 1488, "s": 1444, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1556, "s": 1488, "text": "Define a function is_balanced_parenthesis() . This will take string" }, { "code": null, "e": 1576, "s": 1556, "text": "stack := a new list" }, { "code": null, "e": 1742, "s": 1576, "text": "for i in range 0 to size of string, doif string[i] is same as '(', thenpush string[i] into stackotherwise,if stack is empty, thenreturn Falseotherwise,pop from stack" }, { "code": null, "e": 1801, "s": 1742, "text": "if string[i] is same as '(', thenpush string[i] into stack" }, { "code": null, "e": 1827, "s": 1801, "text": "push string[i] into stack" }, { "code": null, "e": 1897, "s": 1827, "text": "otherwise,if stack is empty, thenreturn Falseotherwise,pop from stack" }, { "code": null, "e": 1933, "s": 1897, "text": "if stack is empty, thenreturn False" }, { "code": null, "e": 1946, "s": 1933, "text": "return False" }, { "code": null, "e": 1971, "s": 1946, "text": "otherwise,pop from stack" }, { "code": null, "e": 1986, "s": 1971, "text": "pop from stack" }, { "code": null, "e": 2026, "s": 1986, "text": "if stack is not empty, thenreturn False" }, { "code": null, "e": 2039, "s": 2026, "text": "return False" }, { "code": null, "e": 2051, "s": 2039, "text": "return True" }, { "code": null, "e": 2091, "s": 2051, "text": "From the main method do the following −" }, { "code": null, "e": 2150, "s": 2091, "text": "if is_balanced_parenthesis(s + t) is true, thenreturn True" }, { "code": null, "e": 2162, "s": 2150, "text": "return True" }, { "code": null, "e": 2200, "s": 2162, "text": "return is_balanced_parenthesis(t + s)" }, { "code": null, "e": 2270, "s": 2200, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2281, "s": 2270, "text": " Live Demo" }, { "code": null, "e": 2744, "s": 2281, "text": "def is_balanced_parenthesis(string):\n stack = []\n for i in range(len(string)):\n if string[i] == '(':\n stack.append(string[i])\n else:\n if len(stack) == 0:\n return False\n else:\n stack.pop()\n if len(stack) > 0:\n return False\n return True\ndef solve(s, t):\n if is_balanced_parenthesis(s + t):\n return True\n return is_balanced_parenthesis(t + s)\ns = \"()()))\"\nt = \"()(()(\"\nprint(solve(s, t))" }, { "code": null, "e": 2763, "s": 2744, "text": "\"()()))\", \"()(()(\"" }, { "code": null, "e": 2768, "s": 2763, "text": "True" } ]
Chained exception in Java
Chained exception helps to relate one exception to other. Often we need to throw a custom exception and want to keep the details of an original exception that in such scenarios we can use the chained exception mechanism. Consider the following example, where we are throwing a custom exception while keeping the message of the original exception. Live Demo public class Tester { public static void main(String[] args) { try { test(); }catch(ApplicationException e) { System.out.println(e.getMessage()); } } public static void test() throws ApplicationException { try { int a = 0; int b = 1; System.out.println(b/a); }catch(Exception e) { throw new ApplicationException(e); } } } class ApplicationException extends Exception { public ApplicationException(Exception e) { super(e); } } java.lang.ArithmeticException: / by zero The throwable class supports chained exception using the following methods: Throwable(Throwable cause) - the cause is the current exception. Throwable(Throwable cause) - the cause is the current exception. Throwable(String msg, Throwable cause) - msg is the exception message, the cause is the current exception. Throwable(String msg, Throwable cause) - msg is the exception message, the cause is the current exception. getCause - returns actual cause. getCause - returns actual cause. initCause(Throwable cause) - sets the cause for calling an exception. initCause(Throwable cause) - sets the cause for calling an exception.
[ { "code": null, "e": 1409, "s": 1062, "text": "Chained exception helps to relate one exception to other. Often we need to throw a custom exception and want to keep the details of an original exception that in such scenarios we can use the chained exception mechanism. Consider the following example, where we are throwing a custom exception while keeping the message of the original exception." }, { "code": null, "e": 1419, "s": 1409, "text": "Live Demo" }, { "code": null, "e": 1983, "s": 1419, "text": "public class Tester {\n public static void main(String[] args) {\n try {\n test();\n }catch(ApplicationException e) { \n System.out.println(e.getMessage());\n }\n } \n\n public static void test() throws ApplicationException {\n try {\n int a = 0;\n int b = 1;\n System.out.println(b/a);\n }catch(Exception e) {\n throw new ApplicationException(e);\n }\n }\n}\n\nclass ApplicationException extends Exception {\n public ApplicationException(Exception e) { \n super(e);\n }\n}" }, { "code": null, "e": 2024, "s": 1983, "text": "java.lang.ArithmeticException: / by zero" }, { "code": null, "e": 2100, "s": 2024, "text": "The throwable class supports chained exception using the following methods:" }, { "code": null, "e": 2165, "s": 2100, "text": "Throwable(Throwable cause) - the cause is the current exception." }, { "code": null, "e": 2230, "s": 2165, "text": "Throwable(Throwable cause) - the cause is the current exception." }, { "code": null, "e": 2337, "s": 2230, "text": "Throwable(String msg, Throwable cause) - msg is the exception message, the cause is the current exception." }, { "code": null, "e": 2444, "s": 2337, "text": "Throwable(String msg, Throwable cause) - msg is the exception message, the cause is the current exception." }, { "code": null, "e": 2477, "s": 2444, "text": "getCause - returns actual cause." }, { "code": null, "e": 2510, "s": 2477, "text": "getCause - returns actual cause." }, { "code": null, "e": 2580, "s": 2510, "text": "initCause(Throwable cause) - sets the cause for calling an exception." }, { "code": null, "e": 2650, "s": 2580, "text": "initCause(Throwable cause) - sets the cause for calling an exception." } ]
COBOL - Data Types
Data Division is used to define the variables used in a program. To describe data in COBOL, one must understand the following terms − Data Name Level Number Picture Clause Value Clause 01 TOTAL-STUDENTS PIC9(5) VALUE '125'. | | | | | | | | | | | | Level Number Data Name Picture Clause Value Clause Data names must be defined in the Data Division before using them in the Procedure Division. They must have a user-defined name; reserved words cannot be used. Data names give reference to the memory locations where actual data is stored. They can be elementary or group type. The following example shows valid and invalid data names − Valid: WS-NAME TOTAL-STUDENTS A100 100B Invalid: MOVE (Reserved Words) COMPUTE (Reserved Words) 100 (No Alphabet) 100+B (+ is not allowed) Level number is used to specify the level of data in a record. They are used to differentiate between elementary items and group items. Elementary items can be grouped together to create group items. 01 Record description entry 02 to 49 Group and Elementary items 66 Rename Clause items 77 Items which cannot be sub-divided 88 Condition name entry Elementary items cannot be divided further. Level number, Data name, Picture clause, and Value clause (optional) are used to describe an elementary item. Elementary items cannot be divided further. Level number, Data name, Picture clause, and Value clause (optional) are used to describe an elementary item. Group items consist of one or more elementary items. Level number, Data name, and Value clause (optional) are used to describe a group item. Group level number is always 01. Group items consist of one or more elementary items. Level number, Data name, and Value clause (optional) are used to describe a group item. Group level number is always 01. The following example shows Group and Elementary items − DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-NAME PIC X(25). ---> ELEMENTARY ITEM 01 WS-CLASS PIC 9(2) VALUE '10'. ---> ELEMENTARY ITEM 01 WS-ADDRESS. ---> GROUP ITEM 05 WS-HOUSE-NUMBER PIC 9(3). ---> ELEMENTARY ITEM 05 WS-STREET PIC X(15). ---> ELEMENTARY ITEM 05 WS-CITY PIC X(15). ---> ELEMENTARY ITEM 05 WS-COUNTRY PIC X(15) VALUE 'INDIA'. ---> ELEMENTARY ITEM Picture clause is used to define the following items − Data type can be numeric, alphabetic, or alphanumeric. Numeric type consists of only digits 0 to 9. Alphabetic type consists of letters A to Z and spaces. Alphanumeric type consists of digits, letters, and special characters. Data type can be numeric, alphabetic, or alphanumeric. Numeric type consists of only digits 0 to 9. Alphabetic type consists of letters A to Z and spaces. Alphanumeric type consists of digits, letters, and special characters. Sign can be used with numeric data. It can be either + or –. Sign can be used with numeric data. It can be either + or –. Decimal point position can be used with numeric data. Assumed position is the position of decimal point and not included in the data. Decimal point position can be used with numeric data. Assumed position is the position of decimal point and not included in the data. Length defines the number of bytes used by the data item. Length defines the number of bytes used by the data item. Symbols used in a Picture clause − 9 Numeric A Alphabetic X Alphanumeric V Implicit Decimal S Sign P Assumed Decimal The following example shows the use of PIC clause − IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-NUM1 PIC S9(3)V9(2). 01 WS-NUM2 PIC PPP999. 01 WS-NUM3 PIC S9(3)V9(2) VALUE -123.45. 01 WS-NAME PIC A(6) VALUE 'ABCDEF'. 01 WS-ID PIC X(5) VALUE 'A121$'. PROCEDURE DIVISION. DISPLAY "WS-NUM1 : "WS-NUM1. DISPLAY "WS-NUM2 : "WS-NUM2. DISPLAY "WS-NUM3 : "WS-NUM3. DISPLAY "WS-NAME : "WS-NAME. DISPLAY "WS-ID : "WS-ID. STOP RUN. JCL to execute the above COBOL program − //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = HELLO When you compile and execute the above program, it produces the following result − WS-NUM1 : +000.00 WS-NUM2 : .000000 WS-NUM3 : -123.45 WS-NAME : ABCDEF WS-ID : A121$ Value clause is an optional clause which is used to initialize the data items. The values can be numeric literal, alphanumeric literal, or figurative constant. It can be used with both group and elementary items. The following example shows the use of VALUE clause − IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-NUM1 PIC 99V9 VALUE IS 3.5. 01 WS-NAME PIC A(6) VALUE 'ABCD'. 01 WS-ID PIC 99 VALUE ZERO. PROCEDURE DIVISION. DISPLAY "WS-NUM1 : "WS-NUM1. DISPLAY "WS-NAME : "WS-NAME. DISPLAY "WS-ID : "WS-ID. STOP RUN. JCL to execute the above COBOL program − //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = HELLO When you compile and execute the above program, it produces the following result − WS-NUM1 : 03.5 WS-NAME : ABCD WS-ID : 00 12 Lectures 2.5 hours Nishant Malik 33 Lectures 3.5 hours Craig Kenneth Kaercher Print Add Notes Bookmark this page
[ { "code": null, "e": 2156, "s": 2022, "text": "Data Division is used to define the variables used in a program. To describe data in COBOL, one must understand the following terms −" }, { "code": null, "e": 2166, "s": 2156, "text": "Data Name" }, { "code": null, "e": 2179, "s": 2166, "text": "Level Number" }, { "code": null, "e": 2194, "s": 2179, "text": "Picture Clause" }, { "code": null, "e": 2207, "s": 2194, "text": "Value Clause" }, { "code": null, "e": 2547, "s": 2207, "text": "01 TOTAL-STUDENTS PIC9(5) VALUE '125'.\n| | | |\n| | | |\n| | | | \nLevel Number Data Name Picture Clause Value Clause\n" }, { "code": null, "e": 2824, "s": 2547, "text": "Data names must be defined in the Data Division before using them in the Procedure Division. They must have a user-defined name; reserved words cannot be used. Data names give reference to the memory locations where actual data is stored. They can be elementary or group type." }, { "code": null, "e": 2883, "s": 2824, "text": "The following example shows valid and invalid data names −" }, { "code": null, "e": 3089, "s": 2883, "text": "Valid:\n WS-NAME\n TOTAL-STUDENTS\n A100\n 100B\n\nInvalid:\n MOVE (Reserved Words)\n COMPUTE (Reserved Words)\n 100 (No Alphabet)\n 100+B (+ is not allowed) " }, { "code": null, "e": 3289, "s": 3089, "text": "Level number is used to specify the level of data in a record. They are used to differentiate between elementary items and group items. Elementary items can be grouped together to create group items." }, { "code": null, "e": 3292, "s": 3289, "text": "01" }, { "code": null, "e": 3317, "s": 3292, "text": "Record description entry" }, { "code": null, "e": 3326, "s": 3317, "text": "02 to 49" }, { "code": null, "e": 3353, "s": 3326, "text": "Group and Elementary items" }, { "code": null, "e": 3356, "s": 3353, "text": "66" }, { "code": null, "e": 3376, "s": 3356, "text": "Rename Clause items" }, { "code": null, "e": 3379, "s": 3376, "text": "77" }, { "code": null, "e": 3413, "s": 3379, "text": "Items which cannot be sub-divided" }, { "code": null, "e": 3416, "s": 3413, "text": "88" }, { "code": null, "e": 3437, "s": 3416, "text": "Condition name entry" }, { "code": null, "e": 3591, "s": 3437, "text": "Elementary items cannot be divided further. Level number, Data name, Picture clause, and Value clause (optional) are used to describe an elementary item." }, { "code": null, "e": 3745, "s": 3591, "text": "Elementary items cannot be divided further. Level number, Data name, Picture clause, and Value clause (optional) are used to describe an elementary item." }, { "code": null, "e": 3919, "s": 3745, "text": "Group items consist of one or more elementary items. Level number, Data name, and Value clause (optional) are used to describe a group item. Group level number is always 01." }, { "code": null, "e": 4093, "s": 3919, "text": "Group items consist of one or more elementary items. Level number, Data name, and Value clause (optional) are used to describe a group item. Group level number is always 01." }, { "code": null, "e": 4150, "s": 4093, "text": "The following example shows Group and Elementary items −" }, { "code": null, "e": 4722, "s": 4150, "text": "DATA DIVISION.\nWORKING-STORAGE SECTION.\n01 WS-NAME PIC X(25). ---> ELEMENTARY ITEM \n01 WS-CLASS PIC 9(2) VALUE '10'. ---> ELEMENTARY ITEM\n\n01 WS-ADDRESS. ---> GROUP ITEM \n 05 WS-HOUSE-NUMBER PIC 9(3). ---> ELEMENTARY ITEM\n 05 WS-STREET PIC X(15). ---> ELEMENTARY ITEM\n 05 WS-CITY PIC X(15). ---> ELEMENTARY ITEM\n 05 WS-COUNTRY PIC X(15) VALUE 'INDIA'. ---> ELEMENTARY ITEM" }, { "code": null, "e": 4777, "s": 4722, "text": "Picture clause is used to define the following items −" }, { "code": null, "e": 5003, "s": 4777, "text": "Data type can be numeric, alphabetic, or alphanumeric. Numeric type consists of only digits 0 to 9. Alphabetic type consists of letters A to Z and spaces. Alphanumeric type consists of digits, letters, and special characters." }, { "code": null, "e": 5229, "s": 5003, "text": "Data type can be numeric, alphabetic, or alphanumeric. Numeric type consists of only digits 0 to 9. Alphabetic type consists of letters A to Z and spaces. Alphanumeric type consists of digits, letters, and special characters." }, { "code": null, "e": 5290, "s": 5229, "text": "Sign can be used with numeric data. It can be either + or –." }, { "code": null, "e": 5351, "s": 5290, "text": "Sign can be used with numeric data. It can be either + or –." }, { "code": null, "e": 5485, "s": 5351, "text": "Decimal point position can be used with numeric data. Assumed position is the position of decimal point and not included in the data." }, { "code": null, "e": 5619, "s": 5485, "text": "Decimal point position can be used with numeric data. Assumed position is the position of decimal point and not included in the data." }, { "code": null, "e": 5677, "s": 5619, "text": "Length defines the number of bytes used by the data item." }, { "code": null, "e": 5735, "s": 5677, "text": "Length defines the number of bytes used by the data item." }, { "code": null, "e": 5770, "s": 5735, "text": "Symbols used in a Picture clause −" }, { "code": null, "e": 5772, "s": 5770, "text": "9" }, { "code": null, "e": 5780, "s": 5772, "text": "Numeric" }, { "code": null, "e": 5782, "s": 5780, "text": "A" }, { "code": null, "e": 5793, "s": 5782, "text": "Alphabetic" }, { "code": null, "e": 5795, "s": 5793, "text": "X" }, { "code": null, "e": 5808, "s": 5795, "text": "Alphanumeric" }, { "code": null, "e": 5810, "s": 5808, "text": "V" }, { "code": null, "e": 5827, "s": 5810, "text": "Implicit Decimal" }, { "code": null, "e": 5829, "s": 5827, "text": "S" }, { "code": null, "e": 5834, "s": 5829, "text": "Sign" }, { "code": null, "e": 5836, "s": 5834, "text": "P" }, { "code": null, "e": 5852, "s": 5836, "text": "Assumed Decimal" }, { "code": null, "e": 5904, "s": 5852, "text": "The following example shows the use of PIC clause −" }, { "code": null, "e": 6354, "s": 5904, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nDATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 WS-NUM1 PIC S9(3)V9(2).\n 01 WS-NUM2 PIC PPP999.\n 01 WS-NUM3 PIC S9(3)V9(2) VALUE -123.45.\n 01 WS-NAME PIC A(6) VALUE 'ABCDEF'.\n 01 WS-ID PIC X(5) VALUE 'A121$'.\n\nPROCEDURE DIVISION.\n DISPLAY \"WS-NUM1 : \"WS-NUM1.\n DISPLAY \"WS-NUM2 : \"WS-NUM2.\n DISPLAY \"WS-NUM3 : \"WS-NUM3.\n DISPLAY \"WS-NAME : \"WS-NAME.\n DISPLAY \"WS-ID : \"WS-ID.\nSTOP RUN." }, { "code": null, "e": 6395, "s": 6354, "text": "JCL to execute the above COBOL program −" }, { "code": null, "e": 6472, "s": 6395, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = HELLO" }, { "code": null, "e": 6555, "s": 6472, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 6641, "s": 6555, "text": "WS-NUM1 : +000.00\nWS-NUM2 : .000000\nWS-NUM3 : -123.45\nWS-NAME : ABCDEF\nWS-ID : A121$\n" }, { "code": null, "e": 6854, "s": 6641, "text": "Value clause is an optional clause which is used to initialize the data items. The values can be numeric literal, alphanumeric literal, or figurative constant. It can be used with both group and elementary items." }, { "code": null, "e": 6908, "s": 6854, "text": "The following example shows the use of VALUE clause −" }, { "code": null, "e": 7226, "s": 6908, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nDATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 WS-NUM1 PIC 99V9 VALUE IS 3.5.\n 01 WS-NAME PIC A(6) VALUE 'ABCD'.\n 01 WS-ID PIC 99 VALUE ZERO.\n\nPROCEDURE DIVISION.\n DISPLAY \"WS-NUM1 : \"WS-NUM1.\n DISPLAY \"WS-NAME : \"WS-NAME.\n DISPLAY \"WS-ID : \"WS-ID.\nSTOP RUN." }, { "code": null, "e": 7267, "s": 7226, "text": "JCL to execute the above COBOL program −" }, { "code": null, "e": 7344, "s": 7267, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = HELLO" }, { "code": null, "e": 7427, "s": 7344, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 7471, "s": 7427, "text": "WS-NUM1 : 03.5\nWS-NAME : ABCD\nWS-ID : 00\n" }, { "code": null, "e": 7506, "s": 7471, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7521, "s": 7506, "text": " Nishant Malik" }, { "code": null, "e": 7556, "s": 7521, "text": "\n 33 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7580, "s": 7556, "text": " Craig Kenneth Kaercher" }, { "code": null, "e": 7587, "s": 7580, "text": " Print" }, { "code": null, "e": 7598, "s": 7587, "text": " Add Notes" } ]
Stream your data changes in MySQL into ElasticSearch using Debezium, Kafka, and Confluent JDBC Sink Connector | by Rizqi Nugroho | Towards Data Science
Fast search capability, realtime integrated data, nowadays is a necessity if we want to build something like e-catalog or e-commerce. We don’t want our users to get angry because they spend a lot of time just to get information from our portal. We also want the product information that inputted by our product team in the different applications immediately ready to search by our users or customers. Say the product team using MySQL as the main data source. And we will use ElasticSearch as a search engine service in our portal. We need every change in MySQL will immediately affect the ElasticSearch Index. How to achieve that requirement? In this my first article, I will demonstrate how can we stream our data changes in MySQL into ElasticSearch using Debezium, Kafka, and Confluent JDBC Sink Connector to achieve the above use case requirement. Credit to my master Erfin Feluzy that introduce me to Debezium and give me the inspiration to write my first article on medium. Debezium is a distributed platform that turns your existing databases into event streams, so applications can quickly react to each row-level change in the databases. Debezium is built on top of Kafka and provides Kafka Connect compatible connectors that monitor specific database management systems. Debezium records the history of data changes in Kafka logs, so your application can be stopped and restarted at any time and can easily consume all of the events it missed while it was not running, ensuring that all events are processed correctly and completely. Debezium is open source under the Apache License, Version 2.0 Apache Kafka is an open-source stream-processing software platform developed by LinkedIn and donated to the Apache Software Foundation, written in Scala and Java. The project aims to provide a unified, high-throughput, low-latency platform for handling real-time data feeds. The Kafka Connect Elasticsearch sink connector allows moving data from Apache Kafka® to Elasticsearch. It writes data from a topic in Apache Kafka® to an index in Elasticsearch and all data for a topic have the same In this tutorial, we will use a separate container for each service and don’t use persistent volume. ZooKeeper and Kafka would typically store their data locally inside the containers, which would require you to mount directories on the host machine as volumes. So in this tutorial, all persisted data is lost when a container is stopped Start zookeeper in the container using debezium/zookeeper image. The container will run with the name zookeeperdbz > docker run -it — name zookeeperdbz -p 2181:2181 -p 2888:2888 -p 3888:3888 debezium/zookeeper:1.1 check the run log to verify zookeeper run successfully and listening on port 2181 Starting up in standalone modeZooKeeper JMX enabled by defaultUsing config: /zookeeper/conf/zoo.cfg...020-05-13 17:18:28,564 - INFO [main:NIOServerCnxnFactory@686] - binding to port 0.0.0.0/0.0.0.0:2181 Start Kafka in the container using debezium/kafka docker image. The container will run with the name kafkadbz > docker run -it — name kafkadbz -p 9092:9092 --link zookeeperdbz:zookeeperdbz debezium/kafka verify Kafka server started In this demonstration, I will use a pre-configured Docker image that also contains sample data provided by Debezium. Start MySQL in a container using debezium/example-mysql image. The container will run with name mysqldbz > docker run -it -d --name mysqldbz -p 3306:3306 -e MYSQL_ROOT_PASSWORD=debezium -e MYSQL_USER=mysqluser -e MYSQL_PASSWORD=mysqlpw debezium/example-mysql the above command will create a container named mysqldbz. Next, let's execute the container and enter the interactive bash shell on the container. > docker exec -it mysqldbz /bin/bash To use capture the CDC on MySQL, Debezium needs bin_log configuration in our MySQL enabled. Thanks to Debezium, since we’re using a pre-configured MySQL Docker image, we don’t need to configure it anymore. Let’s check the configuration. # more /etc/mysql/conf.d/mysql.cnf As you can see, bin_log enabled, by default it's disabled. Check the sample DB # mysql -u root -p Enter password: <enter your password>mysql> use inventoryDatabase changedmysql> show tables;+---------------------+| Tables_in_inventory |+---------------------+| addresses || customers || geom || orders || products || products_on_hand |+---------------------+6 rows in set (0.00 sec)mysql> select * from customers;+------+------------+-----------+-----------------------+| id | first_name | last_name | email |+------+------------+-----------+-----------------------+| 1001 | Sally | Thomas | sally.thomas@acme.com || 1002 | George | Bailey | gbailey@foobar.com || 1003 | Edward | Walker | ed@walker.com || 1004 | Anne | Kretchmar | annek@noanswer.org |+------+------------+-----------+-----------------------+4 rows in set (0.00 sec) here we will use single-node elastic and elastic version 7.7. The container will run with the name elasticdbz. > docker run -it --name elasticdbz -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" docker.elastic.co/elasticsearch/elasticsearch:7.7.0 This service exposes REST API to manage the Debezium MySQL connector. The container will run with the name connectdbz. > docker run -it --name connectdbz -p 8083:8083 -e GROUP_ID=1 -e CONFIG_STORAGE_TOPIC=my_connect_configs -e OFFSET_STORAGE_TOPIC=my_connect_offsets -e STATUS_STORAGE_TOPIC=my_connect_statuses --link zookeeperdbz:zookeeperdbz --link kafkadbz:kafkadbz --link mysqldbz:mysqldbz --link elasticdbz:elasticdbz debezium/connect don’t forget to link this container with kafkadbz, zookeeperdbz, elasticdbz since this service needs to communicate with kafkadbz, zookeeperdbz, elasticdbz services. check the status of Debezium Kafka Connect Service using CURL, from the response we will see we’re using version 2.4.0 > curl -H "Accept:application/json" localhost:8083/{"version":"2.4.0","commit":"77a89fcf8d7fa018","kafka_cluster_id":"XcbUOTN_TNG4hCftkY_j3w"} Let’s Register MySQL connector to monitor CDC in the inventory DB > curl -i -X POST -H "Accept:application/json" -H "Content-Type:application/json" localhost:8083/connectors/ -d '{"name": "inventory-connector","config": {"connector.class": "io.debezium.connector.mysql.MySqlConnector","tasks.max": "1","database.hostname": "mysqldbz","database.port": "3306","database.user": "debezium","database.password": "dbz","database.server.id": "184054","database.server.name": "dbserver1","database.whitelist": "inventory","database.history.kafka.bootstrap.servers": "kafkadbz:9092","database.history.kafka.topic": "schema-changes.inventory"}}' verify the connector is registered in the list of connectors > curl -H "Accept:application/json" localhost:8083/connectors/["inventory-connector"] now, inventory-connector is registered in the list of connectors This step is only for example watch the changes on DB, if you want to consume the topic, you have to write your Kafka Consumer After deploying Debezium MySQL connector, it starts monitoring inventory database for data changes events. To watch the dbserver1.inventory.customers topic, we will need to start Kafka console consumers. The container will run with the name watcher. > docker run -it --rm --name watcher --link zookeeperdbz:zookeeperdbz --link kafkadbz:kafkadbz debezium/kafka watch-topic -a -k dbserver1.inventory.customers after running the watcher, we can see that Debezium starts monitoring the inventory database and put the result as dbserver1.inventory.customers topic. "payload":{"before":null, "after":{"id":1004, "first_name":"Anne", "last_name":"Kretchmar", "email":"annek@noanswer.org"}, "source":{"version":"1.1.1.Final", "connector":"mysql", "name":"dbserver1", "ts_ms":0, "snapshot":"true", "db":"inventory", "table":"customers", "server_id":0, "gtid":null, "file":"mysql-bin.000003", "pos":154, "row":0, "thread":null, "query":null}, "op":"c", "ts_ms":1589504913171, "transaction":null} Let's compare with table inventory.customers mysql> select * from customers;+------+------------+-----------+-----------------------+| id | first_name | last_name | email |+------+------------+-----------+-----------------------+| 1001 | Sally | Thomas | sally.thomas@acme.com || 1002 | George | Bailey | gbailey@foobar.com || 1003 | Edward | Walker | ed@walker.com || 1004 | Anne | Kretchmar | annek@noanswer.org |+------+------------+-----------+-----------------------+ It looks like the last event from the Kafka topic matching with the records in the Customers inventory table Let’s try to update the customer table. mysql > UPDATE `inventory`.`customers` SET `last_name` = 'Kretchmar Kretchmer' WHERE `id` = 1004; And here is the result in the watcher ..."payload":{"before":{ "id":1004, "first_name":"Anne", "last_name":"Kretchmar", "email":"annek@noanswer.org"}, "after":{ "id":1004, "first_name":"Anne", "last_name":"Kretchmar Kretchmer", "email":"annek@noanswer.org"},... until the step, we have achieved to integrate MySQL-Debezium-Kafka.We will get streamed data from Kafka's topic when there is new or changed data in MySQL. What’s Next? To make an integration with Elastic Search we need Kafka Connect Elastic Sink Connector installed on our Debezium Kafka connect container. Step 7 Download Kafka Connect Elastic Sink Connector https://www.confluent.io/hub/confluentinc/kafka-connect-elasticsearch Step 8 Extract downloaded zip file Step 9 Rename lib folder into kafka-connect-jdbc Step 10 Copy kafka-connect-jdbc into debezium the container of kafka-connect > docker cp /path-to-file/confluentinc-kafka-connect-elasticsearch-5.5.0/kafka-connect-jdbc/* connectdbz:/kafka/connect/ Step 11 Verify that all dependency is copied > docker exec -it connectdbz /bin/bash$ cd connect/kafka-connect-jdbc/$ ls -all Step 12 Restart Debezium Kafka Connect container we need to restart Kafka connect service to make Kafka connect can detect newly installed connector plugin > docker stop connectdbz> docker start connectdbz Step 13 Register ElasticsearchSinkConnector > curl -i -X POST -H "Accept:application/json" -H "Content-Type:application/json" localhost:8083/connectors/ -d '{"name": "elastic-sink","config": {"connector.class":"io.confluent.connect.elasticsearch.ElasticsearchSinkConnector","tasks.max": "1","topics": "dbserver1.inventory.customers","connection.url": "http://elasticdbz:9200","transforms": "unwrap,key","transforms.unwrap.type": "io.debezium.transforms.UnwrapFromEnvelope","transforms.key.type": "org.apache.kafka.connect.transforms.ExtractField$Key","transforms.key.field": "id","key.ignore": "false","type.name": "customer"}}' verify ElasticsearchSinkConnector connector is registered in the list of connectors > curl -H "Accept:application/json" localhost:8083/connectors/["elastic-sink","inventory-connector"] Step 14 Check MySQL ElasticSearch Synchronization Let’s check if the databases and the search server are synchronized. > curl ‘http://localhost:9200/dbserver1.inventory.customers/_search?pretty'{ "took" : 12, "timed_out" : false, "_shards" : { "total" : 1, "successful" : 1, "skipped" : 0, "failed" : 0 }, "hits" : { "total" : { "value" : 4, "relation" : "eq" }, "max_score" : 1.0, "hits" : [ { "_index" : "dbserver1.inventory.customers", "_type" : "customer", "_id" : "1001", "_score" : 1.0, "_source" : { "id" : 1001, "first_name" : "Sally", "last_name" : "Thomas", "email" : "sally.thomas@acme.com" } }, { "_index" : "dbserver1.inventory.customers", "_type" : "customer", "_id" : "1004", "_score" : 1.0, "_source" : { "id" : 1004, "first_name" : "Anne", "last_name" : "Kretchmar Kretchme", "email" : "annek@noanswer.org" } }, { "_index" : "dbserver1.inventory.customers", "_type" : "customer", "_id" : "1002", "_score" : 1.0, "_source" : { "id" : 1002, "first_name" : "George", "last_name" : "Bailey", "email" : "gbailey@foobar.com" } }, { "_index" : "dbserver1.inventory.customers", "_type" : "customer", "_id" : "1003", "_score" : 1.0, "_source" : { "id" : 1003, "first_name" : "Edward", "last_name" : "Walker", "email" : "ed@walker.com" } } ] }} as we can see, now all data in MySQL is synchronized. All the data in MySQL can be found in the above elastic index. Let’s insert new data into the Customers table and see what happens in the elastic index. mysql> insert into customers values(default, 'Rizqi', 'Nugrohon', 'rizqi.nugroho@example.com');Query OK, 1 row affected (0.05 sec)mysql> select * from customers;+------+------------+--------------------+------------------------+| id | first_name | last_name | email |+------+------------+--------------------+-----------------------+|| 1001 | Sally | Thomas | sally.thomas@acme.com || 1002 | George | Bailey | gbailey@foobar.com || 1003 | Edward | Walker | ed@walker.com || 1004 | Anne | Kretchmar Kretchme | annek@noanswer.org || 1005 | Rizqi | Nugrohon | rizqi.nugroho@example.com |+------+------------+--------------------+---------------------------+ Check elastic index > curl ‘http://localhost:9200/dbserver1.inventory.customers/_search?pretty'{ "took" : 1476, "timed_out" : false, "_shards" : { "total" : 1, "successful" : 1, "skipped" : 0, "failed" : 0 }, "hits" : { "total" : { "value" : 5, "relation" : "eq" }, "max_score" : 1.0, "hits" : [ { "_index" : "dbserver1.inventory.customers", "_type" : "customer", "_id" : "1001", "_score" : 1.0, "_source" : { "id" : 1001, "first_name" : "Sally", "last_name" : "Thomas", "email" : "sally.thomas@acme.com" } }, ... { "_index" : "dbserver1.inventory.customers", "_type" : "customer", "_id" : "1005", "_score" : 1.0, "_source" : { "id" : 1005, "first_name" : "Rizqi", "last_name" : "Nugrohon", "email" : "rizqi.nugroho@example.com" } } ] }} Viola New data with first_name Rizqi is inserted How about UPDATE statement mysql> UPDATE `inventory`.`customers` SET `last_name` = 'Adhi Nugroho' WHERE `id` = 1005;Query OK, 1 row affected (0.05 sec)mysql> select * from customers;+------+------------+--------------------+------------------------+| id | first_name | last_name | email |+------+------------+--------------------+-----------------------+|| 1001 | Sally | Thomas | sally.thomas@acme.com || 1002 | George | Bailey | gbailey@foobar.com || 1003 | Edward | Walker | ed@walker.com || 1004 | Anne | Kretchmar Kretchme | annek@noanswer.org || 1005 | Rizqi | Adhi Nugroho | rizqi.nugroho@example.com |+------+------------+--------------------+---------------------------+ Again, check the elastic index > curl ‘http://localhost:9200/dbserver1.inventory.customers/_search?pretty'... { "_index" : "dbserver1.inventory.customers", "_type" : "customer", "_id" : "1005", "_score" : 1.0, "_source" : { "id" : 1005, "first_name" : "Rizqi", "last_name" : "Adhi Nugroho", "email" : "rizqi.nugroho@example.com" } } ] }} Mama mia, data updated !!! Thanks to the article written by my master Erfin Feluzy article https://medium.com/@erfin.feluzy/tutorial-streaming-cdc-mysql-ke-kafka-dengan-debezium-3a1ec9150cf8 that inspired me to create this article. Finally, we made integration between MySQL and ElasticSearch using Debezium. I hope this demonstration can help you to solve the data latency problem between MySQL DB and ElasticSearch. Now all changed in MySQL DB will immediately be affected in Elastic Index. You can try to use another DB such as PostgreSQL, Oracle, DB2, MSSQL, etc.
[ { "code": null, "e": 573, "s": 172, "text": "Fast search capability, realtime integrated data, nowadays is a necessity if we want to build something like e-catalog or e-commerce. We don’t want our users to get angry because they spend a lot of time just to get information from our portal. We also want the product information that inputted by our product team in the different applications immediately ready to search by our users or customers." }, { "code": null, "e": 815, "s": 573, "text": "Say the product team using MySQL as the main data source. And we will use ElasticSearch as a search engine service in our portal. We need every change in MySQL will immediately affect the ElasticSearch Index. How to achieve that requirement?" }, { "code": null, "e": 1151, "s": 815, "text": "In this my first article, I will demonstrate how can we stream our data changes in MySQL into ElasticSearch using Debezium, Kafka, and Confluent JDBC Sink Connector to achieve the above use case requirement. Credit to my master Erfin Feluzy that introduce me to Debezium and give me the inspiration to write my first article on medium." }, { "code": null, "e": 1715, "s": 1151, "text": "Debezium is a distributed platform that turns your existing databases into event streams, so applications can quickly react to each row-level change in the databases. Debezium is built on top of Kafka and provides Kafka Connect compatible connectors that monitor specific database management systems. Debezium records the history of data changes in Kafka logs, so your application can be stopped and restarted at any time and can easily consume all of the events it missed while it was not running, ensuring that all events are processed correctly and completely." }, { "code": null, "e": 1777, "s": 1715, "text": "Debezium is open source under the Apache License, Version 2.0" }, { "code": null, "e": 2052, "s": 1777, "text": "Apache Kafka is an open-source stream-processing software platform developed by LinkedIn and donated to the Apache Software Foundation, written in Scala and Java. The project aims to provide a unified, high-throughput, low-latency platform for handling real-time data feeds." }, { "code": null, "e": 2268, "s": 2052, "text": "The Kafka Connect Elasticsearch sink connector allows moving data from Apache Kafka® to Elasticsearch. It writes data from a topic in Apache Kafka® to an index in Elasticsearch and all data for a topic have the same" }, { "code": null, "e": 2606, "s": 2268, "text": "In this tutorial, we will use a separate container for each service and don’t use persistent volume. ZooKeeper and Kafka would typically store their data locally inside the containers, which would require you to mount directories on the host machine as volumes. So in this tutorial, all persisted data is lost when a container is stopped" }, { "code": null, "e": 2721, "s": 2606, "text": "Start zookeeper in the container using debezium/zookeeper image. The container will run with the name zookeeperdbz" }, { "code": null, "e": 2820, "s": 2721, "text": "> docker run -it — name zookeeperdbz -p 2181:2181 -p 2888:2888 -p 3888:3888 debezium/zookeeper:1.1" }, { "code": null, "e": 2902, "s": 2820, "text": "check the run log to verify zookeeper run successfully and listening on port 2181" }, { "code": null, "e": 3106, "s": 2902, "text": "Starting up in standalone modeZooKeeper JMX enabled by defaultUsing config: /zookeeper/conf/zoo.cfg...020-05-13 17:18:28,564 - INFO [main:NIOServerCnxnFactory@686] - binding to port 0.0.0.0/0.0.0.0:2181" }, { "code": null, "e": 3216, "s": 3106, "text": "Start Kafka in the container using debezium/kafka docker image. The container will run with the name kafkadbz" }, { "code": null, "e": 3310, "s": 3216, "text": "> docker run -it — name kafkadbz -p 9092:9092 --link zookeeperdbz:zookeeperdbz debezium/kafka" }, { "code": null, "e": 3338, "s": 3310, "text": "verify Kafka server started" }, { "code": null, "e": 3455, "s": 3338, "text": "In this demonstration, I will use a pre-configured Docker image that also contains sample data provided by Debezium." }, { "code": null, "e": 3560, "s": 3455, "text": "Start MySQL in a container using debezium/example-mysql image. The container will run with name mysqldbz" }, { "code": null, "e": 3714, "s": 3560, "text": "> docker run -it -d --name mysqldbz -p 3306:3306 -e MYSQL_ROOT_PASSWORD=debezium -e MYSQL_USER=mysqluser -e MYSQL_PASSWORD=mysqlpw debezium/example-mysql" }, { "code": null, "e": 3772, "s": 3714, "text": "the above command will create a container named mysqldbz." }, { "code": null, "e": 3861, "s": 3772, "text": "Next, let's execute the container and enter the interactive bash shell on the container." }, { "code": null, "e": 3898, "s": 3861, "text": "> docker exec -it mysqldbz /bin/bash" }, { "code": null, "e": 4135, "s": 3898, "text": "To use capture the CDC on MySQL, Debezium needs bin_log configuration in our MySQL enabled. Thanks to Debezium, since we’re using a pre-configured MySQL Docker image, we don’t need to configure it anymore. Let’s check the configuration." }, { "code": null, "e": 4170, "s": 4135, "text": "# more /etc/mysql/conf.d/mysql.cnf" }, { "code": null, "e": 4229, "s": 4170, "text": "As you can see, bin_log enabled, by default it's disabled." }, { "code": null, "e": 4249, "s": 4229, "text": "Check the sample DB" }, { "code": null, "e": 5126, "s": 4249, "text": "# mysql -u root -p Enter password: <enter your password>mysql> use inventoryDatabase changedmysql> show tables;+---------------------+| Tables_in_inventory |+---------------------+| addresses || customers || geom || orders || products || products_on_hand |+---------------------+6 rows in set (0.00 sec)mysql> select * from customers;+------+------------+-----------+-----------------------+| id | first_name | last_name | email |+------+------------+-----------+-----------------------+| 1001 | Sally | Thomas | sally.thomas@acme.com || 1002 | George | Bailey | gbailey@foobar.com || 1003 | Edward | Walker | ed@walker.com || 1004 | Anne | Kretchmar | annek@noanswer.org |+------+------------+-----------+-----------------------+4 rows in set (0.00 sec)" }, { "code": null, "e": 5237, "s": 5126, "text": "here we will use single-node elastic and elastic version 7.7. The container will run with the name elasticdbz." }, { "code": null, "e": 5383, "s": 5237, "text": "> docker run -it --name elasticdbz -p 9200:9200 -p 9300:9300 -e \"discovery.type=single-node\" docker.elastic.co/elasticsearch/elasticsearch:7.7.0 " }, { "code": null, "e": 5502, "s": 5383, "text": "This service exposes REST API to manage the Debezium MySQL connector. The container will run with the name connectdbz." }, { "code": null, "e": 5823, "s": 5502, "text": "> docker run -it --name connectdbz -p 8083:8083 -e GROUP_ID=1 -e CONFIG_STORAGE_TOPIC=my_connect_configs -e OFFSET_STORAGE_TOPIC=my_connect_offsets -e STATUS_STORAGE_TOPIC=my_connect_statuses --link zookeeperdbz:zookeeperdbz --link kafkadbz:kafkadbz --link mysqldbz:mysqldbz --link elasticdbz:elasticdbz debezium/connect" }, { "code": null, "e": 5989, "s": 5823, "text": "don’t forget to link this container with kafkadbz, zookeeperdbz, elasticdbz since this service needs to communicate with kafkadbz, zookeeperdbz, elasticdbz services." }, { "code": null, "e": 6108, "s": 5989, "text": "check the status of Debezium Kafka Connect Service using CURL, from the response we will see we’re using version 2.4.0" }, { "code": null, "e": 6251, "s": 6108, "text": "> curl -H \"Accept:application/json\" localhost:8083/{\"version\":\"2.4.0\",\"commit\":\"77a89fcf8d7fa018\",\"kafka_cluster_id\":\"XcbUOTN_TNG4hCftkY_j3w\"}" }, { "code": null, "e": 6317, "s": 6251, "text": "Let’s Register MySQL connector to monitor CDC in the inventory DB" }, { "code": null, "e": 6887, "s": 6317, "text": "> curl -i -X POST -H \"Accept:application/json\" -H \"Content-Type:application/json\" localhost:8083/connectors/ -d '{\"name\": \"inventory-connector\",\"config\": {\"connector.class\": \"io.debezium.connector.mysql.MySqlConnector\",\"tasks.max\": \"1\",\"database.hostname\": \"mysqldbz\",\"database.port\": \"3306\",\"database.user\": \"debezium\",\"database.password\": \"dbz\",\"database.server.id\": \"184054\",\"database.server.name\": \"dbserver1\",\"database.whitelist\": \"inventory\",\"database.history.kafka.bootstrap.servers\": \"kafkadbz:9092\",\"database.history.kafka.topic\": \"schema-changes.inventory\"}}'" }, { "code": null, "e": 6948, "s": 6887, "text": "verify the connector is registered in the list of connectors" }, { "code": null, "e": 7034, "s": 6948, "text": "> curl -H \"Accept:application/json\" localhost:8083/connectors/[\"inventory-connector\"]" }, { "code": null, "e": 7099, "s": 7034, "text": "now, inventory-connector is registered in the list of connectors" }, { "code": null, "e": 7226, "s": 7099, "text": "This step is only for example watch the changes on DB, if you want to consume the topic, you have to write your Kafka Consumer" }, { "code": null, "e": 7333, "s": 7226, "text": "After deploying Debezium MySQL connector, it starts monitoring inventory database for data changes events." }, { "code": null, "e": 7476, "s": 7333, "text": "To watch the dbserver1.inventory.customers topic, we will need to start Kafka console consumers. The container will run with the name watcher." }, { "code": null, "e": 7634, "s": 7476, "text": "> docker run -it --rm --name watcher --link zookeeperdbz:zookeeperdbz --link kafkadbz:kafkadbz debezium/kafka watch-topic -a -k dbserver1.inventory.customers" }, { "code": null, "e": 7786, "s": 7634, "text": "after running the watcher, we can see that Debezium starts monitoring the inventory database and put the result as dbserver1.inventory.customers topic." }, { "code": null, "e": 8365, "s": 7786, "text": "\"payload\":{\"before\":null, \"after\":{\"id\":1004, \"first_name\":\"Anne\", \"last_name\":\"Kretchmar\", \"email\":\"annek@noanswer.org\"}, \"source\":{\"version\":\"1.1.1.Final\", \"connector\":\"mysql\", \"name\":\"dbserver1\", \"ts_ms\":0, \"snapshot\":\"true\", \"db\":\"inventory\", \"table\":\"customers\", \"server_id\":0, \"gtid\":null, \"file\":\"mysql-bin.000003\", \"pos\":154, \"row\":0, \"thread\":null, \"query\":null}, \"op\":\"c\", \"ts_ms\":1589504913171, \"transaction\":null}" }, { "code": null, "e": 8410, "s": 8365, "text": "Let's compare with table inventory.customers" }, { "code": null, "e": 8898, "s": 8410, "text": "mysql> select * from customers;+------+------------+-----------+-----------------------+| id | first_name | last_name | email |+------+------------+-----------+-----------------------+| 1001 | Sally | Thomas | sally.thomas@acme.com || 1002 | George | Bailey | gbailey@foobar.com || 1003 | Edward | Walker | ed@walker.com || 1004 | Anne | Kretchmar | annek@noanswer.org |+------+------------+-----------+-----------------------+" }, { "code": null, "e": 9007, "s": 8898, "text": "It looks like the last event from the Kafka topic matching with the records in the Customers inventory table" }, { "code": null, "e": 9047, "s": 9007, "text": "Let’s try to update the customer table." }, { "code": null, "e": 9145, "s": 9047, "text": "mysql > UPDATE `inventory`.`customers` SET `last_name` = 'Kretchmar Kretchmer' WHERE `id` = 1004;" }, { "code": null, "e": 9183, "s": 9145, "text": "And here is the result in the watcher" }, { "code": null, "e": 9476, "s": 9183, "text": "...\"payload\":{\"before\":{ \"id\":1004, \"first_name\":\"Anne\", \"last_name\":\"Kretchmar\", \"email\":\"annek@noanswer.org\"}, \"after\":{ \"id\":1004, \"first_name\":\"Anne\", \"last_name\":\"Kretchmar Kretchmer\", \"email\":\"annek@noanswer.org\"},..." }, { "code": null, "e": 9632, "s": 9476, "text": "until the step, we have achieved to integrate MySQL-Debezium-Kafka.We will get streamed data from Kafka's topic when there is new or changed data in MySQL." }, { "code": null, "e": 9645, "s": 9632, "text": "What’s Next?" }, { "code": null, "e": 9784, "s": 9645, "text": "To make an integration with Elastic Search we need Kafka Connect Elastic Sink Connector installed on our Debezium Kafka connect container." }, { "code": null, "e": 9907, "s": 9784, "text": "Step 7 Download Kafka Connect Elastic Sink Connector https://www.confluent.io/hub/confluentinc/kafka-connect-elasticsearch" }, { "code": null, "e": 9942, "s": 9907, "text": "Step 8 Extract downloaded zip file" }, { "code": null, "e": 9991, "s": 9942, "text": "Step 9 Rename lib folder into kafka-connect-jdbc" }, { "code": null, "e": 10068, "s": 9991, "text": "Step 10 Copy kafka-connect-jdbc into debezium the container of kafka-connect" }, { "code": null, "e": 10189, "s": 10068, "text": "> docker cp /path-to-file/confluentinc-kafka-connect-elasticsearch-5.5.0/kafka-connect-jdbc/* connectdbz:/kafka/connect/" }, { "code": null, "e": 10234, "s": 10189, "text": "Step 11 Verify that all dependency is copied" }, { "code": null, "e": 10314, "s": 10234, "text": "> docker exec -it connectdbz /bin/bash$ cd connect/kafka-connect-jdbc/$ ls -all" }, { "code": null, "e": 10363, "s": 10314, "text": "Step 12 Restart Debezium Kafka Connect container" }, { "code": null, "e": 10470, "s": 10363, "text": "we need to restart Kafka connect service to make Kafka connect can detect newly installed connector plugin" }, { "code": null, "e": 10520, "s": 10470, "text": "> docker stop connectdbz> docker start connectdbz" }, { "code": null, "e": 10564, "s": 10520, "text": "Step 13 Register ElasticsearchSinkConnector" }, { "code": null, "e": 11149, "s": 10564, "text": "> curl -i -X POST -H \"Accept:application/json\" -H \"Content-Type:application/json\" localhost:8083/connectors/ -d '{\"name\": \"elastic-sink\",\"config\": {\"connector.class\":\"io.confluent.connect.elasticsearch.ElasticsearchSinkConnector\",\"tasks.max\": \"1\",\"topics\": \"dbserver1.inventory.customers\",\"connection.url\": \"http://elasticdbz:9200\",\"transforms\": \"unwrap,key\",\"transforms.unwrap.type\": \"io.debezium.transforms.UnwrapFromEnvelope\",\"transforms.key.type\": \"org.apache.kafka.connect.transforms.ExtractField$Key\",\"transforms.key.field\": \"id\",\"key.ignore\": \"false\",\"type.name\": \"customer\"}}'" }, { "code": null, "e": 11233, "s": 11149, "text": "verify ElasticsearchSinkConnector connector is registered in the list of connectors" }, { "code": null, "e": 11334, "s": 11233, "text": "> curl -H \"Accept:application/json\" localhost:8083/connectors/[\"elastic-sink\",\"inventory-connector\"]" }, { "code": null, "e": 11384, "s": 11334, "text": "Step 14 Check MySQL ElasticSearch Synchronization" }, { "code": null, "e": 11453, "s": 11384, "text": "Let’s check if the databases and the search server are synchronized." }, { "code": null, "e": 12981, "s": 11453, "text": "> curl ‘http://localhost:9200/dbserver1.inventory.customers/_search?pretty'{ \"took\" : 12, \"timed_out\" : false, \"_shards\" : { \"total\" : 1, \"successful\" : 1, \"skipped\" : 0, \"failed\" : 0 }, \"hits\" : { \"total\" : { \"value\" : 4, \"relation\" : \"eq\" }, \"max_score\" : 1.0, \"hits\" : [ { \"_index\" : \"dbserver1.inventory.customers\", \"_type\" : \"customer\", \"_id\" : \"1001\", \"_score\" : 1.0, \"_source\" : { \"id\" : 1001, \"first_name\" : \"Sally\", \"last_name\" : \"Thomas\", \"email\" : \"sally.thomas@acme.com\" } }, { \"_index\" : \"dbserver1.inventory.customers\", \"_type\" : \"customer\", \"_id\" : \"1004\", \"_score\" : 1.0, \"_source\" : { \"id\" : 1004, \"first_name\" : \"Anne\", \"last_name\" : \"Kretchmar Kretchme\", \"email\" : \"annek@noanswer.org\" } }, { \"_index\" : \"dbserver1.inventory.customers\", \"_type\" : \"customer\", \"_id\" : \"1002\", \"_score\" : 1.0, \"_source\" : { \"id\" : 1002, \"first_name\" : \"George\", \"last_name\" : \"Bailey\", \"email\" : \"gbailey@foobar.com\" } }, { \"_index\" : \"dbserver1.inventory.customers\", \"_type\" : \"customer\", \"_id\" : \"1003\", \"_score\" : 1.0, \"_source\" : { \"id\" : 1003, \"first_name\" : \"Edward\", \"last_name\" : \"Walker\", \"email\" : \"ed@walker.com\" } } ] }}" }, { "code": null, "e": 13098, "s": 12981, "text": "as we can see, now all data in MySQL is synchronized. All the data in MySQL can be found in the above elastic index." }, { "code": null, "e": 13188, "s": 13098, "text": "Let’s insert new data into the Customers table and see what happens in the elastic index." }, { "code": null, "e": 13962, "s": 13188, "text": "mysql> insert into customers values(default, 'Rizqi', 'Nugrohon', 'rizqi.nugroho@example.com');Query OK, 1 row affected (0.05 sec)mysql> select * from customers;+------+------------+--------------------+------------------------+| id | first_name | last_name | email |+------+------------+--------------------+-----------------------+|| 1001 | Sally | Thomas | sally.thomas@acme.com || 1002 | George | Bailey | gbailey@foobar.com || 1003 | Edward | Walker | ed@walker.com || 1004 | Anne | Kretchmar Kretchme | annek@noanswer.org || 1005 | Rizqi | Nugrohon | rizqi.nugroho@example.com |+------+------------+--------------------+---------------------------+" }, { "code": null, "e": 13982, "s": 13962, "text": "Check elastic index" }, { "code": null, "e": 14924, "s": 13982, "text": "> curl ‘http://localhost:9200/dbserver1.inventory.customers/_search?pretty'{ \"took\" : 1476, \"timed_out\" : false, \"_shards\" : { \"total\" : 1, \"successful\" : 1, \"skipped\" : 0, \"failed\" : 0 }, \"hits\" : { \"total\" : { \"value\" : 5, \"relation\" : \"eq\" }, \"max_score\" : 1.0, \"hits\" : [ { \"_index\" : \"dbserver1.inventory.customers\", \"_type\" : \"customer\", \"_id\" : \"1001\", \"_score\" : 1.0, \"_source\" : { \"id\" : 1001, \"first_name\" : \"Sally\", \"last_name\" : \"Thomas\", \"email\" : \"sally.thomas@acme.com\" } }, ... { \"_index\" : \"dbserver1.inventory.customers\", \"_type\" : \"customer\", \"_id\" : \"1005\", \"_score\" : 1.0, \"_source\" : { \"id\" : 1005, \"first_name\" : \"Rizqi\", \"last_name\" : \"Nugrohon\", \"email\" : \"rizqi.nugroho@example.com\" } } ] }}" }, { "code": null, "e": 14973, "s": 14924, "text": "Viola New data with first_name Rizqi is inserted" }, { "code": null, "e": 15000, "s": 14973, "text": "How about UPDATE statement" }, { "code": null, "e": 15772, "s": 15000, "text": "mysql> UPDATE `inventory`.`customers` SET `last_name` = 'Adhi Nugroho' WHERE `id` = 1005;Query OK, 1 row affected (0.05 sec)mysql> select * from customers;+------+------------+--------------------+------------------------+| id | first_name | last_name | email |+------+------------+--------------------+-----------------------+|| 1001 | Sally | Thomas | sally.thomas@acme.com || 1002 | George | Bailey | gbailey@foobar.com || 1003 | Edward | Walker | ed@walker.com || 1004 | Anne | Kretchmar Kretchme | annek@noanswer.org || 1005 | Rizqi | Adhi Nugroho | rizqi.nugroho@example.com |+------+------------+--------------------+---------------------------+" }, { "code": null, "e": 15803, "s": 15772, "text": "Again, check the elastic index" }, { "code": null, "e": 16202, "s": 15803, "text": "> curl ‘http://localhost:9200/dbserver1.inventory.customers/_search?pretty'... { \"_index\" : \"dbserver1.inventory.customers\", \"_type\" : \"customer\", \"_id\" : \"1005\", \"_score\" : 1.0, \"_source\" : { \"id\" : 1005, \"first_name\" : \"Rizqi\", \"last_name\" : \"Adhi Nugroho\", \"email\" : \"rizqi.nugroho@example.com\" } } ] }}" }, { "code": null, "e": 16229, "s": 16202, "text": "Mama mia, data updated !!!" }, { "code": null, "e": 16434, "s": 16229, "text": "Thanks to the article written by my master Erfin Feluzy article https://medium.com/@erfin.feluzy/tutorial-streaming-cdc-mysql-ke-kafka-dengan-debezium-3a1ec9150cf8 that inspired me to create this article." } ]
A Practitioner’s Guide To Difference-In-Differences Approach | by Leihua Ye, PhD | Towards Data Science
Executive Summary In a perfectly competitive market, conventional economic theory predicts an increase in the minimum wage leads to a rise in unemployment. Cross-sectional studies provide conflicting evidence but not a causal effect. Card and Krueger adopt a DID approach and find the wage increase leads to higher employment. Foreword In this post, I’ll replicate Card and Krueger’s paper with step-to-step explanations and complement with additional information on the definition of quasi-experimental design, assumptions, R code, and a Potential Outcomes Framework explanation. What is a quasi-experiment? A quasi-experimental design is sort of an experimental design without a true randomization process. Due to the lack of a random assignment, the treatment and control groups are not equivalent before the intervention. So, any differences from these two groups could be caused by the pre-existing differences. The quasi design has been well received by policy analysts, health care providers, and Direct-To-Consumer companies (in particular, Netflix and Airbnb). Why a quasi-experimental design? In other posts, I’ve explained the benefits of experimental studies and why they should be the number one choice for causal inference, if possible. So, why don’t we run experiments all the time? Great question! A quick answer is experimental designs are not good for some types of problems. For example, it’s not ethical to randomly assign people to hazardous conditions (e.g., smoking) that may harm their health. In the policy arena, we can’t randomly assign California, not New York, to receive a new tax break. Besides, there are spillover effects between the treatment and control groups in experimental designs. Netflix doesn’t run A/B testing for some types of questions but rely on quasi-experimental solutions (In this post, Netflix explained why A/B testing isn’t feasible all the time). Under these circumstances, the quasi designs come in handy when a full-fledged experimental study isn’t an option. “The results of a quasi-experiment won’t be as precise as an A/B, but we aspire towards a directional read on causality.” — — Colin McFarland, Michael Pow, Julia Glick @ Netflix Background A bill signed into law on November 1989 raised the federal minimum wage from $3.35 per hour to $3.8 effective April 1, 1990, with a further increase from $4.25 per hour to $5.05 on April 1, 1992. New Jersey experiences the wage increase but not in Pennsylvania. David and Krueger run two rounds of survey right before and after the rise. A brief timeline that may help: February and March 1992: initial round of surveyApril 1992: an increase in the minimum wage from $4.25 to $5.05 in New JerseyNovember and December 1992: a follow-up survey February and March 1992: initial round of survey April 1992: an increase in the minimum wage from $4.25 to $5.05 in New Jersey November and December 1992: a follow-up survey Here are the reasons why we run quasi design. #1 New Jersey and Pennsylvania are not comparable in a lot of aspects. #2 The legislative process isn’t random. However, we can identify the causal effects of the wage increase on the unemployment rate following a DID approach. A quasi-experiment design does not require equivalent groups. A Potential Outcomes Framework Analysis of the study Here are the notations. Let D represent whether it receives the treatment, T for the time, i for the number of research subjects. Di = 1: New Jersey receives the treatment (minimum wage increase) Di = 0: Pennsylvania does not receive the treatment T=1: After the wage increase (1992 November and December) T=0: Before the wage increase (1992 February and March) Y: the outcome variable (unemployment rate) There is a potential problem. We don’t know how the control group (Pennsylvania) would behave if they would have received the treatment (missing E[Y0i(1)|D=1]). We can use the DID approach can solve this issue: the ATT E[Y1(1) — Y(0(1)|D=1] = {E[Y(1)|D=1] — E[Y(1)|D = 0]} — {E[Y(0)|D=1] — E[Y(0)|D=0], assuming parallel trends. The Parallel Trends Assumption means the difference between the treatment and control groups would stay constant if there were no treatment. In this case, the differences between the employment rates in NJ and PA would be the same if there were no wage increase law. R analysis: # Credits to Jonathan Mummolod <- read.csv(“wage_data.csv”,convert.factors = FALSE)head(d[, c(“ID”, “nj”, “postperiod”, “emptot”)])with(d, ( mean(emptot[nj == 1 & postperiod == 1], na.rm = TRUE) — mean(emptot[nj == 1 & postperiod == 0], na.rm = TRUE) )- (mean(emptot[nj == 0 & postperiod == 1], na.rm = TRUE) — mean(emptot[nj == 0 & postperiod == 0], na.rm = TRUE) ))ols <- lm(emptot ~ postperiod * nj, data = d)coeftest(ols) To control for region and time differences, we can build a fixed effects regression model with unit and period fixed effects. #A set of estimators and tests for panel data econometricslibrary(plm)library(lmtest)d$Dit <- d$nj * d$postperiodd <- plm.data(d, indexes = c("ID", "postperiod"))did.reg <- plm(emptot ~ postperiod + Dit, data = d,model = "within")coeftest(did.reg, vcov=function(x)#Heteroskedasticity-Consistent Covariance Matrix EstimationvcovHC(x, cluster="group", type="HC1")) After comparing it to the original table, we have successfully replicated the results! The original paper is here. The replication dataset is here. A caveat: this is the raw data, and we need to process it for analysis. Medium recently evolved its Writer Partner Program, which supports ordinary writers like myself. If you are not a subscriber yet and sign up via the following link, I’ll receive a portion of the membership fees. leihua-ye.medium.com Please find me on LinkedIn and Youtube. Also, check my other posts on Artificial Intelligence and Machine Learning.
[ { "code": null, "e": 65, "s": 47, "text": "Executive Summary" }, { "code": null, "e": 203, "s": 65, "text": "In a perfectly competitive market, conventional economic theory predicts an increase in the minimum wage leads to a rise in unemployment." }, { "code": null, "e": 281, "s": 203, "text": "Cross-sectional studies provide conflicting evidence but not a causal effect." }, { "code": null, "e": 374, "s": 281, "text": "Card and Krueger adopt a DID approach and find the wage increase leads to higher employment." }, { "code": null, "e": 383, "s": 374, "text": "Foreword" }, { "code": null, "e": 628, "s": 383, "text": "In this post, I’ll replicate Card and Krueger’s paper with step-to-step explanations and complement with additional information on the definition of quasi-experimental design, assumptions, R code, and a Potential Outcomes Framework explanation." }, { "code": null, "e": 656, "s": 628, "text": "What is a quasi-experiment?" }, { "code": null, "e": 964, "s": 656, "text": "A quasi-experimental design is sort of an experimental design without a true randomization process. Due to the lack of a random assignment, the treatment and control groups are not equivalent before the intervention. So, any differences from these two groups could be caused by the pre-existing differences." }, { "code": null, "e": 1117, "s": 964, "text": "The quasi design has been well received by policy analysts, health care providers, and Direct-To-Consumer companies (in particular, Netflix and Airbnb)." }, { "code": null, "e": 1150, "s": 1117, "text": "Why a quasi-experimental design?" }, { "code": null, "e": 1345, "s": 1150, "text": "In other posts, I’ve explained the benefits of experimental studies and why they should be the number one choice for causal inference, if possible. So, why don’t we run experiments all the time?" }, { "code": null, "e": 1565, "s": 1345, "text": "Great question! A quick answer is experimental designs are not good for some types of problems. For example, it’s not ethical to randomly assign people to hazardous conditions (e.g., smoking) that may harm their health." }, { "code": null, "e": 1665, "s": 1565, "text": "In the policy arena, we can’t randomly assign California, not New York, to receive a new tax break." }, { "code": null, "e": 1948, "s": 1665, "text": "Besides, there are spillover effects between the treatment and control groups in experimental designs. Netflix doesn’t run A/B testing for some types of questions but rely on quasi-experimental solutions (In this post, Netflix explained why A/B testing isn’t feasible all the time)." }, { "code": null, "e": 2063, "s": 1948, "text": "Under these circumstances, the quasi designs come in handy when a full-fledged experimental study isn’t an option." }, { "code": null, "e": 2185, "s": 2063, "text": "“The results of a quasi-experiment won’t be as precise as an A/B, but we aspire towards a directional read on causality.”" }, { "code": null, "e": 2241, "s": 2185, "text": "— — Colin McFarland, Michael Pow, Julia Glick @ Netflix" }, { "code": null, "e": 2252, "s": 2241, "text": "Background" }, { "code": null, "e": 2590, "s": 2252, "text": "A bill signed into law on November 1989 raised the federal minimum wage from $3.35 per hour to $3.8 effective April 1, 1990, with a further increase from $4.25 per hour to $5.05 on April 1, 1992. New Jersey experiences the wage increase but not in Pennsylvania. David and Krueger run two rounds of survey right before and after the rise." }, { "code": null, "e": 2622, "s": 2590, "text": "A brief timeline that may help:" }, { "code": null, "e": 2794, "s": 2622, "text": "February and March 1992: initial round of surveyApril 1992: an increase in the minimum wage from $4.25 to $5.05 in New JerseyNovember and December 1992: a follow-up survey" }, { "code": null, "e": 2843, "s": 2794, "text": "February and March 1992: initial round of survey" }, { "code": null, "e": 2921, "s": 2843, "text": "April 1992: an increase in the minimum wage from $4.25 to $5.05 in New Jersey" }, { "code": null, "e": 2968, "s": 2921, "text": "November and December 1992: a follow-up survey" }, { "code": null, "e": 3126, "s": 2968, "text": "Here are the reasons why we run quasi design. #1 New Jersey and Pennsylvania are not comparable in a lot of aspects. #2 The legislative process isn’t random." }, { "code": null, "e": 3242, "s": 3126, "text": "However, we can identify the causal effects of the wage increase on the unemployment rate following a DID approach." }, { "code": null, "e": 3304, "s": 3242, "text": "A quasi-experiment design does not require equivalent groups." }, { "code": null, "e": 3357, "s": 3304, "text": "A Potential Outcomes Framework Analysis of the study" }, { "code": null, "e": 3487, "s": 3357, "text": "Here are the notations. Let D represent whether it receives the treatment, T for the time, i for the number of research subjects." }, { "code": null, "e": 3553, "s": 3487, "text": "Di = 1: New Jersey receives the treatment (minimum wage increase)" }, { "code": null, "e": 3605, "s": 3553, "text": "Di = 0: Pennsylvania does not receive the treatment" }, { "code": null, "e": 3663, "s": 3605, "text": "T=1: After the wage increase (1992 November and December)" }, { "code": null, "e": 3719, "s": 3663, "text": "T=0: Before the wage increase (1992 February and March)" }, { "code": null, "e": 3763, "s": 3719, "text": "Y: the outcome variable (unemployment rate)" }, { "code": null, "e": 3924, "s": 3763, "text": "There is a potential problem. We don’t know how the control group (Pennsylvania) would behave if they would have received the treatment (missing E[Y0i(1)|D=1])." }, { "code": null, "e": 3974, "s": 3924, "text": "We can use the DID approach can solve this issue:" }, { "code": null, "e": 4006, "s": 3974, "text": "the ATT E[Y1(1) — Y(0(1)|D=1] =" }, { "code": null, "e": 4092, "s": 4006, "text": "{E[Y(1)|D=1] — E[Y(1)|D = 0]} — {E[Y(0)|D=1] — E[Y(0)|D=0], assuming parallel trends." }, { "code": null, "e": 4359, "s": 4092, "text": "The Parallel Trends Assumption means the difference between the treatment and control groups would stay constant if there were no treatment. In this case, the differences between the employment rates in NJ and PA would be the same if there were no wage increase law." }, { "code": null, "e": 4371, "s": 4359, "text": "R analysis:" }, { "code": null, "e": 4799, "s": 4371, "text": "# Credits to Jonathan Mummolod <- read.csv(“wage_data.csv”,convert.factors = FALSE)head(d[, c(“ID”, “nj”, “postperiod”, “emptot”)])with(d, ( mean(emptot[nj == 1 & postperiod == 1], na.rm = TRUE) — mean(emptot[nj == 1 & postperiod == 0], na.rm = TRUE) )- (mean(emptot[nj == 0 & postperiod == 1], na.rm = TRUE) — mean(emptot[nj == 0 & postperiod == 0], na.rm = TRUE) ))ols <- lm(emptot ~ postperiod * nj, data = d)coeftest(ols)" }, { "code": null, "e": 4925, "s": 4799, "text": "To control for region and time differences, we can build a fixed effects regression model with unit and period fixed effects." }, { "code": null, "e": 5288, "s": 4925, "text": "#A set of estimators and tests for panel data econometricslibrary(plm)library(lmtest)d$Dit <- d$nj * d$postperiodd <- plm.data(d, indexes = c(\"ID\", \"postperiod\"))did.reg <- plm(emptot ~ postperiod + Dit, data = d,model = \"within\")coeftest(did.reg, vcov=function(x)#Heteroskedasticity-Consistent Covariance Matrix EstimationvcovHC(x, cluster=\"group\", type=\"HC1\"))" }, { "code": null, "e": 5375, "s": 5288, "text": "After comparing it to the original table, we have successfully replicated the results!" }, { "code": null, "e": 5403, "s": 5375, "text": "The original paper is here." }, { "code": null, "e": 5508, "s": 5403, "text": "The replication dataset is here. A caveat: this is the raw data, and we need to process it for analysis." }, { "code": null, "e": 5720, "s": 5508, "text": "Medium recently evolved its Writer Partner Program, which supports ordinary writers like myself. If you are not a subscriber yet and sign up via the following link, I’ll receive a portion of the membership fees." }, { "code": null, "e": 5741, "s": 5720, "text": "leihua-ye.medium.com" }, { "code": null, "e": 5781, "s": 5741, "text": "Please find me on LinkedIn and Youtube." } ]
Print colored message with different fonts and sizes in C
C/C++ programming language, the user is provided with functionality to customize the output based on the requirement of the user. C/C++ graphics functions are included in graphics.h header file. Using this library you can create different objects, set the color of text, change the font and size of the text and change the background of the output. Now, let's see the working of all the function to alter the text of the output in c/c++ programming language − setcolor() − This function is used to change the color of the output text. setcolor(int) #include<stdio.h> #include<graphics.h> int main(){ int gdriver = DETECT,gmode,i; initgraph(&gdriver,&gmode,"C:\\Turboc3\\BGI"); setcolor(5); return 0; } settexttyle() − This function is used to change the font style, orientation, and size of the output text. settexttyle(int style , int orientation , int size); #include<stdio.h> #include<graphics.h> int main(){ int gdriver = DETECT,gmode,i; initgraph(&gdriver,&gmode,"C:\\Turboc3\\BGI"); settextstyle(3,1,4); return 0; } Outtext − this function is used to print the message passed to it at some certain coordinates(x,y) on the screen. outtext(int x_cordinate , int y_cordinate, text) #include<stdio.h> #include<graphics.h> int main(){ int gdriver = DETECT,gmode,i; initgraph(&gdriver,&gmode,"C:\\Turboc3\\BGI"); settextstyle(25,15,’hello!’); return 0; } textheight() − this function is used to change the height of the text in the output screen. textheight(int) textwidth() − This function is used to change the width of the text in the output screen. textwidth(int)
[ { "code": null, "e": 1411, "s": 1062, "text": "C/C++ programming language, the user is provided with functionality to customize the output based on the requirement of the user. C/C++ graphics functions are included in graphics.h header file. Using this library you can create different objects, set the color of text, change the font and size of the text and change the background of the output." }, { "code": null, "e": 1522, "s": 1411, "text": "Now, let's see the working of all the function to alter the text of the output in c/c++ programming language −" }, { "code": null, "e": 1597, "s": 1522, "text": "setcolor() − This function is used to change the color of the output text." }, { "code": null, "e": 1611, "s": 1597, "text": "setcolor(int)" }, { "code": null, "e": 1776, "s": 1611, "text": "#include<stdio.h>\n#include<graphics.h>\nint main(){\n int gdriver = DETECT,gmode,i;\n initgraph(&gdriver,&gmode,\"C:\\\\Turboc3\\\\BGI\");\n setcolor(5);\n return 0;\n}" }, { "code": null, "e": 1882, "s": 1776, "text": "settexttyle() − This function is used to change the font style, orientation, and size of the output text." }, { "code": null, "e": 1935, "s": 1882, "text": "settexttyle(int style , int orientation , int size);" }, { "code": null, "e": 2108, "s": 1935, "text": "#include<stdio.h>\n#include<graphics.h>\nint main(){\n int gdriver = DETECT,gmode,i;\n initgraph(&gdriver,&gmode,\"C:\\\\Turboc3\\\\BGI\");\n settextstyle(3,1,4);\n return 0;\n}" }, { "code": null, "e": 2222, "s": 2108, "text": "Outtext − this function is used to print the message passed to it at some certain coordinates(x,y) on the screen." }, { "code": null, "e": 2271, "s": 2222, "text": "outtext(int x_cordinate , int y_cordinate, text)" }, { "code": null, "e": 2453, "s": 2271, "text": "#include<stdio.h>\n#include<graphics.h>\nint main(){\n int gdriver = DETECT,gmode,i;\n initgraph(&gdriver,&gmode,\"C:\\\\Turboc3\\\\BGI\");\n settextstyle(25,15,’hello!’);\n return 0;\n}" }, { "code": null, "e": 2545, "s": 2453, "text": "textheight() − this function is used to change the height of the text in the output screen." }, { "code": null, "e": 2561, "s": 2545, "text": "textheight(int)" }, { "code": null, "e": 2651, "s": 2561, "text": "textwidth() − This function is used to change the width of the text in the output screen." }, { "code": null, "e": 2666, "s": 2651, "text": "textwidth(int)" } ]
How do I get the id after INSERT into MySQL database in Python?
First, we need to complete the below requirements. The following are the prerequisites. We need to install MySQL version 8.0.12. We need to install Python version 3.6.3 (32 bit). We need to install pymysql with the help of pip command. To install “pymysql” with the help of pip command. The database name is ‘business’ and the table name is ‘student’ with ID 3 after inserting records. Here is the query. mysql> select *from student; The following is the output. +------+-------+ | id | Name | +------+-------+ | 1 | John | | 2 | Bob | | 3 | Smith | +------+-------+ 3 rows in set (0.00 sec) We can get it with the help of Python for the same table name and database business. The Python code snapshot is as follows − The following is the output. The output for MySQL and Python gets the ID after inserting::
[ { "code": null, "e": 1150, "s": 1062, "text": "First, we need to complete the below requirements. The following are the prerequisites." }, { "code": null, "e": 1191, "s": 1150, "text": "We need to install MySQL version 8.0.12." }, { "code": null, "e": 1241, "s": 1191, "text": "We need to install Python version 3.6.3 (32 bit)." }, { "code": null, "e": 1298, "s": 1241, "text": "We need to install pymysql with the help of pip command." }, { "code": null, "e": 1349, "s": 1298, "text": "To install “pymysql” with the help of pip command." }, { "code": null, "e": 1448, "s": 1349, "text": "The database name is ‘business’ and the table name is ‘student’ with ID 3 after inserting records." }, { "code": null, "e": 1467, "s": 1448, "text": "Here is the query." }, { "code": null, "e": 1496, "s": 1467, "text": "mysql> select *from student;" }, { "code": null, "e": 1525, "s": 1496, "text": "The following is the output." }, { "code": null, "e": 1670, "s": 1525, "text": "+------+-------+\n| id | Name |\n+------+-------+\n| 1 | John |\n| 2 | Bob |\n| 3 | Smith |\n+------+-------+\n3 rows in set (0.00 sec)\n" }, { "code": null, "e": 1755, "s": 1670, "text": "We can get it with the help of Python for the same table name and database business." }, { "code": null, "e": 1796, "s": 1755, "text": "The Python code snapshot is as follows −" }, { "code": null, "e": 1825, "s": 1796, "text": "The following is the output." }, { "code": null, "e": 1887, "s": 1825, "text": "The output for MySQL and Python gets the ID after inserting::" } ]
Linking of MySql Database in Node.js Backend Side - GeeksforGeeks
18 Nov, 2020 We can link our MySQL Database in Node.js Backend Side with the mysql module. This module helps in connecting our database with the backend server for storing the data. Prerequisites: Properly installed node in your system. Properly installed npm (node package manager) in your system. MySQL server installed in your system. Module installation: To download and install the mysql module, open the Command Terminal, and execute the following command: npm install mysql Create Connection & Database: Start by creating a connection to the database by creating a database name as gfg. Use the username and password from your MySQL database gfg. Filename: db.js Javascript var mysql = require('mysql'); var con = mysql.createConnection({ host: "localhost", user: "yourusername", password: "yourpassword"}); // Created the Connection/*con.connect(function(err) { if (err) throw err; console.log("Connected!");});*/ // Created the Database named as "gfg"con.connect(function (err) { if (err) throw err; console.log("Connected!"); con.query("CREATE DATABASE gfg", function (err, result) { if (err) throw err; console.log("Database created"); });}); Run the db.js file using the following command: node db.js The output of the above command Query a Database: Use SQL statements to read from (or write to) a MySQL database. This is also called ‘to query’ the database. The connection object created in the example above has a method for querying the database. Now let’s create a new file named table.js by creating the table name as ‘geeksforgeeks’. Filename: table.js Javascript var mysql = require('mysql');var con = mysql.createConnection({ host: "localhost", user: "yourusername", password: "yourpassword", database: "gfg"}); con.connect(function (err) { if (err) throw err; console.log("Connected!"); // var sql = "CREATE TABLE // geeksforgeeks (name VARCHAR(255), // address VARCHAR(255))"; // var sql = "ALTER TABLE // geeksforgeeks ADD COLUMN id INT // AUTO_INCREMENT PRIMARY KEY"; var sql1 = "CREATE TABLE geeksforgeeks " + "(id INT AUTO_INCREMENT PRIMARY KEY," + " name VARCHAR(255), address VARCHAR(255))"; var sql2 = "INSERT INTO geeksforgeeks (name, " + "address) VALUES ('Company Inc', " + "'Highway 37')"; var sql3 = "SELECT * FROM geeksforgeeks " + "WHERE address = 'Highway 37'"; con.query(sql1, function (err, result) { if (err) throw err; console.log("Table created"); }); con.query(sql2, function (err, result) { if (err) throw err; console.log("Insertion Successful"); }); con.query(sql3, function (err, result) { if (err) throw err; console.log(result); });}); Run the table.js file using the following command: node table.js We will create the table, insert the records, and do the query as per requirement. In this way, we have created the database, table, and done the query after insertion of the records. Node.js-Misc Technical Scripter 2020 Node.js SQL Technical Scripter Web Technologies SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Express.js express.Router() Function JWT Authentication with Node.js Express.js req.params Property Difference between npm i and npm ci in Node.js Mongoose Populate() Method SQL | DDL, DQL, DML, DCL and TCL Commands SQL | Join (Inner, Left, Right and Full Joins) SQL | WITH clause How to find Nth highest salary from a table SQL | ALTER (RENAME)
[ { "code": null, "e": 24842, "s": 24814, "text": "\n18 Nov, 2020" }, { "code": null, "e": 25011, "s": 24842, "text": "We can link our MySQL Database in Node.js Backend Side with the mysql module. This module helps in connecting our database with the backend server for storing the data." }, { "code": null, "e": 25026, "s": 25011, "text": "Prerequisites:" }, { "code": null, "e": 25066, "s": 25026, "text": "Properly installed node in your system." }, { "code": null, "e": 25128, "s": 25066, "text": "Properly installed npm (node package manager) in your system." }, { "code": null, "e": 25167, "s": 25128, "text": "MySQL server installed in your system." }, { "code": null, "e": 25292, "s": 25167, "text": "Module installation: To download and install the mysql module, open the Command Terminal, and execute the following command:" }, { "code": null, "e": 25310, "s": 25292, "text": "npm install mysql" }, { "code": null, "e": 25483, "s": 25310, "text": "Create Connection & Database: Start by creating a connection to the database by creating a database name as gfg. Use the username and password from your MySQL database gfg." }, { "code": null, "e": 25499, "s": 25483, "text": "Filename: db.js" }, { "code": null, "e": 25510, "s": 25499, "text": "Javascript" }, { "code": "var mysql = require('mysql'); var con = mysql.createConnection({ host: \"localhost\", user: \"yourusername\", password: \"yourpassword\"}); // Created the Connection/*con.connect(function(err) { if (err) throw err; console.log(\"Connected!\");});*/ // Created the Database named as \"gfg\"con.connect(function (err) { if (err) throw err; console.log(\"Connected!\"); con.query(\"CREATE DATABASE gfg\", function (err, result) { if (err) throw err; console.log(\"Database created\"); });});", "e": 26044, "s": 25510, "text": null }, { "code": null, "e": 26092, "s": 26044, "text": "Run the db.js file using the following command:" }, { "code": null, "e": 26103, "s": 26092, "text": "node db.js" }, { "code": null, "e": 26135, "s": 26103, "text": "The output of the above command" }, { "code": null, "e": 26353, "s": 26135, "text": "Query a Database: Use SQL statements to read from (or write to) a MySQL database. This is also called ‘to query’ the database. The connection object created in the example above has a method for querying the database." }, { "code": null, "e": 26443, "s": 26353, "text": "Now let’s create a new file named table.js by creating the table name as ‘geeksforgeeks’." }, { "code": null, "e": 26462, "s": 26443, "text": "Filename: table.js" }, { "code": null, "e": 26473, "s": 26462, "text": "Javascript" }, { "code": "var mysql = require('mysql');var con = mysql.createConnection({ host: \"localhost\", user: \"yourusername\", password: \"yourpassword\", database: \"gfg\"}); con.connect(function (err) { if (err) throw err; console.log(\"Connected!\"); // var sql = \"CREATE TABLE // geeksforgeeks (name VARCHAR(255), // address VARCHAR(255))\"; // var sql = \"ALTER TABLE // geeksforgeeks ADD COLUMN id INT // AUTO_INCREMENT PRIMARY KEY\"; var sql1 = \"CREATE TABLE geeksforgeeks \" + \"(id INT AUTO_INCREMENT PRIMARY KEY,\" + \" name VARCHAR(255), address VARCHAR(255))\"; var sql2 = \"INSERT INTO geeksforgeeks (name, \" + \"address) VALUES ('Company Inc', \" + \"'Highway 37')\"; var sql3 = \"SELECT * FROM geeksforgeeks \" + \"WHERE address = 'Highway 37'\"; con.query(sql1, function (err, result) { if (err) throw err; console.log(\"Table created\"); }); con.query(sql2, function (err, result) { if (err) throw err; console.log(\"Insertion Successful\"); }); con.query(sql3, function (err, result) { if (err) throw err; console.log(result); });});", "e": 27636, "s": 26473, "text": null }, { "code": null, "e": 27687, "s": 27636, "text": "Run the table.js file using the following command:" }, { "code": null, "e": 27701, "s": 27687, "text": "node table.js" }, { "code": null, "e": 27885, "s": 27701, "text": "We will create the table, insert the records, and do the query as per requirement. In this way, we have created the database, table, and done the query after insertion of the records." }, { "code": null, "e": 27898, "s": 27885, "text": "Node.js-Misc" }, { "code": null, "e": 27922, "s": 27898, "text": "Technical Scripter 2020" }, { "code": null, "e": 27930, "s": 27922, "text": "Node.js" }, { "code": null, "e": 27934, "s": 27930, "text": "SQL" }, { "code": null, "e": 27953, "s": 27934, "text": "Technical Scripter" }, { "code": null, "e": 27970, "s": 27953, "text": "Web Technologies" }, { "code": null, "e": 27974, "s": 27970, "text": "SQL" }, { "code": null, "e": 28072, "s": 27974, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28081, "s": 28072, "text": "Comments" }, { "code": null, "e": 28094, "s": 28081, "text": "Old Comments" }, { "code": null, "e": 28131, "s": 28094, "text": "Express.js express.Router() Function" }, { "code": null, "e": 28163, "s": 28131, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 28194, "s": 28163, "text": "Express.js req.params Property" }, { "code": null, "e": 28241, "s": 28194, "text": "Difference between npm i and npm ci in Node.js" }, { "code": null, "e": 28268, "s": 28241, "text": "Mongoose Populate() Method" }, { "code": null, "e": 28310, "s": 28268, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 28357, "s": 28310, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 28375, "s": 28357, "text": "SQL | WITH clause" }, { "code": null, "e": 28419, "s": 28375, "text": "How to find Nth highest salary from a table" } ]
Nodejs & DevOps: tricks to configure GitHub actions for node. | Towards Data Science
Who has read my articles knows my vision about the future of DevOps and cloud adoption (just DevOps is dead, long life to NoOps to mention one). To explain it without losing myself in out of scope though, I believe in automation and getting ready to go solutions (cloud, tools, etc.) that make us focus on application only. This approach leads developers to a sustainable approach and we should always find an automated way for deployments that comes for free with limited effort. In this article, I will share with you the configuration that I have adopted for deploying MESS (MongoDB Event Sourcing System), my first Node.js opensource project. The configuration is a single YAML file that unlocks infinite powers to your GitHub repository. What I realized here is a simple configuration that satisfies all the basic needs of a nowadays enterprise application: automatically version code run test on every release publish artefact to NPMJS (in case you have a library or you are delivering through NPM) publish your docker container ready to go to a container repository All these features may seem hard to be reached, but you will discover that will come more or less out of the box using GitHub actions. This guide will explain the tricks in few simple steps: creating a simple node.js applicationAdding a workflow with GitHub ActionAuto-tagging the source code using SemverPushing on NPM.js on each commitPushing on Docker Hub on each commit creating a simple node.js application Adding a workflow with GitHub Action Auto-tagging the source code using Semver Pushing on NPM.js on each commit Pushing on Docker Hub on each commit Let’s see how it is easy! It’s clear that we need something to deploy before starting the cool part of the tutorial. To do so, we need just a simple node.js application. The first step is to create a new one using npm CLI. npm init npm install express --save The command above init the node application and install express as a web server. For demo purposes, we can just create an app with some dummy endpoints. Create a file named main.js with the following content: Now you can alter the npm package by entering the definition of the run command. In the next example, I used supervisor for having hot reload on dev environment and regular node for the production. Type npm run serve for seeing your app live. Once we have a dummy application to test, we have to commit it to a public or private GitHub repo. This step should be quite easy for all developers so I won’t waste time explaining it 😃 Once the code is pushed, you can open the GitHub pages and click on “Action”, then click on the “New Workflow” button as in the next image. This will ask what template use, in our case we will choose the node.js one, but this won't exclude do access to all other action available. Now we are ready for setting up the workflow! First of all few words about SemVer for those who are not used to it. SemVer is a semantic versioning numbering system that, in simple words, compute the version of a software basing on the commit history. In an example, it increases the patch number (1.0.x) on each commit or increments the minor version (1.X.0) each time you merge a feature branch on the master. As you can imagine you can adapt the convention to meet your numbering requirements. To enable the automatic versioning you just need to add the following steps: As you can see in the code there are two different steps. The first one enables the plugin for managing semver tagging, the second one simply displays it to the console. The trick here is to add an id for the first step, this will allow you to use the output variable like ${{steps.version-bump.outputs.newTag}} . At this point, we have the versioning done. Yes, because this package tags each commit and change the package.json version attribute automatically. Well, now it’s time to push our code to NPM! The push step on NPM is quite easy. The first step is to add a Secret value with the NPM token that you can get from your profile on NPM. The Secret section is available on GitHub under the “Settings” tab on your repo. In the next image, you will see the NPM_TOKEN and the other settings that we will use for docker support. Now we can add the following configuration to the workflow: This step uses the information on the package.json file for testing and publishing the code on NPM. That’s all! Just jump to the next section to publishing our code to docker also. The first step for enabling the deployment on docker is to create a Docker image to commit. To do so, just add a Dockerfile with the following content: ROM node:alpine as builder WORKDIR /usr/src/app COPY ./ /usr/src/app RUN npm install FROM node:alpine as app WORKDIR /usr/src/app COPY --from=builder /usr/src/app /usr/src/app ENTRYPOINT ["/bin/sh", "-c" , "pwd & ls & npm run serve"] To build and publish the Docker image you have just to add another piece of code into the workflow YAML. The next one is enough: The YAML performs the steps: login, get info for the image, build & publish. The variables DOCKER_USERNAME,DOCKER_PASSWORD are GitHub secret. For security, you can use an auth token instead of a password. This can be generated by your Docker Hub account profile. In this example I use a double tag: I tag with “latest” each image and I add a tag based on the Semver. The Trick is done by adding two labels on the same image with the setting: tags: zeppaman/mongo-event-sourcing:latest, zeppaman/mongo-event-sourcing:${{ steps.version-bump.outputs.newTag }} As you can see, I used the output variable from the tagging steps. Now all the configuration is completed and we have the pipeline set. Easy, right? GitHub action is a very easy tool for implementing a build pipeline. The setup easily integrates with NPM and Docker and this enables your application to be easily consumed by all the platform that is based on containers. I’m referring to Kubernetes and to the other cloud platforms. Moreover, you can also deploy by npm for sharing the library or for allowing customization of your application. That’s why I chose this setup for my open-source app and I easily find a setup that could help users to adopt it smoothly. Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you. The GitHub Project The NPM package The Docker Image
[ { "code": null, "e": 557, "s": 172, "text": "Who has read my articles knows my vision about the future of DevOps and cloud adoption (just DevOps is dead, long life to NoOps to mention one). To explain it without losing myself in out of scope though, I believe in automation and getting ready to go solutions (cloud, tools, etc.) that make us focus on application only. This approach leads developers to a sustainable approach and" }, { "code": null, "e": 653, "s": 557, "text": "we should always find an automated way for deployments that comes for free with limited effort." }, { "code": null, "e": 915, "s": 653, "text": "In this article, I will share with you the configuration that I have adopted for deploying MESS (MongoDB Event Sourcing System), my first Node.js opensource project. The configuration is a single YAML file that unlocks infinite powers to your GitHub repository." }, { "code": null, "e": 1035, "s": 915, "text": "What I realized here is a simple configuration that satisfies all the basic needs of a nowadays enterprise application:" }, { "code": null, "e": 1062, "s": 1035, "text": "automatically version code" }, { "code": null, "e": 1088, "s": 1062, "text": "run test on every release" }, { "code": null, "e": 1177, "s": 1088, "text": "publish artefact to NPMJS (in case you have a library or you are delivering through NPM)" }, { "code": null, "e": 1245, "s": 1177, "text": "publish your docker container ready to go to a container repository" }, { "code": null, "e": 1436, "s": 1245, "text": "All these features may seem hard to be reached, but you will discover that will come more or less out of the box using GitHub actions. This guide will explain the tricks in few simple steps:" }, { "code": null, "e": 1619, "s": 1436, "text": "creating a simple node.js applicationAdding a workflow with GitHub ActionAuto-tagging the source code using SemverPushing on NPM.js on each commitPushing on Docker Hub on each commit" }, { "code": null, "e": 1657, "s": 1619, "text": "creating a simple node.js application" }, { "code": null, "e": 1694, "s": 1657, "text": "Adding a workflow with GitHub Action" }, { "code": null, "e": 1736, "s": 1694, "text": "Auto-tagging the source code using Semver" }, { "code": null, "e": 1769, "s": 1736, "text": "Pushing on NPM.js on each commit" }, { "code": null, "e": 1806, "s": 1769, "text": "Pushing on Docker Hub on each commit" }, { "code": null, "e": 1832, "s": 1806, "text": "Let’s see how it is easy!" }, { "code": null, "e": 2029, "s": 1832, "text": "It’s clear that we need something to deploy before starting the cool part of the tutorial. To do so, we need just a simple node.js application. The first step is to create a new one using npm CLI." }, { "code": null, "e": 2065, "s": 2029, "text": "npm init npm install express --save" }, { "code": null, "e": 2274, "s": 2065, "text": "The command above init the node application and install express as a web server. For demo purposes, we can just create an app with some dummy endpoints. Create a file named main.js with the following content:" }, { "code": null, "e": 2472, "s": 2274, "text": "Now you can alter the npm package by entering the definition of the run command. In the next example, I used supervisor for having hot reload on dev environment and regular node for the production." }, { "code": null, "e": 2517, "s": 2472, "text": "Type npm run serve for seeing your app live." }, { "code": null, "e": 2704, "s": 2517, "text": "Once we have a dummy application to test, we have to commit it to a public or private GitHub repo. This step should be quite easy for all developers so I won’t waste time explaining it 😃" }, { "code": null, "e": 2844, "s": 2704, "text": "Once the code is pushed, you can open the GitHub pages and click on “Action”, then click on the “New Workflow” button as in the next image." }, { "code": null, "e": 2985, "s": 2844, "text": "This will ask what template use, in our case we will choose the node.js one, but this won't exclude do access to all other action available." }, { "code": null, "e": 3031, "s": 2985, "text": "Now we are ready for setting up the workflow!" }, { "code": null, "e": 3482, "s": 3031, "text": "First of all few words about SemVer for those who are not used to it. SemVer is a semantic versioning numbering system that, in simple words, compute the version of a software basing on the commit history. In an example, it increases the patch number (1.0.x) on each commit or increments the minor version (1.X.0) each time you merge a feature branch on the master. As you can imagine you can adapt the convention to meet your numbering requirements." }, { "code": null, "e": 3559, "s": 3482, "text": "To enable the automatic versioning you just need to add the following steps:" }, { "code": null, "e": 4021, "s": 3559, "text": "As you can see in the code there are two different steps. The first one enables the plugin for managing semver tagging, the second one simply displays it to the console. The trick here is to add an id for the first step, this will allow you to use the output variable like ${{steps.version-bump.outputs.newTag}} . At this point, we have the versioning done. Yes, because this package tags each commit and change the package.json version attribute automatically." }, { "code": null, "e": 4066, "s": 4021, "text": "Well, now it’s time to push our code to NPM!" }, { "code": null, "e": 4391, "s": 4066, "text": "The push step on NPM is quite easy. The first step is to add a Secret value with the NPM token that you can get from your profile on NPM. The Secret section is available on GitHub under the “Settings” tab on your repo. In the next image, you will see the NPM_TOKEN and the other settings that we will use for docker support." }, { "code": null, "e": 4451, "s": 4391, "text": "Now we can add the following configuration to the workflow:" }, { "code": null, "e": 4632, "s": 4451, "text": "This step uses the information on the package.json file for testing and publishing the code on NPM. That’s all! Just jump to the next section to publishing our code to docker also." }, { "code": null, "e": 4784, "s": 4632, "text": "The first step for enabling the deployment on docker is to create a Docker image to commit. To do so, just add a Dockerfile with the following content:" }, { "code": null, "e": 5019, "s": 4784, "text": "ROM node:alpine as builder WORKDIR /usr/src/app COPY ./ /usr/src/app RUN npm install FROM node:alpine as app WORKDIR /usr/src/app COPY --from=builder /usr/src/app /usr/src/app ENTRYPOINT [\"/bin/sh\", \"-c\" , \"pwd & ls & npm run serve\"]" }, { "code": null, "e": 5148, "s": 5019, "text": "To build and publish the Docker image you have just to add another piece of code into the workflow YAML. The next one is enough:" }, { "code": null, "e": 5590, "s": 5148, "text": "The YAML performs the steps: login, get info for the image, build & publish. The variables DOCKER_USERNAME,DOCKER_PASSWORD are GitHub secret. For security, you can use an auth token instead of a password. This can be generated by your Docker Hub account profile. In this example I use a double tag: I tag with “latest” each image and I add a tag based on the Semver. The Trick is done by adding two labels on the same image with the setting:" }, { "code": null, "e": 5705, "s": 5590, "text": "tags: zeppaman/mongo-event-sourcing:latest, zeppaman/mongo-event-sourcing:${{ steps.version-bump.outputs.newTag }}" }, { "code": null, "e": 5854, "s": 5705, "text": "As you can see, I used the output variable from the tagging steps. Now all the configuration is completed and we have the pipeline set. Easy, right?" }, { "code": null, "e": 6250, "s": 5854, "text": "GitHub action is a very easy tool for implementing a build pipeline. The setup easily integrates with NPM and Docker and this enables your application to be easily consumed by all the platform that is based on containers. I’m referring to Kubernetes and to the other cloud platforms. Moreover, you can also deploy by npm for sharing the library or for allowing customization of your application." }, { "code": null, "e": 6373, "s": 6250, "text": "That’s why I chose this setup for my open-source app and I easily find a setup that could help users to adopt it smoothly." }, { "code": null, "e": 6556, "s": 6373, "text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you." }, { "code": null, "e": 6575, "s": 6556, "text": "The GitHub Project" }, { "code": null, "e": 6591, "s": 6575, "text": "The NPM package" } ]
JavaScript | Classes
25 Nov, 2021 Introduction of new version of JavaScript (ES6) introduced the use of classes instead of functions.Classes are similar to functions.They use class keyword instead of function keyword. They use constructor method to initialise. Syntax: class classname { constructor(parameter) { this.classname = parameter; } } Below example illustrates the JavaScript classes: html <!DOCTYPE html><html> <body> <center> <h1 style="color: green;"> GeeksforGeeks </h1> <p> A Computer Science Portal for Geeks </p> <b>JavaScript Classes</b> <p id="demo"></p> <script> class class_name { constructor(value) { this.classes = value; } } myvalue = new class_name("GeeksforGeeks"); document.getElementById("demo").innerHTML = myvalue.classes; </script> </center></body> </html> Output: varshagumber28 javascript-basics Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Nov, 2021" }, { "code": null, "e": 280, "s": 52, "text": "Introduction of new version of JavaScript (ES6) introduced the use of classes instead of functions.Classes are similar to functions.They use class keyword instead of function keyword. They use constructor method to initialise. " }, { "code": null, "e": 288, "s": 280, "text": "Syntax:" }, { "code": null, "e": 371, "s": 288, "text": "class classname {\n constructor(parameter) {\n this.classname = parameter;\n }\n}" }, { "code": null, "e": 421, "s": 371, "text": "Below example illustrates the JavaScript classes:" }, { "code": null, "e": 426, "s": 421, "text": "html" }, { "code": "<!DOCTYPE html><html> <body> <center> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <p> A Computer Science Portal for Geeks </p> <b>JavaScript Classes</b> <p id=\"demo\"></p> <script> class class_name { constructor(value) { this.classes = value; } } myvalue = new class_name(\"GeeksforGeeks\"); document.getElementById(\"demo\").innerHTML = myvalue.classes; </script> </center></body> </html>", "e": 1010, "s": 426, "text": null }, { "code": null, "e": 1020, "s": 1010, "text": "Output: " }, { "code": null, "e": 1037, "s": 1022, "text": "varshagumber28" }, { "code": null, "e": 1055, "s": 1037, "text": "javascript-basics" }, { "code": null, "e": 1062, "s": 1055, "text": "Picked" }, { "code": null, "e": 1073, "s": 1062, "text": "JavaScript" }, { "code": null, "e": 1090, "s": 1073, "text": "Web Technologies" } ]
Using Lynx to Browse the Web From the Linux Terminal
03 Oct, 2019 Lynx is a terminal-based web browser for all Linux distributions. It shows the result as plain text on the terminal. It is a classic non-graphical text-mode web browser which displays the pages on the terminal. Lynx does not load images and multimedia contents, hence it is fast as compared to other browsers. One who do not want so many images and multimedia contents on web pages, they prefer using lynx. It is easy to install and easy to use and it does not require any additional interface to run or show the contents, it does so on the terminal.Lynx does not come by default with ubuntu, we need to install it using the command: sudo apt-get install lynx After installation, we can simply browse the pages using the command: lynx desired url Up arrow, Down arrow and Tab keys are used to navigate to different links in the web page. It also provides a feature to ask to save cookies of the requested web page i.e we are given choices whether choosing to save the cookies or not. Properties of Lynx Browser: Text-based Web Browser Highly configurable Commands used to configure Oldest web browser in use Supports many features of HTML Compatible with old hardware Linux-Unix Technical Scripter TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ZIP command in Linux with examples tar command in Linux with examples curl command in Linux with Examples TCP Server-Client implementation in C Conditional Statements | Shell Script How to Find the Wi-Fi Password Using CMD in Windows? Docker - COPY Instruction Setting up the environment in Java How to Run a Python Script using Docker? Running Python script on GPU.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Oct, 2019" }, { "code": null, "e": 662, "s": 28, "text": "Lynx is a terminal-based web browser for all Linux distributions. It shows the result as plain text on the terminal. It is a classic non-graphical text-mode web browser which displays the pages on the terminal. Lynx does not load images and multimedia contents, hence it is fast as compared to other browsers. One who do not want so many images and multimedia contents on web pages, they prefer using lynx. It is easy to install and easy to use and it does not require any additional interface to run or show the contents, it does so on the terminal.Lynx does not come by default with ubuntu, we need to install it using the command:" }, { "code": null, "e": 688, "s": 662, "text": "sudo apt-get install lynx" }, { "code": null, "e": 758, "s": 688, "text": "After installation, we can simply browse the pages using the command:" }, { "code": null, "e": 775, "s": 758, "text": "lynx desired url" }, { "code": null, "e": 1012, "s": 775, "text": "Up arrow, Down arrow and Tab keys are used to navigate to different links in the web page. It also provides a feature to ask to save cookies of the requested web page i.e we are given choices whether choosing to save the cookies or not." }, { "code": null, "e": 1040, "s": 1012, "text": "Properties of Lynx Browser:" }, { "code": null, "e": 1063, "s": 1040, "text": "Text-based Web Browser" }, { "code": null, "e": 1083, "s": 1063, "text": "Highly configurable" }, { "code": null, "e": 1110, "s": 1083, "text": "Commands used to configure" }, { "code": null, "e": 1136, "s": 1110, "text": "Oldest web browser in use" }, { "code": null, "e": 1167, "s": 1136, "text": "Supports many features of HTML" }, { "code": null, "e": 1196, "s": 1167, "text": "Compatible with old hardware" }, { "code": null, "e": 1207, "s": 1196, "text": "Linux-Unix" }, { "code": null, "e": 1226, "s": 1207, "text": "Technical Scripter" }, { "code": null, "e": 1235, "s": 1226, "text": "TechTips" }, { "code": null, "e": 1333, "s": 1235, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1368, "s": 1333, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 1403, "s": 1368, "text": "tar command in Linux with examples" }, { "code": null, "e": 1439, "s": 1403, "text": "curl command in Linux with Examples" }, { "code": null, "e": 1477, "s": 1439, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 1515, "s": 1477, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 1568, "s": 1515, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 1594, "s": 1568, "text": "Docker - COPY Instruction" }, { "code": null, "e": 1629, "s": 1594, "text": "Setting up the environment in Java" }, { "code": null, "e": 1670, "s": 1629, "text": "How to Run a Python Script using Docker?" } ]
What is the Shortcut to Auto Import All in Android Studio?
07 Mar, 2021 There are some basics import in Android Studio that is predefined present in Android studio. like Menu, AppBar, MenuItem, Bundle, Toast, etc. When we require those then we import that manually. In case of pasting some code copied from the Internet in Editor, it asks to import every Views and class. You can simply import all of them by pressing the ALT + ENTER key. Here, we are going to explain how to auto-import all in Android studio. Import like this: import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; Step 1: Go to File and then Select Settings Step 2: Then Go to Editor > General > Auto Import Here Select Java and then change Insert imports on paste value to All Step 3: Then mark the “Add unambiguous imports on the fly” option as checked. Then click on Apply and Ok. Note: We can import a single missing import using Alt + Enter which shown in the pop-up. To optimize imports (to remove unused imports ) use Ctrl + Alt + O. If for some reason auto-import is not enabled you can go to settings by typing shortcut: Ctrl + Alt + S. If you use macOS, the only difference is where you can configure the above settings. Just click Android Studio > Preferences. The subsequent settings are very similar. Android-Studio Picked Android Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference Between Implicit Intent and Explicit Intent in Android Retrofit with Kotlin Coroutine in Android Flutter - BoxShadow Widget Bundle in Android with Example Animation in Android with Example ExoPlayer in Android with Example Bottom Navigation Bar in Android Using Kotlin How to Post Data to API using Retrofit in Android? Android | How to Create/Start a New Project in Android Studio? Data Binding in Android with Example
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Mar, 2021" }, { "code": null, "e": 492, "s": 52, "text": "There are some basics import in Android Studio that is predefined present in Android studio. like Menu, AppBar, MenuItem, Bundle, Toast, etc. When we require those then we import that manually. In case of pasting some code copied from the Internet in Editor, it asks to import every Views and class. You can simply import all of them by pressing the ALT + ENTER key. Here, we are going to explain how to auto-import all in Android studio. " }, { "code": null, "e": 510, "s": 492, "text": "Import like this:" }, { "code": null, "e": 536, "s": 510, "text": "import android.os.Bundle;" }, { "code": null, "e": 585, "s": 536, "text": "import android.support.v7.app.ActionBarActivity;" }, { "code": null, "e": 611, "s": 585, "text": "import android.view.Menu;" }, { "code": null, "e": 641, "s": 611, "text": "import android.view.MenuItem;" }, { "code": null, "e": 685, "s": 641, "text": "Step 1: Go to File and then Select Settings" }, { "code": null, "e": 736, "s": 685, "text": "Step 2: Then Go to Editor > General > Auto Import " }, { "code": null, "e": 806, "s": 736, "text": "Here Select Java and then change Insert imports on paste value to All" }, { "code": null, "e": 912, "s": 806, "text": "Step 3: Then mark the “Add unambiguous imports on the fly” option as checked. Then click on Apply and Ok." }, { "code": null, "e": 1174, "s": 912, "text": "Note: We can import a single missing import using Alt + Enter which shown in the pop-up. To optimize imports (to remove unused imports ) use Ctrl + Alt + O. If for some reason auto-import is not enabled you can go to settings by typing shortcut: Ctrl + Alt + S." }, { "code": null, "e": 1342, "s": 1174, "text": "If you use macOS, the only difference is where you can configure the above settings. Just click Android Studio > Preferences. The subsequent settings are very similar." }, { "code": null, "e": 1357, "s": 1342, "text": "Android-Studio" }, { "code": null, "e": 1364, "s": 1357, "text": "Picked" }, { "code": null, "e": 1372, "s": 1364, "text": "Android" }, { "code": null, "e": 1380, "s": 1372, "text": "Android" }, { "code": null, "e": 1478, "s": 1380, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1544, "s": 1478, "text": "Difference Between Implicit Intent and Explicit Intent in Android" }, { "code": null, "e": 1586, "s": 1544, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 1613, "s": 1586, "text": "Flutter - BoxShadow Widget" }, { "code": null, "e": 1644, "s": 1613, "text": "Bundle in Android with Example" }, { "code": null, "e": 1678, "s": 1644, "text": "Animation in Android with Example" }, { "code": null, "e": 1712, "s": 1678, "text": "ExoPlayer in Android with Example" }, { "code": null, "e": 1758, "s": 1712, "text": "Bottom Navigation Bar in Android Using Kotlin" }, { "code": null, "e": 1809, "s": 1758, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 1872, "s": 1809, "text": "Android | How to Create/Start a New Project in Android Studio?" } ]
Java Program to Display Floyd’s Triangle
28 Jul, 2021 Floyd’s triangle is a triangle with first natural numbers. It is the right arrangement of the numbers/values or patterns. Basically, it is a left to right arrangement of natural numbers in a right-angled triangle Illustration: Suppose if no of rows to be displayed is 5 then the desired output should display 5 rows as: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Algorithm: Initialization of variablesCreate variables in memory holding rows and columns.Create and initialize variable holding patterns or values to be displayed.Traversing over rows and columns using nested for loops.Outer loop for rows.Inner loop for columns in the current row.Dealing with variable holding dynamic values as per execution as initialized outside nested loops.If values are to be displayed, increment this variable inside the loop for rows and outside loop for columns.If patterns are to be displayed, assign the character outside loop while creation and no alternation of holder value in any of loops. Initialization of variablesCreate variables in memory holding rows and columns.Create and initialize variable holding patterns or values to be displayed. Create variables in memory holding rows and columns. Create and initialize variable holding patterns or values to be displayed. Traversing over rows and columns using nested for loops.Outer loop for rows.Inner loop for columns in the current row. Outer loop for rows. Inner loop for columns in the current row. Dealing with variable holding dynamic values as per execution as initialized outside nested loops.If values are to be displayed, increment this variable inside the loop for rows and outside loop for columns.If patterns are to be displayed, assign the character outside loop while creation and no alternation of holder value in any of loops. If values are to be displayed, increment this variable inside the loop for rows and outside loop for columns. If patterns are to be displayed, assign the character outside loop while creation and no alternation of holder value in any of loops. Implementation: Floyd’s Triangle Example Java // Java program to display Floyd's triangle // Importing Java librariesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // No of rows to be printed int n = 5; // Creating and initializing variable for // rows, columns and display value int i, j, k = 1; // Nested iterating for 2D matrix // Outer loop for rows for (i = 1; i <= n; i++) { // Inner loop for columns for (j = 1; j <= i; j++) { // Printing value to be displayed System.out.print(k + " "); // Incremeting value displayed k++; } // Print elements of next row System.out.println(); } }} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 abhijithoyur pradiptamukherjee Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jul, 2021" }, { "code": null, "e": 267, "s": 54, "text": "Floyd’s triangle is a triangle with first natural numbers. It is the right arrangement of the numbers/values or patterns. Basically, it is a left to right arrangement of natural numbers in a right-angled triangle" }, { "code": null, "e": 374, "s": 267, "text": "Illustration: Suppose if no of rows to be displayed is 5 then the desired output should display 5 rows as:" }, { "code": null, "e": 410, "s": 374, "text": "1\n2 3\n4 5 6\n7 8 9 10\n11 12 13 14 15" }, { "code": null, "e": 421, "s": 410, "text": "Algorithm:" }, { "code": null, "e": 1033, "s": 421, "text": "Initialization of variablesCreate variables in memory holding rows and columns.Create and initialize variable holding patterns or values to be displayed.Traversing over rows and columns using nested for loops.Outer loop for rows.Inner loop for columns in the current row.Dealing with variable holding dynamic values as per execution as initialized outside nested loops.If values are to be displayed, increment this variable inside the loop for rows and outside loop for columns.If patterns are to be displayed, assign the character outside loop while creation and no alternation of holder value in any of loops." }, { "code": null, "e": 1187, "s": 1033, "text": "Initialization of variablesCreate variables in memory holding rows and columns.Create and initialize variable holding patterns or values to be displayed." }, { "code": null, "e": 1240, "s": 1187, "text": "Create variables in memory holding rows and columns." }, { "code": null, "e": 1315, "s": 1240, "text": "Create and initialize variable holding patterns or values to be displayed." }, { "code": null, "e": 1434, "s": 1315, "text": "Traversing over rows and columns using nested for loops.Outer loop for rows.Inner loop for columns in the current row." }, { "code": null, "e": 1455, "s": 1434, "text": "Outer loop for rows." }, { "code": null, "e": 1498, "s": 1455, "text": "Inner loop for columns in the current row." }, { "code": null, "e": 1839, "s": 1498, "text": "Dealing with variable holding dynamic values as per execution as initialized outside nested loops.If values are to be displayed, increment this variable inside the loop for rows and outside loop for columns.If patterns are to be displayed, assign the character outside loop while creation and no alternation of holder value in any of loops." }, { "code": null, "e": 1949, "s": 1839, "text": "If values are to be displayed, increment this variable inside the loop for rows and outside loop for columns." }, { "code": null, "e": 2083, "s": 1949, "text": "If patterns are to be displayed, assign the character outside loop while creation and no alternation of holder value in any of loops." }, { "code": null, "e": 2116, "s": 2083, "text": "Implementation: Floyd’s Triangle" }, { "code": null, "e": 2125, "s": 2116, "text": "Example " }, { "code": null, "e": 2130, "s": 2125, "text": "Java" }, { "code": "// Java program to display Floyd's triangle // Importing Java librariesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // No of rows to be printed int n = 5; // Creating and initializing variable for // rows, columns and display value int i, j, k = 1; // Nested iterating for 2D matrix // Outer loop for rows for (i = 1; i <= n; i++) { // Inner loop for columns for (j = 1; j <= i; j++) { // Printing value to be displayed System.out.print(k + \" \"); // Incremeting value displayed k++; } // Print elements of next row System.out.println(); } }}", "e": 2933, "s": 2130, "text": null }, { "code": null, "e": 2987, "s": 2933, "text": "1 \n2 3 \n4 5 6 \n7 8 9 10 \n11 12 13 14 15" }, { "code": null, "e": 3000, "s": 2987, "text": "abhijithoyur" }, { "code": null, "e": 3018, "s": 3000, "text": "pradiptamukherjee" }, { "code": null, "e": 3025, "s": 3018, "text": "Picked" }, { "code": null, "e": 3049, "s": 3025, "text": "Technical Scripter 2020" }, { "code": null, "e": 3054, "s": 3049, "text": "Java" }, { "code": null, "e": 3068, "s": 3054, "text": "Java Programs" }, { "code": null, "e": 3087, "s": 3068, "text": "Technical Scripter" }, { "code": null, "e": 3092, "s": 3087, "text": "Java" }, { "code": null, "e": 3190, "s": 3092, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3205, "s": 3190, "text": "Stream In Java" }, { "code": null, "e": 3226, "s": 3205, "text": "Introduction to Java" }, { "code": null, "e": 3247, "s": 3226, "text": "Constructors in Java" }, { "code": null, "e": 3266, "s": 3247, "text": "Exceptions in Java" }, { "code": null, "e": 3283, "s": 3266, "text": "Generics in Java" }, { "code": null, "e": 3309, "s": 3283, "text": "Java Programming Examples" }, { "code": null, "e": 3343, "s": 3309, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 3390, "s": 3343, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 3428, "s": 3390, "text": "Factory method design pattern in Java" } ]
Parametric & Geometric Continuity of Curves in Computer Graphics
27 Jan, 2022 Prerequisite: B-spline curve, Bezier curve The continuity condition represents that how smoothly a curve transit from one curve segment to another segment. Consider you are given a curve as shown below: There are three kinds of Parametric continuities that exist: (a) Zero-order parametric continuity(_C0 ) : A curve is said to be zero-order parametric continuous if both segments of the curve intersect at one endpoint. P(t2) = Q(t1) (b) First-order parametric continuity(C1) : A curve is said to be first-order parametric continuous if it is Co Continuous and the first-order derivative of segment P at t=t2 is equal to the first-order derivative of segment Q at t=t1. Such kinds of curves have the same tangent line at the intersection point. P'(t2) = Q'(t1) (c) Second-order parametric continuity(C2) : A curve is said to be second-order parametric continuous if it is Co and C1 Continuous and the second-order derivative of the segment P at t=t1 is equal to the second-order derivative of segment Q at t=t2. P''(t2) = Q''(t1) Geometric Continuity : It is an alternate method for joining two curve segments, where it requires the parametric derivation of both segments which are proportional to each other rather than equal to each other. (a) Zero-order geometric continuity(Go) : It is similar to the zero-order parametric curve continuity condition. P(t2) = Q(t1) (b) First-order geometric continuity(G1) : The junction point between two points is said to be G1 continuous if the coordinate of both curve segments is G0 continuous and following the below condition: P'(t2) = k * Q'(t1) for all x, y, z and k > 0. (c) Second-order geometric continuity(G2) : The junction point between two points is said to be G2 continuous if the coordinate of both curve segments is G1 continuous and following the below condition: P''(t2) = k * Q''(t1) for all x, y, z and k > 0. miclack30 computer-graphics Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to write Regular Expressions? Virtualization In Cloud Computing and Types Association Rule OOPs | Object Oriented Design Software Engineering | Prototyping Model std::unique in C++ Distributed Database System Java Math min() method with Examples Recursive Functions fgets() and gets() in C language
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Jan, 2022" }, { "code": null, "e": 71, "s": 28, "text": "Prerequisite: B-spline curve, Bezier curve" }, { "code": null, "e": 231, "s": 71, "text": "The continuity condition represents that how smoothly a curve transit from one curve segment to another segment. Consider you are given a curve as shown below:" }, { "code": null, "e": 292, "s": 231, "text": "There are three kinds of Parametric continuities that exist:" }, { "code": null, "e": 449, "s": 292, "text": "(a) Zero-order parametric continuity(_C0 ) : A curve is said to be zero-order parametric continuous if both segments of the curve intersect at one endpoint." }, { "code": null, "e": 504, "s": 449, "text": " P(t2) = Q(t1)" }, { "code": null, "e": 816, "s": 504, "text": "(b) First-order parametric continuity(C1) : A curve is said to be first-order parametric continuous if it is Co Continuous and the first-order derivative of segment P at t=t2 is equal to the first-order derivative of segment Q at t=t1. Such kinds of curves have the same tangent line at the intersection point." }, { "code": null, "e": 869, "s": 816, "text": " P'(t2) = Q'(t1)" }, { "code": null, "e": 1121, "s": 869, "text": "(c) Second-order parametric continuity(C2) : A curve is said to be second-order parametric continuous if it is Co and C1 Continuous and the second-order derivative of the segment P at t=t1 is equal to the second-order derivative of segment Q at t=t2. " }, { "code": null, "e": 1175, "s": 1121, "text": " P''(t2) = Q''(t1)" }, { "code": null, "e": 1387, "s": 1175, "text": "Geometric Continuity : It is an alternate method for joining two curve segments, where it requires the parametric derivation of both segments which are proportional to each other rather than equal to each other." }, { "code": null, "e": 1500, "s": 1387, "text": "(a) Zero-order geometric continuity(Go) : It is similar to the zero-order parametric curve continuity condition." }, { "code": null, "e": 1556, "s": 1500, "text": " P(t2) = Q(t1)" }, { "code": null, "e": 1759, "s": 1556, "text": " (b) First-order geometric continuity(G1) : The junction point between two points is said to be G1 continuous if the coordinate of both curve segments is G0 continuous and following the below condition:" }, { "code": null, "e": 1841, "s": 1759, "text": " P'(t2) = k * Q'(t1) for all x, y, z and k > 0." }, { "code": null, "e": 2044, "s": 1841, "text": "(c) Second-order geometric continuity(G2) : The junction point between two points is said to be G2 continuous if the coordinate of both curve segments is G1 continuous and following the below condition:" }, { "code": null, "e": 2127, "s": 2044, "text": " P''(t2) = k * Q''(t1) for all x, y, z and k > 0." }, { "code": null, "e": 2137, "s": 2127, "text": "miclack30" }, { "code": null, "e": 2155, "s": 2137, "text": "computer-graphics" }, { "code": null, "e": 2160, "s": 2155, "text": "Misc" }, { "code": null, "e": 2165, "s": 2160, "text": "Misc" }, { "code": null, "e": 2170, "s": 2165, "text": "Misc" }, { "code": null, "e": 2268, "s": 2170, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2302, "s": 2268, "text": "How to write Regular Expressions?" }, { "code": null, "e": 2346, "s": 2302, "text": "Virtualization In Cloud Computing and Types" }, { "code": null, "e": 2363, "s": 2346, "text": "Association Rule" }, { "code": null, "e": 2393, "s": 2363, "text": "OOPs | Object Oriented Design" }, { "code": null, "e": 2434, "s": 2393, "text": "Software Engineering | Prototyping Model" }, { "code": null, "e": 2453, "s": 2434, "text": "std::unique in C++" }, { "code": null, "e": 2481, "s": 2453, "text": "Distributed Database System" }, { "code": null, "e": 2518, "s": 2481, "text": "Java Math min() method with Examples" }, { "code": null, "e": 2538, "s": 2518, "text": "Recursive Functions" } ]
Generate a set of Sample data from a Data set in R Programming – sample() Function
28 Jul, 2020 sample() function in R Language creates random sample based on the parameters provided in the function call. It takes either a vector or a positive integer as the object in the function parameter. 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 To know about more optional parameters, use below command in console: help("sample") Example 1: # Create samplex <- sample(1:100, 10, replace=TRUE) # Print# Output may differ each time the command is executedprint(x) Output: [1] 47 52 22 98 75 94 91 94 42 53 Example 2: # Create samplepos <- sample(1:nrow(mtcars), 5, replace = TRUE) # Print sample observations# Output may differ each time the command is executedprint(mtcars[pos, ]) Output: mpg cyl disp hp drat wt qsec vs am gear carb Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2 Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2 Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 Hornet 4 Drive.1 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1 R Statistics-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? R - if statement Logistic Regression in R Programming How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jul, 2020" }, { "code": null, "e": 225, "s": 28, "text": "sample() function in R Language creates random sample based on the parameters provided in the function call. It takes either a vector or a positive integer as the object in the function parameter." }, { "code": null, "e": 257, "s": 225, "text": "Syntax:sample(x, size, replace)" }, { "code": null, "e": 456, "s": 257, "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": 526, "s": 456, "text": "To know about more optional parameters, use below command in console:" }, { "code": null, "e": 542, "s": 526, "text": "help(\"sample\")\n" }, { "code": null, "e": 553, "s": 542, "text": "Example 1:" }, { "code": "# Create samplex <- sample(1:100, 10, replace=TRUE) # Print# Output may differ each time the command is executedprint(x)", "e": 675, "s": 553, "text": null }, { "code": null, "e": 683, "s": 675, "text": "Output:" }, { "code": null, "e": 718, "s": 683, "text": "[1] 47 52 22 98 75 94 91 94 42 53\n" }, { "code": null, "e": 729, "s": 718, "text": "Example 2:" }, { "code": "# Create samplepos <- sample(1:nrow(mtcars), 5, replace = TRUE) # Print sample observations# Output may differ each time the command is executedprint(mtcars[pos, ])", "e": 895, "s": 729, "text": null }, { "code": null, "e": 903, "s": 895, "text": "Output:" }, { "code": null, "e": 1318, "s": 903, "text": " mpg cyl disp hp drat wt qsec vs am gear carb\nHonda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2\nMerc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2\nHornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1\nHornet 4 Drive.1 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1\nFiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1\n" }, { "code": null, "e": 1340, "s": 1318, "text": "R Statistics-Function" }, { "code": null, "e": 1351, "s": 1340, "text": "R Language" }, { "code": null, "e": 1449, "s": 1351, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1501, "s": 1449, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 1559, "s": 1501, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 1594, "s": 1559, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 1632, "s": 1594, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 1649, "s": 1632, "text": "R - if statement" }, { "code": null, "e": 1686, "s": 1649, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 1735, "s": 1686, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 1778, "s": 1735, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 1815, "s": 1778, "text": "How to import an Excel File into R ?" } ]
Node.js Request Module
08 Oct, 2021 The request module is used to make HTTP calls. It is the simplest way of making HTTP calls in node.js using this request module. It follows redirects by default. Feature of Request module: It is easy to get started and easy to use.It is widely used and popular module for making HTTP calls. It is easy to get started and easy to use. It is widely used and popular module for making HTTP calls. Installation of request module: You can visit the link Install Request module. You can install this package by using this command.npm install requestAfter installing request module you can check your request version in command prompt using the command.npm version requestAfter that, you can create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js You can visit the link Install Request module. You can install this package by using this command.npm install request npm install request After installing request module you can check your request version in command prompt using the command.npm version request npm version request After that, you can create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js node index.js Filename: index.js const request = require('request') // Request URLvar url = 'https://jsonplaceholder.typicode.com/todos/1'; request(url, (error, response, body)=>{ // Printing the error if occurred if(error) console.log(error) // Printing status code console.log(response.statusCode); // Printing body console.log(body);}); Steps to run the program: The project structure will look like this:Make sure you have install express and request module using following commands:npm install requestnpm install expressRun index.js file using below command:node index.js The project structure will look like this: Make sure you have install express and request module using following commands:npm install requestnpm install express npm install request npm install express Run index.js file using below command:node index.js node index.js So this is how you can use the request module for making HTTP calls. It is very simple and easy to use. Node.js-Misc Node.js Web Technologies Web technologies Questions Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.writeFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function Installation of Node.js on Windows Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Oct, 2021" }, { "code": null, "e": 216, "s": 54, "text": "The request module is used to make HTTP calls. It is the simplest way of making HTTP calls in node.js using this request module. It follows redirects by default." }, { "code": null, "e": 243, "s": 216, "text": "Feature of Request module:" }, { "code": null, "e": 345, "s": 243, "text": "It is easy to get started and easy to use.It is widely used and popular module for making HTTP calls." }, { "code": null, "e": 388, "s": 345, "text": "It is easy to get started and easy to use." }, { "code": null, "e": 448, "s": 388, "text": "It is widely used and popular module for making HTTP calls." }, { "code": null, "e": 480, "s": 448, "text": "Installation of request module:" }, { "code": null, "e": 861, "s": 480, "text": "You can visit the link Install Request module. You can install this package by using this command.npm install requestAfter installing request module you can check your request version in command prompt using the command.npm version requestAfter that, you can create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js" }, { "code": null, "e": 979, "s": 861, "text": "You can visit the link Install Request module. You can install this package by using this command.npm install request" }, { "code": null, "e": 999, "s": 979, "text": "npm install request" }, { "code": null, "e": 1122, "s": 999, "text": "After installing request module you can check your request version in command prompt using the command.npm version request" }, { "code": null, "e": 1142, "s": 1122, "text": "npm version request" }, { "code": null, "e": 1284, "s": 1142, "text": "After that, you can create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js" }, { "code": null, "e": 1298, "s": 1284, "text": "node index.js" }, { "code": null, "e": 1317, "s": 1298, "text": "Filename: index.js" }, { "code": "const request = require('request') // Request URLvar url = 'https://jsonplaceholder.typicode.com/todos/1'; request(url, (error, response, body)=>{ // Printing the error if occurred if(error) console.log(error) // Printing status code console.log(response.statusCode); // Printing body console.log(body);}); ", "e": 1661, "s": 1317, "text": null }, { "code": null, "e": 1687, "s": 1661, "text": "Steps to run the program:" }, { "code": null, "e": 1898, "s": 1687, "text": "The project structure will look like this:Make sure you have install express and request module using following commands:npm install requestnpm install expressRun index.js file using below command:node index.js" }, { "code": null, "e": 1941, "s": 1898, "text": "The project structure will look like this:" }, { "code": null, "e": 2059, "s": 1941, "text": "Make sure you have install express and request module using following commands:npm install requestnpm install express" }, { "code": null, "e": 2079, "s": 2059, "text": "npm install request" }, { "code": null, "e": 2099, "s": 2079, "text": "npm install express" }, { "code": null, "e": 2151, "s": 2099, "text": "Run index.js file using below command:node index.js" }, { "code": null, "e": 2165, "s": 2151, "text": "node index.js" }, { "code": null, "e": 2269, "s": 2165, "text": "So this is how you can use the request module for making HTTP calls. It is very simple and easy to use." }, { "code": null, "e": 2282, "s": 2269, "text": "Node.js-Misc" }, { "code": null, "e": 2290, "s": 2282, "text": "Node.js" }, { "code": null, "e": 2307, "s": 2290, "text": "Web Technologies" }, { "code": null, "e": 2334, "s": 2307, "text": "Web technologies Questions" }, { "code": null, "e": 2350, "s": 2334, "text": "Write From Home" }, { "code": null, "e": 2448, "s": 2350, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2478, "s": 2448, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 2535, "s": 2478, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 2589, "s": 2535, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 2629, "s": 2589, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 2664, "s": 2629, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 2726, "s": 2664, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2787, "s": 2726, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2837, "s": 2787, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2880, "s": 2837, "text": "How to fetch data from an API in ReactJS ?" } ]
Containerization using Docker
08 Jun, 2022 Docker is the containerization platform that is used to package your application and all its dependencies together in the form of containers to make sure that your application works seamlessly in any environment which can be developed or tested or in production. Docker is a tool designed to make it easier to create, deploy, and run applications by using containers. Docker is the world’s leading software container platform. It was launched in 2013 by a company called Dotcloud, Inc which was later renamed Docker, Inc. It is written in the Go language. It has been just six years since Docker was launched yet communities have already shifted to it from VMs. Docker is designed to benefit both developers and system administrators making it a part of many DevOps toolchains. Developers can write code without worrying about the testing and production environment. Sysadmins need not worry about infrastructure as Docker can easily scale up and scale down the number of systems. Docker comes into play at the deployment stage of the software development cycle. 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. Containerization is OS-based virtualization that creates multiple virtual units in the userspace, known as Containers. Containers share the same host kernel but are isolated from each other through private namespaces and resource control mechanisms at the OS level. Container-based Virtualization provides a different level of abstraction in terms of virtualization and isolation when compared with hypervisors. Hypervisors use a lot of hardware which results in overhead in terms of virtualizing hardware and virtual device drivers. A full operating system (e.g -Linux, Windows) runs on top of this virtualized hardware in each virtual machine instance. But in contrast, containers implement isolation of processes at the operating system level, thus avoiding such overhead. These containers run on top of the same shared operating system kernel of the underlying host machine and one or more processes can be run within each container. In containers you don’t have to pre-allocate any RAM, it is allocated dynamically during the creation of containers while in VMs you need to first pre-allocate the memory and then create the virtual machine. Containerization has better resource utilization compared to VMs and a short boot-up process. It is the next evolution in virtualization. Containers can run virtually anywhere, greatly easy development and deployment: on Linux, Windows, and Mac operating systems; on virtual machines or bare metal, on a developer’s machine or in data centers on-premises; and of course, in the public cloud. Containers virtualize CPU, memory, storage, and network resources at the OS level, providing developers with a sandboxed view of the OS logically isolated from other applications. Docker is the most popular open-source container format available and is supported on Google Cloud Platform and by Google Kubernetes Engine. Docker architecture consists of Docker client, Docker Daemon running on Docker Host, and Docker Hub repository. Docker has client-server architecture in which the client communicates with the Docker Daemon running on the Docker Host using a combination of REST APIs, Socket IO, and TCP. If we have to build the Docker image, then we use the client to execute the build command to Docker Daemon then Docker Daemon builds an image based on given inputs and saves it into the Docker registry. If you don’t want to create an image then just execute the pull command from the client and then Docker Daemon will pull the image from the Docker Hub finally if we want to run the image then execute the run command from the client which will create the container. The main components of Docker include – Docker clients and servers, Docker images, Dockerfile, Docker Registries, and Docker containers. These components are explained in detail in the below section : Docker Clients and Servers– Docker has a client-server architecture. The Docker Daemon/Server consists of all containers. The Docker Daemon/Server receives the request from the Docker client through CLI or REST APIs and thus processes the request accordingly. Docker client and Daemon can be present on the same host or different host. Docker Clients and Servers– Docker has a client-server architecture. The Docker Daemon/Server consists of all containers. The Docker Daemon/Server receives the request from the Docker client through CLI or REST APIs and thus processes the request accordingly. Docker client and Daemon can be present on the same host or different host. Docker Images– Docker images are used to build docker containers by using a read-only template. The foundation of every image is a base image eg. base images such as – ubuntu14.04 LTS, and Fedora 20. Base images can also be created from scratch and then required applications can be added to the base image by modifying it thus this process of creating a new image is called “committing the change”.Docker File– Dockerfile is a text file that contains a series of instructions on how to build your Docker image. This image contains all the project code and its dependencies. The same Docker image can be used to spin ‘n’ number of containers each with modification to the underlying image. The final image can be uploaded to Docker Hub and shared among various collaborators for testing and deployment. The set of commands that you need to use in your Docker File is FROM, CMD, ENTRYPOINT, VOLUME, ENV, and many more.Docker Registries– Docker Registry is a storage component for Docker images. We can store the images in either public/private repositories so that multiple users can collaborate in building the application. Docker Hub is Docker’s cloud repository. Docker Hub is called a public registry where everyone can pull available images and push their images without creating an image from scratch.Docker Containers– Docker Containers are runtime instances of Docker images. Containers contain the whole kit required for an application, so the application can be run in an isolated way. For eg.- Suppose there is an image of Ubuntu OS with NGINX SERVER when this image is run with the docker run command, then a container will be created and NGINX SERVER will be running on Ubuntu OS. Docker Images– Docker images are used to build docker containers by using a read-only template. The foundation of every image is a base image eg. base images such as – ubuntu14.04 LTS, and Fedora 20. Base images can also be created from scratch and then required applications can be added to the base image by modifying it thus this process of creating a new image is called “committing the change”. Docker File– Dockerfile is a text file that contains a series of instructions on how to build your Docker image. This image contains all the project code and its dependencies. The same Docker image can be used to spin ‘n’ number of containers each with modification to the underlying image. The final image can be uploaded to Docker Hub and shared among various collaborators for testing and deployment. The set of commands that you need to use in your Docker File is FROM, CMD, ENTRYPOINT, VOLUME, ENV, and many more. Docker Registries– Docker Registry is a storage component for Docker images. We can store the images in either public/private repositories so that multiple users can collaborate in building the application. Docker Hub is Docker’s cloud repository. Docker Hub is called a public registry where everyone can pull available images and push their images without creating an image from scratch. Docker Containers– Docker Containers are runtime instances of Docker images. Containers contain the whole kit required for an application, so the application can be run in an isolated way. For eg.- Suppose there is an image of Ubuntu OS with NGINX SERVER when this image is run with the docker run command, then a container will be created and NGINX SERVER will be running on Ubuntu OS. Docker Compose is a tool with which we can create a multi-container application. It makes it easier to configure and run applications made up of multiple containers. For example, suppose you had an application that required WordPress and MySQL, you could create one file which would start both the containers as a service without the need to start each one separately. We define a multi-container application in a YAML file. With the docker-compose-up command, we can start the application in the foreground. Docker-compose will look for the docker-compose. YAML file in the current folder to start the application. By adding the -d option to the docker-compose-up command, we can start the application in the background. Creating a docker-compose. YAML file for WordPress application : #cat docker-compose.yaml version: ’2’ services: db: image: mysql:5.7 volumes:db_data:/var/lib/mysql restart: always environment: MYSQL_ROOT_PASSWORD: WordPress MYSQL_DATABASE: WordPress MYSQL_USER: WordPress MYSQL_PASSWORD: WordPress WordPress: depends_on: - DB image: WordPress:latest ports: - "8000:80" restart: always environment: WORDPRESS_DB_HOST: db:3306 WORDPRESS_DB_PASSWORD: wordpress volumes: db_data: In this docker-compose. YAML file, we have the following ports section for the WordPress container, which means that we are going to map the host’s 8000 port with the container’s 80 port. So that host can access the application with its IP and port no. When we create and run a container, Docker by itself assigns an IP address to it, by default. Most of the time, it is required to create and deploy Docker networks as per our needs. So, Docker let us design the network as per our requirements. There are three types of Docker networks- default networks, user-defined networks, and overlay networks. To get a list of all the default networks that Docker creates, we run the command shown below – There are three types of networks in Docker – Bridged network: When a new Docker container is created without the –network argument, Docker by default connects the container with the bridge network. In bridged networks, all the containers in a single host can connect through their IP addresses. A Bridge network is created when the span of Docker hosts is one i.e. when all containers run on a single host. We need an overlay network to create a network that has a span of more than one Docker host.Host network: When a new Docker container is created with the –network=host argument it pushes the container into the host network stack where the Docker daemon is running. All interfaces of the host are accessible from the container which is assigned to the host network.None network: When a new Docker container is created with the –network=none argument it puts the Docker container in its network stack. So, in this none network, no IP addresses are assigned to the container, because of which they cannot communicate with each other. Bridged network: When a new Docker container is created without the –network argument, Docker by default connects the container with the bridge network. In bridged networks, all the containers in a single host can connect through their IP addresses. A Bridge network is created when the span of Docker hosts is one i.e. when all containers run on a single host. We need an overlay network to create a network that has a span of more than one Docker host. Host network: When a new Docker container is created with the –network=host argument it pushes the container into the host network stack where the Docker daemon is running. All interfaces of the host are accessible from the container which is assigned to the host network. None network: When a new Docker container is created with the –network=none argument it puts the Docker container in its network stack. So, in this none network, no IP addresses are assigned to the container, because of which they cannot communicate with each other. We can assign any one of the networks to the Docker containers. The –network option of the ‘docker run’ command is used to assign a specific network to the container. $docker run --network ="network name" To get detailed information about a particular network we use the command- $docker network inspect "network name" Docker has become popular nowadays because of the benefits provided by Docker containers. The main advantages of Docker are: Speed – The speed of Docker containers compared to a virtual machine is very fast. The time required to build a container is very fast because they are tiny and lightweight. Development, testing, and deployment can be done faster as containers are small. Containers can be pushed for testing once they have been built and then from there on to the production environment.Portability – The applications that are built inside docker containers are extremely portable. These portable applications can easily be moved anywhere as a single element and their performance also remains the same.Scalability – Docker has the ability that it can be deployed on several physical servers, data servers, and cloud platforms. It can also be run on every Linux machine. Containers can easily be moved from a cloud environment to a local host and from there back to the cloud again at a fast pace.Density – Docker uses the resources that are available more efficiently because it does not use a hypervisor. This is the reason that more containers can be run on a single host as compared to virtual machines. Docker Containers have higher performance because of their high density and no overhead wastage of resources. Speed – The speed of Docker containers compared to a virtual machine is very fast. The time required to build a container is very fast because they are tiny and lightweight. Development, testing, and deployment can be done faster as containers are small. Containers can be pushed for testing once they have been built and then from there on to the production environment. Portability – The applications that are built inside docker containers are extremely portable. These portable applications can easily be moved anywhere as a single element and their performance also remains the same. Scalability – Docker has the ability that it can be deployed on several physical servers, data servers, and cloud platforms. It can also be run on every Linux machine. Containers can easily be moved from a cloud environment to a local host and from there back to the cloud again at a fast pace. Density – Docker uses the resources that are available more efficiently because it does not use a hypervisor. This is the reason that more containers can be run on a single host as compared to virtual machines. Docker Containers have higher performance because of their high density and no overhead wastage of resources. Aman884036 aekansh53 GBlog Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You! Geek Streak - 24 Days POTD Challenge How to Learn Data Science in 10 weeks? What is Hashing | A Complete Tutorial Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jun, 2022" }, { "code": null, "e": 424, "s": 54, "text": "Docker is the containerization platform that is used to package your application and all its dependencies together in the form of containers to make sure that your application works seamlessly in any environment which can be developed or tested or in production. Docker is a tool designed to make it easier to create, deploy, and run applications by using containers. " }, { "code": null, "e": 1121, "s": 424, "text": "Docker is the world’s leading software container platform. It was launched in 2013 by a company called Dotcloud, Inc which was later renamed Docker, Inc. It is written in the Go language. It has been just six years since Docker was launched yet communities have already shifted to it from VMs. Docker is designed to benefit both developers and system administrators making it a part of many DevOps toolchains. Developers can write code without worrying about the testing and production environment. Sysadmins need not worry about infrastructure as Docker can easily scale up and scale down the number of systems. Docker comes into play at the deployment stage of the software development cycle. " }, { "code": null, "e": 1132, "s": 1123, "text": "Chapters" }, { "code": null, "e": 1159, "s": 1132, "text": "descriptions off, selected" }, { "code": null, "e": 1209, "s": 1159, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1232, "s": 1209, "text": "captions off, selected" }, { "code": null, "e": 1240, "s": 1232, "text": "English" }, { "code": null, "e": 1264, "s": 1240, "text": "This is a modal window." }, { "code": null, "e": 1333, "s": 1264, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1355, "s": 1333, "text": "End of dialog window." }, { "code": null, "e": 2640, "s": 1355, "text": "Containerization is OS-based virtualization that creates multiple virtual units in the userspace, known as Containers. Containers share the same host kernel but are isolated from each other through private namespaces and resource control mechanisms at the OS level. Container-based Virtualization provides a different level of abstraction in terms of virtualization and isolation when compared with hypervisors. Hypervisors use a lot of hardware which results in overhead in terms of virtualizing hardware and virtual device drivers. A full operating system (e.g -Linux, Windows) runs on top of this virtualized hardware in each virtual machine instance. But in contrast, containers implement isolation of processes at the operating system level, thus avoiding such overhead. These containers run on top of the same shared operating system kernel of the underlying host machine and one or more processes can be run within each container. In containers you don’t have to pre-allocate any RAM, it is allocated dynamically during the creation of containers while in VMs you need to first pre-allocate the memory and then create the virtual machine. Containerization has better resource utilization compared to VMs and a short boot-up process. It is the next evolution in virtualization. " }, { "code": null, "e": 3216, "s": 2640, "text": "Containers can run virtually anywhere, greatly easy development and deployment: on Linux, Windows, and Mac operating systems; on virtual machines or bare metal, on a developer’s machine or in data centers on-premises; and of course, in the public cloud. Containers virtualize CPU, memory, storage, and network resources at the OS level, providing developers with a sandboxed view of the OS logically isolated from other applications. Docker is the most popular open-source container format available and is supported on Google Cloud Platform and by Google Kubernetes Engine. " }, { "code": null, "e": 3976, "s": 3220, "text": "Docker architecture consists of Docker client, Docker Daemon running on Docker Host, and Docker Hub repository. Docker has client-server architecture in which the client communicates with the Docker Daemon running on the Docker Host using a combination of REST APIs, Socket IO, and TCP. If we have to build the Docker image, then we use the client to execute the build command to Docker Daemon then Docker Daemon builds an image based on given inputs and saves it into the Docker registry. If you don’t want to create an image then just execute the pull command from the client and then Docker Daemon will pull the image from the Docker Hub finally if we want to run the image then execute the run command from the client which will create the container. " }, { "code": null, "e": 4183, "s": 3980, "text": "The main components of Docker include – Docker clients and servers, Docker images, Dockerfile, Docker Registries, and Docker containers. These components are explained in detail in the below section : " }, { "code": null, "e": 4521, "s": 4183, "text": "Docker Clients and Servers– Docker has a client-server architecture. The Docker Daemon/Server consists of all containers. The Docker Daemon/Server receives the request from the Docker client through CLI or REST APIs and thus processes the request accordingly. Docker client and Daemon can be present on the same host or different host. " }, { "code": null, "e": 4859, "s": 4521, "text": "Docker Clients and Servers– Docker has a client-server architecture. The Docker Daemon/Server consists of all containers. The Docker Daemon/Server receives the request from the Docker client through CLI or REST APIs and thus processes the request accordingly. Docker client and Daemon can be present on the same host or different host. " }, { "code": null, "e": 6554, "s": 4859, "text": "Docker Images– Docker images are used to build docker containers by using a read-only template. The foundation of every image is a base image eg. base images such as – ubuntu14.04 LTS, and Fedora 20. Base images can also be created from scratch and then required applications can be added to the base image by modifying it thus this process of creating a new image is called “committing the change”.Docker File– Dockerfile is a text file that contains a series of instructions on how to build your Docker image. This image contains all the project code and its dependencies. The same Docker image can be used to spin ‘n’ number of containers each with modification to the underlying image. The final image can be uploaded to Docker Hub and shared among various collaborators for testing and deployment. The set of commands that you need to use in your Docker File is FROM, CMD, ENTRYPOINT, VOLUME, ENV, and many more.Docker Registries– Docker Registry is a storage component for Docker images. We can store the images in either public/private repositories so that multiple users can collaborate in building the application. Docker Hub is Docker’s cloud repository. Docker Hub is called a public registry where everyone can pull available images and push their images without creating an image from scratch.Docker Containers– Docker Containers are runtime instances of Docker images. Containers contain the whole kit required for an application, so the application can be run in an isolated way. For eg.- Suppose there is an image of Ubuntu OS with NGINX SERVER when this image is run with the docker run command, then a container will be created and NGINX SERVER will be running on Ubuntu OS. " }, { "code": null, "e": 6954, "s": 6554, "text": "Docker Images– Docker images are used to build docker containers by using a read-only template. The foundation of every image is a base image eg. base images such as – ubuntu14.04 LTS, and Fedora 20. Base images can also be created from scratch and then required applications can be added to the base image by modifying it thus this process of creating a new image is called “committing the change”." }, { "code": null, "e": 7473, "s": 6954, "text": "Docker File– Dockerfile is a text file that contains a series of instructions on how to build your Docker image. This image contains all the project code and its dependencies. The same Docker image can be used to spin ‘n’ number of containers each with modification to the underlying image. The final image can be uploaded to Docker Hub and shared among various collaborators for testing and deployment. The set of commands that you need to use in your Docker File is FROM, CMD, ENTRYPOINT, VOLUME, ENV, and many more." }, { "code": null, "e": 7863, "s": 7473, "text": "Docker Registries– Docker Registry is a storage component for Docker images. We can store the images in either public/private repositories so that multiple users can collaborate in building the application. Docker Hub is Docker’s cloud repository. Docker Hub is called a public registry where everyone can pull available images and push their images without creating an image from scratch." }, { "code": null, "e": 8252, "s": 7863, "text": "Docker Containers– Docker Containers are runtime instances of Docker images. Containers contain the whole kit required for an application, so the application can be run in an isolated way. For eg.- Suppose there is an image of Ubuntu OS with NGINX SERVER when this image is run with the docker run command, then a container will be created and NGINX SERVER will be running on Ubuntu OS. " }, { "code": null, "e": 9044, "s": 8256, "text": "Docker Compose is a tool with which we can create a multi-container application. It makes it easier to configure and run applications made up of multiple containers. For example, suppose you had an application that required WordPress and MySQL, you could create one file which would start both the containers as a service without the need to start each one separately. We define a multi-container application in a YAML file. With the docker-compose-up command, we can start the application in the foreground. Docker-compose will look for the docker-compose. YAML file in the current folder to start the application. By adding the -d option to the docker-compose-up command, we can start the application in the background. Creating a docker-compose. YAML file for WordPress application : " }, { "code": null, "e": 9459, "s": 9046, "text": "#cat docker-compose.yaml\nversion: ’2’\nservices:\ndb:\nimage: mysql:5.7\nvolumes:db_data:/var/lib/mysql\nrestart: always\nenvironment:\nMYSQL_ROOT_PASSWORD: WordPress\nMYSQL_DATABASE: WordPress\nMYSQL_USER: WordPress\nMYSQL_PASSWORD: WordPress\nWordPress:\ndepends_on:\n- DB\nimage: WordPress:latest\nports:\n- \"8000:80\"\nrestart: always\nenvironment:\nWORDPRESS_DB_HOST: db:3306\n\nWORDPRESS_DB_PASSWORD: wordpress\nvolumes:\ndb_data:" }, { "code": null, "e": 9713, "s": 9459, "text": "In this docker-compose. YAML file, we have the following ports section for the WordPress container, which means that we are going to map the host’s 8000 port with the container’s 80 port. So that host can access the application with its IP and port no. " }, { "code": null, "e": 10066, "s": 9715, "text": "When we create and run a container, Docker by itself assigns an IP address to it, by default. Most of the time, it is required to create and deploy Docker networks as per our needs. So, Docker let us design the network as per our requirements. There are three types of Docker networks- default networks, user-defined networks, and overlay networks. " }, { "code": null, "e": 10164, "s": 10066, "text": "To get a list of all the default networks that Docker creates, we run the command shown below – " }, { "code": null, "e": 10212, "s": 10164, "text": "There are three types of networks in Docker – " }, { "code": null, "e": 11205, "s": 10212, "text": "Bridged network: When a new Docker container is created without the –network argument, Docker by default connects the container with the bridge network. In bridged networks, all the containers in a single host can connect through their IP addresses. A Bridge network is created when the span of Docker hosts is one i.e. when all containers run on a single host. We need an overlay network to create a network that has a span of more than one Docker host.Host network: When a new Docker container is created with the –network=host argument it pushes the container into the host network stack where the Docker daemon is running. All interfaces of the host are accessible from the container which is assigned to the host network.None network: When a new Docker container is created with the –network=none argument it puts the Docker container in its network stack. So, in this none network, no IP addresses are assigned to the container, because of which they cannot communicate with each other." }, { "code": null, "e": 11660, "s": 11205, "text": "Bridged network: When a new Docker container is created without the –network argument, Docker by default connects the container with the bridge network. In bridged networks, all the containers in a single host can connect through their IP addresses. A Bridge network is created when the span of Docker hosts is one i.e. when all containers run on a single host. We need an overlay network to create a network that has a span of more than one Docker host." }, { "code": null, "e": 11933, "s": 11660, "text": "Host network: When a new Docker container is created with the –network=host argument it pushes the container into the host network stack where the Docker daemon is running. All interfaces of the host are accessible from the container which is assigned to the host network." }, { "code": null, "e": 12200, "s": 11933, "text": "None network: When a new Docker container is created with the –network=none argument it puts the Docker container in its network stack. So, in this none network, no IP addresses are assigned to the container, because of which they cannot communicate with each other." }, { "code": null, "e": 12369, "s": 12200, "text": "We can assign any one of the networks to the Docker containers. The –network option of the ‘docker run’ command is used to assign a specific network to the container. " }, { "code": null, "e": 12407, "s": 12369, "text": "$docker run --network =\"network name\"" }, { "code": null, "e": 12484, "s": 12407, "text": "To get detailed information about a particular network we use the command- " }, { "code": null, "e": 12523, "s": 12484, "text": "$docker network inspect \"network name\"" }, { "code": null, "e": 12652, "s": 12525, "text": "Docker has become popular nowadays because of the benefits provided by Docker containers. The main advantages of Docker are: " }, { "code": null, "e": 13854, "s": 12652, "text": "Speed – The speed of Docker containers compared to a virtual machine is very fast. The time required to build a container is very fast because they are tiny and lightweight. Development, testing, and deployment can be done faster as containers are small. Containers can be pushed for testing once they have been built and then from there on to the production environment.Portability – The applications that are built inside docker containers are extremely portable. These portable applications can easily be moved anywhere as a single element and their performance also remains the same.Scalability – Docker has the ability that it can be deployed on several physical servers, data servers, and cloud platforms. It can also be run on every Linux machine. Containers can easily be moved from a cloud environment to a local host and from there back to the cloud again at a fast pace.Density – Docker uses the resources that are available more efficiently because it does not use a hypervisor. This is the reason that more containers can be run on a single host as compared to virtual machines. Docker Containers have higher performance because of their high density and no overhead wastage of resources." }, { "code": null, "e": 14226, "s": 13854, "text": "Speed – The speed of Docker containers compared to a virtual machine is very fast. The time required to build a container is very fast because they are tiny and lightweight. Development, testing, and deployment can be done faster as containers are small. Containers can be pushed for testing once they have been built and then from there on to the production environment." }, { "code": null, "e": 14443, "s": 14226, "text": "Portability – The applications that are built inside docker containers are extremely portable. These portable applications can easily be moved anywhere as a single element and their performance also remains the same." }, { "code": null, "e": 14738, "s": 14443, "text": "Scalability – Docker has the ability that it can be deployed on several physical servers, data servers, and cloud platforms. It can also be run on every Linux machine. Containers can easily be moved from a cloud environment to a local host and from there back to the cloud again at a fast pace." }, { "code": null, "e": 15059, "s": 14738, "text": "Density – Docker uses the resources that are available more efficiently because it does not use a hypervisor. This is the reason that more containers can be run on a single host as compared to virtual machines. Docker Containers have higher performance because of their high density and no overhead wastage of resources." }, { "code": null, "e": 15072, "s": 15061, "text": "Aman884036" }, { "code": null, "e": 15082, "s": 15072, "text": "aekansh53" }, { "code": null, "e": 15088, "s": 15082, "text": "GBlog" }, { "code": null, "e": 15105, "s": 15088, "text": "Web Technologies" }, { "code": null, "e": 15203, "s": 15105, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15228, "s": 15203, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 15283, "s": 15228, "text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!" }, { "code": null, "e": 15320, "s": 15283, "text": "Geek Streak - 24 Days POTD Challenge" }, { "code": null, "e": 15359, "s": 15320, "text": "How to Learn Data Science in 10 weeks?" }, { "code": null, "e": 15397, "s": 15359, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 15430, "s": 15397, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 15491, "s": 15430, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 15541, "s": 15491, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 15584, "s": 15541, "text": "How to fetch data from an API in ReactJS ?" } ]
Python Seaborn – Catplot
26 Nov, 2020 Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. Seaborn helps resolve the two major problems faced by Matplotlib; the problems are? Default Matplotlib parameters Working with data frames As Seaborn compliments and extends Matplotlib, the learning curve is quite gradual. If you know Matplotlib, you are already half-way through Seaborn. Seaborn library offers many advantages over other plotting libraries: It is very easy to use and requires less code syntax Works really well with `pandas` data structures, which is just what you need as a data scientist. It is built on top of Matplotlib, another vast and deep data visualization library. Syntax: seaborn.catplot(*, x=None, y=None, hue=None, data=None, row=None, col=None, kind=’strip’, color=None, palette=None, **kwargs) Parameters x, y, hue: names of variables in dataInputs for plotting long-form data. See examples for interpretation. data: DataFrameLong-form (tidy) dataset for plotting. Each column should correspond to a variable, and each row should correspond to an observation. row, col: names of variables in data, optionalCategorical variables that will determine the faceting of the grid. kind: str, optionalThe kind of plot to draw, corresponds to the name of a categorical axes-level plotting function. Options are: “strip”, “swarm”, “box”, “violin”, “boxen”, “point”, “bar”, or “count”. color: matplotlib color, optionalColor for all of the elements, or seed for a gradient palette. palette: palette name, list, or dictColors to use for the different levels of the hue variable. Should be something that can be interpreted by color_palette(), or a dictionary mapping hue levels to matplotlib colors. kwargs: key, value pairingsOther keyword arguments are passed through to the underlying plotting function. Examples: If you are working with data that involves any categorical variables like survey responses, your best tools to visualize and compare different features of your data would be categorical plots. Plotting categorical plots it is very easy in seaborn. In this example x,y and hue take the names of the features in your data. Hue parameters encode the points with different colors with respect to the target variable. Python3 import seaborn as sns exercise = sns.load_dataset("exercise")g = sns.catplot(x="time", y="pulse", hue="kind", data=exercise) Output: For the count plot, we set a kind parameter to count and feed in the data using data parameters. Let’s start by exploring the time feature. We start off with catplot() function and use x argument to specify the axis we want to show the categories. Python3 import seaborn as sns sns.set_theme(style="ticks")exercise = sns.load_dataset("exercise") g = sns.catplot(x="time", kind="count", data=exercise) Output: Another popular choice for plotting categorical data is a bar plot. In the count plot example, our plot only needed a single variable. In the bar plot, we often use one categorical variable and one quantitative. Let’s see how the time compares to each other. Python3 import seaborn as sns exercise = sns.load_dataset("exercise")g = sns.catplot(x="time", y="pulse", kind="bar", data=exercise) Output: For creating the horizontal bar plot we have to change the x and y features. When you have lots of categories or long category names it’s a good idea to change the orientation. Python3 import seaborn as sns exercise = sns.load_dataset("exercise")g = sns.catplot(x="pulse", y="time", kind="bar", data=exercise) Output: Use a different plot kind to visualize the same data: Python3 import seaborn as sns exercise = sns.load_dataset("exercise") g = sns.catplot(x="time", y="pulse", hue="kind", data=exercise, kind="violin") Output: Python3 import seaborn as sns exercise = sns.load_dataset("exercise") g = sns.catplot(x="time", y="pulse", hue="kind", col="diet", data=exercise) Output: Make many column facets and wrap them into the rows of the grid. The aspect will change the width while keeping the height constant. Python3 titanic = sns.load_dataset("titanic")g = sns.catplot(x="alive", col="deck", col_wrap=4, data=titanic[titanic.deck.notnull()], kind="count", height=2.5, aspect=.8) Output: Plot horizontally and pass other keyword arguments to the plot function: Python3 g = sns.catplot(x="age", y="embark_town", hue="sex", row="class", data=titanic[titanic.embark_town.notnull()], orient="h", height=2, aspect=3, palette="Set3", kind="violin", dodge=True, cut=0, bw=.2) Output: Box plots are visuals that can be a little difficult to understand but depict the distribution of data very beautifully. It is best to start the explanation with an example of a box plot. I am going to use one of the common built-in datasets in Seaborn: Python3 tips = sns.load_dataset('tips')sns.catplot(x='day', y='total_bill', data=tips, kind='box'); Output: Outlier Detection Using Box Plot: The edges of the blue box are the 25th and 75th percentiles of the distribution of all bills. This means that 75% of all the bills on Thursday were lower than 20 dollars, while another 75% (from the bottom to the top) was higher than almost 13 dollars. The horizontal line in the box shows the median value of the distribution. Find Inter Quartile Range (IQR) by subtracting the 25th percentile from the 75th: 75% — 25% The lower outlier limit is calculated by subtracting 1.5 times of IQR from the 25th: 25% — 1.5*IQR The upper outlier limit is calculated by adding 1.5 times of IQR to the 75th: 75% + 1.5*IQR Python-Seaborn Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas Python Dictionary How to get column names in Pandas dataframe Different ways to create Pandas Dataframe Taking input in Python Enumerate() in Python Read a file line by line in Python Python String | replace()
[ { "code": null, "e": 52, "s": 24, "text": "\n26 Nov, 2020" }, { "code": null, "e": 300, "s": 52, "text": "Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. Seaborn helps resolve the two major problems faced by Matplotlib; the problems are?" }, { "code": null, "e": 330, "s": 300, "text": "Default Matplotlib parameters" }, { "code": null, "e": 355, "s": 330, "text": "Working with data frames" }, { "code": null, "e": 575, "s": 355, "text": "As Seaborn compliments and extends Matplotlib, the learning curve is quite gradual. If you know Matplotlib, you are already half-way through Seaborn. Seaborn library offers many advantages over other plotting libraries:" }, { "code": null, "e": 628, "s": 575, "text": "It is very easy to use and requires less code syntax" }, { "code": null, "e": 726, "s": 628, "text": "Works really well with `pandas` data structures, which is just what you need as a data scientist." }, { "code": null, "e": 810, "s": 726, "text": "It is built on top of Matplotlib, another vast and deep data visualization library." }, { "code": null, "e": 945, "s": 810, "text": "Syntax: seaborn.catplot(*, x=None, y=None, hue=None, data=None, row=None, col=None, kind=’strip’, color=None, palette=None, **kwargs) " }, { "code": null, "e": 956, "s": 945, "text": "Parameters" }, { "code": null, "e": 1063, "s": 956, "text": "x, y, hue: names of variables in dataInputs for plotting long-form data. See examples for interpretation." }, { "code": null, "e": 1213, "s": 1063, "text": "data: DataFrameLong-form (tidy) dataset for plotting. Each column should correspond to a variable, and each row should correspond to an observation." }, { "code": null, "e": 1329, "s": 1213, "text": "row, col: names of variables in data, optionalCategorical variables that will determine the faceting of the grid." }, { "code": null, "e": 1531, "s": 1329, "text": "kind: str, optionalThe kind of plot to draw, corresponds to the name of a categorical axes-level plotting function. Options are: “strip”, “swarm”, “box”, “violin”, “boxen”, “point”, “bar”, or “count”." }, { "code": null, "e": 1628, "s": 1531, "text": "color: matplotlib color, optionalColor for all of the elements, or seed for a gradient palette." }, { "code": null, "e": 1846, "s": 1628, "text": "palette: palette name, list, or dictColors to use for the different levels of the hue variable. Should be something that can be interpreted by color_palette(), or a dictionary mapping hue levels to matplotlib colors." }, { "code": null, "e": 1954, "s": 1846, "text": "kwargs: key, value pairingsOther keyword arguments are passed through to the underlying plotting function." }, { "code": null, "e": 1964, "s": 1954, "text": "Examples:" }, { "code": null, "e": 2377, "s": 1964, "text": "If you are working with data that involves any categorical variables like survey responses, your best tools to visualize and compare different features of your data would be categorical plots. Plotting categorical plots it is very easy in seaborn. In this example x,y and hue take the names of the features in your data. Hue parameters encode the points with different colors with respect to the target variable." }, { "code": null, "e": 2385, "s": 2377, "text": "Python3" }, { "code": "import seaborn as sns exercise = sns.load_dataset(\"exercise\")g = sns.catplot(x=\"time\", y=\"pulse\", hue=\"kind\", data=exercise)", "e": 2541, "s": 2385, "text": null }, { "code": null, "e": 2549, "s": 2541, "text": "Output:" }, { "code": null, "e": 2798, "s": 2549, "text": "For the count plot, we set a kind parameter to count and feed in the data using data parameters. Let’s start by exploring the time feature. We start off with catplot() function and use x argument to specify the axis we want to show the categories. " }, { "code": null, "e": 2806, "s": 2798, "text": "Python3" }, { "code": "import seaborn as sns sns.set_theme(style=\"ticks\")exercise = sns.load_dataset(\"exercise\") g = sns.catplot(x=\"time\", kind=\"count\", data=exercise)", "e": 2983, "s": 2806, "text": null }, { "code": null, "e": 2991, "s": 2983, "text": "Output:" }, { "code": null, "e": 3250, "s": 2991, "text": "Another popular choice for plotting categorical data is a bar plot. In the count plot example, our plot only needed a single variable. In the bar plot, we often use one categorical variable and one quantitative. Let’s see how the time compares to each other." }, { "code": null, "e": 3258, "s": 3250, "text": "Python3" }, { "code": "import seaborn as sns exercise = sns.load_dataset(\"exercise\")g = sns.catplot(x=\"time\", y=\"pulse\", kind=\"bar\", data=exercise)", "e": 3430, "s": 3258, "text": null }, { "code": null, "e": 3438, "s": 3430, "text": "Output:" }, { "code": null, "e": 3615, "s": 3438, "text": "For creating the horizontal bar plot we have to change the x and y features. When you have lots of categories or long category names it’s a good idea to change the orientation." }, { "code": null, "e": 3623, "s": 3615, "text": "Python3" }, { "code": "import seaborn as sns exercise = sns.load_dataset(\"exercise\")g = sns.catplot(x=\"pulse\", y=\"time\", kind=\"bar\", data=exercise)", "e": 3794, "s": 3623, "text": null }, { "code": null, "e": 3802, "s": 3794, "text": "Output:" }, { "code": null, "e": 3856, "s": 3802, "text": "Use a different plot kind to visualize the same data:" }, { "code": null, "e": 3864, "s": 3856, "text": "Python3" }, { "code": "import seaborn as sns exercise = sns.load_dataset(\"exercise\") g = sns.catplot(x=\"time\", y=\"pulse\", hue=\"kind\", data=exercise, kind=\"violin\")", "e": 4070, "s": 3864, "text": null }, { "code": null, "e": 4078, "s": 4070, "text": "Output:" }, { "code": null, "e": 4086, "s": 4078, "text": "Python3" }, { "code": "import seaborn as sns exercise = sns.load_dataset(\"exercise\") g = sns.catplot(x=\"time\", y=\"pulse\", hue=\"kind\", col=\"diet\", data=exercise)", "e": 4287, "s": 4086, "text": null }, { "code": null, "e": 4295, "s": 4287, "text": "Output:" }, { "code": null, "e": 4428, "s": 4295, "text": "Make many column facets and wrap them into the rows of the grid. The aspect will change the width while keeping the height constant." }, { "code": null, "e": 4436, "s": 4428, "text": "Python3" }, { "code": "titanic = sns.load_dataset(\"titanic\")g = sns.catplot(x=\"alive\", col=\"deck\", col_wrap=4, data=titanic[titanic.deck.notnull()], kind=\"count\", height=2.5, aspect=.8)", "e": 4629, "s": 4436, "text": null }, { "code": null, "e": 4637, "s": 4629, "text": "Output:" }, { "code": null, "e": 4710, "s": 4637, "text": "Plot horizontally and pass other keyword arguments to the plot function:" }, { "code": null, "e": 4718, "s": 4710, "text": "Python3" }, { "code": "g = sns.catplot(x=\"age\", y=\"embark_town\", hue=\"sex\", row=\"class\", data=titanic[titanic.embark_town.notnull()], orient=\"h\", height=2, aspect=3, palette=\"Set3\", kind=\"violin\", dodge=True, cut=0, bw=.2)", "e": 4978, "s": 4718, "text": null }, { "code": null, "e": 4986, "s": 4978, "text": "Output:" }, { "code": null, "e": 5240, "s": 4986, "text": "Box plots are visuals that can be a little difficult to understand but depict the distribution of data very beautifully. It is best to start the explanation with an example of a box plot. I am going to use one of the common built-in datasets in Seaborn:" }, { "code": null, "e": 5248, "s": 5240, "text": "Python3" }, { "code": "tips = sns.load_dataset('tips')sns.catplot(x='day', y='total_bill', data=tips, kind='box');", "e": 5374, "s": 5248, "text": null }, { "code": null, "e": 5382, "s": 5374, "text": "Output:" }, { "code": null, "e": 5416, "s": 5382, "text": "Outlier Detection Using Box Plot:" }, { "code": null, "e": 5744, "s": 5416, "text": "The edges of the blue box are the 25th and 75th percentiles of the distribution of all bills. This means that 75% of all the bills on Thursday were lower than 20 dollars, while another 75% (from the bottom to the top) was higher than almost 13 dollars. The horizontal line in the box shows the median value of the distribution." }, { "code": null, "e": 5836, "s": 5744, "text": "Find Inter Quartile Range (IQR) by subtracting the 25th percentile from the 75th: 75% — 25%" }, { "code": null, "e": 5935, "s": 5836, "text": "The lower outlier limit is calculated by subtracting 1.5 times of IQR from the 25th: 25% — 1.5*IQR" }, { "code": null, "e": 6027, "s": 5935, "text": "The upper outlier limit is calculated by adding 1.5 times of IQR to the 75th: 75% + 1.5*IQR" }, { "code": null, "e": 6042, "s": 6027, "text": "Python-Seaborn" }, { "code": null, "e": 6049, "s": 6042, "text": "Python" }, { "code": null, "e": 6147, "s": 6049, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6175, "s": 6147, "text": "Read JSON file using Python" }, { "code": null, "e": 6197, "s": 6175, "text": "Python map() function" }, { "code": null, "e": 6247, "s": 6197, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 6265, "s": 6247, "text": "Python Dictionary" }, { "code": null, "e": 6309, "s": 6265, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 6351, "s": 6309, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 6374, "s": 6351, "text": "Taking input in Python" }, { "code": null, "e": 6396, "s": 6374, "text": "Enumerate() in Python" }, { "code": null, "e": 6431, "s": 6396, "text": "Read a file line by line in Python" } ]
Generators in Dart
21 Jul, 2020 Generators in Dart allows the user to produce a sequence of value easily. One can generate a sequence of values in dart with the help of two generator functions : Synchronous Generator: Returns an Iterable object.Asynchronous Generator: Returns a Stream object. Synchronous Generator: Returns an Iterable object. Asynchronous Generator: Returns a Stream object. The synchronous generator returns an iterable object i.e. it returns the collection of values, or “elements”, that can be accessed sequentially. To implement synchronous generator function, mark the function body as sync*, and use yield statements to deliver value(s). Example: Implementing a synchronous generator in Dart. Dart // sync* functions return an iterableIterable geeksForGeeks(int number) sync* { int geek = number; while (geek >= 0) { // Checking for even number if (geek % 2 == 0) { // 'yield' suspends // the function yield geek; } // Decreasing the // variable geek geek--; }} // Main Functionvoid main() { print("------- Geeks For Geeks --------"); print("Dart Synchronous Generator Example For Printing Even Numbers From 10 In Reverse Order:"); // Printing positive even numbers // from 10 in reverse order geeksForGeeks(10).forEach(print);} Output: --------------------- Geeks For Geeks --------------------- Dart Synchronous Generator Example For Printing Even Numbers From 10 In Reverse Order: 10 8 6 4 2 0 The asynchronous generator returns a stream object. A Stream provides a way to receive a sequence of events. Each event is either a data event, also called an element of the stream, or an error event, which is a notification that something has failed. To implement an asynchronous generator function, mark the function body as async*, and use yield statements to deliver value(s). Example: Implementing an asynchronous generator in Dart. Dart // async* function(s) return an streamStream geeksForGeeks(int number) async* { int geek = 0; // Checking for every // geek less than number while (geek <= number) yield geek++; // Incrementing geek // after printing it} // Main Functionvoid main() { print("-------- Geeks For Geeks -----------"); print("Dart Asynchronous Generator Example For Printing Numbers Less Than 10:"); // Printing numbers less // than or equal to 10 geeksForGeeks(10).forEach(print);} Output: --------------------- Geeks For Geeks --------------------- Dart Asynchronous Generator Example For Printing Numbers Less Than 10: 0 1 2 3 4 5 6 7 8 9 10 Dart 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 - Search Bar Flutter - FutureBuilder Widget Flutter - Flexible Widget Flutter - Dialogs Android Studio Setup for Flutter Development Flutter - Pop Up Menu Flutter - CircleAvatar Widget Flutter - RichText Widget
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jul, 2020" }, { "code": null, "e": 191, "s": 28, "text": "Generators in Dart allows the user to produce a sequence of value easily. One can generate a sequence of values in dart with the help of two generator functions :" }, { "code": null, "e": 290, "s": 191, "text": "Synchronous Generator: Returns an Iterable object.Asynchronous Generator: Returns a Stream object." }, { "code": null, "e": 341, "s": 290, "text": "Synchronous Generator: Returns an Iterable object." }, { "code": null, "e": 390, "s": 341, "text": "Asynchronous Generator: Returns a Stream object." }, { "code": null, "e": 659, "s": 390, "text": "The synchronous generator returns an iterable object i.e. it returns the collection of values, or “elements”, that can be accessed sequentially. To implement synchronous generator function, mark the function body as sync*, and use yield statements to deliver value(s)." }, { "code": null, "e": 714, "s": 659, "text": "Example: Implementing a synchronous generator in Dart." }, { "code": null, "e": 719, "s": 714, "text": "Dart" }, { "code": "// sync* functions return an iterableIterable geeksForGeeks(int number) sync* { int geek = number; while (geek >= 0) { // Checking for even number if (geek % 2 == 0) { // 'yield' suspends // the function yield geek; } // Decreasing the // variable geek geek--; }} // Main Functionvoid main() { print(\"------- Geeks For Geeks --------\"); print(\"Dart Synchronous Generator Example For Printing Even Numbers From 10 In Reverse Order:\"); // Printing positive even numbers // from 10 in reverse order geeksForGeeks(10).forEach(print);}", "e": 1336, "s": 719, "text": null }, { "code": null, "e": 1344, "s": 1336, "text": "Output:" }, { "code": null, "e": 1505, "s": 1344, "text": "--------------------- Geeks For Geeks ---------------------\nDart Synchronous Generator Example For Printing Even Numbers From 10 In Reverse Order:\n10\n8\n6\n4\n2\n0\n" }, { "code": null, "e": 1886, "s": 1505, "text": "The asynchronous generator returns a stream object. A Stream provides a way to receive a sequence of events. Each event is either a data event, also called an element of the stream, or an error event, which is a notification that something has failed. To implement an asynchronous generator function, mark the function body as async*, and use yield statements to deliver value(s)." }, { "code": null, "e": 1943, "s": 1886, "text": "Example: Implementing an asynchronous generator in Dart." }, { "code": null, "e": 1948, "s": 1943, "text": "Dart" }, { "code": "// async* function(s) return an streamStream geeksForGeeks(int number) async* { int geek = 0; // Checking for every // geek less than number while (geek <= number) yield geek++; // Incrementing geek // after printing it} // Main Functionvoid main() { print(\"-------- Geeks For Geeks -----------\"); print(\"Dart Asynchronous Generator Example For Printing Numbers Less Than 10:\"); // Printing numbers less // than or equal to 10 geeksForGeeks(10).forEach(print);}", "e": 2435, "s": 1948, "text": null }, { "code": null, "e": 2445, "s": 2437, "text": "Output:" }, { "code": null, "e": 2600, "s": 2445, "text": "--------------------- Geeks For Geeks ---------------------\nDart Asynchronous Generator Example For Printing Numbers Less Than 10:\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n" }, { "code": null, "e": 2605, "s": 2600, "text": "Dart" }, { "code": null, "e": 2703, "s": 2605, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2742, "s": 2703, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 2768, "s": 2742, "text": "ListView Class in Flutter" }, { "code": null, "e": 2789, "s": 2768, "text": "Flutter - Search Bar" }, { "code": null, "e": 2820, "s": 2789, "text": "Flutter - FutureBuilder Widget" }, { "code": null, "e": 2846, "s": 2820, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 2864, "s": 2846, "text": "Flutter - Dialogs" }, { "code": null, "e": 2909, "s": 2864, "text": "Android Studio Setup for Flutter Development" }, { "code": null, "e": 2931, "s": 2909, "text": "Flutter - Pop Up Menu" }, { "code": null, "e": 2961, "s": 2931, "text": "Flutter - CircleAvatar Widget" } ]
Select Pandas dataframe rows between two dates
24 Feb, 2021 Prerequisites: pandas Pandas is an open-source library that is built on top of NumPy library. It is a Python package that offers various data structures and operations for manipulating numerical data and time series. It is mainly popular for importing and analyzing data much easier. Pandas is fast and it has high-performance & productivity for users. This article focuses on getting selected pandas data frame rows between two dates. We can do this by using a filter. Dates can be represented initially in several ways : string np.datetime64 datetime.datetime To manipulate dates in pandas, we use the pd.to_datetime() function in pandas to convert different date representations to datetime64[ns] format. Syntax: pandas.to_datetime(arg, errors=’raise’, dayfirst=False, yearfirst=False, utc=None, box=True, format=None, exact=True, unit=None, infer_datetime_format=False, origin=’unix’, cache=False) Parameters: arg: An integer, string, float, list or dict object to convert in to Date time object. dayfirst: Boolean value, places day first if True. yearfirst: Boolean value, places year first if True. utc: Boolean value, Returns time in UTC if True. format: String input to tell position of day, month and year. Import module Create or load data Create dataframe Convert the dates column to datetime64[ns] data type Define a start date and end date. Use a filter to display the updated dataframe and store it. Display dataframe Example: Original dataframe Python3 import pandas as pddata = {'Name': ['Tani', 'Saumya', 'Ganesh', 'Kirti'], 'Articles': [5, 3, 4, 3], 'Location': ['Kanpur', 'Kolkata', 'Kolkata', 'Bombay'], 'Dates': ['2020-08-04', '2020-08-07', '2020-08-08', '2020-06-08']} # Create DataFramedf = pd.DataFrame(data)display(df) Output: Example: Selecting data frame rows between two rows Python3 import pandas as pddata = {'Name': ['Tani', 'Saumya', 'Ganesh', 'Kirti'], 'Articles': [5, 3, 4, 3], 'Location': ['Kanpur', 'Kolkata', 'Kolkata', 'Bombay'], 'Dates': ['2020-08-04', '2020-08-07', '2020-08-08', '2020-06-08']} # Create DataFramedf = pd.DataFrame(data)start_date = '2020-08-05'end_date = '2020-08-08'mask = (df['Dates'] > start_date) & (df['Dates'] <= end_date) df = df.loc[mask]display(df) Output: Picked Python pandas-dataFrame Python Pandas-exercise Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Feb, 2021" }, { "code": null, "e": 76, "s": 54, "text": "Prerequisites: pandas" }, { "code": null, "e": 407, "s": 76, "text": "Pandas is an open-source library that is built on top of NumPy library. It is a Python package that offers various data structures and operations for manipulating numerical data and time series. It is mainly popular for importing and analyzing data much easier. Pandas is fast and it has high-performance & productivity for users." }, { "code": null, "e": 524, "s": 407, "text": "This article focuses on getting selected pandas data frame rows between two dates. We can do this by using a filter." }, { "code": null, "e": 577, "s": 524, "text": "Dates can be represented initially in several ways :" }, { "code": null, "e": 584, "s": 577, "text": "string" }, { "code": null, "e": 598, "s": 584, "text": "np.datetime64" }, { "code": null, "e": 616, "s": 598, "text": "datetime.datetime" }, { "code": null, "e": 762, "s": 616, "text": "To manipulate dates in pandas, we use the pd.to_datetime() function in pandas to convert different date representations to datetime64[ns] format." }, { "code": null, "e": 956, "s": 762, "text": "Syntax: pandas.to_datetime(arg, errors=’raise’, dayfirst=False, yearfirst=False, utc=None, box=True, format=None, exact=True, unit=None, infer_datetime_format=False, origin=’unix’, cache=False)" }, { "code": null, "e": 968, "s": 956, "text": "Parameters:" }, { "code": null, "e": 1055, "s": 968, "text": "arg: An integer, string, float, list or dict object to convert in to Date time object." }, { "code": null, "e": 1106, "s": 1055, "text": "dayfirst: Boolean value, places day first if True." }, { "code": null, "e": 1159, "s": 1106, "text": "yearfirst: Boolean value, places year first if True." }, { "code": null, "e": 1208, "s": 1159, "text": "utc: Boolean value, Returns time in UTC if True." }, { "code": null, "e": 1270, "s": 1208, "text": "format: String input to tell position of day, month and year." }, { "code": null, "e": 1284, "s": 1270, "text": "Import module" }, { "code": null, "e": 1304, "s": 1284, "text": "Create or load data" }, { "code": null, "e": 1321, "s": 1304, "text": "Create dataframe" }, { "code": null, "e": 1374, "s": 1321, "text": "Convert the dates column to datetime64[ns] data type" }, { "code": null, "e": 1408, "s": 1374, "text": "Define a start date and end date." }, { "code": null, "e": 1468, "s": 1408, "text": "Use a filter to display the updated dataframe and store it." }, { "code": null, "e": 1486, "s": 1468, "text": "Display dataframe" }, { "code": null, "e": 1514, "s": 1486, "text": "Example: Original dataframe" }, { "code": null, "e": 1522, "s": 1514, "text": "Python3" }, { "code": "import pandas as pddata = {'Name': ['Tani', 'Saumya', 'Ganesh', 'Kirti'], 'Articles': [5, 3, 4, 3], 'Location': ['Kanpur', 'Kolkata', 'Kolkata', 'Bombay'], 'Dates': ['2020-08-04', '2020-08-07', '2020-08-08', '2020-06-08']} # Create DataFramedf = pd.DataFrame(data)display(df)", "e": 1860, "s": 1522, "text": null }, { "code": null, "e": 1868, "s": 1860, "text": "Output:" }, { "code": null, "e": 1920, "s": 1868, "text": "Example: Selecting data frame rows between two rows" }, { "code": null, "e": 1928, "s": 1920, "text": "Python3" }, { "code": "import pandas as pddata = {'Name': ['Tani', 'Saumya', 'Ganesh', 'Kirti'], 'Articles': [5, 3, 4, 3], 'Location': ['Kanpur', 'Kolkata', 'Kolkata', 'Bombay'], 'Dates': ['2020-08-04', '2020-08-07', '2020-08-08', '2020-06-08']} # Create DataFramedf = pd.DataFrame(data)start_date = '2020-08-05'end_date = '2020-08-08'mask = (df['Dates'] > start_date) & (df['Dates'] <= end_date) df = df.loc[mask]display(df)", "e": 2394, "s": 1928, "text": null }, { "code": null, "e": 2402, "s": 2394, "text": "Output:" }, { "code": null, "e": 2409, "s": 2402, "text": "Picked" }, { "code": null, "e": 2433, "s": 2409, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2456, "s": 2433, "text": "Python Pandas-exercise" }, { "code": null, "e": 2470, "s": 2456, "text": "Python-pandas" }, { "code": null, "e": 2477, "s": 2470, "text": "Python" }, { "code": null, "e": 2575, "s": 2477, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2607, "s": 2575, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2634, "s": 2607, "text": "Python Classes and Objects" }, { "code": null, "e": 2655, "s": 2634, "text": "Python OOPs Concepts" }, { "code": null, "e": 2678, "s": 2655, "text": "Introduction To PYTHON" }, { "code": null, "e": 2734, "s": 2678, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2765, "s": 2734, "text": "Python | os.path.join() method" }, { "code": null, "e": 2807, "s": 2765, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2849, "s": 2807, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2888, "s": 2849, "text": "Python | Get unique values from a list" } ]
How to Use Linux Commands in Windows with Cygwin
11 Oct, 2021 Cygwin is a collection of tools that provide a Linux Operating System’s terminal look, feel, and some of its basic functionality for users of Windows OS who want to have a go over the basic commands of Linux without worrying about installing a Linux OS. To use this tool, first of all, we need to download Cygwin setup depending on the version of Windows i.e either 32 bit or 64bit. Step 1: Launch the Cygwin installation setup and press Next Step 2: Choose “Install from Internet” and press Next Step 3: Select the root install directory where you want to install it and choose whether to install it for yourself or for all users and press Next Step 4: Select a directory where you want to store installation files downloaded by this installation setup and press Next Step 5: Select the way you want installation setup to connect to the internet and press Next Step 6: Choose a download site from available download sites and press Next Step 7: Select packages to install depending upon your needs and press Next Step 8: Review and Confirm changes Step 9: Packages will take some time to get downloaded Step 10: Installation completes and Cygwin is ready to be explored now, press Next To make Cygwin work in your normal command prompt, we need to add Cygwin to Windows Environment Variables as follow:- Step 1: In the search bar type “Advanced System Settings” and click on the matching field Step 2: Click on the Environment Variable button on the bottom right side Step 3: Under the system variable tab, select the Path variable and press OK Step 4: In the installation phase of Cygwin, i.e in Step 3 where the root install directory was chosen for Cygwin installation, go to that location and inside it, copy the location of the bin folder. copy Location Step 5: Paste it in the environment variable section which was opened after the completion of Step 3 and press OK Setting up of Environment variables is completed, we can now run our Linux commands in command prompt To use Linux commands in Windows with Cygwin, we can now either open Cygwin or command prompt and all we have to do is to type the command into the terminal/prompt and press Enter, as follows : Example 1: pwd command in command prompt pwd Example 2: ls command in command prompt ls Example 3: echo command in command prompt echo "your text" There might come some situation when you want to execute some non-basic commands of Linux in Cygwin whose packages are not installed during the installation process, as follows : Example 1: nano command in command prompt nano file_name.txt This happens because of the reason that the installed package of Cygwin doesn’t contain the functionality for these commands. To use these commands you have to select packages in the Installation Phase (Step 7) containing the functionality for this command. Picked How To Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Set Git Username and Password in GitBash? How to Install Jupyter Notebook on MacOS? How to Install and Use NVM on Windows? How to Install Python Packages for AWS Lambda Layers? How to Add External JAR File to an IntelliJ IDEA Project? Sed Command in Linux/Unix with examples AWK command in Unix/Linux with examples grep command in Unix/Linux cut command in Linux with examples cp command in Linux with examples
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Oct, 2021" }, { "code": null, "e": 282, "s": 28, "text": "Cygwin is a collection of tools that provide a Linux Operating System’s terminal look, feel, and some of its basic functionality for users of Windows OS who want to have a go over the basic commands of Linux without worrying about installing a Linux OS." }, { "code": null, "e": 411, "s": 282, "text": "To use this tool, first of all, we need to download Cygwin setup depending on the version of Windows i.e either 32 bit or 64bit." }, { "code": null, "e": 471, "s": 411, "text": "Step 1: Launch the Cygwin installation setup and press Next" }, { "code": null, "e": 525, "s": 471, "text": "Step 2: Choose “Install from Internet” and press Next" }, { "code": null, "e": 674, "s": 525, "text": "Step 3: Select the root install directory where you want to install it and choose whether to install it for yourself or for all users and press Next" }, { "code": null, "e": 797, "s": 674, "text": "Step 4: Select a directory where you want to store installation files downloaded by this installation setup and press Next" }, { "code": null, "e": 890, "s": 797, "text": "Step 5: Select the way you want installation setup to connect to the internet and press Next" }, { "code": null, "e": 966, "s": 890, "text": "Step 6: Choose a download site from available download sites and press Next" }, { "code": null, "e": 1042, "s": 966, "text": "Step 7: Select packages to install depending upon your needs and press Next" }, { "code": null, "e": 1077, "s": 1042, "text": "Step 8: Review and Confirm changes" }, { "code": null, "e": 1132, "s": 1077, "text": "Step 9: Packages will take some time to get downloaded" }, { "code": null, "e": 1215, "s": 1132, "text": "Step 10: Installation completes and Cygwin is ready to be explored now, press Next" }, { "code": null, "e": 1333, "s": 1215, "text": "To make Cygwin work in your normal command prompt, we need to add Cygwin to Windows Environment Variables as follow:-" }, { "code": null, "e": 1423, "s": 1333, "text": "Step 1: In the search bar type “Advanced System Settings” and click on the matching field" }, { "code": null, "e": 1498, "s": 1423, "text": "Step 2: Click on the Environment Variable button on the bottom right side " }, { "code": null, "e": 1575, "s": 1498, "text": "Step 3: Under the system variable tab, select the Path variable and press OK" }, { "code": null, "e": 1775, "s": 1575, "text": "Step 4: In the installation phase of Cygwin, i.e in Step 3 where the root install directory was chosen for Cygwin installation, go to that location and inside it, copy the location of the bin folder." }, { "code": null, "e": 1789, "s": 1775, "text": "copy Location" }, { "code": null, "e": 1903, "s": 1789, "text": "Step 5: Paste it in the environment variable section which was opened after the completion of Step 3 and press OK" }, { "code": null, "e": 2005, "s": 1903, "text": "Setting up of Environment variables is completed, we can now run our Linux commands in command prompt" }, { "code": null, "e": 2199, "s": 2005, "text": "To use Linux commands in Windows with Cygwin, we can now either open Cygwin or command prompt and all we have to do is to type the command into the terminal/prompt and press Enter, as follows :" }, { "code": null, "e": 2240, "s": 2199, "text": "Example 1: pwd command in command prompt" }, { "code": null, "e": 2245, "s": 2240, "text": "pwd " }, { "code": null, "e": 2285, "s": 2245, "text": "Example 2: ls command in command prompt" }, { "code": null, "e": 2289, "s": 2285, "text": "ls " }, { "code": null, "e": 2331, "s": 2289, "text": "Example 3: echo command in command prompt" }, { "code": null, "e": 2348, "s": 2331, "text": "echo \"your text\"" }, { "code": null, "e": 2527, "s": 2348, "text": "There might come some situation when you want to execute some non-basic commands of Linux in Cygwin whose packages are not installed during the installation process, as follows :" }, { "code": null, "e": 2569, "s": 2527, "text": "Example 1: nano command in command prompt" }, { "code": null, "e": 2589, "s": 2569, "text": "nano file_name.txt " }, { "code": null, "e": 2847, "s": 2589, "text": "This happens because of the reason that the installed package of Cygwin doesn’t contain the functionality for these commands. To use these commands you have to select packages in the Installation Phase (Step 7) containing the functionality for this command." }, { "code": null, "e": 2854, "s": 2847, "text": "Picked" }, { "code": null, "e": 2861, "s": 2854, "text": "How To" }, { "code": null, "e": 2872, "s": 2861, "text": "Linux-Unix" }, { "code": null, "e": 2970, "s": 2872, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3019, "s": 2970, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 3061, "s": 3019, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 3100, "s": 3061, "text": "How to Install and Use NVM on Windows?" }, { "code": null, "e": 3154, "s": 3100, "text": "How to Install Python Packages for AWS Lambda Layers?" }, { "code": null, "e": 3212, "s": 3154, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 3252, "s": 3212, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 3292, "s": 3252, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 3319, "s": 3292, "text": "grep command in Unix/Linux" }, { "code": null, "e": 3354, "s": 3319, "text": "cut command in Linux with examples" } ]
Java Program to Implement the Monoalphabetic Cypher
11 Aug, 2021 Monoalphabetic Cipher is a cipher where the letters of the plain text are mapped to ciphertext letters based on a single alphabetic key. It is a one to one mapping. Given plain text, the task is to implement the Monoalphabetic Cipher. Examples: Input: Welcome to geeksforgeeks Output: Plain text: Welcome to geeksforgeeks Encrypted message: VTSEGDT ZG UTTALYGKUTTAL Decrypted message: welcome to geeksforgeeks Input: Live the moment Output: Plain text: Live the moment Encrypted message: SOCT ZIT DGDTFZ Decrypted message: live the moment Mapping characters to cipher text letters which we used in our code: Explanation of Output: Welcome to geeksforgeeks → VTSEGDT ZG UTTALYGKUTTAL Approach: 1. Create two char arrays, one for normal alphabets(say normalChar[]) and another is for encoding(say codedChar[]). 2. We will use two functions: stringEncryption: We pass string(string with all characters in lower case) as a parameter. Initialize an empty string(say encryptedString). We use for loop and compare each character with normal char array, whenever the condition is true, add the character with the corresponding index of codedChar to the encrypted string. In the case of special characters, we will add them directly to the string. stringDescryption: We pass the encrypted string as the parameter. Initialize an empty string(say descryptedString). In the same way, we run the for loop and add the character with the corresponding index of normalChar to the decrypted string. In the case of special characters, we will add them directly to the string. Below is the implementation of the above approach: Java // Java Program to Implement the Monoalphabetic Cypher import java.io.*;class GFG { public static char normalChar[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; public static char codedChar[] = { 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M' }; // Function which returns encrypted string public static String stringEncryption(String s) { // initializing an empty String String encryptedString = ""; // comparing each character of the string and // encoding each character using the indices for (int i = 0; i < s.length(); i++) { for (int j = 0; j < 26; j++) { // comparing the character and // adding the corresponding char // to the encryptedString if (s.charAt(i) == normalChar[j]) { encryptedString += codedChar[j]; break; } // if there are any special characters // add them directly to the string if (s.charAt(i) < 'a' || s.charAt(i) > 'z') { encryptedString += s.charAt(i); break; } } } // return encryptedString return encryptedString; } // Function which returns descryptedString public static String stringDecryption(String s) { // Initializing the string String decryptedString = ""; // Run the for loop for total string for (int i = 0; i < s.length(); i++) { for (int j = 0; j < 26; j++) { // compare each characters and decode them // using indices if (s.charAt(i) == codedChar[j]) { decryptedString += normalChar[j]; break; } // Add the special characters directly to // the String if (s.charAt(i) < 'A' || s.charAt(i) > 'Z') { decryptedString += s.charAt(i); break; } } } // return the decryptedString return decryptedString; } public static void main(String args[]) { String str = "Welcome to geeksforgeeks"; // print plain text System.out.println("Plain text: " + str); // Changing whole string to lower case // function call to stringEncryption and storing in // encryptedString String encryptedString = stringEncryption(str.toLowerCase()); // printing encryptedString System.out.println("Encrypted message: " + encryptedString); // function call to stringDecryption and printing // the decryptedString System.out.println("Decrypted message: " + stringDecryption(encryptedString)); }} Plain text: Welcome to geeksforgeeks Encrypted message: VTSEGDT ZG UTTALYGKUTTAL Decrypted message: welcome to geeksforgeeks simranarora5sos Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Aug, 2021" }, { "code": null, "e": 219, "s": 54, "text": "Monoalphabetic Cipher is a cipher where the letters of the plain text are mapped to ciphertext letters based on a single alphabetic key. It is a one to one mapping." }, { "code": null, "e": 289, "s": 219, "text": "Given plain text, the task is to implement the Monoalphabetic Cipher." }, { "code": null, "e": 299, "s": 289, "text": "Examples:" }, { "code": null, "e": 628, "s": 299, "text": "Input: Welcome to geeksforgeeks\nOutput: Plain text: Welcome to geeksforgeeks\n Encrypted message: VTSEGDT ZG UTTALYGKUTTAL\n Decrypted message: welcome to geeksforgeeks\n\nInput: Live the moment\nOutput: Plain text: Live the moment\n Encrypted message: SOCT ZIT DGDTFZ\n Decrypted message: live the moment" }, { "code": null, "e": 697, "s": 628, "text": "Mapping characters to cipher text letters which we used in our code:" }, { "code": null, "e": 720, "s": 697, "text": "Explanation of Output:" }, { "code": null, "e": 772, "s": 720, "text": "Welcome to geeksforgeeks → VTSEGDT ZG UTTALYGKUTTAL" }, { "code": null, "e": 783, "s": 772, "text": "Approach: " }, { "code": null, "e": 900, "s": 783, "text": "1. Create two char arrays, one for normal alphabets(say normalChar[]) and another is for encoding(say codedChar[])." }, { "code": null, "e": 931, "s": 900, "text": "2. We will use two functions:" }, { "code": null, "e": 1331, "s": 931, "text": "stringEncryption: We pass string(string with all characters in lower case) as a parameter. Initialize an empty string(say encryptedString). We use for loop and compare each character with normal char array, whenever the condition is true, add the character with the corresponding index of codedChar to the encrypted string. In the case of special characters, we will add them directly to the string." }, { "code": null, "e": 1650, "s": 1331, "text": "stringDescryption: We pass the encrypted string as the parameter. Initialize an empty string(say descryptedString). In the same way, we run the for loop and add the character with the corresponding index of normalChar to the decrypted string. In the case of special characters, we will add them directly to the string." }, { "code": null, "e": 1701, "s": 1650, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1706, "s": 1701, "text": "Java" }, { "code": "// Java Program to Implement the Monoalphabetic Cypher import java.io.*;class GFG { public static char normalChar[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; public static char codedChar[] = { 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M' }; // Function which returns encrypted string public static String stringEncryption(String s) { // initializing an empty String String encryptedString = \"\"; // comparing each character of the string and // encoding each character using the indices for (int i = 0; i < s.length(); i++) { for (int j = 0; j < 26; j++) { // comparing the character and // adding the corresponding char // to the encryptedString if (s.charAt(i) == normalChar[j]) { encryptedString += codedChar[j]; break; } // if there are any special characters // add them directly to the string if (s.charAt(i) < 'a' || s.charAt(i) > 'z') { encryptedString += s.charAt(i); break; } } } // return encryptedString return encryptedString; } // Function which returns descryptedString public static String stringDecryption(String s) { // Initializing the string String decryptedString = \"\"; // Run the for loop for total string for (int i = 0; i < s.length(); i++) { for (int j = 0; j < 26; j++) { // compare each characters and decode them // using indices if (s.charAt(i) == codedChar[j]) { decryptedString += normalChar[j]; break; } // Add the special characters directly to // the String if (s.charAt(i) < 'A' || s.charAt(i) > 'Z') { decryptedString += s.charAt(i); break; } } } // return the decryptedString return decryptedString; } public static void main(String args[]) { String str = \"Welcome to geeksforgeeks\"; // print plain text System.out.println(\"Plain text: \" + str); // Changing whole string to lower case // function call to stringEncryption and storing in // encryptedString String encryptedString = stringEncryption(str.toLowerCase()); // printing encryptedString System.out.println(\"Encrypted message: \" + encryptedString); // function call to stringDecryption and printing // the decryptedString System.out.println(\"Decrypted message: \" + stringDecryption(encryptedString)); }}", "e": 4846, "s": 1706, "text": null }, { "code": null, "e": 4974, "s": 4849, "text": "Plain text: Welcome to geeksforgeeks\nEncrypted message: VTSEGDT ZG UTTALYGKUTTAL\nDecrypted message: welcome to geeksforgeeks" }, { "code": null, "e": 4992, "s": 4976, "text": "simranarora5sos" }, { "code": null, "e": 4999, "s": 4992, "text": "Picked" }, { "code": null, "e": 5023, "s": 4999, "text": "Technical Scripter 2020" }, { "code": null, "e": 5028, "s": 5023, "text": "Java" }, { "code": null, "e": 5042, "s": 5028, "text": "Java Programs" }, { "code": null, "e": 5061, "s": 5042, "text": "Technical Scripter" }, { "code": null, "e": 5066, "s": 5061, "text": "Java" } ]
Palindrome pair in an array of words (or strings)
08 Jul, 2022 Given a list of words, find if any of the two words can be joined to form a palindrome. Examples: Input : list[] = {"geekf", "geeks", "or", "keeg", "abc", "bc"} Output : Yes There is a pair "geekf" and "keeg" Input : list[] = {"abc", "xyxcba", "geekst", "or", "keeg", "bc"} Output : Yes There is a pair "abc" and "xyxcba" Asked in : Google Interview Simple approach: 1- Consider each pair one by one. 2- Check if any of the pairs forms a palindrome after concatenating them. 3- Return true, if any such pair exists. 4- Else, return false. Implementation: C++ Java Python3 C# Javascript // C++ program to find if there is a pair that// can form a palindrome.#include<bits/stdc++.h>using namespace std; // Utility function to check if a string is a// palindromebool isPalindrome(string str){ int len = str.length(); // compare each character from starting // with its corresponding character from last for (int i = 0; i < len/2; i++ ) if (str[i] != str[len-i-1]) return false; return true;} // Function to check if a palindrome pair existsbool checkPalindromePair(vector <string> vect){ // Consider each pair one by one for (int i = 0; i< vect.size()-1; i++) { for (int j = i+1; j< vect.size() ; j++) { string check_str; // concatenate both strings check_str = vect[i] + vect[j]; // check if the concatenated string is // palindrome if (isPalindrome(check_str)) return true; // check for other combination of the two strings check_str = vect[j] + vect[i]; if (isPalindrome(check_str)) return true; } } return false;} // Driver codeint main(){ vector <string> vect = {"geekf", "geeks", "or", "keeg", "abc", "bc"}; checkPalindromePair(vect)? cout << "Yes" : cout << "No"; return 0;} // Java program to find if there is a pair that// can form a palindrome.import java.util.Arrays;import java.util.List;public class Palin_pair1 { // Utility function to check if a string is a // palindrome static boolean isPalindrome(String str) { int len = str.length(); // compare each character from starting // with its corresponding character from last for (int i = 0; i < len/2; i++ ) if (str.charAt(i) != str.charAt(len-i-1)) return false; return true; } // Function to check if a palindrome pair exists static boolean checkPalindromePair(List<String> vect) { // Consider each pair one by one for (int i = 0; i< vect.size()-1; i++) { for (int j = i+1; j< vect.size() ; j++) { String check_str = ""; // concatenate both strings check_str = check_str + vect.get(i) + vect.get(j); // check if the concatenated string is // palindrome if (isPalindrome(check_str)) return true; check_str = vect.get(j) + vect.get(i); // check if the concatenated string is // palindrome if (isPalindrome(check_str)) return true; } } return false; } // Driver code public static void main(String args[]) { List<String> vect = Arrays.asList("geekf", "geeks", "or", "keeg", "abc", "bc"); if (checkPalindromePair(vect) == true) System.out.println("Yes"); else System.out.println("No"); }}//This code is contributed by Sumit Ghosh # Python3 program to find if# there is a pair that# can form a palindrome. # Utility function to check# if a string is a palindromedef isPalindrome(st): length = len(st) # Compare each character # from starting with its # corresponding character from last for i in range(length // 2): if (st[i] != st[length - i - 1]): return False return True # Function to check if a# palindrome pair existsdef checkPalindromePair(vect): # Consider each pair one by one for i in range(len(vect) - 1): for j in range(i + 1, len(vect)): # Concatenate both strings check_str = vect[i] + vect[j] # Check if the concatenated # string is palindrome if (isPalindrome(check_str)): return True # Check for other combination # of the two strings check_str = vect[j] + vect[i] if (isPalindrome(check_str)): return True return False # Driver codeif __name__ == "__main__": vect = ["geekf", "geeks", "or", "keeg", "abc", "bc"] if checkPalindromePair(vect): print("Yes") else: print ("No") # This code is contributed by Chitranayal // C# program to find if there is a pair that// can form a palindrome.using System;using System.Collections.Generic; class GFG{ // Utility function to check if // a string is a palindrome static Boolean isPalindrome(String str) { int len = str.Length; // compare each character from starting // with its corresponding character from last for (int i = 0; i < len / 2; i++ ) if (str[i] != str[len - i - 1]) return false; return true; } // Function to check if a palindrome pair exists static Boolean checkPalindromePair(List<String> vect) { // Consider each pair one by one for (int i = 0; i< vect.Count - 1; i++) { for (int j = i + 1; j< vect.Count ; j++) { String check_str = ""; // concatenate both strings check_str = check_str + vect[i] + vect[j]; // check if the concatenated string is // palindrome if (isPalindrome(check_str)) return true; check_str = vect[j] + vect[j]; // check if the concatenated string is // palindrome if (isPalindrome(check_str)) return true; } } return false; } // Driver code public static void Main(String []args) { List<String> vect = new List<String>(){"geekf", "geeks", "or", "keeg", "abc", "bc"}; if (checkPalindromePair(vect) == true) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by Rajput-Ji <script> // Javascript program to find if there// is a pair that can form a palindrome. // Utility function to check if a// string is a palindromefunction isPalindrome(str){ let len = str.length; // Compare each character from starting // with its corresponding character from last for(let i = 0; i < len / 2; i++ ) if (str[i] != str[len - i - 1]) return false; return true;} // Function to check if a palindrome pair existsfunction checkPalindromePair(vect){ // Consider each pair one by one for(let i = 0; i < vect.length - 1; i++) { for(let j = i + 1; j < vect.length; j++) { let check_str = ""; // Concatenate both strings check_str = check_str + vect[i] + vect[j]; // Check if the concatenated string is // palindrome if (isPalindrome(check_str)) return true; check_str = vect[j] + vect[i]; // Check if the concatenated string is // palindrome if (isPalindrome(check_str)) return true; } } return false;} // Driver codelet vect = [ "geekf", "geeks", "or", "keeg", "abc", "bc" ] if (checkPalindromePair(vect) == true) document.write("Yes");else document.write("No"); // This code is contributed by rag2127 </script> Yes Time Complexity : O(n2k) Here n is the number of the words in the list and k is the maximum length that is checked for a palindrome. Auxiliary Space : O(1) Efficient method: It can be done efficiently by using the Trie data structure. The idea is to maintain a Trie of the reverse of all words. 1) Create an empty Trie. 2) Do following for every word:- a) Insert reverse of current word. b) Also store up to which index it is a palindrome. 3) Traverse list of words again and do following for every word. a) If it is available in Trie then return true b) If it is partially available Check the remaining word is palindrome or not If yes then return true that means a pair forms a palindrome. Note: Position upto which the word is palindrome is stored because of these type of cases. C++ Java C# // C++ program to check if there is a pair that// of above method using Trie#include<bits/stdc++.h>using namespace std;#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0]) // Alphabet size (# of symbols)#define ALPHABET_SIZE (26) // Converts key current character into index// use only 'a' through 'z' and lower case#define CHAR_TO_INDEX(c) ((int)c - (int)'a') // Trie nodestruct TrieNode{ struct TrieNode *children[ALPHABET_SIZE]; vector<int> pos; // To store palindromic // positions in str int id; // isLeaf is true if the node represents // end of a word bool isLeaf;}; // Returns new Trie node (initialized to NULLs)struct TrieNode *getNode(void){ struct TrieNode *pNode = new TrieNode; pNode->isLeaf = false; for (int i = 0; i < ALPHABET_SIZE; i++) pNode->children[i] = NULL; return pNode;} // Utility function to check if a string is a// palindromebool isPalindrome(string str, int i, int len){ // compare each character from starting // with its corresponding character from last while (i < len) { if (str[i] != str[len]) return false; i++, len--; } return true;} // If not present, inserts reverse of key into Trie. If// the key is prefix of a Trie node, just mark leaf nodevoid insert(struct TrieNode* root, string key, int id){ struct TrieNode *pCrawl = root; // Start traversing word from the last for (int level = key.length()-1; level >=0; level--) { // If it is not available in Trie, then // store it int index = CHAR_TO_INDEX(key[level]); if (!pCrawl->children[index]) pCrawl->children[index] = getNode(); // If current word is palindrome till this // level, store index of current word. if (isPalindrome(key, 0, level)) (pCrawl->pos).push_back(id); pCrawl = pCrawl->children[index]; } pCrawl->id = id; pCrawl->pos.push_back(id); // mark last node as leaf pCrawl->isLeaf = true;} // Returns true if key presents in Trie, else falsevoid search(struct TrieNode *root, string key, int id, vector<vector<int> > &result){ struct TrieNode *pCrawl = root; for (int level = 0; level < key.length(); level++) { int index = CHAR_TO_INDEX(key[level]); // If it is present also check upto which index // it is palindrome if (pCrawl->id >= 0 && pCrawl->id != id && isPalindrome(key, level, key.size()-1)) result.push_back({id, pCrawl->id}); // If not present then return if (!pCrawl->children[index]) return; pCrawl = pCrawl->children[index]; } for (int i: pCrawl->pos) { if (i == id) continue; result.push_back({id, i}); }} // Function to check if a palindrome pair existsbool checkPalindromePair(vector <string> vect){ // Construct trie struct TrieNode *root = getNode(); for (int i = 0; i < vect.size(); i++) insert(root, vect[i], i); // Search for different keys vector<vector<int> > result; for (int i=0; i<vect.size(); i++) { search(root, vect[i], i, result); if (result.size() > 0) return true; } return false;} // Driver codeint main(){ vector <string> vect = {"geekf", "geeks", "or", "keeg", "abc", "bc"}; checkPalindromePair(vect)? cout << "Yes" : cout << "No"; return 0;} //Java program to check if there is a pair that//of above method using Trieimport java.util.ArrayList;import java.util.Arrays;import java.util.List; public class Palin_pair2 { // Alphabet size (# of symbols) static final int ALPHABET_SIZE = 26; // Trie node static class TrieNode { TrieNode[] children = new TrieNode[ALPHABET_SIZE]; List<Integer> pos; // To store palindromic // positions in str int id; // isLeaf is true if the node represents // end of a word boolean isLeaf; // constructor public TrieNode() { isLeaf = false; pos = new ArrayList<>(); for (int i = 0; i < ALPHABET_SIZE; i++) children[i] = null; } } // Utility function to check if a string is a // palindrome static boolean isPalindrome(String str, int i, int len) { // compare each character from starting // with its corresponding character from last while (i < len) { if (str.charAt(i) != str.charAt(len)) return false; i++; len--; } return true; } // If not present, inserts reverse of key into Trie. If // the key is prefix of a Trie node, just mark leaf node static void insert(TrieNode root, String key, int id) { TrieNode pCrawl = root; // Start traversing word from the last for (int level = key.length() - 1; level >= 0; level--) { // If it is not available in Trie, then // store it int index = key.charAt(level) - 'a'; if (pCrawl.children[index] == null) pCrawl.children[index] = new TrieNode(); // If current word is palindrome till this // level, store index of current word. if (isPalindrome(key, 0, level)) (pCrawl.pos).add(id); pCrawl = pCrawl.children[index]; } pCrawl.id = id; pCrawl.pos.add(id); // mark last node as leaf pCrawl.isLeaf = true; } // list to store result static List<List<Integer>> result; // Returns true if key presents in Trie, else false static void search(TrieNode root, String key, int id) { TrieNode pCrawl = root; for (int level = 0; level < key.length(); level++) { int index = key.charAt(level) - 'a'; // If it is present also check upto which index // it is palindrome if (pCrawl.id >= 0 && pCrawl.id != id && isPalindrome(key, level, key.length() - 1)) { List<Integer> l = new ArrayList<>(); l.add(id); l.add(pCrawl.id); result.add(l); } // If not present then return if (pCrawl.children[index] == null) return; pCrawl = pCrawl.children[index]; } for (int i : pCrawl.pos) { if (i == id) continue; List<Integer> l = new ArrayList<>(); l.add(id); l.add(i); result.add(l); } } // Function to check if a palindrome pair exists static boolean checkPalindromePair(List<String> vect) { // Construct trie TrieNode root = new TrieNode(); for (int i = 0; i < vect.size(); i++) insert(root, vect.get(i), i); // Search for different keys result = new ArrayList<>(); for (int i = 0; i < vect.size(); i++) { search(root, vect.get(i), i); if (result.size() > 0) return true; } return false; } // Driver code public static void main(String args[]) { List<String> vect = Arrays.asList("geekf", "geeks", "or", "keeg", "abc", "bc"); if (checkPalindromePair(vect) == true) System.out.println("Yes"); else System.out.println("No"); }}//This code is contributed by Sumit Ghosh // C# program to check if there is// a pair that of above method using Trieusing System;using System.Collections.Generic; class GFG{ // Alphabet size (# of symbols) static readonly int ALPHABET_SIZE = 26; // Trie node class TrieNode { public TrieNode[] children = new TrieNode[ALPHABET_SIZE]; public List<int> pos; // To store palindromic // positions in str public int id; // isLeaf is true if the node // represents end of a word public Boolean isLeaf; // constructor public TrieNode() { isLeaf = false; pos = new List<int>(); for (int i = 0; i < ALPHABET_SIZE; i++) children[i] = null; } } // Utility function to check if // a string is a palindrome static Boolean isPalindrome(String str, int i, int len) { // compare each character from starting // with its corresponding character from last while (i < len) { if (str[i] != str[len]) return false; i++; len--; } return true; } // If not present, inserts reverse of // key into Trie. If the key is prefix of // a Trie node, just mark leaf node static void insert(TrieNode root, String key, int id) { TrieNode pCrawl = root; // Start traversing word from the last for (int level = key.Length - 1; level >= 0; level--) { // If it is not available in Trie, // then store it int index = key[level] - 'a'; if (pCrawl.children[index] == null) pCrawl.children[index] = new TrieNode(); // If current word is palindrome till this // level, store index of current word. if (isPalindrome(key, 0, level)) (pCrawl.pos).Add(id); pCrawl = pCrawl.children[index]; } pCrawl.id = id; pCrawl.pos.Add(id); // mark last node as leaf pCrawl.isLeaf = true; } // list to store result static List<List<int>> result; // Returns true if key presents // in Trie, else false static void search(TrieNode root, String key, int id) { TrieNode pCrawl = root; for (int level = 0; level < key.Length; level++) { int index = key[level] - 'a'; // If it is present also check // upto which index it is palindrome if (pCrawl.id >= 0 && pCrawl.id != id && isPalindrome(key, level, key.Length - 1)) { List<int> l = new List<int>(); l.Add(id); l.Add(pCrawl.id); result.Add(l); } // If not present then return if (pCrawl.children[index] == null) return; pCrawl = pCrawl.children[index]; } foreach (int i in pCrawl.pos) { if (i == id) continue; List<int> l = new List<int>(); l.Add(id); l.Add(i); result.Add(l); } } // Function to check if a palindrome pair exists static Boolean checkPalindromePair(List<String> vect) { // Construct trie TrieNode root = new TrieNode(); for (int i = 0; i < vect.Count; i++) insert(root, vect[i], i); // Search for different keys result = new List<List<int>>(); for (int i = 0; i < vect.Count; i++) { search(root, vect[i], i); if (result.Count > 0) return true; } return false; } // Driver code public static void Main(String []args) { List<String> vect = new List<String>(){"geekf", "geeks", "or", "keeg", "abc", "bc"}; if (checkPalindromePair(vect) == true) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by Rajput-Ji Yes Time Complexity: O(nk2), Where n is the number of words in the list and k is the maximum length that is checked for palindrome.Auxiliary Space: O(1) Method 3: Below given is a program which is based upon the above discussed algorithm, but instead of trie it uses hashmap datastructure for giving efficient storage and retrieval method. Hence it reduces complexity a lot. Implementation: Python3 def function(wordlist): #storing word in reverse format along with their indices. hashmap_reverse = {word[::-1]: index for index, word in enumerate(wordlist)} ans = [] #enumerating over all words and for each character of them for index, word in enumerate(wordlist): for i in range(len(word)): #extracting left and right of them left, right = word[:i+1], word[i+1:] #checking if left exists and is palindrome and also right is present in map #this is to make sure the best edge case described holds. if not len(left) == 0 and left == left[::-1] and right in hashmap_reverse and hashmap_reverse[right] != index: ans.append([hashmap_reverse[right], index]) #normal case. if right == right[::-1] and left in hashmap_reverse and hashmap_reverse[left] != index: ans.append([index, hashmap_reverse[left]]) if len(ans)>0: return True return False words = ["geekf", "geeks", "or","keeg", "abc", "bc"]print(function(words)) True Time Complexity: O(nl) where n = length of array and l = length of longest string.Auxiliary Space: O(n) This article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. IshanBhargava Rajput-Ji ukasp rag2127 harshkumarchoudhary144 shivamanandrj9 hardikkoriintern palindrome Trie Advanced Data Structure Strings Strings palindrome Trie Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jul, 2022" }, { "code": null, "e": 140, "s": 52, "text": "Given a list of words, find if any of the two words can be joined to form a palindrome." }, { "code": null, "e": 151, "s": 140, "text": "Examples: " }, { "code": null, "e": 445, "s": 151, "text": "Input : list[] = {\"geekf\", \"geeks\", \"or\", \n \"keeg\", \"abc\", \"bc\"}\nOutput : Yes\nThere is a pair \"geekf\" and \"keeg\"\n\nInput : list[] = {\"abc\", \"xyxcba\", \"geekst\", \"or\",\n \"keeg\", \"bc\"}\nOutput : Yes\nThere is a pair \"abc\" and \"xyxcba\"" }, { "code": null, "e": 474, "s": 445, "text": "Asked in : Google Interview " }, { "code": null, "e": 492, "s": 474, "text": "Simple approach: " }, { "code": null, "e": 667, "s": 492, "text": "1- Consider each pair one by one.\n2- Check if any of the pairs forms a palindrome\n after concatenating them.\n3- Return true, if any such pair exists.\n4- Else, return false." }, { "code": null, "e": 683, "s": 667, "text": "Implementation:" }, { "code": null, "e": 687, "s": 683, "text": "C++" }, { "code": null, "e": 692, "s": 687, "text": "Java" }, { "code": null, "e": 700, "s": 692, "text": "Python3" }, { "code": null, "e": 703, "s": 700, "text": "C#" }, { "code": null, "e": 714, "s": 703, "text": "Javascript" }, { "code": "// C++ program to find if there is a pair that// can form a palindrome.#include<bits/stdc++.h>using namespace std; // Utility function to check if a string is a// palindromebool isPalindrome(string str){ int len = str.length(); // compare each character from starting // with its corresponding character from last for (int i = 0; i < len/2; i++ ) if (str[i] != str[len-i-1]) return false; return true;} // Function to check if a palindrome pair existsbool checkPalindromePair(vector <string> vect){ // Consider each pair one by one for (int i = 0; i< vect.size()-1; i++) { for (int j = i+1; j< vect.size() ; j++) { string check_str; // concatenate both strings check_str = vect[i] + vect[j]; // check if the concatenated string is // palindrome if (isPalindrome(check_str)) return true; // check for other combination of the two strings check_str = vect[j] + vect[i]; if (isPalindrome(check_str)) return true; } } return false;} // Driver codeint main(){ vector <string> vect = {\"geekf\", \"geeks\", \"or\", \"keeg\", \"abc\", \"bc\"}; checkPalindromePair(vect)? cout << \"Yes\" : cout << \"No\"; return 0;}", "e": 2078, "s": 714, "text": null }, { "code": "// Java program to find if there is a pair that// can form a palindrome.import java.util.Arrays;import java.util.List;public class Palin_pair1 { // Utility function to check if a string is a // palindrome static boolean isPalindrome(String str) { int len = str.length(); // compare each character from starting // with its corresponding character from last for (int i = 0; i < len/2; i++ ) if (str.charAt(i) != str.charAt(len-i-1)) return false; return true; } // Function to check if a palindrome pair exists static boolean checkPalindromePair(List<String> vect) { // Consider each pair one by one for (int i = 0; i< vect.size()-1; i++) { for (int j = i+1; j< vect.size() ; j++) { String check_str = \"\"; // concatenate both strings check_str = check_str + vect.get(i) + vect.get(j); // check if the concatenated string is // palindrome if (isPalindrome(check_str)) return true; check_str = vect.get(j) + vect.get(i); // check if the concatenated string is // palindrome if (isPalindrome(check_str)) return true; } } return false; } // Driver code public static void main(String args[]) { List<String> vect = Arrays.asList(\"geekf\", \"geeks\", \"or\", \"keeg\", \"abc\", \"bc\"); if (checkPalindromePair(vect) == true) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}//This code is contributed by Sumit Ghosh", "e": 3885, "s": 2078, "text": null }, { "code": "# Python3 program to find if# there is a pair that# can form a palindrome. # Utility function to check# if a string is a palindromedef isPalindrome(st): length = len(st) # Compare each character # from starting with its # corresponding character from last for i in range(length // 2): if (st[i] != st[length - i - 1]): return False return True # Function to check if a# palindrome pair existsdef checkPalindromePair(vect): # Consider each pair one by one for i in range(len(vect) - 1): for j in range(i + 1, len(vect)): # Concatenate both strings check_str = vect[i] + vect[j] # Check if the concatenated # string is palindrome if (isPalindrome(check_str)): return True # Check for other combination # of the two strings check_str = vect[j] + vect[i] if (isPalindrome(check_str)): return True return False # Driver codeif __name__ == \"__main__\": vect = [\"geekf\", \"geeks\", \"or\", \"keeg\", \"abc\", \"bc\"] if checkPalindromePair(vect): print(\"Yes\") else: print (\"No\") # This code is contributed by Chitranayal", "e": 5134, "s": 3885, "text": null }, { "code": "// C# program to find if there is a pair that// can form a palindrome.using System;using System.Collections.Generic; class GFG{ // Utility function to check if // a string is a palindrome static Boolean isPalindrome(String str) { int len = str.Length; // compare each character from starting // with its corresponding character from last for (int i = 0; i < len / 2; i++ ) if (str[i] != str[len - i - 1]) return false; return true; } // Function to check if a palindrome pair exists static Boolean checkPalindromePair(List<String> vect) { // Consider each pair one by one for (int i = 0; i< vect.Count - 1; i++) { for (int j = i + 1; j< vect.Count ; j++) { String check_str = \"\"; // concatenate both strings check_str = check_str + vect[i] + vect[j]; // check if the concatenated string is // palindrome if (isPalindrome(check_str)) return true; check_str = vect[j] + vect[j]; // check if the concatenated string is // palindrome if (isPalindrome(check_str)) return true; } } return false; } // Driver code public static void Main(String []args) { List<String> vect = new List<String>(){\"geekf\", \"geeks\", \"or\", \"keeg\", \"abc\", \"bc\"}; if (checkPalindromePair(vect) == true) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by Rajput-Ji", "e": 6909, "s": 5134, "text": null }, { "code": "<script> // Javascript program to find if there// is a pair that can form a palindrome. // Utility function to check if a// string is a palindromefunction isPalindrome(str){ let len = str.length; // Compare each character from starting // with its corresponding character from last for(let i = 0; i < len / 2; i++ ) if (str[i] != str[len - i - 1]) return false; return true;} // Function to check if a palindrome pair existsfunction checkPalindromePair(vect){ // Consider each pair one by one for(let i = 0; i < vect.length - 1; i++) { for(let j = i + 1; j < vect.length; j++) { let check_str = \"\"; // Concatenate both strings check_str = check_str + vect[i] + vect[j]; // Check if the concatenated string is // palindrome if (isPalindrome(check_str)) return true; check_str = vect[j] + vect[i]; // Check if the concatenated string is // palindrome if (isPalindrome(check_str)) return true; } } return false;} // Driver codelet vect = [ \"geekf\", \"geeks\", \"or\", \"keeg\", \"abc\", \"bc\" ] if (checkPalindromePair(vect) == true) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by rag2127 </script>", "e": 8292, "s": 6909, "text": null }, { "code": null, "e": 8296, "s": 8292, "text": "Yes" }, { "code": null, "e": 8429, "s": 8296, "text": "Time Complexity : O(n2k) Here n is the number of the words in the list and k is the maximum length that is checked for a palindrome." }, { "code": null, "e": 8452, "s": 8429, "text": "Auxiliary Space : O(1)" }, { "code": null, "e": 8470, "s": 8452, "text": "Efficient method:" }, { "code": null, "e": 8592, "s": 8470, "text": "It can be done efficiently by using the Trie data structure. The idea is to maintain a Trie of the reverse of all words. " }, { "code": null, "e": 9160, "s": 8592, "text": "1) Create an empty Trie.\n2) Do following for every word:-\n a) Insert reverse of current word.\n b) Also store up to which index it is \n a palindrome.\n3) Traverse list of words again and do following \n for every word.\n a) If it is available in Trie then return true\n b) If it is partially available\n Check the remaining word is palindrome or not \n If yes then return true that means a pair\n forms a palindrome.\n Note: Position upto which the word is palindrome\n is stored because of these type of cases." }, { "code": null, "e": 9164, "s": 9160, "text": "C++" }, { "code": null, "e": 9169, "s": 9164, "text": "Java" }, { "code": null, "e": 9172, "s": 9169, "text": "C#" }, { "code": "// C++ program to check if there is a pair that// of above method using Trie#include<bits/stdc++.h>using namespace std;#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0]) // Alphabet size (# of symbols)#define ALPHABET_SIZE (26) // Converts key current character into index// use only 'a' through 'z' and lower case#define CHAR_TO_INDEX(c) ((int)c - (int)'a') // Trie nodestruct TrieNode{ struct TrieNode *children[ALPHABET_SIZE]; vector<int> pos; // To store palindromic // positions in str int id; // isLeaf is true if the node represents // end of a word bool isLeaf;}; // Returns new Trie node (initialized to NULLs)struct TrieNode *getNode(void){ struct TrieNode *pNode = new TrieNode; pNode->isLeaf = false; for (int i = 0; i < ALPHABET_SIZE; i++) pNode->children[i] = NULL; return pNode;} // Utility function to check if a string is a// palindromebool isPalindrome(string str, int i, int len){ // compare each character from starting // with its corresponding character from last while (i < len) { if (str[i] != str[len]) return false; i++, len--; } return true;} // If not present, inserts reverse of key into Trie. If// the key is prefix of a Trie node, just mark leaf nodevoid insert(struct TrieNode* root, string key, int id){ struct TrieNode *pCrawl = root; // Start traversing word from the last for (int level = key.length()-1; level >=0; level--) { // If it is not available in Trie, then // store it int index = CHAR_TO_INDEX(key[level]); if (!pCrawl->children[index]) pCrawl->children[index] = getNode(); // If current word is palindrome till this // level, store index of current word. if (isPalindrome(key, 0, level)) (pCrawl->pos).push_back(id); pCrawl = pCrawl->children[index]; } pCrawl->id = id; pCrawl->pos.push_back(id); // mark last node as leaf pCrawl->isLeaf = true;} // Returns true if key presents in Trie, else falsevoid search(struct TrieNode *root, string key, int id, vector<vector<int> > &result){ struct TrieNode *pCrawl = root; for (int level = 0; level < key.length(); level++) { int index = CHAR_TO_INDEX(key[level]); // If it is present also check upto which index // it is palindrome if (pCrawl->id >= 0 && pCrawl->id != id && isPalindrome(key, level, key.size()-1)) result.push_back({id, pCrawl->id}); // If not present then return if (!pCrawl->children[index]) return; pCrawl = pCrawl->children[index]; } for (int i: pCrawl->pos) { if (i == id) continue; result.push_back({id, i}); }} // Function to check if a palindrome pair existsbool checkPalindromePair(vector <string> vect){ // Construct trie struct TrieNode *root = getNode(); for (int i = 0; i < vect.size(); i++) insert(root, vect[i], i); // Search for different keys vector<vector<int> > result; for (int i=0; i<vect.size(); i++) { search(root, vect[i], i, result); if (result.size() > 0) return true; } return false;} // Driver codeint main(){ vector <string> vect = {\"geekf\", \"geeks\", \"or\", \"keeg\", \"abc\", \"bc\"}; checkPalindromePair(vect)? cout << \"Yes\" : cout << \"No\"; return 0;}", "e": 12638, "s": 9172, "text": null }, { "code": "//Java program to check if there is a pair that//of above method using Trieimport java.util.ArrayList;import java.util.Arrays;import java.util.List; public class Palin_pair2 { // Alphabet size (# of symbols) static final int ALPHABET_SIZE = 26; // Trie node static class TrieNode { TrieNode[] children = new TrieNode[ALPHABET_SIZE]; List<Integer> pos; // To store palindromic // positions in str int id; // isLeaf is true if the node represents // end of a word boolean isLeaf; // constructor public TrieNode() { isLeaf = false; pos = new ArrayList<>(); for (int i = 0; i < ALPHABET_SIZE; i++) children[i] = null; } } // Utility function to check if a string is a // palindrome static boolean isPalindrome(String str, int i, int len) { // compare each character from starting // with its corresponding character from last while (i < len) { if (str.charAt(i) != str.charAt(len)) return false; i++; len--; } return true; } // If not present, inserts reverse of key into Trie. If // the key is prefix of a Trie node, just mark leaf node static void insert(TrieNode root, String key, int id) { TrieNode pCrawl = root; // Start traversing word from the last for (int level = key.length() - 1; level >= 0; level--) { // If it is not available in Trie, then // store it int index = key.charAt(level) - 'a'; if (pCrawl.children[index] == null) pCrawl.children[index] = new TrieNode(); // If current word is palindrome till this // level, store index of current word. if (isPalindrome(key, 0, level)) (pCrawl.pos).add(id); pCrawl = pCrawl.children[index]; } pCrawl.id = id; pCrawl.pos.add(id); // mark last node as leaf pCrawl.isLeaf = true; } // list to store result static List<List<Integer>> result; // Returns true if key presents in Trie, else false static void search(TrieNode root, String key, int id) { TrieNode pCrawl = root; for (int level = 0; level < key.length(); level++) { int index = key.charAt(level) - 'a'; // If it is present also check upto which index // it is palindrome if (pCrawl.id >= 0 && pCrawl.id != id && isPalindrome(key, level, key.length() - 1)) { List<Integer> l = new ArrayList<>(); l.add(id); l.add(pCrawl.id); result.add(l); } // If not present then return if (pCrawl.children[index] == null) return; pCrawl = pCrawl.children[index]; } for (int i : pCrawl.pos) { if (i == id) continue; List<Integer> l = new ArrayList<>(); l.add(id); l.add(i); result.add(l); } } // Function to check if a palindrome pair exists static boolean checkPalindromePair(List<String> vect) { // Construct trie TrieNode root = new TrieNode(); for (int i = 0; i < vect.size(); i++) insert(root, vect.get(i), i); // Search for different keys result = new ArrayList<>(); for (int i = 0; i < vect.size(); i++) { search(root, vect.get(i), i); if (result.size() > 0) return true; } return false; } // Driver code public static void main(String args[]) { List<String> vect = Arrays.asList(\"geekf\", \"geeks\", \"or\", \"keeg\", \"abc\", \"bc\"); if (checkPalindromePair(vect) == true) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}//This code is contributed by Sumit Ghosh", "e": 16669, "s": 12638, "text": null }, { "code": "// C# program to check if there is// a pair that of above method using Trieusing System;using System.Collections.Generic; class GFG{ // Alphabet size (# of symbols) static readonly int ALPHABET_SIZE = 26; // Trie node class TrieNode { public TrieNode[] children = new TrieNode[ALPHABET_SIZE]; public List<int> pos; // To store palindromic // positions in str public int id; // isLeaf is true if the node // represents end of a word public Boolean isLeaf; // constructor public TrieNode() { isLeaf = false; pos = new List<int>(); for (int i = 0; i < ALPHABET_SIZE; i++) children[i] = null; } } // Utility function to check if // a string is a palindrome static Boolean isPalindrome(String str, int i, int len) { // compare each character from starting // with its corresponding character from last while (i < len) { if (str[i] != str[len]) return false; i++; len--; } return true; } // If not present, inserts reverse of // key into Trie. If the key is prefix of // a Trie node, just mark leaf node static void insert(TrieNode root, String key, int id) { TrieNode pCrawl = root; // Start traversing word from the last for (int level = key.Length - 1; level >= 0; level--) { // If it is not available in Trie, // then store it int index = key[level] - 'a'; if (pCrawl.children[index] == null) pCrawl.children[index] = new TrieNode(); // If current word is palindrome till this // level, store index of current word. if (isPalindrome(key, 0, level)) (pCrawl.pos).Add(id); pCrawl = pCrawl.children[index]; } pCrawl.id = id; pCrawl.pos.Add(id); // mark last node as leaf pCrawl.isLeaf = true; } // list to store result static List<List<int>> result; // Returns true if key presents // in Trie, else false static void search(TrieNode root, String key, int id) { TrieNode pCrawl = root; for (int level = 0; level < key.Length; level++) { int index = key[level] - 'a'; // If it is present also check // upto which index it is palindrome if (pCrawl.id >= 0 && pCrawl.id != id && isPalindrome(key, level, key.Length - 1)) { List<int> l = new List<int>(); l.Add(id); l.Add(pCrawl.id); result.Add(l); } // If not present then return if (pCrawl.children[index] == null) return; pCrawl = pCrawl.children[index]; } foreach (int i in pCrawl.pos) { if (i == id) continue; List<int> l = new List<int>(); l.Add(id); l.Add(i); result.Add(l); } } // Function to check if a palindrome pair exists static Boolean checkPalindromePair(List<String> vect) { // Construct trie TrieNode root = new TrieNode(); for (int i = 0; i < vect.Count; i++) insert(root, vect[i], i); // Search for different keys result = new List<List<int>>(); for (int i = 0; i < vect.Count; i++) { search(root, vect[i], i); if (result.Count > 0) return true; } return false; } // Driver code public static void Main(String []args) { List<String> vect = new List<String>(){\"geekf\", \"geeks\", \"or\", \"keeg\", \"abc\", \"bc\"}; if (checkPalindromePair(vect) == true) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by Rajput-Ji", "e": 20878, "s": 16669, "text": null }, { "code": null, "e": 20882, "s": 20878, "text": "Yes" }, { "code": null, "e": 21031, "s": 20882, "text": "Time Complexity: O(nk2), Where n is the number of words in the list and k is the maximum length that is checked for palindrome.Auxiliary Space: O(1)" }, { "code": null, "e": 21041, "s": 21031, "text": "Method 3:" }, { "code": null, "e": 21218, "s": 21041, "text": "Below given is a program which is based upon the above discussed algorithm, but instead of trie it uses hashmap datastructure for giving efficient storage and retrieval method." }, { "code": null, "e": 21253, "s": 21218, "text": "Hence it reduces complexity a lot." }, { "code": null, "e": 21269, "s": 21253, "text": "Implementation:" }, { "code": null, "e": 21277, "s": 21269, "text": "Python3" }, { "code": "def function(wordlist): #storing word in reverse format along with their indices. hashmap_reverse = {word[::-1]: index for index, word in enumerate(wordlist)} ans = [] #enumerating over all words and for each character of them for index, word in enumerate(wordlist): for i in range(len(word)): #extracting left and right of them left, right = word[:i+1], word[i+1:] #checking if left exists and is palindrome and also right is present in map #this is to make sure the best edge case described holds. if not len(left) == 0 and left == left[::-1] and right in hashmap_reverse and hashmap_reverse[right] != index: ans.append([hashmap_reverse[right], index]) #normal case. if right == right[::-1] and left in hashmap_reverse and hashmap_reverse[left] != index: ans.append([index, hashmap_reverse[left]]) if len(ans)>0: return True return False words = [\"geekf\", \"geeks\", \"or\",\"keeg\", \"abc\", \"bc\"]print(function(words))", "e": 22366, "s": 21277, "text": null }, { "code": null, "e": 22371, "s": 22366, "text": "True" }, { "code": null, "e": 22476, "s": 22371, "text": "Time Complexity: O(nl) where n = length of array and l = length of longest string.Auxiliary Space: O(n)" }, { "code": null, "e": 22780, "s": 22476, "text": "This article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 22794, "s": 22780, "text": "IshanBhargava" }, { "code": null, "e": 22804, "s": 22794, "text": "Rajput-Ji" }, { "code": null, "e": 22810, "s": 22804, "text": "ukasp" }, { "code": null, "e": 22818, "s": 22810, "text": "rag2127" }, { "code": null, "e": 22841, "s": 22818, "text": "harshkumarchoudhary144" }, { "code": null, "e": 22856, "s": 22841, "text": "shivamanandrj9" }, { "code": null, "e": 22873, "s": 22856, "text": "hardikkoriintern" }, { "code": null, "e": 22884, "s": 22873, "text": "palindrome" }, { "code": null, "e": 22889, "s": 22884, "text": "Trie" }, { "code": null, "e": 22913, "s": 22889, "text": "Advanced Data Structure" }, { "code": null, "e": 22921, "s": 22913, "text": "Strings" }, { "code": null, "e": 22929, "s": 22921, "text": "Strings" }, { "code": null, "e": 22940, "s": 22929, "text": "palindrome" }, { "code": null, "e": 22945, "s": 22940, "text": "Trie" } ]
Plot Multiple Data Sets on the Same Chart in Excel
29 Jun, 2021 Sometimes while dealing with hierarchical data we need to combine two or more various chart types into a single chart for better visualization and analysis. This type of chart having multiple data sets is known as “Combination charts”. In this article, we are going to see how to make combination charts from a set of two different charts in Excel using the example shown below. Example: Consider a famous coaching institute that deals with both free content in their YouTube channel and also have their own paid online courses. There are broadly two categories of students in this institute : The students who enrolled in the coaching but are learning from YouTube free video content.The students who enrolled as well as bought paid online courses. The students who enrolled in the coaching but are learning from YouTube free video content. The students who enrolled as well as bought paid online courses. So, the institute asked their Sales Department to make a statistical chart about how many paid courses from a pool of courses which the institute deals with were sold from the year 2014 to the last year 2020 and also show the percentage of students who have enrolled in these paid courses. Here, the first data is “Number of Paid courses sold” and the second one is “Percentage of Students enrolled”. Now our aim is to plot these two data in the same chart with different y-axis. Follow the below steps to implement the same: Step 1: Insert the data in the cells. After insertion, select the rows and columns by dragging the cursor. Step 2: Now click on Insert Tab from the top of the Excel window and then select Insert Line or Area Chart. From the pop-down menu select the first “2-D Line”. From the above chart we can observe that the second data line is almost invisible because of scaling. The present y-axis line is having much higher values and the percentage line will be having values lesser than 1 i.e. in decimal values. Hence, we need a secondary axis in order to plot the two lines in the same chart. In Excel, it is also known as clustering of two charts. The steps to add a secondary axis are as follows : 1. Open the Chart Type dialog box Select the Chart -> Design -> Change Chart Type Another way is : Select the Chart -> Right Click on it -> Change Chart Type 2. The Chart Type dialog box opens. Now go to the “Combo” option and check the “Secondary Axis” box for the “Percentage of Students Enrolled” column. This will add the secondary axis in the original chart and will separate the two charts. This will result in better visualization for analysis purposes. The combination chart with two data sets is now ready. The secondary axis is for the “Percentage of Students Enrolled” column in the data set as discussed above. Now various formatting can be carried out in this secondary axis using the Format Axis window on the right corner of Excel. Select the secondary Axis -> Right Click -> Format Axis -> Format Axis Dialog Box Changing the Bounds of Secondary Axis You can further format the above chart by making it more interactive by changing the “Chart Styles”, adding suitable “Axis Titles”, “Chart Title”, “Data Labels”, changing the “Chart Type” etc. It can be done using the “+” button in the top right corner of the Excel chart. Finally, after all the modification, the chart with multiple data sets looks like : We can infer from the above chart that in the year 2019, the percentage of students who enrolled in the online paid courses are relatively less but in 2020 more students have enrolled in paid courses than free content on YouTube. Picked Excel Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jun, 2021" }, { "code": null, "e": 264, "s": 28, "text": "Sometimes while dealing with hierarchical data we need to combine two or more various chart types into a single chart for better visualization and analysis. This type of chart having multiple data sets is known as “Combination charts”." }, { "code": null, "e": 407, "s": 264, "text": "In this article, we are going to see how to make combination charts from a set of two different charts in Excel using the example shown below." }, { "code": null, "e": 622, "s": 407, "text": "Example: Consider a famous coaching institute that deals with both free content in their YouTube channel and also have their own paid online courses. There are broadly two categories of students in this institute :" }, { "code": null, "e": 778, "s": 622, "text": "The students who enrolled in the coaching but are learning from YouTube free video content.The students who enrolled as well as bought paid online courses." }, { "code": null, "e": 870, "s": 778, "text": "The students who enrolled in the coaching but are learning from YouTube free video content." }, { "code": null, "e": 935, "s": 870, "text": "The students who enrolled as well as bought paid online courses." }, { "code": null, "e": 1225, "s": 935, "text": "So, the institute asked their Sales Department to make a statistical chart about how many paid courses from a pool of courses which the institute deals with were sold from the year 2014 to the last year 2020 and also show the percentage of students who have enrolled in these paid courses." }, { "code": null, "e": 1415, "s": 1225, "text": "Here, the first data is “Number of Paid courses sold” and the second one is “Percentage of Students enrolled”. Now our aim is to plot these two data in the same chart with different y-axis." }, { "code": null, "e": 1461, "s": 1415, "text": "Follow the below steps to implement the same:" }, { "code": null, "e": 1568, "s": 1461, "text": "Step 1: Insert the data in the cells. After insertion, select the rows and columns by dragging the cursor." }, { "code": null, "e": 1728, "s": 1568, "text": "Step 2: Now click on Insert Tab from the top of the Excel window and then select Insert Line or Area Chart. From the pop-down menu select the first “2-D Line”." }, { "code": null, "e": 2105, "s": 1728, "text": "From the above chart we can observe that the second data line is almost invisible because of scaling. The present y-axis line is having much higher values and the percentage line will be having values lesser than 1 i.e. in decimal values. Hence, we need a secondary axis in order to plot the two lines in the same chart. In Excel, it is also known as clustering of two charts." }, { "code": null, "e": 2156, "s": 2105, "text": "The steps to add a secondary axis are as follows :" }, { "code": null, "e": 2190, "s": 2156, "text": "1. Open the Chart Type dialog box" }, { "code": null, "e": 2238, "s": 2190, "text": "Select the Chart -> Design -> Change Chart Type" }, { "code": null, "e": 2255, "s": 2238, "text": "Another way is :" }, { "code": null, "e": 2314, "s": 2255, "text": "Select the Chart -> Right Click on it -> Change Chart Type" }, { "code": null, "e": 2619, "s": 2314, "text": "2. The Chart Type dialog box opens. Now go to the “Combo” option and check the “Secondary Axis” box for the “Percentage of Students Enrolled” column. This will add the secondary axis in the original chart and will separate the two charts. This will result in better visualization for analysis purposes. " }, { "code": null, "e": 2781, "s": 2619, "text": "The combination chart with two data sets is now ready. The secondary axis is for the “Percentage of Students Enrolled” column in the data set as discussed above." }, { "code": null, "e": 2906, "s": 2781, "text": " Now various formatting can be carried out in this secondary axis using the Format Axis window on the right corner of Excel." }, { "code": null, "e": 2988, "s": 2906, "text": "Select the secondary Axis -> Right Click -> Format Axis -> Format Axis Dialog Box" }, { "code": null, "e": 3026, "s": 2988, "text": "Changing the Bounds of Secondary Axis" }, { "code": null, "e": 3299, "s": 3026, "text": "You can further format the above chart by making it more interactive by changing the “Chart Styles”, adding suitable “Axis Titles”, “Chart Title”, “Data Labels”, changing the “Chart Type” etc. It can be done using the “+” button in the top right corner of the Excel chart." }, { "code": null, "e": 3383, "s": 3299, "text": "Finally, after all the modification, the chart with multiple data sets looks like :" }, { "code": null, "e": 3613, "s": 3383, "text": "We can infer from the above chart that in the year 2019, the percentage of students who enrolled in the online paid courses are relatively less but in 2020 more students have enrolled in paid courses than free content on YouTube." }, { "code": null, "e": 3620, "s": 3613, "text": "Picked" }, { "code": null, "e": 3626, "s": 3620, "text": "Excel" } ]
JavaScript Date now() Method
25 Nov, 2021 In this article, we will learn about the Date now() method in Javascript. The date.now() method is used to return the number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC. Since now() is a static method of Date, it will always be used as Date.now(). Syntax: var A = Date.now(); Parameters: This method does not accept any parameter. Return Values: It returns the number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC. Please refer to the JavaScript Get Date Methods article for other Date methods in detail. More codes for the above method are as follows: Example 1: The below example illustrates the Date now() method. Javascript <script> // Use of method Date.now() var A = Date.now(); // Printing the number of millisecond elapsed document.write("The time elapsed in millisecond is: " + A);</script> Output: The time elapsed in millisecond is: 1529644667834 Example 2: This example illustrates getting the current date using the Date.now() method. Javascript <script> // Use of Date.now() method var d = Date(Date.now()); // Converting the number of millisecond // in date string a = d.toString() // Printing the current date document.write("The current date is: " + a)</script> Output: The current date is: Fri Jun 22 2018 10:54:33 GMT+0530 (India Standard Time) Example 3: The Date(Date.now()) is the same as Date(), so the same result can be achieved i.e, the current date using the following code. Javascript <script> // Using Date() method var d = Date(); // Converting the number value to string a = d.toString() // Printing the current date document.write("The current date is: " + a)</script> Output: The current date is: Fri Jun 22 2018 11:02:01 GMT+0530 (India Standard Time) Supported Browsers: The browsers supported by JavaScript Date now() method are listed below: Google Chrome 5 and above Microsoft Edge 12 and above Firefox 3 and above Internet Explorer 9 and above Opera 10.5 and above Safari 4 and above ysachin2314 bhaskargeeksforgeeks javascript-date JavaScript-Methods JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property Roadmap to Learn JavaScript For Beginners Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Nov, 2021" }, { "code": null, "e": 317, "s": 52, "text": "In this article, we will learn about the Date now() method in Javascript. The date.now() method is used to return the number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC. Since now() is a static method of Date, it will always be used as Date.now(). " }, { "code": null, "e": 325, "s": 317, "text": "Syntax:" }, { "code": null, "e": 345, "s": 325, "text": "var A = Date.now();" }, { "code": null, "e": 401, "s": 345, "text": "Parameters: This method does not accept any parameter. " }, { "code": null, "e": 499, "s": 401, "text": "Return Values: It returns the number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC." }, { "code": null, "e": 589, "s": 499, "text": "Please refer to the JavaScript Get Date Methods article for other Date methods in detail." }, { "code": null, "e": 638, "s": 589, "text": "More codes for the above method are as follows: " }, { "code": null, "e": 702, "s": 638, "text": "Example 1: The below example illustrates the Date now() method." }, { "code": null, "e": 713, "s": 702, "text": "Javascript" }, { "code": "<script> // Use of method Date.now() var A = Date.now(); // Printing the number of millisecond elapsed document.write(\"The time elapsed in millisecond is: \" + A);</script>", "e": 891, "s": 713, "text": null }, { "code": null, "e": 899, "s": 891, "text": "Output:" }, { "code": null, "e": 949, "s": 899, "text": "The time elapsed in millisecond is: 1529644667834" }, { "code": null, "e": 1039, "s": 949, "text": "Example 2: This example illustrates getting the current date using the Date.now() method." }, { "code": null, "e": 1050, "s": 1039, "text": "Javascript" }, { "code": "<script> // Use of Date.now() method var d = Date(Date.now()); // Converting the number of millisecond // in date string a = d.toString() // Printing the current date document.write(\"The current date is: \" + a)</script>", "e": 1299, "s": 1050, "text": null }, { "code": null, "e": 1307, "s": 1299, "text": "Output:" }, { "code": null, "e": 1385, "s": 1307, "text": "The current date is: Fri Jun 22 2018 10:54:33 \nGMT+0530 (India Standard Time)" }, { "code": null, "e": 1523, "s": 1385, "text": "Example 3: The Date(Date.now()) is the same as Date(), so the same result can be achieved i.e, the current date using the following code." }, { "code": null, "e": 1534, "s": 1523, "text": "Javascript" }, { "code": "<script> // Using Date() method var d = Date(); // Converting the number value to string a = d.toString() // Printing the current date document.write(\"The current date is: \" + a)</script>", "e": 1734, "s": 1534, "text": null }, { "code": null, "e": 1742, "s": 1734, "text": "Output:" }, { "code": null, "e": 1820, "s": 1742, "text": "The current date is: Fri Jun 22 2018 11:02:01 \nGMT+0530 (India Standard Time)" }, { "code": null, "e": 1913, "s": 1820, "text": "Supported Browsers: The browsers supported by JavaScript Date now() method are listed below:" }, { "code": null, "e": 1939, "s": 1913, "text": "Google Chrome 5 and above" }, { "code": null, "e": 1967, "s": 1939, "text": "Microsoft Edge 12 and above" }, { "code": null, "e": 1987, "s": 1967, "text": "Firefox 3 and above" }, { "code": null, "e": 2017, "s": 1987, "text": "Internet Explorer 9 and above" }, { "code": null, "e": 2038, "s": 2017, "text": "Opera 10.5 and above" }, { "code": null, "e": 2057, "s": 2038, "text": "Safari 4 and above" }, { "code": null, "e": 2069, "s": 2057, "text": "ysachin2314" }, { "code": null, "e": 2090, "s": 2069, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 2106, "s": 2090, "text": "javascript-date" }, { "code": null, "e": 2125, "s": 2106, "text": "JavaScript-Methods" }, { "code": null, "e": 2136, "s": 2125, "text": "JavaScript" }, { "code": null, "e": 2153, "s": 2136, "text": "Web Technologies" }, { "code": null, "e": 2251, "s": 2153, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2312, "s": 2251, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2384, "s": 2312, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2424, "s": 2384, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2477, "s": 2424, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2519, "s": 2477, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2552, "s": 2519, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2614, "s": 2552, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2675, "s": 2614, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2725, "s": 2675, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Java Program to Check Whether an Element Occurs in a List
07 Jan, 2021 The List Interface in Java represents an ordered collection or sequence. This Interface helps us control where to insert elements and also access elements through an integer index. This Interface is a member of the Java Collections Framework and the java.util package. The classes that implement the List Interface include ArrayList, LinkedList, Stack, and Vector. The Vector class has been deprecated since Java 5. The classes, ArrayList, LinkedList, and Stack, all use the contains() method to check whether an element occurs in the List. The contains() method of List interface in Java is used for checking if the specified element exists in the given list or not. Syntax: public boolean contains(Object obj) object-element to be searched for Parameters: This method accepts a single parameter obj whose presence in this list is to be tested. Return Value: It returns true if the specified element is found in the list else it returns false. Steps: Import the necessary packages. In this case, we need to import the java.util package.Create an ArrayList with the help of the List Interface.Add elements to the ArrayList using the add() method.Check whether the required element occurs in the ArrayList with the help of the contains() method. Import the necessary packages. In this case, we need to import the java.util package. Create an ArrayList with the help of the List Interface. Add elements to the ArrayList using the add() method. Check whether the required element occurs in the ArrayList with the help of the contains() method. Example: Java // Java program to check whether an element// is present in an ArrayList // importing packageimport java.util.*;class GFG { public static void main(String[] args) { // Creating an ArrayList of String type List<String> GFG = new ArrayList<String>(); // Adding elements to the ArrayList GFG.add("Welcome"); GFG.add("To"); GFG.add("Geeks"); GFG.add("For"); GFG.add("Geeks"); // Using contains() method to check whether the // particular // element is present in the List or not System.out.println(GFG.contains("Welcome")); System.out.println(GFG.contains("Java")); }} true false Java-Collections java-list Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jan, 2021" }, { "code": null, "e": 444, "s": 28, "text": "The List Interface in Java represents an ordered collection or sequence. This Interface helps us control where to insert elements and also access elements through an integer index. This Interface is a member of the Java Collections Framework and the java.util package. The classes that implement the List Interface include ArrayList, LinkedList, Stack, and Vector. The Vector class has been deprecated since Java 5." }, { "code": null, "e": 569, "s": 444, "text": "The classes, ArrayList, LinkedList, and Stack, all use the contains() method to check whether an element occurs in the List." }, { "code": null, "e": 696, "s": 569, "text": "The contains() method of List interface in Java is used for checking if the specified element exists in the given list or not." }, { "code": null, "e": 704, "s": 696, "text": "Syntax:" }, { "code": null, "e": 775, "s": 704, "text": "public boolean contains(Object obj)\n\nobject-element to be searched for" }, { "code": null, "e": 875, "s": 775, "text": "Parameters: This method accepts a single parameter obj whose presence in this list is to be tested." }, { "code": null, "e": 974, "s": 875, "text": "Return Value: It returns true if the specified element is found in the list else it returns false." }, { "code": null, "e": 981, "s": 974, "text": "Steps:" }, { "code": null, "e": 1274, "s": 981, "text": "Import the necessary packages. In this case, we need to import the java.util package.Create an ArrayList with the help of the List Interface.Add elements to the ArrayList using the add() method.Check whether the required element occurs in the ArrayList with the help of the contains() method." }, { "code": null, "e": 1360, "s": 1274, "text": "Import the necessary packages. In this case, we need to import the java.util package." }, { "code": null, "e": 1417, "s": 1360, "text": "Create an ArrayList with the help of the List Interface." }, { "code": null, "e": 1471, "s": 1417, "text": "Add elements to the ArrayList using the add() method." }, { "code": null, "e": 1570, "s": 1471, "text": "Check whether the required element occurs in the ArrayList with the help of the contains() method." }, { "code": null, "e": 1579, "s": 1570, "text": "Example:" }, { "code": null, "e": 1584, "s": 1579, "text": "Java" }, { "code": "// Java program to check whether an element// is present in an ArrayList // importing packageimport java.util.*;class GFG { public static void main(String[] args) { // Creating an ArrayList of String type List<String> GFG = new ArrayList<String>(); // Adding elements to the ArrayList GFG.add(\"Welcome\"); GFG.add(\"To\"); GFG.add(\"Geeks\"); GFG.add(\"For\"); GFG.add(\"Geeks\"); // Using contains() method to check whether the // particular // element is present in the List or not System.out.println(GFG.contains(\"Welcome\")); System.out.println(GFG.contains(\"Java\")); }}", "e": 2258, "s": 1584, "text": null }, { "code": null, "e": 2269, "s": 2258, "text": "true\nfalse" }, { "code": null, "e": 2286, "s": 2269, "text": "Java-Collections" }, { "code": null, "e": 2296, "s": 2286, "text": "java-list" }, { "code": null, "e": 2303, "s": 2296, "text": "Picked" }, { "code": null, "e": 2327, "s": 2303, "text": "Technical Scripter 2020" }, { "code": null, "e": 2332, "s": 2327, "text": "Java" }, { "code": null, "e": 2346, "s": 2332, "text": "Java Programs" }, { "code": null, "e": 2365, "s": 2346, "text": "Technical Scripter" }, { "code": null, "e": 2370, "s": 2365, "text": "Java" }, { "code": null, "e": 2387, "s": 2370, "text": "Java-Collections" } ]
Sparse Matrix and its representations | Set 2 (Using List of Lists and Dictionary of keys)
07 Jul, 2022 Prerequisite : Sparse Matrix and its representations Set 1 (Using Arrays and Linked Lists)In this post other two methods of sparse matrix representation are discussed. List of ListsDictionary List of Lists Dictionary List of Lists (LIL) One of the possible representation of sparse matrix is List of Lists (LIL). Where one list is used to represent the rows and each row contains the list of triples: Column index, Value(non – zero element) and address field, for non – zero elements. For the best performance both lists should be stored in order of ascending keys. Implementation: C++ C // C++ program for Sparse Matrix Representation// using List Of Lists#include<bits/stdc++.h>using namespace std;#define R 4#define C 5 // Node to represent row - liststruct row_list{ int row_number; struct row_list *link_down; struct value_list *link_right;}; // Node to represent triplesstruct value_list{ int column_index; int value; struct value_list *next;}; // Function to create node for non - zero elementsvoid create_value_node(int data, int j, struct row_list **z){ struct value_list *temp, *d; // Create new node dynamically temp = new value_list(); temp->column_index = j+1; temp->value = data; temp->next = NULL; // Connect with row list if ((*z)->link_right==NULL) (*z)->link_right = temp; else { // d points to data list node d = (*z)->link_right; while(d->next != NULL) d = d->next; d->next = temp; }} // Function to create row listvoid create_row_list(struct row_list **start, int row, int column, int Sparse_Matrix[R][C]){ // For every row, node is created for (int i = 0; i < row; i++) { struct row_list *z, *r; // Create new node dynamically z = new row_list(); z->row_number = i+1; z->link_down = NULL; z->link_right = NULL; if (i==0) *start = z; else { r = *start; while (r->link_down != NULL) r = r->link_down; r->link_down = z; } // Firstiy node for row is created, // and then traversing is done in that row for (int j = 0; j < 5; j++) { if (Sparse_Matrix[i][j] != 0) { create_value_node(Sparse_Matrix[i][j], j, &z); } } }} //Function display data of LILvoid print_LIL(struct row_list *start){ struct row_list *r; struct value_list *z; r = start; // Traversing row list while (r != NULL) { if (r->link_right != NULL) { cout<<"row="<<r->row_number<<endl; z = r->link_right; // Traversing data list while (z != NULL) { cout<<"column="<<z->column_index<<" value="<<z->value<<endl; z = z->next; } } r = r->link_down; }} //Driver of the programint main(){ // Assume 4x5 sparse matrix int Sparse_Matrix[R][C] = { {0 , 0 , 3 , 0 , 4 }, {0 , 0 , 5 , 7 , 0 }, {0 , 0 , 0 , 0 , 0 }, {0 , 2 , 6 , 0 , 0 } }; // Start with the empty List of lists struct row_list* start = NULL; //Function creating List of Lists create_row_list(&start, R, C, Sparse_Matrix); // Display data of List of lists print_LIL(start); return 0;} // This code is contributed by rutvik_56. // C program for Sparse Matrix Representation// using List Of Lists#include<stdio.h>#include<stdlib.h>#define R 4#define C 5 // Node to represent row - liststruct row_list{ int row_number; struct row_list *link_down; struct value_list *link_right;}; // Node to represent triplesstruct value_list{ int column_index; int value; struct value_list *next;}; // Function to create node for non - zero elementsvoid create_value_node(int data, int j, struct row_list **z){ struct value_list *temp, *d; // Create new node dynamically temp = (struct value_list*)malloc(sizeof(struct value_list)); temp->column_index = j+1; temp->value = data; temp->next = NULL; // Connect with row list if ((*z)->link_right==NULL) (*z)->link_right = temp; else { // d points to data list node d = (*z)->link_right; while(d->next != NULL) d = d->next; d->next = temp; }} // Function to create row listvoid create_row_list(struct row_list **start, int row, int column, int Sparse_Matrix[R][C]){ // For every row, node is created for (int i = 0; i < row; i++) { struct row_list *z, *r; // Create new node dynamically z = (struct row_list*)malloc(sizeof(struct row_list)); z->row_number = i+1; z->link_down = NULL; z->link_right = NULL; if (i==0) *start = z; else { r = *start; while (r->link_down != NULL) r = r->link_down; r->link_down = z; } // Firstiy node for row is created, // and then traversing is done in that row for (int j = 0; j < 5; j++) { if (Sparse_Matrix[i][j] != 0) { create_value_node(Sparse_Matrix[i][j], j, &z); } } }} //Function display data of LILvoid print_LIL(struct row_list *start){ struct row_list *r; struct value_list *z; r = start; // Traversing row list while (r != NULL) { if (r->link_right != NULL) { printf("row=%d \n", r->row_number); z = r->link_right; // Traversing data list while (z != NULL) { printf("column=%d value=%d \n", z->column_index, z->value); z = z->next; } } r = r->link_down; }} //Driver of the programint main(){ // Assume 4x5 sparse matrix int Sparse_Matrix[R][C] = { {0 , 0 , 3 , 0 , 4 }, {0 , 0 , 5 , 7 , 0 }, {0 , 0 , 0 , 0 , 0 }, {0 , 2 , 6 , 0 , 0 } }; // Start with the empty List of lists struct row_list* start = NULL; //Function creating List of Lists create_row_list(&start, R, C, Sparse_Matrix); // Display data of List of lists print_LIL(start); return 0;} row=1 column=3 value=3 column=5 value=4 row=2 column=3 value=5 column=4 value=7 row=4 column=2 value=2 column=3 value=6 Dictionary of Keys An alternative representation of sparse matrix is Dictionary. For the key field of the dictionary, pair of row and column index is used that maps with the non – zero element of the matrix. This method saves space but sequential access of items is costly. In C++, dictionary is defined as map class of STL(Standard Template Library). To know more about map click the link below: Basics of map Implementation: CPP Python3 // C++ program for Sparse Matrix Representation// using Dictionary#include<bits/stdc++.h>using namespace std;#define R 4#define C 5 // Driver of the programint main(){ // Assume 4x5 sparse matrix int Sparse_Matrix[R][C] = { {0 , 0 , 3 , 0 , 4 }, {0 , 0 , 5 , 7 , 0 }, {0 , 0 , 0 , 0 , 0 }, {0 , 2 , 6 , 0 , 0 } }; /* Declaration of map where first field(pair of row and column) represent key and second field represent value */ map< pair<int,int>, int > new_matrix; for (int i = 0; i < R; i++) for (int j = 0; j < C; j++) if (Sparse_Matrix[i][j] != 0) new_matrix[make_pair(i+1,j+1)] = Sparse_Matrix[i][j] ; int c = 0; // Iteration over map for (auto i = new_matrix.begin(); i != new_matrix.end(); i++ ) { if (c != i->first.first) { cout << "row = " << i->first.first << endl ; c = i->first.first; } cout << "column = " << i->first.second <<" "; cout << "value = " << i->second << endl; } return 0;} # Python program for Sparse Matrix Representation# using DictionaryR = 4C = 5 # Driver of the program # Assume 4x5 sparse matrixSparse_Matrix=[[0 , 0 , 3 , 0 , 4] , [0 , 0 , 5 , 7 , 0] , [0 , 0 , 0 , 0 , 0] , [0 , 2 , 6 , 0 , 0]] ''' Declaration of map where first field(pair of row and column) represent key and second field represent value '''new_matrix = {} for i in range(R): for j in range(C): if (Sparse_Matrix[i][j] != 0): new_matrix[(i + 1, j + 1)] = Sparse_Matrix[i][j]c = 0 # Iteration over mapfor i in new_matrix: if (c != i[0]): print("row =", i[0]) c = i[0] print("column =", i[1], end = " ") print("value =", new_matrix[i]) # This code is contributed by Shubham Singh row = 1 column = 3 value = 3 column = 5 value = 4 row = 2 column = 3 value = 5 column = 4 value = 7 row = 4 column = 2 value = 2 column = 3 value = 6 This article is contributed by Akash Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Akanksha_Rai rutvik_56 sweetyty SHUBHAMSINGH10 hardikkoriintern c-array Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sudoku | Backtracking-7 The Celebrity Problem Rotate a matrix by 90 degree in clockwise direction without using any extra space Count all possible paths from top left to bottom right of a mXn matrix Maximum size rectangle binary sub-matrix with all 1s Unique paths in a Grid with Obstacles Inplace rotate square matrix by 90 degrees | Set 1 Printing all solutions in N-Queen Problem Maximum size square sub-matrix with all 1s Search a Word in a 2D Grid of characters
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jul, 2022" }, { "code": null, "e": 221, "s": 52, "text": "Prerequisite : Sparse Matrix and its representations Set 1 (Using Arrays and Linked Lists)In this post other two methods of sparse matrix representation are discussed. " }, { "code": null, "e": 245, "s": 221, "text": "List of ListsDictionary" }, { "code": null, "e": 259, "s": 245, "text": "List of Lists" }, { "code": null, "e": 270, "s": 259, "text": "Dictionary" }, { "code": null, "e": 291, "s": 270, "text": "List of Lists (LIL) " }, { "code": null, "e": 620, "s": 291, "text": "One of the possible representation of sparse matrix is List of Lists (LIL). Where one list is used to represent the rows and each row contains the list of triples: Column index, Value(non – zero element) and address field, for non – zero elements. For the best performance both lists should be stored in order of ascending keys." }, { "code": null, "e": 636, "s": 620, "text": "Implementation:" }, { "code": null, "e": 640, "s": 636, "text": "C++" }, { "code": null, "e": 642, "s": 640, "text": "C" }, { "code": "// C++ program for Sparse Matrix Representation// using List Of Lists#include<bits/stdc++.h>using namespace std;#define R 4#define C 5 // Node to represent row - liststruct row_list{ int row_number; struct row_list *link_down; struct value_list *link_right;}; // Node to represent triplesstruct value_list{ int column_index; int value; struct value_list *next;}; // Function to create node for non - zero elementsvoid create_value_node(int data, int j, struct row_list **z){ struct value_list *temp, *d; // Create new node dynamically temp = new value_list(); temp->column_index = j+1; temp->value = data; temp->next = NULL; // Connect with row list if ((*z)->link_right==NULL) (*z)->link_right = temp; else { // d points to data list node d = (*z)->link_right; while(d->next != NULL) d = d->next; d->next = temp; }} // Function to create row listvoid create_row_list(struct row_list **start, int row, int column, int Sparse_Matrix[R][C]){ // For every row, node is created for (int i = 0; i < row; i++) { struct row_list *z, *r; // Create new node dynamically z = new row_list(); z->row_number = i+1; z->link_down = NULL; z->link_right = NULL; if (i==0) *start = z; else { r = *start; while (r->link_down != NULL) r = r->link_down; r->link_down = z; } // Firstiy node for row is created, // and then traversing is done in that row for (int j = 0; j < 5; j++) { if (Sparse_Matrix[i][j] != 0) { create_value_node(Sparse_Matrix[i][j], j, &z); } } }} //Function display data of LILvoid print_LIL(struct row_list *start){ struct row_list *r; struct value_list *z; r = start; // Traversing row list while (r != NULL) { if (r->link_right != NULL) { cout<<\"row=\"<<r->row_number<<endl; z = r->link_right; // Traversing data list while (z != NULL) { cout<<\"column=\"<<z->column_index<<\" value=\"<<z->value<<endl; z = z->next; } } r = r->link_down; }} //Driver of the programint main(){ // Assume 4x5 sparse matrix int Sparse_Matrix[R][C] = { {0 , 0 , 3 , 0 , 4 }, {0 , 0 , 5 , 7 , 0 }, {0 , 0 , 0 , 0 , 0 }, {0 , 2 , 6 , 0 , 0 } }; // Start with the empty List of lists struct row_list* start = NULL; //Function creating List of Lists create_row_list(&start, R, C, Sparse_Matrix); // Display data of List of lists print_LIL(start); return 0;} // This code is contributed by rutvik_56.", "e": 3471, "s": 642, "text": null }, { "code": "// C program for Sparse Matrix Representation// using List Of Lists#include<stdio.h>#include<stdlib.h>#define R 4#define C 5 // Node to represent row - liststruct row_list{ int row_number; struct row_list *link_down; struct value_list *link_right;}; // Node to represent triplesstruct value_list{ int column_index; int value; struct value_list *next;}; // Function to create node for non - zero elementsvoid create_value_node(int data, int j, struct row_list **z){ struct value_list *temp, *d; // Create new node dynamically temp = (struct value_list*)malloc(sizeof(struct value_list)); temp->column_index = j+1; temp->value = data; temp->next = NULL; // Connect with row list if ((*z)->link_right==NULL) (*z)->link_right = temp; else { // d points to data list node d = (*z)->link_right; while(d->next != NULL) d = d->next; d->next = temp; }} // Function to create row listvoid create_row_list(struct row_list **start, int row, int column, int Sparse_Matrix[R][C]){ // For every row, node is created for (int i = 0; i < row; i++) { struct row_list *z, *r; // Create new node dynamically z = (struct row_list*)malloc(sizeof(struct row_list)); z->row_number = i+1; z->link_down = NULL; z->link_right = NULL; if (i==0) *start = z; else { r = *start; while (r->link_down != NULL) r = r->link_down; r->link_down = z; } // Firstiy node for row is created, // and then traversing is done in that row for (int j = 0; j < 5; j++) { if (Sparse_Matrix[i][j] != 0) { create_value_node(Sparse_Matrix[i][j], j, &z); } } }} //Function display data of LILvoid print_LIL(struct row_list *start){ struct row_list *r; struct value_list *z; r = start; // Traversing row list while (r != NULL) { if (r->link_right != NULL) { printf(\"row=%d \\n\", r->row_number); z = r->link_right; // Traversing data list while (z != NULL) { printf(\"column=%d value=%d \\n\", z->column_index, z->value); z = z->next; } } r = r->link_down; }} //Driver of the programint main(){ // Assume 4x5 sparse matrix int Sparse_Matrix[R][C] = { {0 , 0 , 3 , 0 , 4 }, {0 , 0 , 5 , 7 , 0 }, {0 , 0 , 0 , 0 , 0 }, {0 , 2 , 6 , 0 , 0 } }; // Start with the empty List of lists struct row_list* start = NULL; //Function creating List of Lists create_row_list(&start, R, C, Sparse_Matrix); // Display data of List of lists print_LIL(start); return 0;}", "e": 6340, "s": 3471, "text": null }, { "code": null, "e": 6460, "s": 6340, "text": "row=1\ncolumn=3 value=3\ncolumn=5 value=4\nrow=2\ncolumn=3 value=5\ncolumn=4 value=7\nrow=4\ncolumn=2 value=2\ncolumn=3 value=6" }, { "code": null, "e": 6479, "s": 6460, "text": "Dictionary of Keys" }, { "code": null, "e": 6872, "s": 6479, "text": "An alternative representation of sparse matrix is Dictionary. For the key field of the dictionary, pair of row and column index is used that maps with the non – zero element of the matrix. This method saves space but sequential access of items is costly. In C++, dictionary is defined as map class of STL(Standard Template Library). To know more about map click the link below: Basics of map " }, { "code": null, "e": 6888, "s": 6872, "text": "Implementation:" }, { "code": null, "e": 6892, "s": 6888, "text": "CPP" }, { "code": null, "e": 6900, "s": 6892, "text": "Python3" }, { "code": "// C++ program for Sparse Matrix Representation// using Dictionary#include<bits/stdc++.h>using namespace std;#define R 4#define C 5 // Driver of the programint main(){ // Assume 4x5 sparse matrix int Sparse_Matrix[R][C] = { {0 , 0 , 3 , 0 , 4 }, {0 , 0 , 5 , 7 , 0 }, {0 , 0 , 0 , 0 , 0 }, {0 , 2 , 6 , 0 , 0 } }; /* Declaration of map where first field(pair of row and column) represent key and second field represent value */ map< pair<int,int>, int > new_matrix; for (int i = 0; i < R; i++) for (int j = 0; j < C; j++) if (Sparse_Matrix[i][j] != 0) new_matrix[make_pair(i+1,j+1)] = Sparse_Matrix[i][j] ; int c = 0; // Iteration over map for (auto i = new_matrix.begin(); i != new_matrix.end(); i++ ) { if (c != i->first.first) { cout << \"row = \" << i->first.first << endl ; c = i->first.first; } cout << \"column = \" << i->first.second <<\" \"; cout << \"value = \" << i->second << endl; } return 0;}", "e": 8004, "s": 6900, "text": null }, { "code": "# Python program for Sparse Matrix Representation# using DictionaryR = 4C = 5 # Driver of the program # Assume 4x5 sparse matrixSparse_Matrix=[[0 , 0 , 3 , 0 , 4] , [0 , 0 , 5 , 7 , 0] , [0 , 0 , 0 , 0 , 0] , [0 , 2 , 6 , 0 , 0]] ''' Declaration of map where first field(pair of row and column) represent key and second field represent value '''new_matrix = {} for i in range(R): for j in range(C): if (Sparse_Matrix[i][j] != 0): new_matrix[(i + 1, j + 1)] = Sparse_Matrix[i][j]c = 0 # Iteration over mapfor i in new_matrix: if (c != i[0]): print(\"row =\", i[0]) c = i[0] print(\"column =\", i[1], end = \" \") print(\"value =\", new_matrix[i]) # This code is contributed by Shubham Singh", "e": 8753, "s": 8004, "text": null }, { "code": null, "e": 8903, "s": 8753, "text": "row = 1\ncolumn = 3 value = 3\ncolumn = 5 value = 4\nrow = 2\ncolumn = 3 value = 5\ncolumn = 4 value = 7\nrow = 4\ncolumn = 2 value = 2\ncolumn = 3 value = 6" }, { "code": null, "e": 9199, "s": 8903, "text": "This article is contributed by Akash Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 9212, "s": 9199, "text": "Akanksha_Rai" }, { "code": null, "e": 9222, "s": 9212, "text": "rutvik_56" }, { "code": null, "e": 9231, "s": 9222, "text": "sweetyty" }, { "code": null, "e": 9246, "s": 9231, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 9263, "s": 9246, "text": "hardikkoriintern" }, { "code": null, "e": 9271, "s": 9263, "text": "c-array" }, { "code": null, "e": 9278, "s": 9271, "text": "Matrix" }, { "code": null, "e": 9285, "s": 9278, "text": "Matrix" }, { "code": null, "e": 9383, "s": 9285, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9407, "s": 9383, "text": "Sudoku | Backtracking-7" }, { "code": null, "e": 9429, "s": 9407, "text": "The Celebrity Problem" }, { "code": null, "e": 9511, "s": 9429, "text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space" }, { "code": null, "e": 9582, "s": 9511, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 9635, "s": 9582, "text": "Maximum size rectangle binary sub-matrix with all 1s" }, { "code": null, "e": 9673, "s": 9635, "text": "Unique paths in a Grid with Obstacles" }, { "code": null, "e": 9724, "s": 9673, "text": "Inplace rotate square matrix by 90 degrees | Set 1" }, { "code": null, "e": 9766, "s": 9724, "text": "Printing all solutions in N-Queen Problem" }, { "code": null, "e": 9809, "s": 9766, "text": "Maximum size square sub-matrix with all 1s" } ]
java.net.URL Class in Java
28 Mar, 2021 URL is an acronym of Uniform resource locater. It is a pointer to locate resource in www (World Wide Web). A resource can be anything from a simple text file to any other like images, file directory etc. The typical URL may look like http://www.example.com:80/index.html The URL has the following parts: Protocol: In this case the protocol is HTTP, It can be HTTPS in some cases Hostname: Hostname represent the address of the machine on which resource is located, in this case, www.example.com Port Number: It is an optional attribute. If not specified then it returns -1. In the above case, the port number is 80. Resource name: It is the name of a resource located on the given server that we want to see You can learn more about the URL here. The Class structure of the URL is as shown below: public final class java.net.URL extends java.lang.Object The Following are constructors provided by the URL class. Constructor Explanation Methods Provided by URL Class: Demonstration 1 In this demonstration, we are going to create an object of URL class for a given String URL, and we are going to print hostname, protocol, filename and Port number for given URL. Java // importing package requiredimport java.net.URL;import java.util.Scanner; class GFG { public static void main(String[] args) { String url = "https://www.geeksforgeeks.org/variables-in-java/"; // Calling method to get URL info getUrlInfo(url); } static void getUrlInfo(String url_string) { // Creating object of URL class try { URL url = new URL(url_string); System.out.println("Hostname: " + url.getHost()); System.out.println("Port Number: " + url.getPort()); System.out.println("File name: " + url.getFile()); System.out.println("Protocol: " + url.getProtocol()); } catch (Exception e) { } }} Hostname: www.geeksforgeeks.org Port Number: -1 File name: /variables-in-java/ Protocol: https Java-net-package Java-URL Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Mar, 2021" }, { "code": null, "e": 233, "s": 28, "text": "URL is an acronym of Uniform resource locater. It is a pointer to locate resource in www (World Wide Web). A resource can be anything from a simple text file to any other like images, file directory etc. " }, { "code": null, "e": 263, "s": 233, "text": "The typical URL may look like" }, { "code": null, "e": 300, "s": 263, "text": "http://www.example.com:80/index.html" }, { "code": null, "e": 333, "s": 300, "text": "The URL has the following parts:" }, { "code": null, "e": 408, "s": 333, "text": "Protocol: In this case the protocol is HTTP, It can be HTTPS in some cases" }, { "code": null, "e": 524, "s": 408, "text": "Hostname: Hostname represent the address of the machine on which resource is located, in this case, www.example.com" }, { "code": null, "e": 645, "s": 524, "text": "Port Number: It is an optional attribute. If not specified then it returns -1. In the above case, the port number is 80." }, { "code": null, "e": 737, "s": 645, "text": "Resource name: It is the name of a resource located on the given server that we want to see" }, { "code": null, "e": 776, "s": 737, "text": "You can learn more about the URL here." }, { "code": null, "e": 826, "s": 776, "text": "The Class structure of the URL is as shown below:" }, { "code": null, "e": 883, "s": 826, "text": "public final class java.net.URL extends java.lang.Object" }, { "code": null, "e": 941, "s": 883, "text": "The Following are constructors provided by the URL class." }, { "code": null, "e": 953, "s": 941, "text": "Constructor" }, { "code": null, "e": 965, "s": 953, "text": "Explanation" }, { "code": null, "e": 996, "s": 965, "text": "Methods Provided by URL Class:" }, { "code": null, "e": 1012, "s": 996, "text": "Demonstration 1" }, { "code": null, "e": 1191, "s": 1012, "text": "In this demonstration, we are going to create an object of URL class for a given String URL, and we are going to print hostname, protocol, filename and Port number for given URL." }, { "code": null, "e": 1196, "s": 1191, "text": "Java" }, { "code": "// importing package requiredimport java.net.URL;import java.util.Scanner; class GFG { public static void main(String[] args) { String url = \"https://www.geeksforgeeks.org/variables-in-java/\"; // Calling method to get URL info getUrlInfo(url); } static void getUrlInfo(String url_string) { // Creating object of URL class try { URL url = new URL(url_string); System.out.println(\"Hostname: \" + url.getHost()); System.out.println(\"Port Number: \" + url.getPort()); System.out.println(\"File name: \" + url.getFile()); System.out.println(\"Protocol: \" + url.getProtocol()); } catch (Exception e) { } }}", "e": 2056, "s": 1196, "text": null }, { "code": null, "e": 2152, "s": 2056, "text": "Hostname: www.geeksforgeeks.org\nPort Number: -1\nFile name: /variables-in-java/\nProtocol: https" }, { "code": null, "e": 2169, "s": 2152, "text": "Java-net-package" }, { "code": null, "e": 2178, "s": 2169, "text": "Java-URL" }, { "code": null, "e": 2185, "s": 2178, "text": "Picked" }, { "code": null, "e": 2190, "s": 2185, "text": "Java" }, { "code": null, "e": 2195, "s": 2190, "text": "Java" }, { "code": null, "e": 2293, "s": 2195, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2308, "s": 2293, "text": "Stream In Java" }, { "code": null, "e": 2329, "s": 2308, "text": "Introduction to Java" }, { "code": null, "e": 2350, "s": 2329, "text": "Constructors in Java" }, { "code": null, "e": 2369, "s": 2350, "text": "Exceptions in Java" }, { "code": null, "e": 2386, "s": 2369, "text": "Generics in Java" }, { "code": null, "e": 2416, "s": 2386, "text": "Functional Interfaces in Java" }, { "code": null, "e": 2442, "s": 2416, "text": "Java Programming Examples" }, { "code": null, "e": 2458, "s": 2442, "text": "Strings in Java" }, { "code": null, "e": 2495, "s": 2458, "text": "Differences between JDK, JRE and JVM" } ]
Concatenate two PySpark dataframes - GeeksforGeeks
04 Jan, 2022 In this article, we are going to see how to concatenate two pyspark dataframe using Python. Creating Dataframe for demonstration: Python3 # Importing necessary librariesfrom pyspark.sql import SparkSession # Create a spark sessionspark = SparkSession.builder.appName('pyspark - example join').getOrCreate() # Create data in dataframedata = [(('Ram'), '1991-04-01', 'M', 3000), (('Mike'), '2000-05-19', 'M', 4000), (('Rohini'), '1978-09-05', 'M', 4000), (('Maria'), '1967-12-01', 'F', 4000), (('Jenis'), '1980-02-17', 'F', 1200)] # Column names in dataframecolumns = ["Name", "DOB", "Gender", "salary"] # Create the spark dataframedf1 = spark.createDataFrame(data=data, schema=columns) # Print the dataframedf1.show() Output: +------+----------+------+------+ | Name| DOB|Gender|salary| +------+----------+------+------+ | Ram|1991-04-01| M| 3000| | Mike|2000-05-19| M| 4000| |Rohini|1978-09-05| M| 4000| | Maria|1967-12-01| F| 4000| | Jenis|1980-02-17| F| 1200| +------+----------+------+------+ Creating Second dataframe for demonstration: Python3 # Create data in dataframedata2 = [(('Mohi'), '1991-04-01', 'M', 3000), (('Ani'), '2000-05-19', 'F', 4300), (('Shipta'), '1978-09-05', 'F', 4200), (('Jessy'), '1967-12-01', 'F', 4010), (('kanne'), '1980-02-17', 'F', 1200)] # Column names in dataframecolumns = ["Name", "DOB", "Gender", "salary"] # Create the spark dataframedf2 = spark.createDataFrame(data=data, schema=columns) # Print the dataframedf2.show() Output: +------+----------+------+------+ | Name| DOB|Gender|salary| +------+----------+------+------+ | Ram|1991-04-01| M| 3000| | Mike|2000-05-19| M| 4000| |Rohini|1978-09-05| M| 4000| | Maria|1967-12-01| F| 4000| | Jenis|1980-02-17| F| 1200| +------+----------+------+------+ Union() methods of the DataFrame are employed to mix two DataFrame’s of an equivalent structure/schema. Syntax: dataframe_1.union(dataframe_2) where, dataframe_1 is the first dataframedataframe_2 is the second dataframe dataframe_1 is the first dataframe dataframe_2 is the second dataframe Example: Python3 # union the above created dataframesresult = df1.union(df2) # displayresult.show() Output: +------+----------+------+------+ | Name| DOB|Gender|salary| +------+----------+------+------+ | Ram|1991-04-01| M| 3000| | Mike|2000-05-19| M| 4000| |Rohini|1978-09-05| M| 4000| | Maria|1967-12-01| F| 4000| | Jenis|1980-02-17| F| 1200| | Ram|1991-04-01| M| 3000| | Mike|2000-05-19| M| 4000| |Rohini|1978-09-05| M| 4000| | Maria|1967-12-01| F| 4000| | Jenis|1980-02-17| F| 1200| +------+----------+------+------+ In Spark 3.1, you can easily achieve this using unionByName() for Concatenating the dataframe Syntax: dataframe_1.unionByName(dataframe_2) where, dataframe_1 is the first dataframedataframe_2 is the second dataframe dataframe_1 is the first dataframe dataframe_2 is the second dataframe Example: Python3 # union the two dataftames by using unionBynameresult1 = df1.unionByName(df2) # displayresult1.show() Output: +------+----------+------+------+ | Name| DOB|Gender|salary| +------+----------+------+------+ | Ram|1991-04-01| M| 3000| | Mike|2000-05-19| M| 4000| |Rohini|1978-09-05| M| 4000| | Maria|1967-12-01| F| 4000| | Jenis|1980-02-17| F| 1200| | Ram|1991-04-01| M| 3000| | Mike|2000-05-19| M| 4000| |Rohini|1978-09-05| M| 4000| | Maria|1967-12-01| F| 4000| | Jenis|1980-02-17| F| 1200| +------+----------+------+------+ Functools module provides functions for working with other functions and callable objects to use or extend them without completely rewriting them. Syntax: functools.reduce(lambda df1, df2: df1.union(df2.select(df1.columns)), dfs) where, df1 is the first dataframe df2 is the second dataframe We create dataframes with columns ‘a’ and ‘b’ of some random values and pass these three dataframes to our above-created method unionAll() and obtain the resultant dataframe as output and show the result. Example: Python3 import functools# explicit function def unionAll(dfs): return functools.reduce(lambda df1, df2: df1.union( df2.select(df1.columns)), dfs) # unionAllresult3 = unionAll([df1, df2])result3.show() Output: +------+----------+------+------+ | Name| DOB|Gender|salary| +------+----------+------+------+ | Ram|1991-04-01| M| 3000| | Mike|2000-05-19| M| 4000| |Rohini|1978-09-05| M| 4000| | Maria|1967-12-01| F| 4000| | Jenis|1980-02-17| F| 1200| | Ram|1991-04-01| M| 3000| | Mike|2000-05-19| M| 4000| |Rohini|1978-09-05| M| 4000| | Maria|1967-12-01| F| 4000| | Jenis|1980-02-17| F| 1200| +------+----------+------+------+ Picked Python-Pyspark 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": "\n04 Jan, 2022" }, { "code": null, "e": 25629, "s": 25537, "text": "In this article, we are going to see how to concatenate two pyspark dataframe using Python." }, { "code": null, "e": 25667, "s": 25629, "text": "Creating Dataframe for demonstration:" }, { "code": null, "e": 25675, "s": 25667, "text": "Python3" }, { "code": "# Importing necessary librariesfrom pyspark.sql import SparkSession # Create a spark sessionspark = SparkSession.builder.appName('pyspark - example join').getOrCreate() # Create data in dataframedata = [(('Ram'), '1991-04-01', 'M', 3000), (('Mike'), '2000-05-19', 'M', 4000), (('Rohini'), '1978-09-05', 'M', 4000), (('Maria'), '1967-12-01', 'F', 4000), (('Jenis'), '1980-02-17', 'F', 1200)] # Column names in dataframecolumns = [\"Name\", \"DOB\", \"Gender\", \"salary\"] # Create the spark dataframedf1 = spark.createDataFrame(data=data, schema=columns) # Print the dataframedf1.show()", "e": 26287, "s": 25675, "text": null }, { "code": null, "e": 26295, "s": 26287, "text": "Output:" }, { "code": null, "e": 26601, "s": 26295, "text": "+------+----------+------+------+\n| Name| DOB|Gender|salary|\n+------+----------+------+------+\n| Ram|1991-04-01| M| 3000|\n| Mike|2000-05-19| M| 4000|\n|Rohini|1978-09-05| M| 4000|\n| Maria|1967-12-01| F| 4000|\n| Jenis|1980-02-17| F| 1200|\n+------+----------+------+------+" }, { "code": null, "e": 26646, "s": 26601, "text": "Creating Second dataframe for demonstration:" }, { "code": null, "e": 26654, "s": 26646, "text": "Python3" }, { "code": "# Create data in dataframedata2 = [(('Mohi'), '1991-04-01', 'M', 3000), (('Ani'), '2000-05-19', 'F', 4300), (('Shipta'), '1978-09-05', 'F', 4200), (('Jessy'), '1967-12-01', 'F', 4010), (('kanne'), '1980-02-17', 'F', 1200)] # Column names in dataframecolumns = [\"Name\", \"DOB\", \"Gender\", \"salary\"] # Create the spark dataframedf2 = spark.createDataFrame(data=data, schema=columns) # Print the dataframedf2.show()", "e": 27100, "s": 26654, "text": null }, { "code": null, "e": 27108, "s": 27100, "text": "Output:" }, { "code": null, "e": 27414, "s": 27108, "text": "+------+----------+------+------+\n| Name| DOB|Gender|salary|\n+------+----------+------+------+\n| Ram|1991-04-01| M| 3000|\n| Mike|2000-05-19| M| 4000|\n|Rohini|1978-09-05| M| 4000|\n| Maria|1967-12-01| F| 4000|\n| Jenis|1980-02-17| F| 1200|\n+------+----------+------+------+" }, { "code": null, "e": 27518, "s": 27414, "text": "Union() methods of the DataFrame are employed to mix two DataFrame’s of an equivalent structure/schema." }, { "code": null, "e": 27557, "s": 27518, "text": "Syntax: dataframe_1.union(dataframe_2)" }, { "code": null, "e": 27564, "s": 27557, "text": "where," }, { "code": null, "e": 27634, "s": 27564, "text": "dataframe_1 is the first dataframedataframe_2 is the second dataframe" }, { "code": null, "e": 27669, "s": 27634, "text": "dataframe_1 is the first dataframe" }, { "code": null, "e": 27705, "s": 27669, "text": "dataframe_2 is the second dataframe" }, { "code": null, "e": 27714, "s": 27705, "text": "Example:" }, { "code": null, "e": 27722, "s": 27714, "text": "Python3" }, { "code": "# union the above created dataframesresult = df1.union(df2) # displayresult.show()", "e": 27806, "s": 27722, "text": null }, { "code": null, "e": 27814, "s": 27806, "text": "Output:" }, { "code": null, "e": 28290, "s": 27814, "text": "+------+----------+------+------+\n| Name| DOB|Gender|salary|\n+------+----------+------+------+\n| Ram|1991-04-01| M| 3000|\n| Mike|2000-05-19| M| 4000|\n|Rohini|1978-09-05| M| 4000|\n| Maria|1967-12-01| F| 4000|\n| Jenis|1980-02-17| F| 1200|\n| Ram|1991-04-01| M| 3000|\n| Mike|2000-05-19| M| 4000|\n|Rohini|1978-09-05| M| 4000|\n| Maria|1967-12-01| F| 4000|\n| Jenis|1980-02-17| F| 1200|\n+------+----------+------+------+" }, { "code": null, "e": 28385, "s": 28290, "text": " In Spark 3.1, you can easily achieve this using unionByName() for Concatenating the dataframe" }, { "code": null, "e": 28430, "s": 28385, "text": "Syntax: dataframe_1.unionByName(dataframe_2)" }, { "code": null, "e": 28437, "s": 28430, "text": "where," }, { "code": null, "e": 28507, "s": 28437, "text": "dataframe_1 is the first dataframedataframe_2 is the second dataframe" }, { "code": null, "e": 28542, "s": 28507, "text": "dataframe_1 is the first dataframe" }, { "code": null, "e": 28578, "s": 28542, "text": "dataframe_2 is the second dataframe" }, { "code": null, "e": 28587, "s": 28578, "text": "Example:" }, { "code": null, "e": 28595, "s": 28587, "text": "Python3" }, { "code": "# union the two dataftames by using unionBynameresult1 = df1.unionByName(df2) # displayresult1.show()", "e": 28698, "s": 28595, "text": null }, { "code": null, "e": 28706, "s": 28698, "text": "Output:" }, { "code": null, "e": 29182, "s": 28706, "text": "+------+----------+------+------+\n| Name| DOB|Gender|salary|\n+------+----------+------+------+\n| Ram|1991-04-01| M| 3000|\n| Mike|2000-05-19| M| 4000|\n|Rohini|1978-09-05| M| 4000|\n| Maria|1967-12-01| F| 4000|\n| Jenis|1980-02-17| F| 1200|\n| Ram|1991-04-01| M| 3000|\n| Mike|2000-05-19| M| 4000|\n|Rohini|1978-09-05| M| 4000|\n| Maria|1967-12-01| F| 4000|\n| Jenis|1980-02-17| F| 1200|\n+------+----------+------+------+" }, { "code": null, "e": 29329, "s": 29182, "text": "Functools module provides functions for working with other functions and callable objects to use or extend them without completely rewriting them." }, { "code": null, "e": 29337, "s": 29329, "text": "Syntax:" }, { "code": null, "e": 29412, "s": 29337, "text": "functools.reduce(lambda df1, df2: df1.union(df2.select(df1.columns)), dfs)" }, { "code": null, "e": 29419, "s": 29412, "text": "where," }, { "code": null, "e": 29446, "s": 29419, "text": "df1 is the first dataframe" }, { "code": null, "e": 29474, "s": 29446, "text": "df2 is the second dataframe" }, { "code": null, "e": 29679, "s": 29474, "text": "We create dataframes with columns ‘a’ and ‘b’ of some random values and pass these three dataframes to our above-created method unionAll() and obtain the resultant dataframe as output and show the result." }, { "code": null, "e": 29688, "s": 29679, "text": "Example:" }, { "code": null, "e": 29696, "s": 29688, "text": "Python3" }, { "code": "import functools# explicit function def unionAll(dfs): return functools.reduce(lambda df1, df2: df1.union( df2.select(df1.columns)), dfs) # unionAllresult3 = unionAll([df1, df2])result3.show()", "e": 29903, "s": 29696, "text": null }, { "code": null, "e": 29911, "s": 29903, "text": "Output:" }, { "code": null, "e": 30387, "s": 29911, "text": "+------+----------+------+------+\n| Name| DOB|Gender|salary|\n+------+----------+------+------+\n| Ram|1991-04-01| M| 3000|\n| Mike|2000-05-19| M| 4000|\n|Rohini|1978-09-05| M| 4000|\n| Maria|1967-12-01| F| 4000|\n| Jenis|1980-02-17| F| 1200|\n| Ram|1991-04-01| M| 3000|\n| Mike|2000-05-19| M| 4000|\n|Rohini|1978-09-05| M| 4000|\n| Maria|1967-12-01| F| 4000|\n| Jenis|1980-02-17| F| 1200|\n+------+----------+------+------+" }, { "code": null, "e": 30394, "s": 30387, "text": "Picked" }, { "code": null, "e": 30409, "s": 30394, "text": "Python-Pyspark" }, { "code": null, "e": 30416, "s": 30409, "text": "Python" }, { "code": null, "e": 30514, "s": 30416, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30546, "s": 30514, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30588, "s": 30546, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30630, "s": 30588, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30657, "s": 30630, "text": "Python Classes and Objects" }, { "code": null, "e": 30713, "s": 30657, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30735, "s": 30713, "text": "Defaultdict in Python" }, { "code": null, "e": 30774, "s": 30735, "text": "Python | Get unique values from a list" }, { "code": null, "e": 30805, "s": 30774, "text": "Python | os.path.join() method" }, { "code": null, "e": 30834, "s": 30805, "text": "Create a directory in Python" } ]
Pivot Cache in Excel - GeeksforGeeks
01 Jun, 2021 Excel automatically makes a copy of the source data and saves it in the Pivot Cache when you build a PivotTable. It is a part of the workbook and is linked to the Pivot Table, even though you can’t see it. When you make adjustments to the Pivot Table, it uses the Pivot Cache rather than the data source. Excel stores the Pivot Cache in its memory. When you create a PivotTable, adjust a Slicer selection, or switch rows/columns around, the PivotTable refers to that data in the Pivot cache. It allows Excel to react quickly to changes in the PivotTable, but it also doubles the file size. Even if you have thousands of rows of data, a pivot table will summarize it quickly. Drag and drop things into the rows/columns etc. to change the results instantly. To show any changes in the data collection, you must refresh the pivot table. Drawback: The Pivot Cache is simply a copy of your source data, so it’s natural that your file size would double. When you create PivotTables referencing the same source data, PivotTables in Excel 2007 and later have become more effective by reusing the same Pivot Cache. We can say that, for the pivot tables using the same source data, the pivot cache is shared automatically. This is advantageous because it prevents pivot cache replication, resulting in decreased memory consumption and hence the file size. Field grouping is also shared when pivot tables share the same pivot cache. For example: , if you group the products by their price range, this change is reflected in all the pivot tables as well. When you refresh one pivot table, it refreshes all the pivot tables that are connected to the same cache. If in any one Pivot table, you insert a calculated field, it appears in all the other Pivot Tables that share the pivot cache. For Using the Same Data Source, Creating Separate Caches for PivotTables Using Excel Table follow the below steps : Click anywhere in your data source & then use the shortcut key CTRL + T to convert the data to an Excel table( before starting to build a PivotTable). Another way can be, on the Insert tab of the Ribbon, click on the Table button. Create Table dialog box will pop up. Click on OK to confirm the data for the table. When you build an Excel table, a Design tab appears on the Ribbon. A Table Name box on the far left of the Design tab shows the table name, which is by default Table1. Now, on the Ribbon’s Design tab, press the Summarize with PivotTable button to begin the process of developing your PivotTable. As soon as you click on Summarize with PivotTable button, a dialog box for Create Pivot Table will pop up. Choose the location for the Pivot Table & then click on OK. You must now convert your table to a normal range. To do so, firstly select any cell in the data range & then go to the Ribbon’s Design tab and click the Convert to Range button. Now you can again newly create a table from the same data source and but it must have a different name – Excel will give it a different name by default, which is most likely Table2. Create the next PivotTable using this new Excel table in the same manner as before. Excel can consider the Excel table as a separate data source and build a separate cache after you renamed it. Follow the below steps to get count of total Pivot Table Caches in a Workbook: To begin, press ALT+F11 to launch the Visual Basic Editor. The Immediate window is located in the lower right corner of the screen. Use the shortcut CTRL+G to open it if it isn’t already open. In that immediate window, enter the following code : Count of ActiveWorkbook.PivotCaches Then press the ENTER key to get count of total pivot table caches in the workbook. Since a PivotTable saves a cached copy of your data, you can remove the original data source and the PivotTable will continue to work. This would greatly reduce the file size. You can then also recreate your data source using your PivotTable. To do so, in the Values area of the Pivot Table, place a field & leave the other areas empty. The cached version of the database will be built on a separate sheet if you double-click on the value that this calculates in the PivotTable. (Example: Double-click on Sum of Price/kg in our example) You will get the sum of all the products even when you deleted the data source. Picked Excel Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Use Solver in Excel? How to Find the Last Used Row and Column in Excel VBA? How to Get Length of Array in Excel VBA? Using CHOOSE Function along with VLOOKUP in Excel Macros in Excel Introduction to Excel Spreadsheet How to Extract the Last Word From a Cell in Excel? How to Show Percentages in Stacked Column Chart in Excel? How to Remove Duplicates From Array Using VBA in Excel? How to Sum Values Based on Criteria in Another Column in Excel?
[ { "code": null, "e": 26289, "s": 26261, "text": "\n01 Jun, 2021" }, { "code": null, "e": 26402, "s": 26289, "text": "Excel automatically makes a copy of the source data and saves it in the Pivot Cache when you build a PivotTable." }, { "code": null, "e": 26781, "s": 26402, "text": "It is a part of the workbook and is linked to the Pivot Table, even though you can’t see it. When you make adjustments to the Pivot Table, it uses the Pivot Cache rather than the data source. Excel stores the Pivot Cache in its memory. When you create a PivotTable, adjust a Slicer selection, or switch rows/columns around, the PivotTable refers to that data in the Pivot cache." }, { "code": null, "e": 27124, "s": 26781, "text": "It allows Excel to react quickly to changes in the PivotTable, but it also doubles the file size. Even if you have thousands of rows of data, a pivot table will summarize it quickly. Drag and drop things into the rows/columns etc. to change the results instantly. To show any changes in the data collection, you must refresh the pivot table." }, { "code": null, "e": 27238, "s": 27124, "text": "Drawback: The Pivot Cache is simply a copy of your source data, so it’s natural that your file size would double." }, { "code": null, "e": 27504, "s": 27238, "text": "When you create PivotTables referencing the same source data, PivotTables in Excel 2007 and later have become more effective by reusing the same Pivot Cache. We can say that, for the pivot tables using the same source data, the pivot cache is shared automatically. " }, { "code": null, "e": 27637, "s": 27504, "text": "This is advantageous because it prevents pivot cache replication, resulting in decreased memory consumption and hence the file size." }, { "code": null, "e": 27834, "s": 27637, "text": "Field grouping is also shared when pivot tables share the same pivot cache. For example: , if you group the products by their price range, this change is reflected in all the pivot tables as well." }, { "code": null, "e": 27940, "s": 27834, "text": "When you refresh one pivot table, it refreshes all the pivot tables that are connected to the same cache." }, { "code": null, "e": 28067, "s": 27940, "text": "If in any one Pivot table, you insert a calculated field, it appears in all the other Pivot Tables that share the pivot cache." }, { "code": null, "e": 28183, "s": 28067, "text": "For Using the Same Data Source, Creating Separate Caches for PivotTables Using Excel Table follow the below steps :" }, { "code": null, "e": 28415, "s": 28183, "text": "Click anywhere in your data source & then use the shortcut key CTRL + T to convert the data to an Excel table( before starting to build a PivotTable). Another way can be, on the Insert tab of the Ribbon, click on the Table button." }, { "code": null, "e": 28499, "s": 28415, "text": "Create Table dialog box will pop up. Click on OK to confirm the data for the table." }, { "code": null, "e": 28667, "s": 28499, "text": "When you build an Excel table, a Design tab appears on the Ribbon. A Table Name box on the far left of the Design tab shows the table name, which is by default Table1." }, { "code": null, "e": 28903, "s": 28667, "text": "Now, on the Ribbon’s Design tab, press the Summarize with PivotTable button to begin the process of developing your PivotTable. As soon as you click on Summarize with PivotTable button, a dialog box for Create Pivot Table will pop up." }, { "code": null, "e": 28963, "s": 28903, "text": "Choose the location for the Pivot Table & then click on OK." }, { "code": null, "e": 29142, "s": 28963, "text": "You must now convert your table to a normal range. To do so, firstly select any cell in the data range & then go to the Ribbon’s Design tab and click the Convert to Range button." }, { "code": null, "e": 29408, "s": 29142, "text": "Now you can again newly create a table from the same data source and but it must have a different name – Excel will give it a different name by default, which is most likely Table2. Create the next PivotTable using this new Excel table in the same manner as before." }, { "code": null, "e": 29518, "s": 29408, "text": "Excel can consider the Excel table as a separate data source and build a separate cache after you renamed it." }, { "code": null, "e": 29597, "s": 29518, "text": "Follow the below steps to get count of total Pivot Table Caches in a Workbook:" }, { "code": null, "e": 29790, "s": 29597, "text": "To begin, press ALT+F11 to launch the Visual Basic Editor. The Immediate window is located in the lower right corner of the screen. Use the shortcut CTRL+G to open it if it isn’t already open." }, { "code": null, "e": 29843, "s": 29790, "text": "In that immediate window, enter the following code :" }, { "code": null, "e": 29879, "s": 29843, "text": "Count of ActiveWorkbook.PivotCaches" }, { "code": null, "e": 29962, "s": 29879, "text": "Then press the ENTER key to get count of total pivot table caches in the workbook." }, { "code": null, "e": 30138, "s": 29962, "text": "Since a PivotTable saves a cached copy of your data, you can remove the original data source and the PivotTable will continue to work. This would greatly reduce the file size." }, { "code": null, "e": 30299, "s": 30138, "text": "You can then also recreate your data source using your PivotTable. To do so, in the Values area of the Pivot Table, place a field & leave the other areas empty." }, { "code": null, "e": 30499, "s": 30299, "text": "The cached version of the database will be built on a separate sheet if you double-click on the value that this calculates in the PivotTable. (Example: Double-click on Sum of Price/kg in our example)" }, { "code": null, "e": 30579, "s": 30499, "text": "You will get the sum of all the products even when you deleted the data source." }, { "code": null, "e": 30586, "s": 30579, "text": "Picked" }, { "code": null, "e": 30592, "s": 30586, "text": "Excel" }, { "code": null, "e": 30690, "s": 30592, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30718, "s": 30690, "text": "How to Use Solver in Excel?" }, { "code": null, "e": 30773, "s": 30718, "text": "How to Find the Last Used Row and Column in Excel VBA?" }, { "code": null, "e": 30814, "s": 30773, "text": "How to Get Length of Array in Excel VBA?" }, { "code": null, "e": 30864, "s": 30814, "text": "Using CHOOSE Function along with VLOOKUP in Excel" }, { "code": null, "e": 30880, "s": 30864, "text": "Macros in Excel" }, { "code": null, "e": 30914, "s": 30880, "text": "Introduction to Excel Spreadsheet" }, { "code": null, "e": 30965, "s": 30914, "text": "How to Extract the Last Word From a Cell in Excel?" }, { "code": null, "e": 31023, "s": 30965, "text": "How to Show Percentages in Stacked Column Chart in Excel?" }, { "code": null, "e": 31079, "s": 31023, "text": "How to Remove Duplicates From Array Using VBA in Excel?" } ]
unordered_set bucket() function in C++ STL - GeeksforGeeks
28 Sep, 2018 The unordered_set::bucket() method is a builtin function in C++ STL which returns the bucket number of a specific element. That is, this function returns the bucket number where a specific element is stored in the unordered_set container. The bucket is a slot in the unordered_set’s internal hash table where elements are stored. Note: Buckets in unordered_set are numbered from 0 to n-1, where n is the total number of buckets. Syntax: unordered_set_name.bucket(element); Parameter: This is a mandatory parameter and specifies the value of the element whose bucket number is needed to know in the unordered_set container. Return Value: This function returns the bucket number of the bucket in the unordered_set container where the element with value element is stored. Below programs illustrate the unordered_set::bucket() function: // C++ program to illustrate the// unordered_set::bucket() function #include <iostream>#include <unordered_set> using namespace std; int main(){ unordered_set<int> sampleSet; // Inserting elements sampleSet.insert(5); sampleSet.insert(10); sampleSet.insert(15); sampleSet.insert(20); sampleSet.insert(25); for (auto itr = sampleSet.begin(); itr != sampleSet.end(); itr++) { cout << "The Element " << (*itr) << " is present in the bucket: " << sampleSet.bucket(*itr); cout << endl; } return 0;} The Element 25 is present in the bucket: 3 The Element 5 is present in the bucket: 5 The Element 10 is present in the bucket: 10 The Element 15 is present in the bucket: 4 The Element 20 is present in the bucket: 9 CPP-Functions cpp-unordered_set cpp-unordered_set-functions C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ C++ Classes and Objects Bitwise Operators in C/C++ Virtual Function in C++ Templates in C++ with Examples Constructors in C++ Operator Overloading in C++ Socket Programming in C/C++ Object Oriented Programming in C++ Copy Constructor in C++
[ { "code": null, "e": 25930, "s": 25902, "text": "\n28 Sep, 2018" }, { "code": null, "e": 26169, "s": 25930, "text": "The unordered_set::bucket() method is a builtin function in C++ STL which returns the bucket number of a specific element. That is, this function returns the bucket number where a specific element is stored in the unordered_set container." }, { "code": null, "e": 26260, "s": 26169, "text": "The bucket is a slot in the unordered_set’s internal hash table where elements are stored." }, { "code": null, "e": 26359, "s": 26260, "text": "Note: Buckets in unordered_set are numbered from 0 to n-1, where n is the total number of buckets." }, { "code": null, "e": 26367, "s": 26359, "text": "Syntax:" }, { "code": null, "e": 26404, "s": 26367, "text": "unordered_set_name.bucket(element);\n" }, { "code": null, "e": 26554, "s": 26404, "text": "Parameter: This is a mandatory parameter and specifies the value of the element whose bucket number is needed to know in the unordered_set container." }, { "code": null, "e": 26701, "s": 26554, "text": "Return Value: This function returns the bucket number of the bucket in the unordered_set container where the element with value element is stored." }, { "code": null, "e": 26765, "s": 26701, "text": "Below programs illustrate the unordered_set::bucket() function:" }, { "code": "// C++ program to illustrate the// unordered_set::bucket() function #include <iostream>#include <unordered_set> using namespace std; int main(){ unordered_set<int> sampleSet; // Inserting elements sampleSet.insert(5); sampleSet.insert(10); sampleSet.insert(15); sampleSet.insert(20); sampleSet.insert(25); for (auto itr = sampleSet.begin(); itr != sampleSet.end(); itr++) { cout << \"The Element \" << (*itr) << \" is present in the bucket: \" << sampleSet.bucket(*itr); cout << endl; } return 0;}", "e": 27326, "s": 26765, "text": null }, { "code": null, "e": 27542, "s": 27326, "text": "The Element 25 is present in the bucket: 3\nThe Element 5 is present in the bucket: 5\nThe Element 10 is present in the bucket: 10\nThe Element 15 is present in the bucket: 4\nThe Element 20 is present in the bucket: 9\n" }, { "code": null, "e": 27556, "s": 27542, "text": "CPP-Functions" }, { "code": null, "e": 27574, "s": 27556, "text": "cpp-unordered_set" }, { "code": null, "e": 27602, "s": 27574, "text": "cpp-unordered_set-functions" }, { "code": null, "e": 27606, "s": 27602, "text": "C++" }, { "code": null, "e": 27610, "s": 27606, "text": "CPP" }, { "code": null, "e": 27708, "s": 27610, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27727, "s": 27708, "text": "Inheritance in C++" }, { "code": null, "e": 27751, "s": 27727, "text": "C++ Classes and Objects" }, { "code": null, "e": 27778, "s": 27751, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 27802, "s": 27778, "text": "Virtual Function in C++" }, { "code": null, "e": 27833, "s": 27802, "text": "Templates in C++ with Examples" }, { "code": null, "e": 27853, "s": 27833, "text": "Constructors in C++" }, { "code": null, "e": 27881, "s": 27853, "text": "Operator Overloading in C++" }, { "code": null, "e": 27909, "s": 27881, "text": "Socket Programming in C/C++" }, { "code": null, "e": 27944, "s": 27909, "text": "Object Oriented Programming in C++" } ]
__closure__ magic function in Python - GeeksforGeeks
11 Oct, 2020 Almost everything in Python is an object, similarly function is an object too and all the function objects have a __closure__ attribute. __closure__ is a dunder/magic function i.e. methods having two underscores as prefix and suffix in the method name A closure is a function object that remembers values in enclosing scopes even if they are not present in memory. The __closure__ attribute of a closure function returns a tuple of cell objects. This cell object also has an attribute called cell_contents, which returns returns the contents of the cell. Syntax: closure_function.__closure__ Example: Python # this is a nested functiondef gfg(raise_power_to): def power(number): return number ** raise_power_to return power raise_power_to_3 = gfg(3)print(raise_power_to_3.__closure__) print(raise_power_to_3.__closure__[0].cell_contents) Output: (<cell at 0x7f34ba2725e0: int object at 0x7f34bde02720>,) 3 In the above example, the nested function power has __closure__ attribute associated with it and it returns a tuple of cell objects. The cell_contents attribute returns the value 3 as it was closed inside the cell object. 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 ? 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 Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n11 Oct, 2020" }, { "code": null, "e": 25789, "s": 25537, "text": "Almost everything in Python is an object, similarly function is an object too and all the function objects have a __closure__ attribute. __closure__ is a dunder/magic function i.e. methods having two underscores as prefix and suffix in the method name" }, { "code": null, "e": 26092, "s": 25789, "text": "A closure is a function object that remembers values in enclosing scopes even if they are not present in memory. The __closure__ attribute of a closure function returns a tuple of cell objects. This cell object also has an attribute called cell_contents, which returns returns the contents of the cell." }, { "code": null, "e": 26100, "s": 26092, "text": "Syntax:" }, { "code": null, "e": 26129, "s": 26100, "text": "closure_function.__closure__" }, { "code": null, "e": 26138, "s": 26129, "text": "Example:" }, { "code": null, "e": 26145, "s": 26138, "text": "Python" }, { "code": "# this is a nested functiondef gfg(raise_power_to): def power(number): return number ** raise_power_to return power raise_power_to_3 = gfg(3)print(raise_power_to_3.__closure__) print(raise_power_to_3.__closure__[0].cell_contents)", "e": 26395, "s": 26145, "text": null }, { "code": null, "e": 26403, "s": 26395, "text": "Output:" }, { "code": null, "e": 26461, "s": 26403, "text": "(<cell at 0x7f34ba2725e0: int object at 0x7f34bde02720>,)" }, { "code": null, "e": 26463, "s": 26461, "text": "3" }, { "code": null, "e": 26685, "s": 26463, "text": "In the above example, the nested function power has __closure__ attribute associated with it and it returns a tuple of cell objects. The cell_contents attribute returns the value 3 as it was closed inside the cell object." }, { "code": null, "e": 26711, "s": 26685, "text": "Python-Built-in-functions" }, { "code": null, "e": 26718, "s": 26711, "text": "Python" }, { "code": null, "e": 26816, "s": 26718, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26848, "s": 26816, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26890, "s": 26848, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26932, "s": 26890, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26959, "s": 26932, "text": "Python Classes and Objects" }, { "code": null, "e": 27015, "s": 26959, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27054, "s": 27015, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27076, "s": 27054, "text": "Defaultdict in Python" }, { "code": null, "e": 27107, "s": 27076, "text": "Python | os.path.join() method" }, { "code": null, "e": 27136, "s": 27107, "text": "Create a directory in Python" } ]
Lodash _.join() Method - GeeksforGeeks
03 Aug, 2020 The _.join() function is used to converts all elements in the array into a string separated by a separator. Syntax: _.join(array, [separator=',']) Parameter: This method accepts two parameters as mentioned above and described below: array: It is the original array from which join operation is to be performed. separator: A string to separate each element of the array. If leave it by default array element separate by comma( , ). Return Value: This function returns a string created by joining all the elements of the array using the separator. Note: Install the lodash module by using command npm to install lodash before using the code given below. Example 1: In this example, the function join() joins together the elements of the array into a string using ‘|’. Javascript // Requiring the lodash library let lodash = require("lodash"); // Original array to be joined let array = [ 1, 2, 3, 4, 5, 6 ]; let newArray = lodash.join(array, '|'); console.log("Before Join: " + array); // Printing newArray console.log("After Join: " + newArray); Output: Example 2: In this example, the function join() joins together the elements of the array into a string using ‘, ‘ since it is the default value. Javascript // Requiring the lodash library let lodash = require("lodash"); // Original array to be joined let array = [ 1, 2, 3, 4, 5, 6 ]; let newArray = lodash.join(array); console.log("Before Join: " + array); // Printing newArray console.log("After Join: " + newArray); Output: Example 3: In this example, the function join() joins together the elements of the array into a string using ‘ ‘ (empty string). Javascript // Requiring the lodash library let lodash = require("lodash"); // Original array to be joined let array = [ 1, 2, 3, 4, 5, 6 ]; let newArray = lodash.join(array,''); console.log("Before Join: " + array); // Printing newArray console.log("After Join: " + newArray); Output: JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26545, "s": 26517, "text": "\n03 Aug, 2020" }, { "code": null, "e": 26653, "s": 26545, "text": "The _.join() function is used to converts all elements in the array into a string separated by a separator." }, { "code": null, "e": 26663, "s": 26653, "text": "Syntax: " }, { "code": null, "e": 26695, "s": 26663, "text": "_.join(array, [separator=','])\n" }, { "code": null, "e": 26781, "s": 26695, "text": "Parameter: This method accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 26859, "s": 26781, "text": "array: It is the original array from which join operation is to be performed." }, { "code": null, "e": 26979, "s": 26859, "text": "separator: A string to separate each element of the array. If leave it by default array element separate by comma( , )." }, { "code": null, "e": 27094, "s": 26979, "text": "Return Value: This function returns a string created by joining all the elements of the array using the separator." }, { "code": null, "e": 27200, "s": 27094, "text": "Note: Install the lodash module by using command npm to install lodash before using the code given below." }, { "code": null, "e": 27314, "s": 27200, "text": "Example 1: In this example, the function join() joins together the elements of the array into a string using ‘|’." }, { "code": null, "e": 27325, "s": 27314, "text": "Javascript" }, { "code": "// Requiring the lodash library let lodash = require(\"lodash\"); // Original array to be joined let array = [ 1, 2, 3, 4, 5, 6 ]; let newArray = lodash.join(array, '|'); console.log(\"Before Join: \" + array); // Printing newArray console.log(\"After Join: \" + newArray);", "e": 27606, "s": 27325, "text": null }, { "code": null, "e": 27614, "s": 27606, "text": "Output:" }, { "code": null, "e": 27759, "s": 27614, "text": "Example 2: In this example, the function join() joins together the elements of the array into a string using ‘, ‘ since it is the default value." }, { "code": null, "e": 27770, "s": 27759, "text": "Javascript" }, { "code": "// Requiring the lodash library let lodash = require(\"lodash\"); // Original array to be joined let array = [ 1, 2, 3, 4, 5, 6 ]; let newArray = lodash.join(array); console.log(\"Before Join: \" + array); // Printing newArray console.log(\"After Join: \" + newArray);", "e": 28046, "s": 27770, "text": null }, { "code": null, "e": 28054, "s": 28046, "text": "Output:" }, { "code": null, "e": 28183, "s": 28054, "text": "Example 3: In this example, the function join() joins together the elements of the array into a string using ‘ ‘ (empty string)." }, { "code": null, "e": 28194, "s": 28183, "text": "Javascript" }, { "code": "// Requiring the lodash library let lodash = require(\"lodash\"); // Original array to be joined let array = [ 1, 2, 3, 4, 5, 6 ]; let newArray = lodash.join(array,''); console.log(\"Before Join: \" + array); // Printing newArray console.log(\"After Join: \" + newArray);", "e": 28473, "s": 28194, "text": null }, { "code": null, "e": 28481, "s": 28473, "text": "Output:" }, { "code": null, "e": 28499, "s": 28481, "text": "JavaScript-Lodash" }, { "code": null, "e": 28510, "s": 28499, "text": "JavaScript" }, { "code": null, "e": 28527, "s": 28510, "text": "Web Technologies" }, { "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": 28665, "s": 28625, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28726, "s": 28665, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28767, "s": 28726, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28789, "s": 28767, "text": "JavaScript | Promises" }, { "code": null, "e": 28843, "s": 28789, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28883, "s": 28843, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28916, "s": 28883, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28959, "s": 28916, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29009, "s": 28959, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to create Shooting Star Animation Effect using CSS ? - GeeksforGeeks
08 Oct, 2021 The Shooting Star effect is one of the coolest background effects that is used for dark-themed websites. Shooting Stars Animation is an extraordinary illustration of a loading screen that grabs your eye for a considerable length of time for the remainder of the content to load on the website. This effect can be used in page loader, UI. Approach: The methodology is to make little roundabout and align their motion in 45 degrees using CSS properties like webkit-transform and transform and afterward adding animations for the tail of star and head of star(shining part) using @keyframes and @-webkit-keyframes property and now add delays for shooting effects. Essential information on these three properties is essential for going any further in this article. HTML Code: In this section, we will create a basic design of the web page. HTML <!DOCTYPE html><html> <head> <title>Shooting Star Animation</title></head> <body> <div class="sky"> <!-- We are making divisions, every div. represent a single roundabout balls --> <div class="star"></div> <div class="star"></div> <div class="star"></div> <div class="star"></div> <div class="star"></div> <div class="star"></div> <div class="star"></div> </div></body> </html> CSS Code: For CSS, follow the given below steps: Align the division components as per your requirement. Give them a circular shape using border-radius property. Use keyframes to animate the balls by increasing the scale. There is no fixed way of doing this you can change the scale on different frames as you like. Use n-th child property to apply some delay between the animation of each element. CSS body { height: 100vh; overflow: hidden; opacity: 0.5; background-color: black; display: -webkit-box; display: flex;} /* Here using -webkit, we make angle of 45 degree of falling star */.sky { position: relative; width: 100%; height: 100%; -webkit-transform: rotateZ(45deg); transform: rotateZ(45deg);} /* Here we are making roundabout balls */.star { position: absolute; left: 50%; top: 50%; height: 2px; border-radius: 885px; background: linear-gradient(-45deg, #eef0f5, rgba(0, 0, 255, 0)); -webkit-filter: drop-shadow(0 0 6px #eef1f8); filter: drop-shadow(0 0 6px #d7dff0); -webkit-animation: tail 3000ms ease-in-out infinite, shooting 3000ms ease-in-out infinite; animation: tail 3000ms ease-in-out infinite, shooting 3000ms ease-in-out infinite;} /* Here we add before and after effect to star */.star::before,.star::after { content: ""; position: absolute; top: calc(50% - 1px); right: 0; height: 2px; background: linear-gradient( -45deg, rgba(0, 0, 255, 0), #eaeef8, rgba(0, 0, 255, 0) ); -webkit-transform: translateX(50%) rotateZ(45deg); transform: translateX(50%) rotateZ(45deg); border-radius: 100%; -webkit-animation: shining 3000ms ease-in-out infinite; animation: shining 3000ms ease-in-out infinite;}.star::after { -webkit-transform: translateX(50%) rotateZ(-45deg); transform: translateX(50%) rotateZ(-45deg);} /* Here we are adding location of each nth-child, animations, delays, and before and after effects to each and every balls(stars) */.star:nth-child(1) { top: calc(50% - -119px); left: calc(50% - 43px); -webkit-animation-delay: 4000ms; animation-delay: 4000ms;}.star:nth-child(1)::before,.star:nth-child(1)::after { -webkit-animation-delay: 4000ms; animation-delay: 4000ms;}.star:nth-child(2) { top: calc(50% - -43px); left: calc(50% - 37px); -webkit-animation-delay: 5000ms; animation-delay: 5000ms;}.star:nth-child(2)::before,.star:nth-child(2)::after { -webkit-animation-delay: 5000ms; animation-delay: 5000ms;}.star:nth-child(3) { top: calc(50% - -40px); left: calc(50% - 222px); -webkit-animation-delay: 7000ms; animation-delay: 7000ms;}.star:nth-child(3)::before,.star:nth-child(3)::after { -webkit-animation-delay: 7000ms; animation-delay: 7000ms;}.star:nth-child(4) { top: calc(50% - -29px); left: calc(50% - 113px); -webkit-animation-delay: 7000ms; animation-delay: 7000ms;}.star:nth-child(4)::before,.star:nth-child(4)::after { -webkit-animation-delay: 7000ms; animation-delay: 7000ms;}.star:nth-child(5) { top: calc(50% - 146px); left: calc(50% - 112px); -webkit-animation-delay: 3000ms; animation-delay: 3000ms;}.star:nth-child(5)::before,.star:nth-child(5)::after { -webkit-animation-delay: 3000ms; animation-delay: 3000ms;}.star:nth-child(6) { top: calc(50% - -108px); left: calc(50% - 160px); -webkit-animation-delay: 3000ms; animation-delay: 3000ms;}.star:nth-child(6)::before,.star:nth-child(6)::after { -webkit-animation-delay: 3000ms; animation-delay: 3000ms;}.star:nth-child(7) { top: calc(50% - 52px); left: calc(50% - 72px); -webkit-animation-delay: 7000ms; animation-delay: 7000ms;}.star:nth-child(7)::before,.star:nth-child(7)::after { -webkit-animation-delay: 7000ms; animation-delay: 7000ms;} /* This code will help to generate effect in tail of star */@keyframes tail { 0% { width: 0; } 30% { width: 100px; } 100% { width: 0; }} /* This code will generate shining effect in head of star */@keyframes shining { 0% { width: 0; } 50% { width: 30px; } 100% { width: 0; }} /* Here we are adding webkit-animation to head of star for shining */@-webkit-keyframes shining { 0% { width: 0; } 50% { width: 30px; } 100% { width: 0; }} /* Here we are adding webkit-animation to tail of star */@-webkit-keyframes tail { 0% { width: 0; } 30% { width: 100px; } 100% { width: 0; }} /* Here we are adding webkit-animation for shooting effect */@-webkit-keyframes shooting { 0% { -webkit-transform: translateX(0); transform: translateX(0); } 100% { -webkit-transform: translateX(270px); transform: translateX(270px); }} /* Here we make shooting effect */@keyframes shooting { 0% { -webkit-transform: translateX(0); transform: translateX(0); } 100% { -webkit-transform: translateX(270px); transform: translateX(270px); }} After combining the above two sections of code i.e. HTML and CSS code to get the desired output. Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Advanced CSS-Questions CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a web page using HTML and CSS Form validation using jQuery How to style a checkbox using CSS? Search Bar using HTML, CSS and JavaScript 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": 26621, "s": 26593, "text": "\n08 Oct, 2021" }, { "code": null, "e": 26959, "s": 26621, "text": "The Shooting Star effect is one of the coolest background effects that is used for dark-themed websites. Shooting Stars Animation is an extraordinary illustration of a loading screen that grabs your eye for a considerable length of time for the remainder of the content to load on the website. This effect can be used in page loader, UI." }, { "code": null, "e": 27382, "s": 26959, "text": "Approach: The methodology is to make little roundabout and align their motion in 45 degrees using CSS properties like webkit-transform and transform and afterward adding animations for the tail of star and head of star(shining part) using @keyframes and @-webkit-keyframes property and now add delays for shooting effects. Essential information on these three properties is essential for going any further in this article." }, { "code": null, "e": 27458, "s": 27382, "text": "HTML Code: In this section, we will create a basic design of the web page." }, { "code": null, "e": 27463, "s": 27458, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Shooting Star Animation</title></head> <body> <div class=\"sky\"> <!-- We are making divisions, every div. represent a single roundabout balls --> <div class=\"star\"></div> <div class=\"star\"></div> <div class=\"star\"></div> <div class=\"star\"></div> <div class=\"star\"></div> <div class=\"star\"></div> <div class=\"star\"></div> </div></body> </html>", "e": 27918, "s": 27463, "text": null }, { "code": null, "e": 27967, "s": 27918, "text": "CSS Code: For CSS, follow the given below steps:" }, { "code": null, "e": 28022, "s": 27967, "text": "Align the division components as per your requirement." }, { "code": null, "e": 28079, "s": 28022, "text": "Give them a circular shape using border-radius property." }, { "code": null, "e": 28233, "s": 28079, "text": "Use keyframes to animate the balls by increasing the scale. There is no fixed way of doing this you can change the scale on different frames as you like." }, { "code": null, "e": 28316, "s": 28233, "text": "Use n-th child property to apply some delay between the animation of each element." }, { "code": null, "e": 28320, "s": 28316, "text": "CSS" }, { "code": "body { height: 100vh; overflow: hidden; opacity: 0.5; background-color: black; display: -webkit-box; display: flex;} /* Here using -webkit, we make angle of 45 degree of falling star */.sky { position: relative; width: 100%; height: 100%; -webkit-transform: rotateZ(45deg); transform: rotateZ(45deg);} /* Here we are making roundabout balls */.star { position: absolute; left: 50%; top: 50%; height: 2px; border-radius: 885px; background: linear-gradient(-45deg, #eef0f5, rgba(0, 0, 255, 0)); -webkit-filter: drop-shadow(0 0 6px #eef1f8); filter: drop-shadow(0 0 6px #d7dff0); -webkit-animation: tail 3000ms ease-in-out infinite, shooting 3000ms ease-in-out infinite; animation: tail 3000ms ease-in-out infinite, shooting 3000ms ease-in-out infinite;} /* Here we add before and after effect to star */.star::before,.star::after { content: \"\"; position: absolute; top: calc(50% - 1px); right: 0; height: 2px; background: linear-gradient( -45deg, rgba(0, 0, 255, 0), #eaeef8, rgba(0, 0, 255, 0) ); -webkit-transform: translateX(50%) rotateZ(45deg); transform: translateX(50%) rotateZ(45deg); border-radius: 100%; -webkit-animation: shining 3000ms ease-in-out infinite; animation: shining 3000ms ease-in-out infinite;}.star::after { -webkit-transform: translateX(50%) rotateZ(-45deg); transform: translateX(50%) rotateZ(-45deg);} /* Here we are adding location of each nth-child, animations, delays, and before and after effects to each and every balls(stars) */.star:nth-child(1) { top: calc(50% - -119px); left: calc(50% - 43px); -webkit-animation-delay: 4000ms; animation-delay: 4000ms;}.star:nth-child(1)::before,.star:nth-child(1)::after { -webkit-animation-delay: 4000ms; animation-delay: 4000ms;}.star:nth-child(2) { top: calc(50% - -43px); left: calc(50% - 37px); -webkit-animation-delay: 5000ms; animation-delay: 5000ms;}.star:nth-child(2)::before,.star:nth-child(2)::after { -webkit-animation-delay: 5000ms; animation-delay: 5000ms;}.star:nth-child(3) { top: calc(50% - -40px); left: calc(50% - 222px); -webkit-animation-delay: 7000ms; animation-delay: 7000ms;}.star:nth-child(3)::before,.star:nth-child(3)::after { -webkit-animation-delay: 7000ms; animation-delay: 7000ms;}.star:nth-child(4) { top: calc(50% - -29px); left: calc(50% - 113px); -webkit-animation-delay: 7000ms; animation-delay: 7000ms;}.star:nth-child(4)::before,.star:nth-child(4)::after { -webkit-animation-delay: 7000ms; animation-delay: 7000ms;}.star:nth-child(5) { top: calc(50% - 146px); left: calc(50% - 112px); -webkit-animation-delay: 3000ms; animation-delay: 3000ms;}.star:nth-child(5)::before,.star:nth-child(5)::after { -webkit-animation-delay: 3000ms; animation-delay: 3000ms;}.star:nth-child(6) { top: calc(50% - -108px); left: calc(50% - 160px); -webkit-animation-delay: 3000ms; animation-delay: 3000ms;}.star:nth-child(6)::before,.star:nth-child(6)::after { -webkit-animation-delay: 3000ms; animation-delay: 3000ms;}.star:nth-child(7) { top: calc(50% - 52px); left: calc(50% - 72px); -webkit-animation-delay: 7000ms; animation-delay: 7000ms;}.star:nth-child(7)::before,.star:nth-child(7)::after { -webkit-animation-delay: 7000ms; animation-delay: 7000ms;} /* This code will help to generate effect in tail of star */@keyframes tail { 0% { width: 0; } 30% { width: 100px; } 100% { width: 0; }} /* This code will generate shining effect in head of star */@keyframes shining { 0% { width: 0; } 50% { width: 30px; } 100% { width: 0; }} /* Here we are adding webkit-animation to head of star for shining */@-webkit-keyframes shining { 0% { width: 0; } 50% { width: 30px; } 100% { width: 0; }} /* Here we are adding webkit-animation to tail of star */@-webkit-keyframes tail { 0% { width: 0; } 30% { width: 100px; } 100% { width: 0; }} /* Here we are adding webkit-animation for shooting effect */@-webkit-keyframes shooting { 0% { -webkit-transform: translateX(0); transform: translateX(0); } 100% { -webkit-transform: translateX(270px); transform: translateX(270px); }} /* Here we make shooting effect */@keyframes shooting { 0% { -webkit-transform: translateX(0); transform: translateX(0); } 100% { -webkit-transform: translateX(270px); transform: translateX(270px); }}", "e": 32689, "s": 28320, "text": null }, { "code": null, "e": 32786, "s": 32689, "text": "After combining the above two sections of code i.e. HTML and CSS code to get the desired output." }, { "code": null, "e": 32795, "s": 32786, "text": "Output: " }, { "code": null, "e": 32932, "s": 32795, "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": 32945, "s": 32932, "text": "CSS-Advanced" }, { "code": null, "e": 32959, "s": 32945, "text": "CSS-Questions" }, { "code": null, "e": 32963, "s": 32959, "text": "CSS" }, { "code": null, "e": 32968, "s": 32963, "text": "HTML" }, { "code": null, "e": 32985, "s": 32968, "text": "Web Technologies" }, { "code": null, "e": 32990, "s": 32985, "text": "HTML" }, { "code": null, "e": 33088, "s": 32990, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33127, "s": 33088, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 33164, "s": 33127, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 33193, "s": 33164, "text": "Form validation using jQuery" }, { "code": null, "e": 33228, "s": 33193, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 33270, "s": 33228, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 33330, "s": 33270, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 33383, "s": 33330, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 33444, "s": 33383, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 33468, "s": 33444, "text": "REST API (Introduction)" } ]
Spring - Dependency Injection by Setter Method - GeeksforGeeks
19 Nov, 2021 Dependency Injection is the main functionality provided by Spring IOC(Inversion of Control). The Spring-Core module is responsible for injecting dependencies through either Constructor or Setter methods. The design principle of Inversion of Control emphasizes keeping the Java classes independent of each other and the container frees them from object creation and maintenance. These classes, managed by Spring, must adhere to the standard definition of Java-Bean. Dependency Injection in Spring also ensures loose coupling between the classes. Suppose class One needs the object of class Two to instantiate or operate a method, then class One is said to be dependent on class Two. Now though it might appear okay to depend on a module on the other but in the real world, this could lead to a lot of problems, including system failure. Hence such dependencies need to be avoided. Spring IOC resolves such dependencies with Dependency Injection, which makes the code easier to test and reuse. Loose coupling between classes can be possible by defining interfaces for common functionality and the injector will instantiate the objects of required implementation. The task of instantiating objects is done by the container according to the configurations specified by the developer. There are two types of Spring Dependency Injection. They are: Setter Dependency Injection (SDI): This is the simpler of the two DI methods. In this, the DI will be injected with the help of setter and/or getter methods. Now to set the DI as SDI in the bean, it is done through the bean-configuration file For this, the property to be set with the SDI is declared under the <property> tag in the bean-config file. Constructor Dependency Injection (CDI): In this, the DI will be injected with the help of constructors. Now to set the DI as CDI in bean, it is done through the bean-configuration file For this, the property to be set with the CDI is declared under the <constructor-arg> tag in the bean-config file. Setter injection is a dependency injection in which the spring framework injects the dependency object using the setter method. The call first goes to no argument constructor and then to the setter method. It does not create any new bean instance. Let’s see an example to inject dependency by the setter method. Employee.java (POJO class)config.xml Main.java Employee.java (POJO class) config.xml Main.java 1. Employee.java file Java package com.spring; public class Student { private String studentName; private String studentCourse; public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public String getStudentCourse() { return studentCourse; } public void setStudentCourse(String studentCourse) { this.studentCourse = studentCourse; } @Override public String toString() { return "Student{" + "studentName=" + studentName + ", studentCourse=" + studentCourse + '}'; }} 2. Config.xml file XML <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <bean class="com.springframework.Student" name="stud"> <property name="studentName"> <value> John </value> <property/> <property name="studentCourse"> <value> Spring Framework </value> <property/> </bean> </beans> 3. Main.java file Java package com.spring; import java.io.*;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationCotenxt; public class GFG { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationCotenxt("config.xml"); Student student= (Student)context.getBean("stud"); System.out.println(student); }} Output: Student{ studentName= John , studentCourse= Spring Framework } Java-Spring Picked 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 Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n19 Nov, 2021" }, { "code": null, "e": 25770, "s": 25225, "text": "Dependency Injection is the main functionality provided by Spring IOC(Inversion of Control). The Spring-Core module is responsible for injecting dependencies through either Constructor or Setter methods. The design principle of Inversion of Control emphasizes keeping the Java classes independent of each other and the container frees them from object creation and maintenance. These classes, managed by Spring, must adhere to the standard definition of Java-Bean. Dependency Injection in Spring also ensures loose coupling between the classes." }, { "code": null, "e": 26505, "s": 25770, "text": "Suppose class One needs the object of class Two to instantiate or operate a method, then class One is said to be dependent on class Two. Now though it might appear okay to depend on a module on the other but in the real world, this could lead to a lot of problems, including system failure. Hence such dependencies need to be avoided. Spring IOC resolves such dependencies with Dependency Injection, which makes the code easier to test and reuse. Loose coupling between classes can be possible by defining interfaces for common functionality and the injector will instantiate the objects of required implementation. The task of instantiating objects is done by the container according to the configurations specified by the developer." }, { "code": null, "e": 26568, "s": 26505, "text": "There are two types of Spring Dependency Injection. They are: " }, { "code": null, "e": 26919, "s": 26568, "text": "Setter Dependency Injection (SDI): This is the simpler of the two DI methods. In this, the DI will be injected with the help of setter and/or getter methods. Now to set the DI as SDI in the bean, it is done through the bean-configuration file For this, the property to be set with the SDI is declared under the <property> tag in the bean-config file." }, { "code": null, "e": 27219, "s": 26919, "text": "Constructor Dependency Injection (CDI): In this, the DI will be injected with the help of constructors. Now to set the DI as CDI in bean, it is done through the bean-configuration file For this, the property to be set with the CDI is declared under the <constructor-arg> tag in the bean-config file." }, { "code": null, "e": 27531, "s": 27219, "text": "Setter injection is a dependency injection in which the spring framework injects the dependency object using the setter method. The call first goes to no argument constructor and then to the setter method. It does not create any new bean instance. Let’s see an example to inject dependency by the setter method." }, { "code": null, "e": 27578, "s": 27531, "text": "Employee.java (POJO class)config.xml Main.java" }, { "code": null, "e": 27605, "s": 27578, "text": "Employee.java (POJO class)" }, { "code": null, "e": 27617, "s": 27605, "text": "config.xml " }, { "code": null, "e": 27627, "s": 27617, "text": "Main.java" }, { "code": null, "e": 27649, "s": 27627, "text": "1. Employee.java file" }, { "code": null, "e": 27654, "s": 27649, "text": "Java" }, { "code": "package com.spring; public class Student { private String studentName; private String studentCourse; public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public String getStudentCourse() { return studentCourse; } public void setStudentCourse(String studentCourse) { this.studentCourse = studentCourse; } @Override public String toString() { return \"Student{\" + \"studentName=\" + studentName + \", studentCourse=\" + studentCourse + '}'; }}", "e": 28301, "s": 27654, "text": null }, { "code": null, "e": 28320, "s": 28301, "text": "2. Config.xml file" }, { "code": null, "e": 28324, "s": 28320, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><beans xmlns=\"http://www.springframework.org/schema/beans\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:context=\"http://www.springframework.org/schema/context\" xsi:schemaLocation=\"http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd\"> <bean class=\"com.springframework.Student\" name=\"stud\"> <property name=\"studentName\"> <value> John </value> <property/> <property name=\"studentCourse\"> <value> Spring Framework </value> <property/> </bean> </beans>", "e": 29131, "s": 28324, "text": null }, { "code": null, "e": 29149, "s": 29131, "text": "3. Main.java file" }, { "code": null, "e": 29154, "s": 29149, "text": "Java" }, { "code": "package com.spring; import java.io.*;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationCotenxt; public class GFG { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationCotenxt(\"config.xml\"); Student student= (Student)context.getBean(\"stud\"); System.out.println(student); }}", "e": 29574, "s": 29154, "text": null }, { "code": null, "e": 29582, "s": 29574, "text": "Output:" }, { "code": null, "e": 29646, "s": 29582, "text": "Student{ studentName= John , studentCourse= Spring Framework }" }, { "code": null, "e": 29658, "s": 29646, "text": "Java-Spring" }, { "code": null, "e": 29665, "s": 29658, "text": "Picked" }, { "code": null, "e": 29670, "s": 29665, "text": "Java" }, { "code": null, "e": 29675, "s": 29670, "text": "Java" }, { "code": null, "e": 29773, "s": 29675, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29788, "s": 29773, "text": "Stream In Java" }, { "code": null, "e": 29809, "s": 29788, "text": "Constructors in Java" }, { "code": null, "e": 29828, "s": 29809, "text": "Exceptions in Java" }, { "code": null, "e": 29858, "s": 29828, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29904, "s": 29858, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 29921, "s": 29904, "text": "Generics in Java" }, { "code": null, "e": 29942, "s": 29921, "text": "Introduction to Java" }, { "code": null, "e": 29985, "s": 29942, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 30021, "s": 29985, "text": "Internal Working of HashMap in Java" } ]
Visualise COVID-19 case data using Python, Dash, and Plotly | by Meinhard Ploner | Towards Data Science
This article is less about COVID-19, but more about how to create a useful web application using Python & Dash. It is intended as a simple guide to get up & running with the technology, and makes it easy to do it by yourself! I wrote pretty much the same article about how to perform this task using R & Shiny, and intentionally wanted to compare these two software stacks. Here I explain the Python-Dash way, but I plan on another article doing a dedicated comparison of the solutions. To get an idea what the final app would look like, test the app: https://go.aws/2xsdb7q The following Step-by-Step guide explains how to create this web application including the interactive plots. The software stack is based on Python & Dash, and it is open-source. Altogether only about 130 lines of code. Btw, a link to the GitHub code repository for download is given at the bottom of the article. The goal is to create a web application that updates the COVID-19 case data on app launch and shows the data on a dashboard. Features: Download and parsing of officially available data on the Coronavirus. Drop-down menus to choose country and state. Two plots showing new and cumulated case statistics of the selected country. Confirmed cases, recovered cases, and deaths can be selected. Set up Python & Visual Studio Code.Set up the Python Project and its folder structure.Implement the logic to load and preprocess the data.Create the User Interface using Dash & Plotly.Add the server logic.[optional] Upload the application to the cloud. Set up Python & Visual Studio Code. Set up the Python Project and its folder structure. Implement the logic to load and preprocess the data. Create the User Interface using Dash & Plotly. Add the server logic. [optional] Upload the application to the cloud. First, download the latest stable release of Python from https://www.python.org/downloads/, start the installer and go through. For the selection of the code editor, there are plenty of possibilities. Visual Studio Code is a valid option. To install it, download the installer from https://code.visualstudio.com/download, run it, and complete the installation. There exist multiple solutions for package management in Python: pip, pipenv, (ana)conda, and virtual environments. For a quick explanation see e.g. this Medium post. We use here virtual environments. Still on the command line, move to the directory where the app should be located. Then create a new app directory and a virtual environment: cd <folder-with-my-apps> # Put here the folder of your choice.mkdir corona-app # Create a dedicated app directory.cd corona-app virtualenv venv # Create the virtual environment 'venv'. Next, activate the virtual environment. On macOS and Linux, do: source venv/bin/activate On Windows, instead, type: venv\Scripts\activate To install the packages into the new environment, type: pip install dash # Installs <plotly>, too.pip install pandas Now open Visual Studio Code. On the top right of the Welcome screen (Customize -> Tools and languages) you can select Python to install the language support for Python: Still on the Welcome screen, click on the left side on “Open folder...” and select the folder you created previously (corona-app): For more details on setting up and customizing VS Code have a look at this dedicated tutorial. The next step is to create the file app.py, which will contain all the app code we need. Click on the plus button on the file explorer and enter the file name. Now we can start coding! In Visual Studio Code, click on the file name “app.py” if the file is not already open. Type the following lines to load the libraries we need: import dashimport dash_core_components as dccimport dash_html_components as htmlimport plotly.graph_objects as gofrom dash.dependencies import Input, Outputimport pandas as pd Next, define a baseURL from which we download the case data of the Coronavirus by country and region. The data is located on a server of the Johns Hopkins Center for Systems Science and Engineering (JHU/CSSE). The function loadData handles the download and some basic transformations, as explained below. baseURL = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/"def loadData(fileName, columnName): data = pd.read_csv(baseURL + fileName) \ .drop(['Lat', 'Long'], axis=1) \ .melt(id_vars=['Province/State', 'Country/Region'], var_name='date', value_name=columnName) \ .astype({'date':'datetime64[ns]', columnName:'Int64'}, errors='ignore') data['Province/State'].fillna('<all>', inplace=True) data[columnName].fillna(0, inplace=True) return data read_csv downloads the file from the web and converts it into a Pandas dataframe. Geo-coordinates are omitted by drop; melt converts the dataframe from wide to long format. Then, astype ensures the types are correct. Finally, the method fillna inserts the text <all> if no region is available or 0 for the column containing the cumulated case number. The last transformation is a conversion into date type for the corresponding column. By calling the function loadData multiple times we load a cleaned dataframe of the Confirmed Cases, Recovered Cases, and Deaths. The function merge joins these 3 data sets to get one data set including all the data: allData = loadData( "time_series_covid19_confirmed_global.csv", "CumConfirmed") \ .merge(loadData( "time_series_covid19_deaths_global.csv", "CumDeaths")) \ .merge(loadData( "time_series_covid19_recovered_global.csv", "CumRecovered")) For the initialization of the user interface, we need the country names. We extract them from the big dataframe using: countries = allData['Country/Region'].unique()countries.sort() Now we are done with the data load. Let’s move to the UI part! [Update 2020-Mar-27]: the file names changed Mar-23 on the server, so I had to update them here, too. First, we initialize a path to an external stylesheet, and a custom font (matching the R-Shiny version of this app): external_stylesheets=['https://codepen.io/chriddyp/pen/bWLwgP.css']tickFont = {'size':12, 'color':"rgb(30,30,30)", \ 'family':"Courier New, monospace"} The Dash app will be initialized with the stylesheet defined above using: app = dash.Dash(__name__, external_stylesheets=external_stylesheets)app.layout = html.Div( style={ 'font-family':"Courier New, monospace" }, children=[ ## ... ]]) While the title and the two plots spread over the whole screen width, the three controls occupy only one third. In terms of the bootstrap grid system, this translates to three columns of a width of 4 each, which sums up to 12. Instead of the three dots (see last code block) we enter now the following code block to define the columns containing the controls: html.H1('Case History of the Coronavirus (COVID-19)'), html.Div(className="row", children=[ html.Div(className="four columns", children= html.H5('Country'), dcc.Dropdown( id='country', options=[{'label':c, 'value':c} \ for c in countries], value='Italy' ) ]), html.Div(className="four columns", children=[ html.H5('State / Province'), dcc.Dropdown( id='state' ) ]), html.Div(className="four columns", children=[ html.H5('Selected Metrics'), dcc.Checklist( id='metrics', options=[{'label':m, 'value':m} for m in \ ['Confirmed', 'Deaths', 'Recovered']], value=['Confirmed', 'Deaths'] ) ]) ]), The controls we defined are: Country Dropdown, filled with unique countries. State/Province Dropdown. Not initialized so far. Metrics Checklist, filled with the 3 metric names. For the two bar charts we use the interactive version of Plotly (documentation), and change the config to hide the overwhelming amount of controls. The code is again part of the children array: dcc.Graph( id="plot_new_metrics", config={ 'displayModeBar': False } ), dcc.Graph( id="plot_cum_metrics", config={ 'displayModeBar': False } ) In contrast to the R-Shiny software stack, Python-Dash has no simple solution to make expressions (=data!) reactive. The next function returns all the data for a specified country and state. The function will be used twice in our code (one per plot) so it would have been an advantage if the calculations would not happen twice: def nonreactive_data(country, state): data = allData.loc[allData['Country/Region'] == country] \ .drop('Country/Region', axis=1) if state == '<all>': data = data.drop('Province/State', axis=1) \ .groupby("date") \ .sum() \ .reset_index() else: data = data.loc[data['Province/State'] == state] newCases = data.select_dtypes(include='Int64').diff().fillna(0) newCases.columns = [column.replace('Cum', 'New') for column in newCases.columns] data = data.join(newCases) data['dateStr'] = data['date'].dt.strftime('%b %d, %Y') return data Besides filtering the overall dataframe for country and state, the function also aggregates the data (using groupby and sum) if the user chooses <all> for a country having states (e.g. US). Further differences are calculated from cumulated statistics and saved into new columns, prefixed with “New” instead of “Cum”. The next block defines a function to create the barchart, which will be used for both the plots. colors = { 'Deaths':'rgb(200,30,30)', \ 'Recovered':'rgb(30,200,30)', \ 'Confirmed':'rgb(100,140,240)' }def barchart(data, metrics, prefix="", yaxisTitle=""): figure = go.Figure(data=[ go.Bar( name=metric, x=data.date, y=data[prefix + metric], marker_line_color='rgb(0,0,0)', marker_line_width=1, marker_color=colors[metric] ) for metric in metrics ]) figure.update_layout( barmode='group', legend=dict(x=.05, y=0.95), plot_bgcolor='#FFFFFF', font=tickFont) \ .update_xaxes( title="", tickangle=-90, type='category', showgrid=True, gridcolor='#DDDDDD', tickfont=tickFont, ticktext=data.dateStr, tickvals=data.date) \ .update_yaxes( title=yaxisTitle, showgrid=True, gridcolor='#DDDDDD') return figure The top part of the function loops through the metrics to add the bars. The bottom part sets the barchart mode (“group”) and does some tweaking and styling on legend, axes, and labels. Most importantly, we wanna show the date on every single tick of the x-axis. While reactive expressions are not supported in Dash so far, reactive UI elements are. The following callbacks are fired if one of the Input values changes (country, state, or metrics). In this case, the subsequent function is called and updates the variables defined in Output (figure). To accomplish the task, the function loads the cleaned data and renders the chart by calling the appropriate function “barchart”. @app.callback( Output('plot_new_metrics', 'figure'), [Input('country', 'value'), Input('state', 'value'), Input('metrics', 'value')])def update_plot_new_metrics(country, state, metrics): data = nonreactive_data(country, state) return barchart(data, metrics, prefix="New", yaxisTitle="New Cases per Day")@app.callback( Output('plot_cum_metrics', 'figure'), [Input('country', 'value'), Input('state', 'value'), Input('metrics', 'value')])def update_plot_cum_metrics(country, state, metrics): data = nonreactive_data(country, state) return barchart(data, metrics, prefix="Cum", yaxisTitle="Cumulated Cases") Last but not least, the States/Provinces shown in the Dropdown menu have to adapt when the user changes the country of choice. update_states extracts the list of unique states, adds <all>, and returns the whole list and updates the selected value. @app.callback( [Output('state', 'options'), Output('state', 'value')], [Input('country', 'value')])def update_states(country): states = list(allData.loc[allData['Country/Region'] == country] ['Province/State'].unique() ) states.insert(0, '<all>') states.sort() state_options = [{'label':s, 'value':s} for s in states] state_value = state_options[0]['value'] return state_options, state_value Done! Now you can run the app by simply pushing the green “Run” button on the top-right of VS Code. Have fun :) All the code above can be found on GitHub: https://github.com/ploner/coronavirus-py Publishing the app on a web server is quite easy, especially with free services like Heroku. The steps are: Add the following line to the app.py file: server = app.server Create an account on Heroku. Install the Heroku CLI (command line interface). Follow the instructions on https://dash.plot.ly/deployment — section “Heroku Example”. Basically, you install gunicorn by pip, create .gitignore, ProcFile and requirements.txt, and commit altogether to Heroku using git. This is my second post on Medium, and it is highly related to my first one: Visualize COVID-19 case data in a blink of an eye — using R, Shiny & Plotly If you are leading a Data Science team and your members are skilled in R and Python as well, comparing Shiny with Dash might be on your To-Do list. Let me know how you make your decision.
[ { "code": null, "e": 398, "s": 172, "text": "This article is less about COVID-19, but more about how to create a useful web application using Python & Dash. It is intended as a simple guide to get up & running with the technology, and makes it easy to do it by yourself!" }, { "code": null, "e": 659, "s": 398, "text": "I wrote pretty much the same article about how to perform this task using R & Shiny, and intentionally wanted to compare these two software stacks. Here I explain the Python-Dash way, but I plan on another article doing a dedicated comparison of the solutions." }, { "code": null, "e": 724, "s": 659, "text": "To get an idea what the final app would look like, test the app:" }, { "code": null, "e": 747, "s": 724, "text": "https://go.aws/2xsdb7q" }, { "code": null, "e": 967, "s": 747, "text": "The following Step-by-Step guide explains how to create this web application including the interactive plots. The software stack is based on Python & Dash, and it is open-source. Altogether only about 130 lines of code." }, { "code": null, "e": 1061, "s": 967, "text": "Btw, a link to the GitHub code repository for download is given at the bottom of the article." }, { "code": null, "e": 1196, "s": 1061, "text": "The goal is to create a web application that updates the COVID-19 case data on app launch and shows the data on a dashboard. Features:" }, { "code": null, "e": 1266, "s": 1196, "text": "Download and parsing of officially available data on the Coronavirus." }, { "code": null, "e": 1311, "s": 1266, "text": "Drop-down menus to choose country and state." }, { "code": null, "e": 1450, "s": 1311, "text": "Two plots showing new and cumulated case statistics of the selected country. Confirmed cases, recovered cases, and deaths can be selected." }, { "code": null, "e": 1703, "s": 1450, "text": "Set up Python & Visual Studio Code.Set up the Python Project and its folder structure.Implement the logic to load and preprocess the data.Create the User Interface using Dash & Plotly.Add the server logic.[optional] Upload the application to the cloud." }, { "code": null, "e": 1739, "s": 1703, "text": "Set up Python & Visual Studio Code." }, { "code": null, "e": 1791, "s": 1739, "text": "Set up the Python Project and its folder structure." }, { "code": null, "e": 1844, "s": 1791, "text": "Implement the logic to load and preprocess the data." }, { "code": null, "e": 1891, "s": 1844, "text": "Create the User Interface using Dash & Plotly." }, { "code": null, "e": 1913, "s": 1891, "text": "Add the server logic." }, { "code": null, "e": 1961, "s": 1913, "text": "[optional] Upload the application to the cloud." }, { "code": null, "e": 2089, "s": 1961, "text": "First, download the latest stable release of Python from https://www.python.org/downloads/, start the installer and go through." }, { "code": null, "e": 2322, "s": 2089, "text": "For the selection of the code editor, there are plenty of possibilities. Visual Studio Code is a valid option. To install it, download the installer from https://code.visualstudio.com/download, run it, and complete the installation." }, { "code": null, "e": 2523, "s": 2322, "text": "There exist multiple solutions for package management in Python: pip, pipenv, (ana)conda, and virtual environments. For a quick explanation see e.g. this Medium post. We use here virtual environments." }, { "code": null, "e": 2664, "s": 2523, "text": "Still on the command line, move to the directory where the app should be located. Then create a new app directory and a virtual environment:" }, { "code": null, "e": 2885, "s": 2664, "text": "cd <folder-with-my-apps> # Put here the folder of your choice.mkdir corona-app # Create a dedicated app directory.cd corona-app virtualenv venv # Create the virtual environment 'venv'." }, { "code": null, "e": 2949, "s": 2885, "text": "Next, activate the virtual environment. On macOS and Linux, do:" }, { "code": null, "e": 2974, "s": 2949, "text": "source venv/bin/activate" }, { "code": null, "e": 3001, "s": 2974, "text": "On Windows, instead, type:" }, { "code": null, "e": 3023, "s": 3001, "text": "venv\\Scripts\\activate" }, { "code": null, "e": 3079, "s": 3023, "text": "To install the packages into the new environment, type:" }, { "code": null, "e": 3145, "s": 3079, "text": "pip install dash # Installs <plotly>, too.pip install pandas" }, { "code": null, "e": 3314, "s": 3145, "text": "Now open Visual Studio Code. On the top right of the Welcome screen (Customize -> Tools and languages) you can select Python to install the language support for Python:" }, { "code": null, "e": 3445, "s": 3314, "text": "Still on the Welcome screen, click on the left side on “Open folder...” and select the folder you created previously (corona-app):" }, { "code": null, "e": 3700, "s": 3445, "text": "For more details on setting up and customizing VS Code have a look at this dedicated tutorial. The next step is to create the file app.py, which will contain all the app code we need. Click on the plus button on the file explorer and enter the file name." }, { "code": null, "e": 3725, "s": 3700, "text": "Now we can start coding!" }, { "code": null, "e": 3869, "s": 3725, "text": "In Visual Studio Code, click on the file name “app.py” if the file is not already open. Type the following lines to load the libraries we need:" }, { "code": null, "e": 4045, "s": 3869, "text": "import dashimport dash_core_components as dccimport dash_html_components as htmlimport plotly.graph_objects as gofrom dash.dependencies import Input, Outputimport pandas as pd" }, { "code": null, "e": 4350, "s": 4045, "text": "Next, define a baseURL from which we download the case data of the Coronavirus by country and region. The data is located on a server of the Johns Hopkins Center for Systems Science and Engineering (JHU/CSSE). The function loadData handles the download and some basic transformations, as explained below." }, { "code": null, "e": 4936, "s": 4350, "text": "baseURL = \"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/\"def loadData(fileName, columnName): data = pd.read_csv(baseURL + fileName) \\ .drop(['Lat', 'Long'], axis=1) \\ .melt(id_vars=['Province/State', 'Country/Region'], var_name='date', value_name=columnName) \\ .astype({'date':'datetime64[ns]', columnName:'Int64'}, errors='ignore') data['Province/State'].fillna('<all>', inplace=True) data[columnName].fillna(0, inplace=True) return data" }, { "code": null, "e": 5287, "s": 4936, "text": "read_csv downloads the file from the web and converts it into a Pandas dataframe. Geo-coordinates are omitted by drop; melt converts the dataframe from wide to long format. Then, astype ensures the types are correct. Finally, the method fillna inserts the text <all> if no region is available or 0 for the column containing the cumulated case number." }, { "code": null, "e": 5372, "s": 5287, "text": "The last transformation is a conversion into date type for the corresponding column." }, { "code": null, "e": 5588, "s": 5372, "text": "By calling the function loadData multiple times we load a cleaned dataframe of the Confirmed Cases, Recovered Cases, and Deaths. The function merge joins these 3 data sets to get one data set including all the data:" }, { "code": null, "e": 5835, "s": 5588, "text": "allData = loadData( \"time_series_covid19_confirmed_global.csv\", \"CumConfirmed\") \\ .merge(loadData( \"time_series_covid19_deaths_global.csv\", \"CumDeaths\")) \\ .merge(loadData( \"time_series_covid19_recovered_global.csv\", \"CumRecovered\"))" }, { "code": null, "e": 5954, "s": 5835, "text": "For the initialization of the user interface, we need the country names. We extract them from the big dataframe using:" }, { "code": null, "e": 6017, "s": 5954, "text": "countries = allData['Country/Region'].unique()countries.sort()" }, { "code": null, "e": 6080, "s": 6017, "text": "Now we are done with the data load. Let’s move to the UI part!" }, { "code": null, "e": 6182, "s": 6080, "text": "[Update 2020-Mar-27]: the file names changed Mar-23 on the server, so I had to update them here, too." }, { "code": null, "e": 6299, "s": 6182, "text": "First, we initialize a path to an external stylesheet, and a custom font (matching the R-Shiny version of this app):" }, { "code": null, "e": 6462, "s": 6299, "text": "external_stylesheets=['https://codepen.io/chriddyp/pen/bWLwgP.css']tickFont = {'size':12, 'color':\"rgb(30,30,30)\", \\ 'family':\"Courier New, monospace\"}" }, { "code": null, "e": 6536, "s": 6462, "text": "The Dash app will be initialized with the stylesheet defined above using:" }, { "code": null, "e": 6712, "s": 6536, "text": "app = dash.Dash(__name__, external_stylesheets=external_stylesheets)app.layout = html.Div( style={ 'font-family':\"Courier New, monospace\" }, children=[ ## ... ]])" }, { "code": null, "e": 6939, "s": 6712, "text": "While the title and the two plots spread over the whole screen width, the three controls occupy only one third. In terms of the bootstrap grid system, this translates to three columns of a width of 4 each, which sums up to 12." }, { "code": null, "e": 7072, "s": 6939, "text": "Instead of the three dots (see last code block) we enter now the following code block to define the columns containing the controls:" }, { "code": null, "e": 8066, "s": 7072, "text": " html.H1('Case History of the Coronavirus (COVID-19)'), html.Div(className=\"row\", children=[ html.Div(className=\"four columns\", children= html.H5('Country'), dcc.Dropdown( id='country', options=[{'label':c, 'value':c} \\ for c in countries], value='Italy' ) ]), html.Div(className=\"four columns\", children=[ html.H5('State / Province'), dcc.Dropdown( id='state' ) ]), html.Div(className=\"four columns\", children=[ html.H5('Selected Metrics'), dcc.Checklist( id='metrics', options=[{'label':m, 'value':m} for m in \\ ['Confirmed', 'Deaths', 'Recovered']], value=['Confirmed', 'Deaths'] ) ]) ])," }, { "code": null, "e": 8095, "s": 8066, "text": "The controls we defined are:" }, { "code": null, "e": 8143, "s": 8095, "text": "Country Dropdown, filled with unique countries." }, { "code": null, "e": 8192, "s": 8143, "text": "State/Province Dropdown. Not initialized so far." }, { "code": null, "e": 8243, "s": 8192, "text": "Metrics Checklist, filled with the 3 metric names." }, { "code": null, "e": 8437, "s": 8243, "text": "For the two bar charts we use the interactive version of Plotly (documentation), and change the config to hide the overwhelming amount of controls. The code is again part of the children array:" }, { "code": null, "e": 8622, "s": 8437, "text": " dcc.Graph( id=\"plot_new_metrics\", config={ 'displayModeBar': False } ), dcc.Graph( id=\"plot_cum_metrics\", config={ 'displayModeBar': False } )" }, { "code": null, "e": 8951, "s": 8622, "text": "In contrast to the R-Shiny software stack, Python-Dash has no simple solution to make expressions (=data!) reactive. The next function returns all the data for a specified country and state. The function will be used twice in our code (one per plot) so it would have been an advantage if the calculations would not happen twice:" }, { "code": null, "e": 9616, "s": 8951, "text": "def nonreactive_data(country, state): data = allData.loc[allData['Country/Region'] == country] \\ .drop('Country/Region', axis=1) if state == '<all>': data = data.drop('Province/State', axis=1) \\ .groupby(\"date\") \\ .sum() \\ .reset_index() else: data = data.loc[data['Province/State'] == state] newCases = data.select_dtypes(include='Int64').diff().fillna(0) newCases.columns = [column.replace('Cum', 'New') for column in newCases.columns] data = data.join(newCases) data['dateStr'] = data['date'].dt.strftime('%b %d, %Y') return data" }, { "code": null, "e": 9933, "s": 9616, "text": "Besides filtering the overall dataframe for country and state, the function also aggregates the data (using groupby and sum) if the user chooses <all> for a country having states (e.g. US). Further differences are calculated from cumulated statistics and saved into new columns, prefixed with “New” instead of “Cum”." }, { "code": null, "e": 10030, "s": 9933, "text": "The next block defines a function to create the barchart, which will be used for both the plots." }, { "code": null, "e": 10946, "s": 10030, "text": "colors = { 'Deaths':'rgb(200,30,30)', \\ 'Recovered':'rgb(30,200,30)', \\ 'Confirmed':'rgb(100,140,240)' }def barchart(data, metrics, prefix=\"\", yaxisTitle=\"\"): figure = go.Figure(data=[ go.Bar( name=metric, x=data.date, y=data[prefix + metric], marker_line_color='rgb(0,0,0)', marker_line_width=1, marker_color=colors[metric] ) for metric in metrics ]) figure.update_layout( barmode='group', legend=dict(x=.05, y=0.95), plot_bgcolor='#FFFFFF', font=tickFont) \\ .update_xaxes( title=\"\", tickangle=-90, type='category', showgrid=True, gridcolor='#DDDDDD', tickfont=tickFont, ticktext=data.dateStr, tickvals=data.date) \\ .update_yaxes( title=yaxisTitle, showgrid=True, gridcolor='#DDDDDD') return figure" }, { "code": null, "e": 11208, "s": 10946, "text": "The top part of the function loops through the metrics to add the bars. The bottom part sets the barchart mode (“group”) and does some tweaking and styling on legend, axes, and labels. Most importantly, we wanna show the date on every single tick of the x-axis." }, { "code": null, "e": 11496, "s": 11208, "text": "While reactive expressions are not supported in Dash so far, reactive UI elements are. The following callbacks are fired if one of the Input values changes (country, state, or metrics). In this case, the subsequent function is called and updates the variables defined in Output (figure)." }, { "code": null, "e": 11626, "s": 11496, "text": "To accomplish the task, the function loads the cleaned data and renders the chart by calling the appropriate function “barchart”." }, { "code": null, "e": 12283, "s": 11626, "text": "@app.callback( Output('plot_new_metrics', 'figure'), [Input('country', 'value'), Input('state', 'value'), Input('metrics', 'value')])def update_plot_new_metrics(country, state, metrics): data = nonreactive_data(country, state) return barchart(data, metrics, prefix=\"New\", yaxisTitle=\"New Cases per Day\")@app.callback( Output('plot_cum_metrics', 'figure'), [Input('country', 'value'), Input('state', 'value'), Input('metrics', 'value')])def update_plot_cum_metrics(country, state, metrics): data = nonreactive_data(country, state) return barchart(data, metrics, prefix=\"Cum\", yaxisTitle=\"Cumulated Cases\")" }, { "code": null, "e": 12531, "s": 12283, "text": "Last but not least, the States/Provinces shown in the Dropdown menu have to adapt when the user changes the country of choice. update_states extracts the list of unique states, adds <all>, and returns the whole list and updates the selected value." }, { "code": null, "e": 12957, "s": 12531, "text": "@app.callback( [Output('state', 'options'), Output('state', 'value')], [Input('country', 'value')])def update_states(country): states = list(allData.loc[allData['Country/Region'] == country] ['Province/State'].unique() ) states.insert(0, '<all>') states.sort() state_options = [{'label':s, 'value':s} for s in states] state_value = state_options[0]['value'] return state_options, state_value" }, { "code": null, "e": 12963, "s": 12957, "text": "Done!" }, { "code": null, "e": 13069, "s": 12963, "text": "Now you can run the app by simply pushing the green “Run” button on the top-right of VS Code. Have fun :)" }, { "code": null, "e": 13153, "s": 13069, "text": "All the code above can be found on GitHub: https://github.com/ploner/coronavirus-py" }, { "code": null, "e": 13246, "s": 13153, "text": "Publishing the app on a web server is quite easy, especially with free services like Heroku." }, { "code": null, "e": 13261, "s": 13246, "text": "The steps are:" }, { "code": null, "e": 13304, "s": 13261, "text": "Add the following line to the app.py file:" }, { "code": null, "e": 13324, "s": 13304, "text": "server = app.server" }, { "code": null, "e": 13353, "s": 13324, "text": "Create an account on Heroku." }, { "code": null, "e": 13402, "s": 13353, "text": "Install the Heroku CLI (command line interface)." }, { "code": null, "e": 13622, "s": 13402, "text": "Follow the instructions on https://dash.plot.ly/deployment — section “Heroku Example”. Basically, you install gunicorn by pip, create .gitignore, ProcFile and requirements.txt, and commit altogether to Heroku using git." }, { "code": null, "e": 13698, "s": 13622, "text": "This is my second post on Medium, and it is highly related to my first one:" }, { "code": null, "e": 13774, "s": 13698, "text": "Visualize COVID-19 case data in a blink of an eye — using R, Shiny & Plotly" } ]
How to process a simple form data using Python CGI script?
suppose there is an HTML file as below − <form action="getData.py" method="post"> FirstName: <input type="text" name="first_name"> LastName: <input type="text" name="last_name"> <input type="submit" value="go"> </form> after submitting this form it should go to a python page named getData.py, where you should fetch the data from this HTML page and show. then below is the code for python CGI #!C:\Python27\python.exe # Import modules for CGI handling import cgi, cgitb # Create instance of FieldStorage form = cgi.FieldStorage() # Get data from fields first_name = form.getvalue('first_name') last_name = form.getvalue('last_name') print("Content-type:text/html") print print("") print("") print("Hello - Second CGI Program") print("") print("") print(" Hello %s %s " % (first_name, last_name)) print("") print("")
[ { "code": null, "e": 1103, "s": 1062, "text": "suppose there is an HTML file as below −" }, { "code": null, "e": 1290, "s": 1103, "text": "<form action=\"getData.py\" method=\"post\">\n FirstName: <input type=\"text\" name=\"first_name\">\n LastName: <input type=\"text\" name=\"last_name\">\n <input type=\"submit\" value=\"go\">\n</form>" }, { "code": null, "e": 1465, "s": 1290, "text": "after submitting this form it should go to a python page named getData.py, where you should fetch the data from this HTML page and show. then below is the code for python CGI" }, { "code": null, "e": 1895, "s": 1465, "text": "#!C:\\Python27\\python.exe\n# Import modules for CGI handling\nimport cgi, cgitb\n# Create instance of FieldStorage\nform = cgi.FieldStorage()\n# Get data from fields\nfirst_name = form.getvalue('first_name')\nlast_name = form.getvalue('last_name')\nprint(\"Content-type:text/html\")\nprint\nprint(\"\")\nprint(\"\")\nprint(\"Hello - Second CGI Program\")\nprint(\"\")\nprint(\"\")\nprint(\"\n Hello %s %s\n \" % (first_name, last_name))\nprint(\"\")\nprint(\"\")" } ]
Ones and Zeroes in C++
Suppose we have a dominator of m 0s and n 1s respectively. On the other hand, there is an array with binary strings. Now our task is to find the maximum number of strings that we can generate with given m 0s and n 1s. Each 0 and 1 can be used at most once. So if the input is like Array = [“10”, “0001”, “111001”, “1”, “0”,] and m = 5 and n = 3, then the output will be 4. This is because there are totally 4 strings can be formed by the using of 5 0s and 3 1s, which are “10,”0001”,”1”,”0”. To solve this, we will follow these steps − Make a matrix of size (m + 1) x (n + 1) ret := 0 for i in range 0 to size of strs arrayone := 0, zero := 0for j in range 0 to size of strs[i]increase one when star[i, j] is 1, or increase zero when it is 0for j in range m down to 0for j in range n down to onedp[j,k] := max of dp[j,k] and 1 + dp[j – zero, k - one]ret := max of ret and dp[j,k] one := 0, zero := 0 for j in range 0 to size of strs[i]increase one when star[i, j] is 1, or increase zero when it is 0 increase one when star[i, j] is 1, or increase zero when it is 0 for j in range m down to 0for j in range n down to onedp[j,k] := max of dp[j,k] and 1 + dp[j – zero, k - one]ret := max of ret and dp[j,k] for j in range n down to onedp[j,k] := max of dp[j,k] and 1 + dp[j – zero, k - one]ret := max of ret and dp[j,k] dp[j,k] := max of dp[j,k] and 1 + dp[j – zero, k - one] ret := max of ret and dp[j,k] return ret Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int findMaxForm(vector<string>& strs, int m, int n) { vector < vector <int> > dp(m + 1, vector <int>(n + 1)); int ret = 0; for(int i = 0; i < strs.size(); i++){ int one = 0; int zero = 0; for(int j = 0; j < strs[i].size(); j++){ one += strs[i][j] == '1'; zero += strs[i][j] == '0'; } for(int j = m; j>= zero; j--){ for(int k = n; k >= one; k--){ dp[j][k] = max(dp[j][k], 1 + dp[j - zero][k - one]); ret = max(ret, dp[j][k]); } } } return ret; } }; main(){ vector<string> v = {"10","0001","111001","1","0"}; Solution ob; cout << (ob.findMaxForm(v, 5, 3)); } ["10","0001","111001","1","0"] 5 3 4
[ { "code": null, "e": 1554, "s": 1062, "text": "Suppose we have a dominator of m 0s and n 1s respectively. On the other hand, there is an array with binary strings. Now our task is to find the maximum number of strings that we can generate with given m 0s and n 1s. Each 0 and 1 can be used at most once. So if the input is like Array = [“10”, “0001”, “111001”, “1”, “0”,] and m = 5 and n = 3, then the output will be 4. This is because there are totally 4 strings can be formed by the using of 5 0s and 3 1s, which are “10,”0001”,”1”,”0”." }, { "code": null, "e": 1598, "s": 1554, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1638, "s": 1598, "text": "Make a matrix of size (m + 1) x (n + 1)" }, { "code": null, "e": 1647, "s": 1638, "text": "ret := 0" }, { "code": null, "e": 1942, "s": 1647, "text": "for i in range 0 to size of strs arrayone := 0, zero := 0for j in range 0 to size of strs[i]increase one when star[i, j] is 1, or increase zero when it is 0for j in range m down to 0for j in range n down to onedp[j,k] := max of dp[j,k] and 1 + dp[j – zero, k - one]ret := max of ret and dp[j,k]" }, { "code": null, "e": 1962, "s": 1942, "text": "one := 0, zero := 0" }, { "code": null, "e": 2062, "s": 1962, "text": "for j in range 0 to size of strs[i]increase one when star[i, j] is 1, or increase zero when it is 0" }, { "code": null, "e": 2127, "s": 2062, "text": "increase one when star[i, j] is 1, or increase zero when it is 0" }, { "code": null, "e": 2266, "s": 2127, "text": "for j in range m down to 0for j in range n down to onedp[j,k] := max of dp[j,k] and 1 + dp[j – zero, k - one]ret := max of ret and dp[j,k]" }, { "code": null, "e": 2379, "s": 2266, "text": "for j in range n down to onedp[j,k] := max of dp[j,k] and 1 + dp[j – zero, k - one]ret := max of ret and dp[j,k]" }, { "code": null, "e": 2435, "s": 2379, "text": "dp[j,k] := max of dp[j,k] and 1 + dp[j – zero, k - one]" }, { "code": null, "e": 2465, "s": 2435, "text": "ret := max of ret and dp[j,k]" }, { "code": null, "e": 2476, "s": 2465, "text": "return ret" }, { "code": null, "e": 2546, "s": 2476, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2557, "s": 2546, "text": " Live Demo" }, { "code": null, "e": 3368, "s": 2557, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int findMaxForm(vector<string>& strs, int m, int n) {\n vector < vector <int> > dp(m + 1, vector <int>(n + 1));\n int ret = 0;\n for(int i = 0; i < strs.size(); i++){\n int one = 0;\n int zero = 0;\n for(int j = 0; j < strs[i].size(); j++){\n one += strs[i][j] == '1';\n zero += strs[i][j] == '0';\n }\n for(int j = m; j>= zero; j--){\n for(int k = n; k >= one; k--){\n dp[j][k] = max(dp[j][k], 1 + dp[j - zero][k - one]);\n ret = max(ret, dp[j][k]);\n }\n }\n }\n return ret;\n }\n};\nmain(){\n vector<string> v = {\"10\",\"0001\",\"111001\",\"1\",\"0\"};\n Solution ob;\n cout << (ob.findMaxForm(v, 5, 3));\n}" }, { "code": null, "e": 3403, "s": 3368, "text": "[\"10\",\"0001\",\"111001\",\"1\",\"0\"]\n5\n3" }, { "code": null, "e": 3405, "s": 3403, "text": "4" } ]
Place the image at the bottom inside a Bootstrap 4 card
To place the image at the bottom inside a card, use the card-img-bottom class. Firstly, set the card body and then use the <img> tag to add an image. The following code snippet is added inside the card class − <div class="card-body"> <h4 class="card-title">Quantitative Aptitude</h4> <p class="card-text">For Entrance Exams</p> <a href="#" class="btn btn-primary">Sample Questions</a> </div> <img class="card-img-bottom" src="Image-Source " alt="Alt-Text" style="width:100%"> The following is an example to learn how to place image at the bottom inside a card in Bootstrap 4 − Live Demo <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h3>Quantitative Aptitude Questions Answers</h3> <div class="card" style="width:400px"> <div class="card-body"> <h4 class="card-title">Quantitative Aptitude</h4> <p class="card-text">For Entrance Exams</p> <a href="#" class="btn btn-primary">Sample Questions</a> </div> <img class="card-img-bottom" src="https://www.tutorialspoint.com/videotutorials/images/numerical_ability_home.jpg" alt="QA" style="width:100%"> </div> </div> </body> </html>
[ { "code": null, "e": 1141, "s": 1062, "text": "To place the image at the bottom inside a card, use the card-img-bottom class." }, { "code": null, "e": 1272, "s": 1141, "text": "Firstly, set the card body and then use the <img> tag to add an image. The following code snippet is added inside the card class −" }, { "code": null, "e": 1544, "s": 1272, "text": "<div class=\"card-body\">\n <h4 class=\"card-title\">Quantitative Aptitude</h4>\n <p class=\"card-text\">For Entrance Exams</p>\n <a href=\"#\" class=\"btn btn-primary\">Sample Questions</a>\n</div>\n<img class=\"card-img-bottom\" src=\"Image-Source \" alt=\"Alt-Text\" style=\"width:100%\">" }, { "code": null, "e": 1645, "s": 1544, "text": "The following is an example to learn how to place image at the bottom inside a card in Bootstrap 4 −" }, { "code": null, "e": 1655, "s": 1645, "text": "Live Demo" }, { "code": null, "e": 2652, "s": 1655, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n </head>\n\n<body>\n\n<div class=\"container\">\n <h3>Quantitative Aptitude Questions Answers</h3>\n <div class=\"card\" style=\"width:400px\">\n <div class=\"card-body\">\n <h4 class=\"card-title\">Quantitative Aptitude</h4>\n <p class=\"card-text\">For Entrance Exams</p>\n <a href=\"#\" class=\"btn btn-primary\">Sample Questions</a>\n </div>\n <img class=\"card-img-bottom\" src=\"https://www.tutorialspoint.com/videotutorials/images/numerical_ability_home.jpg\" alt=\"QA\" style=\"width:100%\">\n </div>\n</div>\n\n</body>\n</html>" } ]
Python - Mirror Image of String - GeeksforGeeks
02 Sep, 2020 Given a String, perform its mirror imaging, return “Not Possible” if mirror image not possible using english characters. Input : test_str = ‘boid’Output : doibExplanation : d replaced by b and vice-versa as being mirror images. Input : test_str = ‘gfg’Output : Not PossibleExplanation : Valid Mirror image not possible. Method : Using loop + loopup dictionary This is one way in which this task can be performed. In this, we construct lookup dictionary for all valid mirrorable english characters, then perform task of access from them. Python3 # Python3 code to demonstrate working of # Mirror Image of String# Using Mirror Image of String # initializing stringstest_str = 'void' # printing original stringprint("The original string is : " + str(test_str)) # initializing mirror dictionarymir_dict = {'b':'d', 'd':'b', 'i':'i', 'o':'o', 'v':'v', 'w':'w', 'x':'x'}res = '' # accessing letters from dictionaryfor ele in test_str: if ele in mir_dict: res += mir_dict[ele] # if any character not present, flagging to be invalid else: res = "Not Possible" break # printing result print("The mirror string : " + str(res)) The original string is : void The mirror string : voib Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? 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 Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 24390, "s": 24362, "text": "\n02 Sep, 2020" }, { "code": null, "e": 24511, "s": 24390, "text": "Given a String, perform its mirror imaging, return “Not Possible” if mirror image not possible using english characters." }, { "code": null, "e": 24618, "s": 24511, "text": "Input : test_str = ‘boid’Output : doibExplanation : d replaced by b and vice-versa as being mirror images." }, { "code": null, "e": 24710, "s": 24618, "text": "Input : test_str = ‘gfg’Output : Not PossibleExplanation : Valid Mirror image not possible." }, { "code": null, "e": 24750, "s": 24710, "text": "Method : Using loop + loopup dictionary" }, { "code": null, "e": 24927, "s": 24750, "text": "This is one way in which this task can be performed. In this, we construct lookup dictionary for all valid mirrorable english characters, then perform task of access from them." }, { "code": null, "e": 24935, "s": 24927, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Mirror Image of String# Using Mirror Image of String # initializing stringstest_str = 'void' # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing mirror dictionarymir_dict = {'b':'d', 'd':'b', 'i':'i', 'o':'o', 'v':'v', 'w':'w', 'x':'x'}res = '' # accessing letters from dictionaryfor ele in test_str: if ele in mir_dict: res += mir_dict[ele] # if any character not present, flagging to be invalid else: res = \"Not Possible\" break # printing result print(\"The mirror string : \" + str(res)) ", "e": 25550, "s": 24935, "text": null }, { "code": null, "e": 25606, "s": 25550, "text": "The original string is : void\nThe mirror string : voib\n" }, { "code": null, "e": 25629, "s": 25606, "text": "Python string-programs" }, { "code": null, "e": 25636, "s": 25629, "text": "Python" }, { "code": null, "e": 25652, "s": 25636, "text": "Python Programs" }, { "code": null, "e": 25750, "s": 25652, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25782, "s": 25750, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25824, "s": 25782, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25866, "s": 25824, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25922, "s": 25866, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25949, "s": 25922, "text": "Python Classes and Objects" }, { "code": null, "e": 25971, "s": 25949, "text": "Defaultdict in Python" }, { "code": null, "e": 26010, "s": 25971, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26056, "s": 26010, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26094, "s": 26056, "text": "Python | Convert a list to dictionary" } ]
Minimum operations of given type to make all elements of a matrix equal - GeeksforGeeks
15 Nov, 2021 Given an integer K and a matrix of N rows and M columns, the task is to find the minimum number of operations required to make all the elements of the matrix equal. In a single operation, K can be added to or subtracted from any element of the matrix. Print -1 if it is impossible to do so. Examples: Input: mat[][] = {{2, 4}, {22, 24}}, K = 2 Output: 20 mat[0][0] = 2 + (10 * K) = 22 ... 10 operations mat[0][1] = 4 + (9 * K) = 22 ... 9 operations mat[1][0] = 22 ... No operation mat[1][1] = 24 – K = 22 ... 1 operations 10 + 9 + 1 = 20 Input: mat[][] = { {3, 63, 42}, {18, 12, 12}, {15, 21, 18}, {33, 84, 24}}, K = 3 Output: 63 Approach: Since we are only allowed to add or subtract K from any element, we can easily infer that the mod of all the elements with K should be equal because x % K = (x + K) % K = (x – K) % K. If that is not the case, simply print -1. Otherwise, sort all the elements of the matrix in non-decreasing order and find the median of the sorted elements. The minimum number of steps would occur if we convert all the elements to equal to the median. Calculate these steps and print the result. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum// number of operations requiredint minOperations(int n, int m, int k, vector<vector<int> >& matrix){ // Create another array to // store the elements of matrix vector<int> arr(n * m, 0); int mod = matrix[0][0] % k; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { arr[i * m + j] = matrix[i][j]; // If not possible if (matrix[i][j] % k != mod) { return -1; } } } // Sort the array to get median sort(arr.begin(), arr.end()); int median = arr[(n * m) / 2]; // To count the minimum operations int minOperations = 0; for (int i = 0; i < n * m; ++i) minOperations += abs(arr[i] - median) / k; // If there are even elements, then there // are two medians. We consider the best // of two as answer. if ((n * m) % 2 == 0) { int median2 = arr[( (n * m) / 2) - 1]; int minOperations2 = 0; for (int i = 0; i < n * m; ++i) minOperations2 += abs(arr[i] - median2) / k; minOperations = min(minOperations, minOperations2); } // Return minimum operations required return minOperations;} // Driver codeint main(){ vector<vector<int> > matrix = { { 2, 4, 6 }, { 8, 10, 12 }, { 14, 16, 18 }, { 20, 22, 24 } }; int n = matrix.size(); int m = matrix[0].size(); int k = 2; cout << minOperations(n, m, k, matrix); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // Function to return the minimum // number of operations required static int minOperations(int n, int m, int k, int matrix[][]) { // Create another array to // store the elements of matrix int [] arr = new int[n * m]; int mod = matrix[0][0] % k; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { arr[i * m + j] = matrix[i][j]; // If not possible if (matrix[i][j] % k != mod) { return -1; } } } // Sort the array to get median Arrays.sort(arr); int median = arr[(n * m) / 2]; // To count the minimum operations int minOperations = 0; for (int i = 0; i < n * m; ++i) minOperations += Math.abs(arr[i] - median) / k; // If there are even elements, then there // are two medians. We consider the best // of two as answer. if ((n * m) % 2 == 0) { int median2 = arr[( (n * m) / 2 ) - 1]; int minOperations2 = 0; for (int i = 0; i < n * m; ++i) minOperations2 += Math.abs(arr[i] - median2) / k; minOperations = Math.min(minOperations, minOperations2); } // Return minimum operations required return minOperations; } // Driver code public static void main(String []args) { int matrix [][] = { { 2, 4, 6 }, { 8, 10, 12 }, { 14, 16, 18 }, { 20, 22, 24 } }; int n = matrix.length; int m = matrix[0].length; int k = 2; System.out.println(minOperations(n, m, k, matrix)); }} // This code is contributed by ihritik # Python3 implementation of the approach # Function to return the minimum# number of operations requireddef minOperations(n, m, k, matrix): # Create another array to store the # elements of matrix arr = [0] * (n * m) mod = matrix[0][0] % k for i in range(0, n): for j in range(0, m): arr[i * m + j] = matrix[i][j] # If not possible if matrix[i][j] % k != mod: return -1 # Sort the array to get median arr.sort() median = arr[(n * m) // 2] # To count the minimum operations minOperations = 0 for i in range(0, n * m): minOperations += abs(arr[i] - median) // k # If there are even elements, then there # are two medians. We consider the best # of two as answer. if (n * m) % 2 == 0: median2 = arr[( (n * m) // 2 ) - 1] minOperations2 = 0 for i in range(0, n * m): minOperations2 += abs(arr[i] - median2) // k minOperations = min(minOperations, minOperations2) # Return minimum operations required return minOperations # Driver codeif __name__ == "__main__": matrix = [[2, 4, 6], [8, 10, 12], [14, 16, 18], [20, 22, 24]] n = len(matrix) m = len(matrix[0]) k = 2 print(minOperations(n, m, k, matrix)) # This code is contributed by Rituraj Jain // C# implementation of the approachusing System; class GFG{ // Function to return the minimum // number of operations required static int minOperations(int n, int m, int k, int [,]matrix) { // Create another array to // store the elements of matrix int []arr = new int[n * m]; int mod = matrix[0, 0] % k; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { arr[i * m + j] = matrix[i,j]; // If not possible if (matrix[i,j] % k != mod) { return -1; } } } // Sort the array to get median Array.Sort(arr); int median = arr[(n * m) / 2]; // To count the minimum operations int minOperations = 0; for (int i = 0; i < n * m; ++i) minOperations += Math.Abs(arr[i] - median) / k; // If there are even elements, then there // are two medians. We consider the best // of two as answer. if ((n * m) % 2 == 0) { int median2 = arr[( (n * m) / 2 ) - 1]; int minOperations2 = 0; for (int i = 0; i < n * m; ++i) minOperations2 += Math.Abs(arr[i] - median2) / k; minOperations = Math.Min(minOperations, minOperations2); } // Return minimum operations required return minOperations; } // Driver code public static void Main() { int [,]matrix = { { 2, 4, 6 }, { 8, 10, 12 }, { 14, 16, 18 }, { 20, 22, 24 } }; int n = matrix.GetLength(0); int m = matrix.GetLength(1); int k = 2; Console.WriteLine(minOperations(n, m, k, matrix)); }} // This code is contributed by Ryuga <script> // Javascript implementation of the approach // Function to return the minimum // number of operations required function minOperations(n, m, k, matrix) { // Create another array to // store the elements of matrix let arr = new Array(n * m); arr.fill(0); let mod = matrix[0][0] % k; for (let i = 0; i < n; ++i) { for (let j = 0; j < m; ++j) { arr[i * m + j] = matrix[i][j]; // If not possible if (matrix[i][j] % k != mod) { return -1; } } } // Sort the array to get median arr.sort(function(a, b){return a - b}); let median = arr[parseInt((n * m) / 2, 10)]; // To count the minimum operations let minOperations = 0; for (let i = 0; i < n * m; ++i) minOperations += parseInt(Math.abs(arr[i] - median) / k, 10); // If there are even elements, then there // are two medians. We consider the best // of two as answer. if ((n * m) % 2 == 0) { let median2 = arr[parseInt((n * m) / 2, 10)]; let minOperations2 = 0; for (let i = 0; i < n * m; ++i) minOperations2 += parseInt(Math.abs(arr[i] - median2) / k, 10); minOperations = Math.min(minOperations, minOperations2); } // Return minimum operations required return minOperations; } // Driver code let matrix = [ [ 2, 4, 6 ], [ 8, 10, 12 ], [ 14, 16, 18 ], [ 20, 22, 24 ] ]; let n = 4; let m = 3; let k = 2; document.write(minOperations(n, m, k, matrix)); // This code is contributed by mukesh07.</script> 36 Below is an implementation that handles negative numbers also in the input matrix: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum// number of operations requiredint minOperations(int n, int m, int k, vector<vector<int> >& matrix){ // Create another array to // store the elements of matrix vector<int> arr; int mod; // will not work for negative elements, so .. // adding this if (matrix[0][0] < 0) { mod = k - (abs(matrix[0][0]) % k); } else { mod = matrix[0][0] % k; } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { arr.push_back(matrix[i][j]); // adding this to handle negative elements too . int val = matrix[i][j]; if (val < 0) { int res = k - (abs(val) % k); if (res != mod) { return -1; } } else { int foo = matrix[i][j]; if (foo % k != mod) { return -1; } } } } // Sort the array to get median sort(arr.begin(), arr.end()); int median = arr[(n * m) / 2]; // To count the minimum operations int minOperations = 0; for (int i = 0; i < n * m; ++i) minOperations += abs(arr[i] - median) / k; // If there are even elements, then there // are two medians. We consider the best // of two as answer. if ((n * m) % 2 == 0) { // changed here as in case of even elements there will be 2 medians int median2 = arr[((n * m) / 2) - 1]; int minOperations2 = 0; for (int i = 0; i < n * m; ++i) minOperations2 += abs(arr[i] - median2) / k; minOperations = min(minOperations, minOperations2); } // Return minimum operations required return minOperations;} // Driver codeint main(){ vector<vector<int> > matrix = { { 2, 4, 6 }, { 8, 10, 12 }, { 14, 16, 18 }, { 20, 22, 24 } }; int n = matrix.size(); int m = matrix[0].size(); int k = 2; cout << minOperations(n, m, k, matrix); return 0;} // Java implementation of the approachimport java.util.*;class GFG{ // Function to return the minimum // number of operations required public static int minOperations(int n, int m, int k, int matrix[][]) { // Create another array to // store the elements of matrix Vector<Integer> arr = new Vector<>(); int mod; // will not work for negative elements, so .. // adding this if (matrix[0][0] < 0) { mod = k - (Math.abs(matrix[0][0]) % k); } else { mod = matrix[0][0] % k; } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { arr.add(matrix[i][j]); // adding this to handle // negative elements too . int val = matrix[i][j]; if (val < 0) { int res = k - (Math.abs(val) % k); if (res != mod) { return -1; } } else { int foo = matrix[i][j]; if (foo % k != mod) { return -1; } } } } // Sort the array to get median Collections.sort(arr); int median = arr.get((n * m) / 2); // To count the minimum operations int minOperations = 0; for (int i = 0; i < n * m; ++i) minOperations += Math.abs(arr.get(i) - median) / k; // If there are even elements, then there // are two medians. We consider the best // of two as answer. if ((n * m) % 2 == 0) { // changed here as in case of // even elements there will be 2 medians int median2 = arr.get(((n * m) / 2) - 1); int minOperations2 = 0; for (int i = 0; i < n * m; ++i) minOperations2 += Math.abs(arr.get(i) - median2) / k; minOperations = Math.min(minOperations, minOperations2); } // Return minimum operations required return minOperations; } // Driver code public static void main(String[] args) { int matrix[][] = { {2, 4, 6}, {8, 10, 12}, {14, 16, 18}, {20, 22, 24} }; int n = matrix.length; int m = matrix[0].length; int k = 2; System.out.println(minOperations(n, m, k, matrix)); }} // This code is contributed by divyesh072019 # Python3 implementation of the# above approach # Function to return the minimum# number of operations requireddef minOperations(n, m, k, matrix): # Create another array to # store the elements of # matrix arr = [] # will not work for negative # elements, so .. adding this if (matrix[0][0] < 0): mod = k - (abs(matrix[0][0]) % k) else: mod = matrix[0][0] % k for i in range(n): for j in range(m): arr.append(matrix[i][j]) # adding this to handle # negative elements too . val = matrix[i][j] if (val < 0): res = k - (abs(val) % k) if (res != mod): return -1 else: foo = matrix[i][j] if (foo % k != mod): return -1 # Sort the array to get median arr.sort() median = arr[(n * m) // 2] # To count the minimum # operations minOperations = 0 for i in range(n * m): minOperations += abs(arr[i] - median) // k # If there are even elements, # then there are two medians. # We consider the best of two # as answer. if ((n * m) % 2 == 0): # changed here as in case of # even elements there will be # 2 medians median2 = arr[((n * m) // 2) - 1] minOperations2 = 0 for i in range(n * m): minOperations2 += abs(arr[i] - median2) / k minOperations = min(minOperations, minOperations2) # Return minimum operations required return minOperations # Driver codeif __name__ == "__main__": matrix = [[2, 4, 6], [8, 10, 12], [14, 16, 18], [20, 22, 24]] n = len(matrix) m = len(matrix[0]) k = 2 print(minOperations(n, m, k, matrix)) # This code is contributed by Chitranayal // C# implementation of the approachusing System;using System.Collections.Generic;class GFG { // Function to return the minimum // number of operations required static int minOperations(int n, int m, int k, List<List<int>> matrix) { // Create another array to // store the elements of matrix List<int> arr = new List<int>(); int mod; // will not work for negative elements, so .. // adding this if (matrix[0][0] < 0) { mod = k - (Math.Abs(matrix[0][0]) % k); } else { mod = matrix[0][0] % k; } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { arr.Add(matrix[i][j]); // adding this to handle negative elements too . int val = matrix[i][j]; if (val < 0) { int res = k - (Math.Abs(val) % k); if (res != mod) { return -1; } } else { int foo = matrix[i][j]; if (foo % k != mod) { return -1; } } } } // Sort the array to get median arr.Sort(); int median = arr[(n * m) / 2]; // To count the minimum operations int minOperations = 0; for (int i = 0; i < n * m; ++i) minOperations += Math.Abs(arr[i] - median) / k; // If there are even elements, then there // are two medians. We consider the best // of two as answer. if ((n * m) % 2 == 0) { // changed here as in case of // even elements there will be 2 medians int median2 = arr[((n * m) / 2) - 1]; int minOperations2 = 0; for (int i = 0; i < n * m; ++i) minOperations2 += Math.Abs(arr[i] - median2) / k; minOperations = Math.Min(minOperations, minOperations2); } // Return minimum operations required return minOperations; } static void Main() { List<List<int>> matrix = new List<List<int>>{ new List<int> {2, 4, 6}, new List<int> {8, 10, 12}, new List<int> {14, 16, 18}, new List<int> {20, 22, 24}, }; int n = matrix.Count; int m = matrix[0].Count; int k = 2; Console.Write(minOperations(n, m, k, matrix)); }} // This code is contributed by divyeshrabadiya07. <script>// Javascript implementation of the approach // Function to return the minimum// number of operations requiredfunction minOperations(n,m,k,matrix){ // Create another array to // store the elements of matrix let arr = []; let mod; // will not work for negative elements, so .. // adding this if (matrix[0][0] < 0) { mod = k - (Math.abs(matrix[0][0]) % k); } else { mod = matrix[0][0] % k; } for (let i = 0; i < n; ++i) { for (let j = 0; j < m; ++j) { arr.push(matrix[i][j]); // adding this to handle // negative elements too . let val = matrix[i][j]; if (val < 0) { let res = k - (Math.abs(val) % k); if (res != mod) { return -1; } } else { let foo = matrix[i][j]; if (foo % k != mod) { return -1; } } } } // Sort the array to get median arr.sort(function(a,b){return a-b;}); let median = arr[(n * m) / 2]; // To count the minimum operations let minOperations = 0; for (let i = 0; i < n * m; ++i) minOperations += Math.abs(arr[i] - median) / k; // If there are even elements, then there // are two medians. We consider the best // of two as answer. if ((n * m) % 2 == 0) { // changed here as in case of // even elements there will be 2 medians let median2 = arr[((n * m) / 2) - 1]; let minOperations2 = 0; for (let i = 0; i < n * m; ++i) minOperations2 += Math.abs(arr[i] - median2) / k; minOperations = Math.min(minOperations, minOperations2); } // Return minimum operations required return minOperations;} // Driver codelet matrix = [[2, 4, 6], [8, 10, 12], [14, 16, 18], [20, 22, 24]]; let n = matrix.length;let m = matrix[0].length;let k = 2;document.write(minOperations(n, m, k, matrix)); // This code is contributed by rag2127</script> 36 ihritik ankthon rituraj_jain ajourney ukasp divyeshrabadiya07 divyesh072019 mukesh07 rag2127 mohitjha727 sumitgumber28 median-finding Modular Arithmetic C++ Programs Matrix Sorting Sorting Matrix Modular Arithmetic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C++ Program for QuickSort CSV file management using C++ delete keyword in C++ Shallow Copy and Deep Copy in C++ cin in C++ Matrix Chain Multiplication | DP-8 Program to find largest element in an array Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Sudoku | Backtracking-7 Rat in a Maze | Backtracking-2
[ { "code": null, "e": 25448, "s": 25420, "text": "\n15 Nov, 2021" }, { "code": null, "e": 25739, "s": 25448, "text": "Given an integer K and a matrix of N rows and M columns, the task is to find the minimum number of operations required to make all the elements of the matrix equal. In a single operation, K can be added to or subtracted from any element of the matrix. Print -1 if it is impossible to do so." }, { "code": null, "e": 25749, "s": 25739, "text": "Examples:" }, { "code": null, "e": 25987, "s": 25749, "text": "Input: mat[][] = {{2, 4}, {22, 24}}, K = 2 Output: 20 mat[0][0] = 2 + (10 * K) = 22 ... 10 operations mat[0][1] = 4 + (9 * K) = 22 ... 9 operations mat[1][0] = 22 ... No operation mat[1][1] = 24 – K = 22 ... 1 operations 10 + 9 + 1 = 20 " }, { "code": null, "e": 26080, "s": 25987, "text": "Input: mat[][] = { {3, 63, 42}, {18, 12, 12}, {15, 21, 18}, {33, 84, 24}}, K = 3 Output: 63 " }, { "code": null, "e": 26570, "s": 26080, "text": "Approach: Since we are only allowed to add or subtract K from any element, we can easily infer that the mod of all the elements with K should be equal because x % K = (x + K) % K = (x – K) % K. If that is not the case, simply print -1. Otherwise, sort all the elements of the matrix in non-decreasing order and find the median of the sorted elements. The minimum number of steps would occur if we convert all the elements to equal to the median. Calculate these steps and print the result." }, { "code": null, "e": 26622, "s": 26570, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26626, "s": 26622, "text": "C++" }, { "code": null, "e": 26631, "s": 26626, "text": "Java" }, { "code": null, "e": 26639, "s": 26631, "text": "Python3" }, { "code": null, "e": 26642, "s": 26639, "text": "C#" }, { "code": null, "e": 26653, "s": 26642, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum// number of operations requiredint minOperations(int n, int m, int k, vector<vector<int> >& matrix){ // Create another array to // store the elements of matrix vector<int> arr(n * m, 0); int mod = matrix[0][0] % k; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { arr[i * m + j] = matrix[i][j]; // If not possible if (matrix[i][j] % k != mod) { return -1; } } } // Sort the array to get median sort(arr.begin(), arr.end()); int median = arr[(n * m) / 2]; // To count the minimum operations int minOperations = 0; for (int i = 0; i < n * m; ++i) minOperations += abs(arr[i] - median) / k; // If there are even elements, then there // are two medians. We consider the best // of two as answer. if ((n * m) % 2 == 0) { int median2 = arr[( (n * m) / 2) - 1]; int minOperations2 = 0; for (int i = 0; i < n * m; ++i) minOperations2 += abs(arr[i] - median2) / k; minOperations = min(minOperations, minOperations2); } // Return minimum operations required return minOperations;} // Driver codeint main(){ vector<vector<int> > matrix = { { 2, 4, 6 }, { 8, 10, 12 }, { 14, 16, 18 }, { 20, 22, 24 } }; int n = matrix.size(); int m = matrix[0].size(); int k = 2; cout << minOperations(n, m, k, matrix); return 0;}", "e": 28304, "s": 26653, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the minimum // number of operations required static int minOperations(int n, int m, int k, int matrix[][]) { // Create another array to // store the elements of matrix int [] arr = new int[n * m]; int mod = matrix[0][0] % k; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { arr[i * m + j] = matrix[i][j]; // If not possible if (matrix[i][j] % k != mod) { return -1; } } } // Sort the array to get median Arrays.sort(arr); int median = arr[(n * m) / 2]; // To count the minimum operations int minOperations = 0; for (int i = 0; i < n * m; ++i) minOperations += Math.abs(arr[i] - median) / k; // If there are even elements, then there // are two medians. We consider the best // of two as answer. if ((n * m) % 2 == 0) { int median2 = arr[( (n * m) / 2 ) - 1]; int minOperations2 = 0; for (int i = 0; i < n * m; ++i) minOperations2 += Math.abs(arr[i] - median2) / k; minOperations = Math.min(minOperations, minOperations2); } // Return minimum operations required return minOperations; } // Driver code public static void main(String []args) { int matrix [][] = { { 2, 4, 6 }, { 8, 10, 12 }, { 14, 16, 18 }, { 20, 22, 24 } }; int n = matrix.length; int m = matrix[0].length; int k = 2; System.out.println(minOperations(n, m, k, matrix)); }} // This code is contributed by ihritik", "e": 30249, "s": 28304, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the minimum# number of operations requireddef minOperations(n, m, k, matrix): # Create another array to store the # elements of matrix arr = [0] * (n * m) mod = matrix[0][0] % k for i in range(0, n): for j in range(0, m): arr[i * m + j] = matrix[i][j] # If not possible if matrix[i][j] % k != mod: return -1 # Sort the array to get median arr.sort() median = arr[(n * m) // 2] # To count the minimum operations minOperations = 0 for i in range(0, n * m): minOperations += abs(arr[i] - median) // k # If there are even elements, then there # are two medians. We consider the best # of two as answer. if (n * m) % 2 == 0: median2 = arr[( (n * m) // 2 ) - 1] minOperations2 = 0 for i in range(0, n * m): minOperations2 += abs(arr[i] - median2) // k minOperations = min(minOperations, minOperations2) # Return minimum operations required return minOperations # Driver codeif __name__ == \"__main__\": matrix = [[2, 4, 6], [8, 10, 12], [14, 16, 18], [20, 22, 24]] n = len(matrix) m = len(matrix[0]) k = 2 print(minOperations(n, m, k, matrix)) # This code is contributed by Rituraj Jain", "e": 31657, "s": 30249, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the minimum // number of operations required static int minOperations(int n, int m, int k, int [,]matrix) { // Create another array to // store the elements of matrix int []arr = new int[n * m]; int mod = matrix[0, 0] % k; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { arr[i * m + j] = matrix[i,j]; // If not possible if (matrix[i,j] % k != mod) { return -1; } } } // Sort the array to get median Array.Sort(arr); int median = arr[(n * m) / 2]; // To count the minimum operations int minOperations = 0; for (int i = 0; i < n * m; ++i) minOperations += Math.Abs(arr[i] - median) / k; // If there are even elements, then there // are two medians. We consider the best // of two as answer. if ((n * m) % 2 == 0) { int median2 = arr[( (n * m) / 2 ) - 1]; int minOperations2 = 0; for (int i = 0; i < n * m; ++i) minOperations2 += Math.Abs(arr[i] - median2) / k; minOperations = Math.Min(minOperations, minOperations2); } // Return minimum operations required return minOperations; } // Driver code public static void Main() { int [,]matrix = { { 2, 4, 6 }, { 8, 10, 12 }, { 14, 16, 18 }, { 20, 22, 24 } }; int n = matrix.GetLength(0); int m = matrix.GetLength(1); int k = 2; Console.WriteLine(minOperations(n, m, k, matrix)); }} // This code is contributed by Ryuga", "e": 33609, "s": 31657, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the minimum // number of operations required function minOperations(n, m, k, matrix) { // Create another array to // store the elements of matrix let arr = new Array(n * m); arr.fill(0); let mod = matrix[0][0] % k; for (let i = 0; i < n; ++i) { for (let j = 0; j < m; ++j) { arr[i * m + j] = matrix[i][j]; // If not possible if (matrix[i][j] % k != mod) { return -1; } } } // Sort the array to get median arr.sort(function(a, b){return a - b}); let median = arr[parseInt((n * m) / 2, 10)]; // To count the minimum operations let minOperations = 0; for (let i = 0; i < n * m; ++i) minOperations += parseInt(Math.abs(arr[i] - median) / k, 10); // If there are even elements, then there // are two medians. We consider the best // of two as answer. if ((n * m) % 2 == 0) { let median2 = arr[parseInt((n * m) / 2, 10)]; let minOperations2 = 0; for (let i = 0; i < n * m; ++i) minOperations2 += parseInt(Math.abs(arr[i] - median2) / k, 10); minOperations = Math.min(minOperations, minOperations2); } // Return minimum operations required return minOperations; } // Driver code let matrix = [ [ 2, 4, 6 ], [ 8, 10, 12 ], [ 14, 16, 18 ], [ 20, 22, 24 ] ]; let n = 4; let m = 3; let k = 2; document.write(minOperations(n, m, k, matrix)); // This code is contributed by mukesh07.</script>", "e": 35464, "s": 33609, "text": null }, { "code": null, "e": 35467, "s": 35464, "text": "36" }, { "code": null, "e": 35554, "s": 35469, "text": "Below is an implementation that handles negative numbers also in the input matrix: " }, { "code": null, "e": 35558, "s": 35554, "text": "C++" }, { "code": null, "e": 35563, "s": 35558, "text": "Java" }, { "code": null, "e": 35571, "s": 35563, "text": "Python3" }, { "code": null, "e": 35574, "s": 35571, "text": "C#" }, { "code": null, "e": 35585, "s": 35574, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum// number of operations requiredint minOperations(int n, int m, int k, vector<vector<int> >& matrix){ // Create another array to // store the elements of matrix vector<int> arr; int mod; // will not work for negative elements, so .. // adding this if (matrix[0][0] < 0) { mod = k - (abs(matrix[0][0]) % k); } else { mod = matrix[0][0] % k; } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { arr.push_back(matrix[i][j]); // adding this to handle negative elements too . int val = matrix[i][j]; if (val < 0) { int res = k - (abs(val) % k); if (res != mod) { return -1; } } else { int foo = matrix[i][j]; if (foo % k != mod) { return -1; } } } } // Sort the array to get median sort(arr.begin(), arr.end()); int median = arr[(n * m) / 2]; // To count the minimum operations int minOperations = 0; for (int i = 0; i < n * m; ++i) minOperations += abs(arr[i] - median) / k; // If there are even elements, then there // are two medians. We consider the best // of two as answer. if ((n * m) % 2 == 0) { // changed here as in case of even elements there will be 2 medians int median2 = arr[((n * m) / 2) - 1]; int minOperations2 = 0; for (int i = 0; i < n * m; ++i) minOperations2 += abs(arr[i] - median2) / k; minOperations = min(minOperations, minOperations2); } // Return minimum operations required return minOperations;} // Driver codeint main(){ vector<vector<int> > matrix = { { 2, 4, 6 }, { 8, 10, 12 }, { 14, 16, 18 }, { 20, 22, 24 } }; int n = matrix.size(); int m = matrix[0].size(); int k = 2; cout << minOperations(n, m, k, matrix); return 0;}", "e": 37782, "s": 35585, "text": null }, { "code": "// Java implementation of the approachimport java.util.*;class GFG{ // Function to return the minimum // number of operations required public static int minOperations(int n, int m, int k, int matrix[][]) { // Create another array to // store the elements of matrix Vector<Integer> arr = new Vector<>(); int mod; // will not work for negative elements, so .. // adding this if (matrix[0][0] < 0) { mod = k - (Math.abs(matrix[0][0]) % k); } else { mod = matrix[0][0] % k; } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { arr.add(matrix[i][j]); // adding this to handle // negative elements too . int val = matrix[i][j]; if (val < 0) { int res = k - (Math.abs(val) % k); if (res != mod) { return -1; } } else { int foo = matrix[i][j]; if (foo % k != mod) { return -1; } } } } // Sort the array to get median Collections.sort(arr); int median = arr.get((n * m) / 2); // To count the minimum operations int minOperations = 0; for (int i = 0; i < n * m; ++i) minOperations += Math.abs(arr.get(i) - median) / k; // If there are even elements, then there // are two medians. We consider the best // of two as answer. if ((n * m) % 2 == 0) { // changed here as in case of // even elements there will be 2 medians int median2 = arr.get(((n * m) / 2) - 1); int minOperations2 = 0; for (int i = 0; i < n * m; ++i) minOperations2 += Math.abs(arr.get(i) - median2) / k; minOperations = Math.min(minOperations, minOperations2); } // Return minimum operations required return minOperations; } // Driver code public static void main(String[] args) { int matrix[][] = { {2, 4, 6}, {8, 10, 12}, {14, 16, 18}, {20, 22, 24} }; int n = matrix.length; int m = matrix[0].length; int k = 2; System.out.println(minOperations(n, m, k, matrix)); }} // This code is contributed by divyesh072019", "e": 39978, "s": 37782, "text": null }, { "code": "# Python3 implementation of the# above approach # Function to return the minimum# number of operations requireddef minOperations(n, m, k, matrix): # Create another array to # store the elements of # matrix arr = [] # will not work for negative # elements, so .. adding this if (matrix[0][0] < 0): mod = k - (abs(matrix[0][0]) % k) else: mod = matrix[0][0] % k for i in range(n): for j in range(m): arr.append(matrix[i][j]) # adding this to handle # negative elements too . val = matrix[i][j] if (val < 0): res = k - (abs(val) % k) if (res != mod): return -1 else: foo = matrix[i][j] if (foo % k != mod): return -1 # Sort the array to get median arr.sort() median = arr[(n * m) // 2] # To count the minimum # operations minOperations = 0 for i in range(n * m): minOperations += abs(arr[i] - median) // k # If there are even elements, # then there are two medians. # We consider the best of two # as answer. if ((n * m) % 2 == 0): # changed here as in case of # even elements there will be # 2 medians median2 = arr[((n * m) // 2) - 1] minOperations2 = 0 for i in range(n * m): minOperations2 += abs(arr[i] - median2) / k minOperations = min(minOperations, minOperations2) # Return minimum operations required return minOperations # Driver codeif __name__ == \"__main__\": matrix = [[2, 4, 6], [8, 10, 12], [14, 16, 18], [20, 22, 24]] n = len(matrix) m = len(matrix[0]) k = 2 print(minOperations(n, m, k, matrix)) # This code is contributed by Chitranayal", "e": 41971, "s": 39978, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic;class GFG { // Function to return the minimum // number of operations required static int minOperations(int n, int m, int k, List<List<int>> matrix) { // Create another array to // store the elements of matrix List<int> arr = new List<int>(); int mod; // will not work for negative elements, so .. // adding this if (matrix[0][0] < 0) { mod = k - (Math.Abs(matrix[0][0]) % k); } else { mod = matrix[0][0] % k; } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { arr.Add(matrix[i][j]); // adding this to handle negative elements too . int val = matrix[i][j]; if (val < 0) { int res = k - (Math.Abs(val) % k); if (res != mod) { return -1; } } else { int foo = matrix[i][j]; if (foo % k != mod) { return -1; } } } } // Sort the array to get median arr.Sort(); int median = arr[(n * m) / 2]; // To count the minimum operations int minOperations = 0; for (int i = 0; i < n * m; ++i) minOperations += Math.Abs(arr[i] - median) / k; // If there are even elements, then there // are two medians. We consider the best // of two as answer. if ((n * m) % 2 == 0) { // changed here as in case of // even elements there will be 2 medians int median2 = arr[((n * m) / 2) - 1]; int minOperations2 = 0; for (int i = 0; i < n * m; ++i) minOperations2 += Math.Abs(arr[i] - median2) / k; minOperations = Math.Min(minOperations, minOperations2); } // Return minimum operations required return minOperations; } static void Main() { List<List<int>> matrix = new List<List<int>>{ new List<int> {2, 4, 6}, new List<int> {8, 10, 12}, new List<int> {14, 16, 18}, new List<int> {20, 22, 24}, }; int n = matrix.Count; int m = matrix[0].Count; int k = 2; Console.Write(minOperations(n, m, k, matrix)); }} // This code is contributed by divyeshrabadiya07.", "e": 44535, "s": 41971, "text": null }, { "code": "<script>// Javascript implementation of the approach // Function to return the minimum// number of operations requiredfunction minOperations(n,m,k,matrix){ // Create another array to // store the elements of matrix let arr = []; let mod; // will not work for negative elements, so .. // adding this if (matrix[0][0] < 0) { mod = k - (Math.abs(matrix[0][0]) % k); } else { mod = matrix[0][0] % k; } for (let i = 0; i < n; ++i) { for (let j = 0; j < m; ++j) { arr.push(matrix[i][j]); // adding this to handle // negative elements too . let val = matrix[i][j]; if (val < 0) { let res = k - (Math.abs(val) % k); if (res != mod) { return -1; } } else { let foo = matrix[i][j]; if (foo % k != mod) { return -1; } } } } // Sort the array to get median arr.sort(function(a,b){return a-b;}); let median = arr[(n * m) / 2]; // To count the minimum operations let minOperations = 0; for (let i = 0; i < n * m; ++i) minOperations += Math.abs(arr[i] - median) / k; // If there are even elements, then there // are two medians. We consider the best // of two as answer. if ((n * m) % 2 == 0) { // changed here as in case of // even elements there will be 2 medians let median2 = arr[((n * m) / 2) - 1]; let minOperations2 = 0; for (let i = 0; i < n * m; ++i) minOperations2 += Math.abs(arr[i] - median2) / k; minOperations = Math.min(minOperations, minOperations2); } // Return minimum operations required return minOperations;} // Driver codelet matrix = [[2, 4, 6], [8, 10, 12], [14, 16, 18], [20, 22, 24]]; let n = matrix.length;let m = matrix[0].length;let k = 2;document.write(minOperations(n, m, k, matrix)); // This code is contributed by rag2127</script>", "e": 46581, "s": 44535, "text": null }, { "code": null, "e": 46584, "s": 46581, "text": "36" }, { "code": null, "e": 46596, "s": 46588, "text": "ihritik" }, { "code": null, "e": 46604, "s": 46596, "text": "ankthon" }, { "code": null, "e": 46617, "s": 46604, "text": "rituraj_jain" }, { "code": null, "e": 46626, "s": 46617, "text": "ajourney" }, { "code": null, "e": 46632, "s": 46626, "text": "ukasp" }, { "code": null, "e": 46650, "s": 46632, "text": "divyeshrabadiya07" }, { "code": null, "e": 46664, "s": 46650, "text": "divyesh072019" }, { "code": null, "e": 46673, "s": 46664, "text": "mukesh07" }, { "code": null, "e": 46681, "s": 46673, "text": "rag2127" }, { "code": null, "e": 46693, "s": 46681, "text": "mohitjha727" }, { "code": null, "e": 46707, "s": 46693, "text": "sumitgumber28" }, { "code": null, "e": 46722, "s": 46707, "text": "median-finding" }, { "code": null, "e": 46741, "s": 46722, "text": "Modular Arithmetic" }, { "code": null, "e": 46754, "s": 46741, "text": "C++ Programs" }, { "code": null, "e": 46761, "s": 46754, "text": "Matrix" }, { "code": null, "e": 46769, "s": 46761, "text": "Sorting" }, { "code": null, "e": 46777, "s": 46769, "text": "Sorting" }, { "code": null, "e": 46784, "s": 46777, "text": "Matrix" }, { "code": null, "e": 46803, "s": 46784, "text": "Modular Arithmetic" }, { "code": null, "e": 46901, "s": 46803, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46910, "s": 46901, "text": "Comments" }, { "code": null, "e": 46923, "s": 46910, "text": "Old Comments" }, { "code": null, "e": 46949, "s": 46923, "text": "C++ Program for QuickSort" }, { "code": null, "e": 46979, "s": 46949, "text": "CSV file management using C++" }, { "code": null, "e": 47001, "s": 46979, "text": "delete keyword in C++" }, { "code": null, "e": 47035, "s": 47001, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 47046, "s": 47035, "text": "cin in C++" }, { "code": null, "e": 47081, "s": 47046, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 47125, "s": 47081, "text": "Program to find largest element in an array" }, { "code": null, "e": 47187, "s": 47125, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" }, { "code": null, "e": 47211, "s": 47187, "text": "Sudoku | Backtracking-7" } ]
Python Program to find sum of array - GeeksforGeeks
22 Oct, 2020 Given an array of integers, find the sum of its elements. Examples : Input : arr[] = {1, 2, 3} Output : 6 1 + 2 + 3 = 6 Input : arr[] = {15, 12, 13, 10} Output : 50 Method 1: # Python 3 code to find sum # of elements in given array def _sum(arr): # initialize a variable # to store the sum # while iterating through # the array later sum=0 # iterate through the array # and add each element to the sum variable # one at a time for i in arr: sum = sum + i return(sum) # driver function arr=[] # input values to list arr = [12, 3, 4, 15] # calculating length of array n = len(arr) ans = _sum(arr) # display sum print ('Sum of the array is ', ans) # This code is contributed by Himanshu Ranjan Sum of the array is 34 Method 2: # Python 3 code to find sum # of elements in given array# driver functionarr = [] # input values to listarr = [12, 3, 4, 15] # sum() is an inbuilt function in python that adds # all the elements in list,set and tuples and returns# the value ans = sum(arr) # display sumprint ('Sum of the array is ',ans) # This code is contributed by Dhananjay Patil Sum of the array is 34 Please refer complete article on Program to find sum of elements in a given array for more details! avsadityavardhan Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python | Convert string dictionary to dictionary Iterate over characters of a string in Python Python | Convert a list into a tuple Python Program for factorial of a number Python | Check if a variable is string Python | Convert set into a list Add a key:value pair to dictionary in Python Appending to list in Python dictionary Python Program for Bubble Sort Python program to find largest number in a list
[ { "code": null, "e": 26381, "s": 26353, "text": "\n22 Oct, 2020" }, { "code": null, "e": 26439, "s": 26381, "text": "Given an array of integers, find the sum of its elements." }, { "code": null, "e": 26450, "s": 26439, "text": "Examples :" }, { "code": null, "e": 26548, "s": 26450, "text": "Input : arr[] = {1, 2, 3}\nOutput : 6\n1 + 2 + 3 = 6\n\nInput : arr[] = {15, 12, 13, 10}\nOutput : 50\n" }, { "code": null, "e": 26558, "s": 26548, "text": "Method 1:" }, { "code": "# Python 3 code to find sum # of elements in given array def _sum(arr): # initialize a variable # to store the sum # while iterating through # the array later sum=0 # iterate through the array # and add each element to the sum variable # one at a time for i in arr: sum = sum + i return(sum) # driver function arr=[] # input values to list arr = [12, 3, 4, 15] # calculating length of array n = len(arr) ans = _sum(arr) # display sum print ('Sum of the array is ', ans) # This code is contributed by Himanshu Ranjan ", "e": 27145, "s": 26558, "text": null }, { "code": null, "e": 27170, "s": 27145, "text": "Sum of the array is 34\n" }, { "code": null, "e": 27180, "s": 27170, "text": "Method 2:" }, { "code": "# Python 3 code to find sum # of elements in given array# driver functionarr = [] # input values to listarr = [12, 3, 4, 15] # sum() is an inbuilt function in python that adds # all the elements in list,set and tuples and returns# the value ans = sum(arr) # display sumprint ('Sum of the array is ',ans) # This code is contributed by Dhananjay Patil ", "e": 27535, "s": 27180, "text": null }, { "code": null, "e": 27560, "s": 27535, "text": "Sum of the array is 34\n" }, { "code": null, "e": 27660, "s": 27560, "text": "Please refer complete article on Program to find sum of elements in a given array for more details!" }, { "code": null, "e": 27677, "s": 27660, "text": "avsadityavardhan" }, { "code": null, "e": 27693, "s": 27677, "text": "Python Programs" }, { "code": null, "e": 27791, "s": 27693, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27840, "s": 27791, "text": "Python | Convert string dictionary to dictionary" }, { "code": null, "e": 27886, "s": 27840, "text": "Iterate over characters of a string in Python" }, { "code": null, "e": 27923, "s": 27886, "text": "Python | Convert a list into a tuple" }, { "code": null, "e": 27964, "s": 27923, "text": "Python Program for factorial of a number" }, { "code": null, "e": 28003, "s": 27964, "text": "Python | Check if a variable is string" }, { "code": null, "e": 28036, "s": 28003, "text": "Python | Convert set into a list" }, { "code": null, "e": 28081, "s": 28036, "text": "Add a key:value pair to dictionary in Python" }, { "code": null, "e": 28120, "s": 28081, "text": "Appending to list in Python dictionary" }, { "code": null, "e": 28151, "s": 28120, "text": "Python Program for Bubble Sort" } ]
How to clone a GitHub repository?
Cloning a repository involves downloading a copy of the source code from source control. In other words, cloning is creating a copy of an existing repository. Consider an example where multiple users are working on a project. This feature can be used by the users to create a development copy. If you have a GitHub repository, you need to first invite collaborators into the repository. Each collaborator will then clone the repository into their local machines. Locally they will work with this cloned repository, make local changes and perform commits on it. Once they are ready to share their changes with others in the team, they will push the commits to the central repository. In order to clone a repository, we need to follow the steps given below − Copy the URL from the text box shown above and paste this into your git bash terminal using the below command. $ git clone {repo_rul} This will create a folder in your machine with the same name as that of the project. $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo $ git clone https://github.com/kannan/sample.git Cloning into 'sample'... remote: Enumerating objects: 3, done. remote: Counting objects: 100% (3/3), done. remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0 Receiving objects: 100% (3/3), done. $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo $ ls sample/ Change the current working directory to the project folder and execute the git log command as shown below $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo $ cd sample/ $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo/sample (main) $ git log --oneline --all --graph * b494547 (HEAD -> main, origin/main, origin/HEAD) Initial commit In the above output, origin is the name given by git for the remote tracking branch (i.e., the source branch that was cloned). origin/main and origin/HEAD are remote tracking branches. In order to view the details of the remote tracking branch use the following command $ git remote -v origin https://github.com/kannan/sample.git (fetch) origin https://github.com/kannan/sample.git (push) -v means verbose so this will list the details of the remote tracking branches.
[ { "code": null, "e": 1356, "s": 1062, "text": "Cloning a repository involves downloading a copy of the source code from source control. In other words, cloning is creating a copy of an existing repository. Consider an example where multiple users are working on a project. This feature can be used by the users to create a development copy." }, { "code": null, "e": 1525, "s": 1356, "text": "If you have a GitHub repository, you need to first invite collaborators into the repository. Each collaborator will then clone the repository into their local machines." }, { "code": null, "e": 1745, "s": 1525, "text": "Locally they will work with this cloned repository, make local changes and perform commits on it. Once they are ready to share their changes with others in the team, they will push the commits to the central repository." }, { "code": null, "e": 1819, "s": 1745, "text": "In order to clone a repository, we need to follow the steps given below −" }, { "code": null, "e": 1930, "s": 1819, "text": "Copy the URL from the text box shown above and paste this into your git bash terminal using the below command." }, { "code": null, "e": 1953, "s": 1930, "text": "$ git clone {repo_rul}" }, { "code": null, "e": 2038, "s": 1953, "text": "This will create a folder in your machine with the same name as that of the project." }, { "code": null, "e": 2392, "s": 2038, "text": "$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo\n$ git clone https://github.com/kannan/sample.git\nCloning into 'sample'...\nremote: Enumerating objects: 3, done.\nremote: Counting objects: 100% (3/3), done.\nremote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0\nReceiving objects: 100% (3/3), done.\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo\n$ ls\nsample/" }, { "code": null, "e": 2498, "s": 2392, "text": "Change the current working directory to the project folder and execute the git log command as shown below" }, { "code": null, "e": 2712, "s": 2498, "text": "$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo\n$ cd sample/\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo/sample (main)\n$ git log --oneline --all --graph\n* b494547 (HEAD -> main, origin/main, origin/HEAD) Initial commit" }, { "code": null, "e": 2982, "s": 2712, "text": "In the above output, origin is the name given by git for the remote tracking branch (i.e., the source branch that was cloned). origin/main and origin/HEAD are remote tracking branches. In order to view the details of the remote tracking branch use the following command" }, { "code": null, "e": 3101, "s": 2982, "text": "$ git remote -v\norigin https://github.com/kannan/sample.git (fetch)\norigin https://github.com/kannan/sample.git (push)" }, { "code": null, "e": 3181, "s": 3101, "text": "-v means verbose so this will list the details of the remote tracking branches." } ]
Alert for unsaved changes in form in JavaScript
Following is the code to display an alert for form’s unsaved changes in JavaScript − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } input { margin: 10px; } </style> </head> <body onbeforeunload="return pageUnload()"> <h1>Alert for unsaved changes in form</h1> <form> Username <input type="text" /> <br /> Password <input type="password" /><br /> <button type="submit">SUBMIT</button> </form> <br /> <script> function pageUnload() { return "The data on this page will be lost if you leave"; } </script> </body> </html> If we click on the reload button then the following warning will be shown −
[ { "code": null, "e": 1147, "s": 1062, "text": "Following is the code to display an alert for form’s unsaved changes in JavaScript −" }, { "code": null, "e": 1158, "s": 1147, "text": " Live Demo" }, { "code": null, "e": 1821, "s": 1158, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n input {\n margin: 10px;\n }\n</style>\n</head>\n<body onbeforeunload=\"return pageUnload()\">\n<h1>Alert for unsaved changes in form</h1>\n<form>\nUsername <input type=\"text\" />\n<br />\nPassword <input type=\"password\" /><br />\n<button type=\"submit\">SUBMIT</button>\n</form>\n<br />\n<script>\n function pageUnload() {\n return \"The data on this page will be lost if you leave\";\n }\n</script>\n</body>\n</html>" }, { "code": null, "e": 1897, "s": 1821, "text": "If we click on the reload button then the following warning will be shown −" } ]
ReactJS - State Management
State management is one of the important and unavoidable features of any dynamic application. React provides a simple and flexible API to support state management in a React component. Let us understand how to maintain state in React application in this chapter. State represents the value of a dynamic properties of a React component at a given instance. React provides a dynamic data store for each component. The internal data represents the state of a React component and can be accessed using this.state member variable of the component. Whenever the state of the component is changed, the component will re-render itself by calling the render() method along with the new state. A simple example to better understand the state management is to analyse a real-time clock component. The clock component primary job is to show the date and time of a location at the given instance. As the current time will change every second, the clock component should maintain the current date and time in it’s state. As the state of the clock component changes every second, the clock’s render() method will be called every second and the render() method show the current time using it’s current state. The simple representation of the state is as follows − { date: '2020-10-10 10:10:10' } Let us create a new Clock component later in this chapter. Here, State management API State management API Stateless component Stateless component State management using React Hooks State management using React Hooks Component Life cycle Component Life cycle Component life cycle using React Hooks Component life cycle using React Hooks Layout in component Layout in component Pagination Pagination Material UI Material UI 20 Lectures 1.5 hours Anadi Sharma 60 Lectures 4.5 hours Skillbakerystudios 165 Lectures 13 hours Paul Carlo Tordecilla 63 Lectures 9.5 hours TELCOMA Global 17 Lectures 2 hours Mohd Raqif Warsi Print Add Notes Bookmark this page
[ { "code": null, "e": 2296, "s": 2033, "text": "State management is one of the important and unavoidable features of any dynamic application. React provides a simple and flexible API to support state management in a React component. Let us understand how to maintain state in React application in this chapter." }, { "code": null, "e": 2717, "s": 2296, "text": "State represents the value of a dynamic properties of a React component at a given instance. React provides a dynamic data store for each component. The internal data represents the state of a React component and can be accessed using this.state member variable of the component. Whenever the state of the component is changed, the component will re-render itself by calling the render() method along with the new state." }, { "code": null, "e": 3226, "s": 2717, "text": "A simple example to better understand the state management is to analyse a real-time clock component. The clock component primary job is to show the date and time of a location at the given instance. As the current time will change every second, the clock component should maintain the current date and time in it’s state. As the state of the clock component changes every second, the clock’s render() method will be called every second and the render() method show the current time using it’s current state." }, { "code": null, "e": 3281, "s": 3226, "text": "The simple representation of the state is as follows −" }, { "code": null, "e": 3319, "s": 3281, "text": "{ \n date: '2020-10-10 10:10:10' \n}\n" }, { "code": null, "e": 3378, "s": 3319, "text": "Let us create a new Clock component later in this chapter." }, { "code": null, "e": 3384, "s": 3378, "text": "Here," }, { "code": null, "e": 3405, "s": 3384, "text": "State management API" }, { "code": null, "e": 3426, "s": 3405, "text": "State management API" }, { "code": null, "e": 3446, "s": 3426, "text": "Stateless component" }, { "code": null, "e": 3466, "s": 3446, "text": "Stateless component" }, { "code": null, "e": 3501, "s": 3466, "text": "State management using React Hooks" }, { "code": null, "e": 3536, "s": 3501, "text": "State management using React Hooks" }, { "code": null, "e": 3557, "s": 3536, "text": "Component Life cycle" }, { "code": null, "e": 3578, "s": 3557, "text": "Component Life cycle" }, { "code": null, "e": 3617, "s": 3578, "text": "Component life cycle using React Hooks" }, { "code": null, "e": 3656, "s": 3617, "text": "Component life cycle using React Hooks" }, { "code": null, "e": 3676, "s": 3656, "text": "Layout in component" }, { "code": null, "e": 3696, "s": 3676, "text": "Layout in component" }, { "code": null, "e": 3707, "s": 3696, "text": "Pagination" }, { "code": null, "e": 3718, "s": 3707, "text": "Pagination" }, { "code": null, "e": 3730, "s": 3718, "text": "Material UI" }, { "code": null, "e": 3742, "s": 3730, "text": "Material UI" }, { "code": null, "e": 3777, "s": 3742, "text": "\n 20 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3791, "s": 3777, "text": " Anadi Sharma" }, { "code": null, "e": 3826, "s": 3791, "text": "\n 60 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3846, "s": 3826, "text": " Skillbakerystudios" }, { "code": null, "e": 3881, "s": 3846, "text": "\n 165 Lectures \n 13 hours \n" }, { "code": null, "e": 3904, "s": 3881, "text": " Paul Carlo Tordecilla" }, { "code": null, "e": 3939, "s": 3904, "text": "\n 63 Lectures \n 9.5 hours \n" }, { "code": null, "e": 3955, "s": 3939, "text": " TELCOMA Global" }, { "code": null, "e": 3988, "s": 3955, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 4006, "s": 3988, "text": " Mohd Raqif Warsi" }, { "code": null, "e": 4013, "s": 4006, "text": " Print" }, { "code": null, "e": 4024, "s": 4013, "text": " Add Notes" } ]
Program to find minimum changes required for alternating binary string in Python
Suppose we have a binary string s. Let us consider an operation where we can flip one bit. The string s is called alternating string if no two adjacent characters are same. We have to find the minimum number of operations needed to make s alternating. So, if the input is like s = "11100011", then the output will be 3 because if we flip bits at position 1, 4 and 7, then, it will be "10101010", then all are alternating. To solve this, we will follow these steps − change := 0 change := 0 even_1 := 0, even_0 := 0 even_1 := 0, even_0 := 0 odd_1 := 0, odd_0 := 0 odd_1 := 0, odd_0 := 0 for i in range 0 to size of s - 1, doif i is even, thenif s[i] is same as '1', theneven_1 := even_1 + 1otherwise,even_0 := even_0 + 1otherwise,if s[i] is same as '1', thenodd_1 := odd_1 + 1otherwise,odd_0 := odd_0 + 1 for i in range 0 to size of s - 1, do if i is even, thenif s[i] is same as '1', theneven_1 := even_1 + 1otherwise,even_0 := even_0 + 1 if i is even, then if s[i] is same as '1', theneven_1 := even_1 + 1 if s[i] is same as '1', then even_1 := even_1 + 1 even_1 := even_1 + 1 otherwise,even_0 := even_0 + 1 otherwise, even_0 := even_0 + 1 even_0 := even_0 + 1 otherwise,if s[i] is same as '1', thenodd_1 := odd_1 + 1otherwise,odd_0 := odd_0 + 1 otherwise, if s[i] is same as '1', thenodd_1 := odd_1 + 1 if s[i] is same as '1', then odd_1 := odd_1 + 1 odd_1 := odd_1 + 1 otherwise,odd_0 := odd_0 + 1 otherwise, odd_0 := odd_0 + 1 odd_0 := odd_0 + 1 if (even_1+odd_0) > (even_0+odd_1), thenchange := even_0 + odd_1 if (even_1+odd_0) > (even_0+odd_1), then change := even_0 + odd_1 change := even_0 + odd_1 otherwise,change := even_1 + odd_0 otherwise, change := even_1 + odd_0 change := even_1 + odd_0 return change return change Let us see the following implementation to get better understanding &minnus; Live Demo def solve(s): change = 0 even_1 = 0 even_0 = 0 odd_1 = 0 odd_0 = 0 for i in range(len(s)): if(i%2 == 0): if(s[i]=='1'): even_1 +=1 else: even_0 +=1 else: if(s[i] == '1'): odd_1 +=1 else: odd_0 +=1 if((even_1+odd_0)>(even_0+odd_1)): change = even_0 + odd_1 else: change = even_1 + odd_0 return change s = "11100011" print(solve(s)) "11100011" 3
[ { "code": null, "e": 1314, "s": 1062, "text": "Suppose we have a binary string s. Let us consider an operation where we can flip one bit. The string s is called alternating string if no two adjacent characters are same. We have to find the minimum number of operations needed to make s alternating." }, { "code": null, "e": 1484, "s": 1314, "text": "So, if the input is like s = \"11100011\", then the output will be 3 because if we flip bits at position 1, 4 and 7, then, it will be \"10101010\", then all are alternating." }, { "code": null, "e": 1528, "s": 1484, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1540, "s": 1528, "text": "change := 0" }, { "code": null, "e": 1552, "s": 1540, "text": "change := 0" }, { "code": null, "e": 1577, "s": 1552, "text": "even_1 := 0, even_0 := 0" }, { "code": null, "e": 1602, "s": 1577, "text": "even_1 := 0, even_0 := 0" }, { "code": null, "e": 1625, "s": 1602, "text": "odd_1 := 0, odd_0 := 0" }, { "code": null, "e": 1648, "s": 1625, "text": "odd_1 := 0, odd_0 := 0" }, { "code": null, "e": 1866, "s": 1648, "text": "for i in range 0 to size of s - 1, doif i is even, thenif s[i] is same as '1', theneven_1 := even_1 + 1otherwise,even_0 := even_0 + 1otherwise,if s[i] is same as '1', thenodd_1 := odd_1 + 1otherwise,odd_0 := odd_0 + 1" }, { "code": null, "e": 1904, "s": 1866, "text": "for i in range 0 to size of s - 1, do" }, { "code": null, "e": 2001, "s": 1904, "text": "if i is even, thenif s[i] is same as '1', theneven_1 := even_1 + 1otherwise,even_0 := even_0 + 1" }, { "code": null, "e": 2020, "s": 2001, "text": "if i is even, then" }, { "code": null, "e": 2069, "s": 2020, "text": "if s[i] is same as '1', theneven_1 := even_1 + 1" }, { "code": null, "e": 2098, "s": 2069, "text": "if s[i] is same as '1', then" }, { "code": null, "e": 2119, "s": 2098, "text": "even_1 := even_1 + 1" }, { "code": null, "e": 2140, "s": 2119, "text": "even_1 := even_1 + 1" }, { "code": null, "e": 2171, "s": 2140, "text": "otherwise,even_0 := even_0 + 1" }, { "code": null, "e": 2182, "s": 2171, "text": "otherwise," }, { "code": null, "e": 2203, "s": 2182, "text": "even_0 := even_0 + 1" }, { "code": null, "e": 2224, "s": 2203, "text": "even_0 := even_0 + 1" }, { "code": null, "e": 2309, "s": 2224, "text": "otherwise,if s[i] is same as '1', thenodd_1 := odd_1 + 1otherwise,odd_0 := odd_0 + 1" }, { "code": null, "e": 2320, "s": 2309, "text": "otherwise," }, { "code": null, "e": 2367, "s": 2320, "text": "if s[i] is same as '1', thenodd_1 := odd_1 + 1" }, { "code": null, "e": 2396, "s": 2367, "text": "if s[i] is same as '1', then" }, { "code": null, "e": 2415, "s": 2396, "text": "odd_1 := odd_1 + 1" }, { "code": null, "e": 2434, "s": 2415, "text": "odd_1 := odd_1 + 1" }, { "code": null, "e": 2463, "s": 2434, "text": "otherwise,odd_0 := odd_0 + 1" }, { "code": null, "e": 2474, "s": 2463, "text": "otherwise," }, { "code": null, "e": 2493, "s": 2474, "text": "odd_0 := odd_0 + 1" }, { "code": null, "e": 2512, "s": 2493, "text": "odd_0 := odd_0 + 1" }, { "code": null, "e": 2577, "s": 2512, "text": "if (even_1+odd_0) > (even_0+odd_1), thenchange := even_0 + odd_1" }, { "code": null, "e": 2618, "s": 2577, "text": "if (even_1+odd_0) > (even_0+odd_1), then" }, { "code": null, "e": 2643, "s": 2618, "text": "change := even_0 + odd_1" }, { "code": null, "e": 2668, "s": 2643, "text": "change := even_0 + odd_1" }, { "code": null, "e": 2703, "s": 2668, "text": "otherwise,change := even_1 + odd_0" }, { "code": null, "e": 2714, "s": 2703, "text": "otherwise," }, { "code": null, "e": 2739, "s": 2714, "text": "change := even_1 + odd_0" }, { "code": null, "e": 2764, "s": 2739, "text": "change := even_1 + odd_0" }, { "code": null, "e": 2778, "s": 2764, "text": "return change" }, { "code": null, "e": 2792, "s": 2778, "text": "return change" }, { "code": null, "e": 2869, "s": 2792, "text": "Let us see the following implementation to get better understanding &minnus;" }, { "code": null, "e": 2880, "s": 2869, "text": " Live Demo" }, { "code": null, "e": 3347, "s": 2880, "text": "def solve(s):\n change = 0\n even_1 = 0\n even_0 = 0\n odd_1 = 0\n odd_0 = 0\n for i in range(len(s)):\n if(i%2 == 0):\n if(s[i]=='1'):\n even_1 +=1\n else:\n even_0 +=1\n else:\n if(s[i] == '1'):\n odd_1 +=1\n else:\n odd_0 +=1\n if((even_1+odd_0)>(even_0+odd_1)):\n change = even_0 + odd_1\n else:\n change = even_1 + odd_0\n return change\n\ns = \"11100011\"\nprint(solve(s))" }, { "code": null, "e": 3358, "s": 3347, "text": "\"11100011\"" }, { "code": null, "e": 3360, "s": 3358, "text": "3" } ]
\limits - Tex Command
\limit - Used to set limits above/below any token of class OP. { \limit } \limit command is used to set limits above/below any token of class OP. \int_a^b f(x)\,dx ∫abf(x)dx \int\limits_a^b f(x)\,dx ∫abf(x)dx \mathop{x}\limits_0^1 x01 \int_a^b f(x)\,dx ∫abf(x)dx \int_a^b f(x)\,dx \int\limits_a^b f(x)\,dx ∫abf(x)dx \int\limits_a^b f(x)\,dx \mathop{x}\limits_0^1 x01 \mathop{x}\limits_0^1 14 Lectures 52 mins Ashraf Said 11 Lectures 1 hours Ashraf Said 9 Lectures 1 hours Emenwa Global, Ejike IfeanyiChukwu 29 Lectures 2.5 hours Mohammad Nauman 14 Lectures 1 hours Daniel Stern 15 Lectures 47 mins Nishant Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 8049, "s": 7986, "text": "\\limit - Used to set limits above/below any token of class OP." }, { "code": null, "e": 8060, "s": 8049, "text": "{ \\limit }" }, { "code": null, "e": 8132, "s": 8060, "text": "\\limit command is used to set limits above/below any token of class OP." }, { "code": null, "e": 8232, "s": 8132, "text": "\n\\int_a^b f(x)\\,dx\n\n∫abf(x)dx\n\n\n\\int\\limits_a^b f(x)\\,dx\n\n∫abf(x)dx\n\n\n\\mathop{x}\\limits_0^1\n\nx01\n\n\n" }, { "code": null, "e": 8263, "s": 8232, "text": "\\int_a^b f(x)\\,dx\n\n∫abf(x)dx\n\n" }, { "code": null, "e": 8281, "s": 8263, "text": "\\int_a^b f(x)\\,dx" }, { "code": null, "e": 8319, "s": 8281, "text": "\\int\\limits_a^b f(x)\\,dx\n\n∫abf(x)dx\n\n" }, { "code": null, "e": 8344, "s": 8319, "text": "\\int\\limits_a^b f(x)\\,dx" }, { "code": null, "e": 8373, "s": 8344, "text": "\\mathop{x}\\limits_0^1\n\nx01\n\n" }, { "code": null, "e": 8395, "s": 8373, "text": "\\mathop{x}\\limits_0^1" }, { "code": null, "e": 8427, "s": 8395, "text": "\n 14 Lectures \n 52 mins\n" }, { "code": null, "e": 8440, "s": 8427, "text": " Ashraf Said" }, { "code": null, "e": 8473, "s": 8440, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 8486, "s": 8473, "text": " Ashraf Said" }, { "code": null, "e": 8518, "s": 8486, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 8554, "s": 8518, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8589, "s": 8554, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8606, "s": 8589, "text": " Mohammad Nauman" }, { "code": null, "e": 8639, "s": 8606, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8653, "s": 8639, "text": " Daniel Stern" }, { "code": null, "e": 8685, "s": 8653, "text": "\n 15 Lectures \n 47 mins\n" }, { "code": null, "e": 8700, "s": 8685, "text": " Nishant Kumar" }, { "code": null, "e": 8707, "s": 8700, "text": " Print" }, { "code": null, "e": 8718, "s": 8707, "text": " Add Notes" } ]
Working with DataFrames in Julia - GeeksforGeeks
02 Aug, 2021 A Data frame is a two-dimensional data structure that resembles a table, where the columns represent variables and rows contain values for those variables. It is mutable and can hold various data types. Julia is a high performance, dynamic programming language which has a high-level syntax. The DataFrame package in Julia gives an ability to create and use data frames to manipulate data for data science and machine learning purposes. To do this, you must gain enough knowledge about data frames in Julia. To know more about the Data Frame package, visit official documentation. Data frame package for Julia must be installed in order to use data frames. Type the following commands in the Julia command prompt and click enter to install the data frame package: using Pkg Pkg.add("DataFrames") The end of the installation process should appear like in the image shown below: Now that you have installed the data frame package, you can create a data frame in various ways. You can simply create a data frame using the DataFrame() function. You can mention the columns and their values in between the brackets of the DataFrame() function as the argument and run it as shown below. Before this you have to tell Julia that you are going to use data frames by using the command ‘using DataFrames‘. Example 1: python3 # Creating a data frameusing DataFrames df = DataFrame(A = 1:5, B = ["A", "E", "I", "O", "U"], C = ["A", "B", "C", "D", "E"]) Output: You can also create an empty data frame and fill in the columns separately as shown below. Example 2: python3 # Creating a data frame by adding columns separatelydf = Dataframe() df.C = 1:5df.D = ["A", "E", "I", "O", "U"]df Output: Another method for creating a data frame is to add rows to an empty data frame one by one with the push!() function. You will have to declare the type of the columns before inserting the rows. Example 3: python3 # Creating a data frame by adding rows separatelydf = Dataframe(E = Int[], F = String[]) push!(df, (1, "A"))push!(df, (2, "E"))push!(df, (3, "I"))push!(df, (4, "O"))push!(df, (5, "U"))df Output: Now that you have created the data frame, it can be explored. We will be using the data frame which was created first with the columns ‘A’, ‘B’ and ‘C’. To access the first or last few rows you can use the first(DataFrame, rows) or last(DataFrame, rows) functions respectively where ‘rows’ represent the number of rows you want to access.Example 1: python3 # Selecting the first two rows of the data framefirst(df, 2) Output: Example 2: python3 # Selecting the last two rows of the data framelast(df, 2) Output: To select specific number of rows or columns, you can mention the index numbers or variables of the rows or columns you want to access respectively in ‘df[:, :]’ as shown below. Example 3: python3 # Selecting the 3rd row of the data framedf[:3, :] Output: Example 4: python3 # Selecting column 'B' of the data framedf[:, [:B]] Output: To create a subset of the data frame with specific columns and number of rows you can use the select() function as shown below: Example 1: python3 # Creating a subset with column 'B' and# first 3 rows of the data framefirst(select(df, :B ), 3) Output: You can also create a subset excluding a specific column with the select() as shown below. Example 2: python3 # Creating a subset with first 4 rows and# excluding column 'B' of the data framefirst(select(df, Not(:B)), 4) Output: A subset of a data frame can also be easily created with specific rows and columns as shown below. Example 3: python3 # Creating a subset with 2nd, 3rd and 4th rows# and 'B', 'C' columns of the data framedf[2:4, [:B, :C]] Output: Data can be replaced with some other data in a data frame using various functions. To perform replacement operations in a data frame you can simply use the replace!() function. Example 1: python3 # Replacing the number 4 with 7 in the column 'A'replace !(df.A, 4 => 7)df Output: Replacement operations on multiple columns can be performed using the broadcasting syntax which creates a subset as shown below. Example 2: python3 # Replacing the character 'E' with 'None'# in the columns 'B' and 'C'df[:, [:B, :C]] .= ifelse.(df[!, [:B, :C]] .== "E", "None", df[!, [:B, :C]])df Output: Replacement operation for the full data frame can be performed as shown below. Example 3: python3 # Replacing the character 'A' with 'E' in the data framedf .= ifelse.(df .== "A", "E", df) Output: Here every ‘A’ is replaced with ‘E. New rows can be added to the end of a data frame by using push!() function. Example 1: python3 # Adding a new column to the end of the data framepush !(df, [6 "None" "F"]) Output: A column can be added to a specific position in a data frame by using the insert!() function. Example 2: python3 # Adding a new column to the 3rd position# of the data frameinsert !(df, 3, ["Q", "W", "E", "R", "T", "Y"], :D) Output: You can also add a column by creating an array of elements you want in the column and add it to the end of the data frame as shown below. Example 3: python3 # Adding a new column in the# last position of the data framearr = [2, 3, 5, 7, 11, 13]df[:E] = arrdf Output: A specific row from a data frame can be deleted using the deleterows!() function.Example 1: python3 # Deleting the 4th row of the data framedeleterows !(df, 4) Output: A column can be deleted using the deletecols!() function. Example 2: python3 # Deleting the 3rd column of the data framedeletecols !(df, 3) Output: Here the column ‘D’, which is the 3rd column had been deleted. Multiple data frames are created here to represent the implementation of merging operations.Example 1: python3 # Creating new data framesdf2 = DataFrame(F =["A", "E", "I", "O", "U"], G =["G", "E", "E", "K", "S"])df4 = DataFrame(H =["G", "R", "E", "A", "T"]) Output: You can merge these two new data frames with the first one using the concatenating function hcat(). This function merges data frames horizontally, note that all of the data frames should contain the same number of rows when merging horizontally. Example 2: python3 # Merging the created data frames horizontallyhcat(df, df2, df4) Output: vcat() concatenating function can be used to merge data frames vertically, hence to represent that data frames with the same number and names of the columns as the first data frame are created. Example 3: python3 # Creating new data framesdf3 = DataFrame(A = 7, B ="O", C ="G", E = 17)df5 = DataFrame(A = 8, B ="None", C ="H", E = 19) # Merging the created dataframes verticallyvcat(df, df3, df5) Output: Basic data frames with manually entered data were used here. Many more operations can be done with many functions for CSV files containing huge amounts of data for analysis. sweetyty arorakashish0911 julia-DataFrames Picked Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Vectors in Julia String concatenation in Julia Getting rounded value of a number in Julia - round() Method Storing Output on a File in Julia Reshaping array dimensions in Julia | Array reshape() Method Manipulating matrices in Julia Comments in Julia while loop in Julia Formatting of Strings in Julia Tuples in Julia
[ { "code": null, "e": 24356, "s": 24328, "text": "\n02 Aug, 2021" }, { "code": null, "e": 24559, "s": 24356, "text": "A Data frame is a two-dimensional data structure that resembles a table, where the columns represent variables and rows contain values for those variables. It is mutable and can hold various data types." }, { "code": null, "e": 24864, "s": 24559, "text": "Julia is a high performance, dynamic programming language which has a high-level syntax. The DataFrame package in Julia gives an ability to create and use data frames to manipulate data for data science and machine learning purposes. To do this, you must gain enough knowledge about data frames in Julia." }, { "code": null, "e": 24938, "s": 24864, "text": "To know more about the Data Frame package, visit official documentation. " }, { "code": null, "e": 25121, "s": 24938, "text": "Data frame package for Julia must be installed in order to use data frames. Type the following commands in the Julia command prompt and click enter to install the data frame package:" }, { "code": null, "e": 25154, "s": 25121, "text": "using Pkg\nPkg.add(\"DataFrames\") " }, { "code": null, "e": 25235, "s": 25154, "text": "The end of the installation process should appear like in the image shown below:" }, { "code": null, "e": 25332, "s": 25235, "text": "Now that you have installed the data frame package, you can create a data frame in various ways." }, { "code": null, "e": 25653, "s": 25332, "text": "You can simply create a data frame using the DataFrame() function. You can mention the columns and their values in between the brackets of the DataFrame() function as the argument and run it as shown below. Before this you have to tell Julia that you are going to use data frames by using the command ‘using DataFrames‘." }, { "code": null, "e": 25666, "s": 25653, "text": "Example 1: " }, { "code": null, "e": 25674, "s": 25666, "text": "python3" }, { "code": "# Creating a data frameusing DataFrames df = DataFrame(A = 1:5, B = [\"A\", \"E\", \"I\", \"O\", \"U\"], C = [\"A\", \"B\", \"C\", \"D\", \"E\"])", "e": 25823, "s": 25674, "text": null }, { "code": null, "e": 25833, "s": 25823, "text": "Output: " }, { "code": null, "e": 25926, "s": 25835, "text": "You can also create an empty data frame and fill in the columns separately as shown below." }, { "code": null, "e": 25938, "s": 25926, "text": "Example 2: " }, { "code": null, "e": 25946, "s": 25938, "text": "python3" }, { "code": "# Creating a data frame by adding columns separatelydf = Dataframe() df.C = 1:5df.D = [\"A\", \"E\", \"I\", \"O\", \"U\"]df", "e": 26060, "s": 25946, "text": null }, { "code": null, "e": 26070, "s": 26060, "text": "Output: " }, { "code": null, "e": 26265, "s": 26072, "text": "Another method for creating a data frame is to add rows to an empty data frame one by one with the push!() function. You will have to declare the type of the columns before inserting the rows." }, { "code": null, "e": 26277, "s": 26265, "text": "Example 3: " }, { "code": null, "e": 26285, "s": 26277, "text": "python3" }, { "code": "# Creating a data frame by adding rows separatelydf = Dataframe(E = Int[], F = String[]) push!(df, (1, \"A\"))push!(df, (2, \"E\"))push!(df, (3, \"I\"))push!(df, (4, \"O\"))push!(df, (5, \"U\"))df", "e": 26472, "s": 26285, "text": null }, { "code": null, "e": 26482, "s": 26472, "text": "Output: " }, { "code": null, "e": 26835, "s": 26484, "text": "Now that you have created the data frame, it can be explored. We will be using the data frame which was created first with the columns ‘A’, ‘B’ and ‘C’. To access the first or last few rows you can use the first(DataFrame, rows) or last(DataFrame, rows) functions respectively where ‘rows’ represent the number of rows you want to access.Example 1: " }, { "code": null, "e": 26843, "s": 26835, "text": "python3" }, { "code": "# Selecting the first two rows of the data framefirst(df, 2)", "e": 26904, "s": 26843, "text": null }, { "code": null, "e": 26914, "s": 26904, "text": "Output: " }, { "code": null, "e": 26926, "s": 26914, "text": "Example 2: " }, { "code": null, "e": 26934, "s": 26926, "text": "python3" }, { "code": "# Selecting the last two rows of the data framelast(df, 2)", "e": 26993, "s": 26934, "text": null }, { "code": null, "e": 27003, "s": 26993, "text": "Output: " }, { "code": null, "e": 27183, "s": 27005, "text": "To select specific number of rows or columns, you can mention the index numbers or variables of the rows or columns you want to access respectively in ‘df[:, :]’ as shown below." }, { "code": null, "e": 27195, "s": 27183, "text": "Example 3: " }, { "code": null, "e": 27203, "s": 27195, "text": "python3" }, { "code": "# Selecting the 3rd row of the data framedf[:3, :]", "e": 27254, "s": 27203, "text": null }, { "code": null, "e": 27264, "s": 27254, "text": "Output: " }, { "code": null, "e": 27276, "s": 27264, "text": "Example 4: " }, { "code": null, "e": 27284, "s": 27276, "text": "python3" }, { "code": "# Selecting column 'B' of the data framedf[:, [:B]]", "e": 27336, "s": 27284, "text": null }, { "code": null, "e": 27346, "s": 27336, "text": "Output: " }, { "code": null, "e": 27488, "s": 27348, "text": "To create a subset of the data frame with specific columns and number of rows you can use the select() function as shown below: Example 1: " }, { "code": null, "e": 27496, "s": 27488, "text": "python3" }, { "code": "# Creating a subset with column 'B' and# first 3 rows of the data framefirst(select(df, :B ), 3)", "e": 27593, "s": 27496, "text": null }, { "code": null, "e": 27603, "s": 27593, "text": "Output: " }, { "code": null, "e": 27696, "s": 27605, "text": "You can also create a subset excluding a specific column with the select() as shown below." }, { "code": null, "e": 27708, "s": 27696, "text": "Example 2: " }, { "code": null, "e": 27716, "s": 27708, "text": "python3" }, { "code": "# Creating a subset with first 4 rows and# excluding column 'B' of the data framefirst(select(df, Not(:B)), 4)", "e": 27827, "s": 27716, "text": null }, { "code": null, "e": 27837, "s": 27827, "text": "Output: " }, { "code": null, "e": 27938, "s": 27839, "text": "A subset of a data frame can also be easily created with specific rows and columns as shown below." }, { "code": null, "e": 27950, "s": 27938, "text": "Example 3: " }, { "code": null, "e": 27958, "s": 27950, "text": "python3" }, { "code": "# Creating a subset with 2nd, 3rd and 4th rows# and 'B', 'C' columns of the data framedf[2:4, [:B, :C]]", "e": 28062, "s": 27958, "text": null }, { "code": null, "e": 28072, "s": 28062, "text": "Output: " }, { "code": null, "e": 28263, "s": 28074, "text": "Data can be replaced with some other data in a data frame using various functions. To perform replacement operations in a data frame you can simply use the replace!() function. Example 1: " }, { "code": null, "e": 28271, "s": 28263, "text": "python3" }, { "code": "# Replacing the number 4 with 7 in the column 'A'replace !(df.A, 4 => 7)df", "e": 28346, "s": 28271, "text": null }, { "code": null, "e": 28356, "s": 28346, "text": "Output: " }, { "code": null, "e": 28487, "s": 28358, "text": "Replacement operations on multiple columns can be performed using the broadcasting syntax which creates a subset as shown below." }, { "code": null, "e": 28499, "s": 28487, "text": "Example 2: " }, { "code": null, "e": 28507, "s": 28499, "text": "python3" }, { "code": "# Replacing the character 'E' with 'None'# in the columns 'B' and 'C'df[:, [:B, :C]] .= ifelse.(df[!, [:B, :C]] .== \"E\", \"None\", df[!, [:B, :C]])df", "e": 28655, "s": 28507, "text": null }, { "code": null, "e": 28665, "s": 28655, "text": "Output: " }, { "code": null, "e": 28746, "s": 28667, "text": "Replacement operation for the full data frame can be performed as shown below." }, { "code": null, "e": 28758, "s": 28746, "text": "Example 3: " }, { "code": null, "e": 28766, "s": 28758, "text": "python3" }, { "code": "# Replacing the character 'A' with 'E' in the data framedf .= ifelse.(df .== \"A\", \"E\", df)", "e": 28857, "s": 28766, "text": null }, { "code": null, "e": 28867, "s": 28857, "text": "Output: " }, { "code": null, "e": 28905, "s": 28869, "text": "Here every ‘A’ is replaced with ‘E." }, { "code": null, "e": 28995, "s": 28907, "text": "New rows can be added to the end of a data frame by using push!() function. Example 1: " }, { "code": null, "e": 29003, "s": 28995, "text": "python3" }, { "code": "# Adding a new column to the end of the data framepush !(df, [6 \"None\" \"F\"])", "e": 29080, "s": 29003, "text": null }, { "code": null, "e": 29090, "s": 29080, "text": "Output: " }, { "code": null, "e": 29186, "s": 29092, "text": "A column can be added to a specific position in a data frame by using the insert!() function." }, { "code": null, "e": 29198, "s": 29186, "text": "Example 2: " }, { "code": null, "e": 29206, "s": 29198, "text": "python3" }, { "code": "# Adding a new column to the 3rd position# of the data frameinsert !(df, 3, [\"Q\", \"W\", \"E\", \"R\", \"T\", \"Y\"], :D)", "e": 29318, "s": 29206, "text": null }, { "code": null, "e": 29328, "s": 29318, "text": "Output: " }, { "code": null, "e": 29468, "s": 29330, "text": "You can also add a column by creating an array of elements you want in the column and add it to the end of the data frame as shown below." }, { "code": null, "e": 29480, "s": 29468, "text": "Example 3: " }, { "code": null, "e": 29488, "s": 29480, "text": "python3" }, { "code": "# Adding a new column in the# last position of the data framearr = [2, 3, 5, 7, 11, 13]df[:E] = arrdf", "e": 29590, "s": 29488, "text": null }, { "code": null, "e": 29600, "s": 29590, "text": "Output: " }, { "code": null, "e": 29695, "s": 29602, "text": "A specific row from a data frame can be deleted using the deleterows!() function.Example 1: " }, { "code": null, "e": 29703, "s": 29695, "text": "python3" }, { "code": "# Deleting the 4th row of the data framedeleterows !(df, 4)", "e": 29763, "s": 29703, "text": null }, { "code": null, "e": 29773, "s": 29763, "text": "Output: " }, { "code": null, "e": 29833, "s": 29775, "text": "A column can be deleted using the deletecols!() function." }, { "code": null, "e": 29845, "s": 29833, "text": "Example 2: " }, { "code": null, "e": 29853, "s": 29845, "text": "python3" }, { "code": "# Deleting the 3rd column of the data framedeletecols !(df, 3)", "e": 29916, "s": 29853, "text": null }, { "code": null, "e": 29926, "s": 29916, "text": "Output: " }, { "code": null, "e": 29991, "s": 29928, "text": "Here the column ‘D’, which is the 3rd column had been deleted." }, { "code": null, "e": 30097, "s": 29993, "text": "Multiple data frames are created here to represent the implementation of merging operations.Example 1: " }, { "code": null, "e": 30105, "s": 30097, "text": "python3" }, { "code": "# Creating new data framesdf2 = DataFrame(F =[\"A\", \"E\", \"I\", \"O\", \"U\"], G =[\"G\", \"E\", \"E\", \"K\", \"S\"])df4 = DataFrame(H =[\"G\", \"R\", \"E\", \"A\", \"T\"])", "e": 30267, "s": 30105, "text": null }, { "code": null, "e": 30277, "s": 30267, "text": "Output: " }, { "code": null, "e": 30525, "s": 30279, "text": "You can merge these two new data frames with the first one using the concatenating function hcat(). This function merges data frames horizontally, note that all of the data frames should contain the same number of rows when merging horizontally." }, { "code": null, "e": 30537, "s": 30525, "text": "Example 2: " }, { "code": null, "e": 30545, "s": 30537, "text": "python3" }, { "code": "# Merging the created data frames horizontallyhcat(df, df2, df4)", "e": 30610, "s": 30545, "text": null }, { "code": null, "e": 30620, "s": 30610, "text": "Output: " }, { "code": null, "e": 30816, "s": 30622, "text": "vcat() concatenating function can be used to merge data frames vertically, hence to represent that data frames with the same number and names of the columns as the first data frame are created." }, { "code": null, "e": 30828, "s": 30816, "text": "Example 3: " }, { "code": null, "e": 30836, "s": 30828, "text": "python3" }, { "code": "# Creating new data framesdf3 = DataFrame(A = 7, B =\"O\", C =\"G\", E = 17)df5 = DataFrame(A = 8, B =\"None\", C =\"H\", E = 19) # Merging the created dataframes verticallyvcat(df, df3, df5)", "e": 31020, "s": 30836, "text": null }, { "code": null, "e": 31030, "s": 31020, "text": "Output: " }, { "code": null, "e": 31206, "s": 31032, "text": "Basic data frames with manually entered data were used here. Many more operations can be done with many functions for CSV files containing huge amounts of data for analysis." }, { "code": null, "e": 31215, "s": 31206, "text": "sweetyty" }, { "code": null, "e": 31232, "s": 31215, "text": "arorakashish0911" }, { "code": null, "e": 31249, "s": 31232, "text": "julia-DataFrames" }, { "code": null, "e": 31256, "s": 31249, "text": "Picked" }, { "code": null, "e": 31262, "s": 31256, "text": "Julia" }, { "code": null, "e": 31360, "s": 31262, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31377, "s": 31360, "text": "Vectors in Julia" }, { "code": null, "e": 31407, "s": 31377, "text": "String concatenation in Julia" }, { "code": null, "e": 31467, "s": 31407, "text": "Getting rounded value of a number in Julia - round() Method" }, { "code": null, "e": 31501, "s": 31467, "text": "Storing Output on a File in Julia" }, { "code": null, "e": 31562, "s": 31501, "text": "Reshaping array dimensions in Julia | Array reshape() Method" }, { "code": null, "e": 31593, "s": 31562, "text": "Manipulating matrices in Julia" }, { "code": null, "e": 31611, "s": 31593, "text": "Comments in Julia" }, { "code": null, "e": 31631, "s": 31611, "text": "while loop in Julia" }, { "code": null, "e": 31662, "s": 31631, "text": "Formatting of Strings in Julia" } ]
MapReduce - API
In this chapter, we will take a close look at the classes and their methods that are involved in the operations of MapReduce programming. We will primarily keep our focus on the following − JobContext Interface Job Class Mapper Class Reducer Class The JobContext interface is the super interface for all the classes, which defines different jobs in MapReduce. It gives you a read-only view of the job that is provided to the tasks while they are running. The following are the sub-interfaces of JobContext interface. Defines the context that is given to the Mapper. Defines the context that is passed to the Reducer. Job class is the main class that implements the JobContext interface. The Job class is the most important class in the MapReduce API. It allows the user to configure the job, submit it, control its execution, and query the state. The set methods only work until the job is submitted, afterwards they will throw an IllegalStateException. Normally, the user creates the application, describes the various facets of the job, and then submits the job and monitors its progress. Here is an example of how to submit a job − // Create a new Job Job job = new Job(new Configuration()); job.setJarByClass(MyJob.class); // Specify various job-specific parameters job.setJobName("myjob"); job.setInputPath(new Path("in")); job.setOutputPath(new Path("out")); job.setMapperClass(MyJob.MyMapper.class); job.setReducerClass(MyJob.MyReducer.class); // Submit the job, then poll for progress until the job is complete job.waitForCompletion(true); Following are the constructor summary of Job class. Some of the important methods of Job class are as follows − User-specified job name. Returns the current state of the Job. Checks if the job is finished or not. Sets the InputFormat for the job. Sets the user-specified job name. Sets the Output Format for the job. Sets the Mapper for the job. Sets the Reducer for the job. Sets the Partitioner for the job. Sets the Combiner for the job. The Mapper class defines the Map job. Maps input key-value pairs to a set of intermediate key-value pairs. Maps are the individual tasks that transform the input records into intermediate records. The transformed intermediate records need not be of the same type as the input records. A given input pair may map to zero or many output pairs. map is the most prominent method of the Mapper class. The syntax is defined below − map(KEYIN key, VALUEIN value, org.apache.hadoop.mapreduce.Mapper.Context context) This method is called once for each key-value pair in the input split. The Reducer class defines the Reduce job in MapReduce. It reduces a set of intermediate values that share a key to a smaller set of values. Reducer implementations can access the Configuration for a job via the JobContext.getConfiguration() method. A Reducer has three primary phases − Shuffle, Sort, and Reduce. Shuffle − The Reducer copies the sorted output from each Mapper using HTTP across the network. Shuffle − The Reducer copies the sorted output from each Mapper using HTTP across the network. Sort − The framework merge-sorts the Reducer inputs by keys (since different Mappers may have output the same key). The shuffle and sort phases occur simultaneously, i.e., while outputs are being fetched, they are merged. Sort − The framework merge-sorts the Reducer inputs by keys (since different Mappers may have output the same key). The shuffle and sort phases occur simultaneously, i.e., while outputs are being fetched, they are merged. Reduce − In this phase the reduce (Object, Iterable, Context) method is called for each <key, (collection of values)> in the sorted inputs. Reduce − In this phase the reduce (Object, Iterable, Context) method is called for each <key, (collection of values)> in the sorted inputs. reduce is the most prominent method of the Reducer class. The syntax is defined below − reduce(KEYIN key, Iterable<VALUEIN> values, org.apache.hadoop.mapreduce.Reducer.Context context) This method is called once for each key on the collection of key-value pairs. 21 Lectures 2.5 hours Zach Miller 17 Lectures 2 hours Lisa Newton 37 Lectures 2 hours Sentinel | 9 63 Lectures 7 hours Stevdza-San 16 Lectures 1.5 hours Paul Nicoara 17 Lectures 50 mins Damtew Engida Print Add Notes Bookmark this page
[ { "code": null, "e": 1980, "s": 1790, "text": "In this chapter, we will take a close look at the classes and their methods that are involved in the operations of MapReduce programming. We will primarily keep our focus on the following −" }, { "code": null, "e": 2001, "s": 1980, "text": "JobContext Interface" }, { "code": null, "e": 2011, "s": 2001, "text": "Job Class" }, { "code": null, "e": 2024, "s": 2011, "text": "Mapper Class" }, { "code": null, "e": 2038, "s": 2024, "text": "Reducer Class" }, { "code": null, "e": 2245, "s": 2038, "text": "The JobContext interface is the super interface for all the classes, which defines different jobs in MapReduce. It gives you a read-only view of the job that is provided to the tasks while they are running." }, { "code": null, "e": 2307, "s": 2245, "text": "The following are the sub-interfaces of JobContext interface." }, { "code": null, "e": 2356, "s": 2307, "text": "Defines the context that is given to the Mapper." }, { "code": null, "e": 2407, "s": 2356, "text": "Defines the context that is passed to the Reducer." }, { "code": null, "e": 2477, "s": 2407, "text": "Job class is the main class that implements the JobContext interface." }, { "code": null, "e": 2744, "s": 2477, "text": "The Job class is the most important class in the MapReduce API. It allows the user to configure the job, submit it, control its execution, and query the state. The set methods only work until the job is submitted, afterwards they will throw an IllegalStateException." }, { "code": null, "e": 2881, "s": 2744, "text": "Normally, the user creates the application, describes the various facets of the job, and then submits the job and monitors its progress." }, { "code": null, "e": 2925, "s": 2881, "text": "Here is an example of how to submit a job −" }, { "code": null, "e": 3342, "s": 2925, "text": "// Create a new Job\nJob job = new Job(new Configuration());\njob.setJarByClass(MyJob.class);\n\n// Specify various job-specific parameters\njob.setJobName(\"myjob\");\njob.setInputPath(new Path(\"in\"));\njob.setOutputPath(new Path(\"out\"));\n\njob.setMapperClass(MyJob.MyMapper.class);\njob.setReducerClass(MyJob.MyReducer.class);\n\n// Submit the job, then poll for progress until the job is complete\njob.waitForCompletion(true);\n" }, { "code": null, "e": 3394, "s": 3342, "text": "Following are the constructor summary of Job class." }, { "code": null, "e": 3454, "s": 3394, "text": "Some of the important methods of Job class are as follows −" }, { "code": null, "e": 3479, "s": 3454, "text": "User-specified job name." }, { "code": null, "e": 3517, "s": 3479, "text": "Returns the current state of the Job." }, { "code": null, "e": 3555, "s": 3517, "text": "Checks if the job is finished or not." }, { "code": null, "e": 3589, "s": 3555, "text": "Sets the InputFormat for the job." }, { "code": null, "e": 3623, "s": 3589, "text": "Sets the user-specified job name." }, { "code": null, "e": 3659, "s": 3623, "text": "Sets the Output Format for the job." }, { "code": null, "e": 3688, "s": 3659, "text": "Sets the Mapper for the job." }, { "code": null, "e": 3718, "s": 3688, "text": "Sets the Reducer for the job." }, { "code": null, "e": 3752, "s": 3718, "text": "Sets the Partitioner for the job." }, { "code": null, "e": 3783, "s": 3752, "text": "Sets the Combiner for the job." }, { "code": null, "e": 4125, "s": 3783, "text": "The Mapper class defines the Map job. Maps input key-value pairs to a set of intermediate key-value pairs. Maps are the individual tasks that transform the input records into intermediate records. The transformed intermediate records need not be of the same type as the input records. A given input pair may map to zero or many output pairs." }, { "code": null, "e": 4210, "s": 4125, "text": "map is the most prominent method of the Mapper class. The syntax is defined below −" }, { "code": null, "e": 4292, "s": 4210, "text": "map(KEYIN key, VALUEIN value, org.apache.hadoop.mapreduce.Mapper.Context context)" }, { "code": null, "e": 4363, "s": 4292, "text": "This method is called once for each key-value pair in the input split." }, { "code": null, "e": 4676, "s": 4363, "text": "The Reducer class defines the Reduce job in MapReduce. It reduces a set of intermediate values that share a key to a smaller set of values. Reducer implementations can access the Configuration for a job via the JobContext.getConfiguration() method. A Reducer has three primary phases − Shuffle, Sort, and Reduce." }, { "code": null, "e": 4771, "s": 4676, "text": "Shuffle − The Reducer copies the sorted output from each Mapper using HTTP across the network." }, { "code": null, "e": 4866, "s": 4771, "text": "Shuffle − The Reducer copies the sorted output from each Mapper using HTTP across the network." }, { "code": null, "e": 5088, "s": 4866, "text": "Sort − The framework merge-sorts the Reducer inputs by keys (since different Mappers may have output the same key). The shuffle and sort phases occur simultaneously, i.e., while outputs are being fetched, they are merged." }, { "code": null, "e": 5310, "s": 5088, "text": "Sort − The framework merge-sorts the Reducer inputs by keys (since different Mappers may have output the same key). The shuffle and sort phases occur simultaneously, i.e., while outputs are being fetched, they are merged." }, { "code": null, "e": 5450, "s": 5310, "text": "Reduce − In this phase the reduce (Object, Iterable, Context) method is called for each <key, (collection of values)> in the sorted inputs." }, { "code": null, "e": 5590, "s": 5450, "text": "Reduce − In this phase the reduce (Object, Iterable, Context) method is called for each <key, (collection of values)> in the sorted inputs." }, { "code": null, "e": 5679, "s": 5590, "text": "reduce is the most prominent method of the Reducer class. The syntax is defined below − " }, { "code": null, "e": 5776, "s": 5679, "text": "reduce(KEYIN key, Iterable<VALUEIN> values, org.apache.hadoop.mapreduce.Reducer.Context context)" }, { "code": null, "e": 5854, "s": 5776, "text": "This method is called once for each key on the collection of key-value pairs." }, { "code": null, "e": 5889, "s": 5854, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5902, "s": 5889, "text": " Zach Miller" }, { "code": null, "e": 5935, "s": 5902, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 5948, "s": 5935, "text": " Lisa Newton" }, { "code": null, "e": 5981, "s": 5948, "text": "\n 37 Lectures \n 2 hours \n" }, { "code": null, "e": 5995, "s": 5981, "text": " Sentinel | 9" }, { "code": null, "e": 6028, "s": 5995, "text": "\n 63 Lectures \n 7 hours \n" }, { "code": null, "e": 6041, "s": 6028, "text": " Stevdza-San" }, { "code": null, "e": 6076, "s": 6041, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6090, "s": 6076, "text": " Paul Nicoara" }, { "code": null, "e": 6122, "s": 6090, "text": "\n 17 Lectures \n 50 mins\n" }, { "code": null, "e": 6137, "s": 6122, "text": " Damtew Engida" }, { "code": null, "e": 6144, "s": 6137, "text": " Print" }, { "code": null, "e": 6155, "s": 6144, "text": " Add Notes" } ]
HTML template Tag - GeeksforGeeks
15 Dec, 2021 The <template> tag in HTML is used to store the HTML code fragments, which can be cloned and inserted in an HTML document. The content of the tag is hidden from clients being stored on the client-side. It is inserted until activated using JavaScript. Use JavaScript to get the content from a template, and add it to the web page. Syntax: <template> Contents </template> Note: The <template> tag is new in HTML 5. Attributes: This tag supports the global attributes in HTML. Example 1: In this example, we have an unordered list of the courses that we have hidden to display using the <template> tag in HTML. HTML <!DOCTYPE html><html><body> <h1>GeeksforGeeks</h1> <h3>HTML template tag</h3> <p> Content inside a template tag will be hidden from the client. </p> <!-- Html script tag starts here --> <template> <h2>GeeksforGeeks: A computer science portal</h2> <h4>GeeksforGeeks Offline Courses</h4> <ul> <li>DSA</li> <li>Placement & Interview Preparation</li> <li>Web Development</li> <li>Algorithms & basic programming</li> </ul> </template> <!-- Html template tag ends here --> <p>End of the example of template tag</p></body></html> Output: HTML template tag Example 2: This example uses a template tag, and it hides the content within the template tag. HTML <!DOCTYPE html><html><body> <h1>GeeksforGeeks</h1> <h3>HTML template tag</h3> <p> Content inside a template tag is hidden from the client. </p> <!-- html script tag starts here --> <template> <h2>GeeksforGeeks: A computer science portal</h2> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20210922100958/gfg3-300x300.png"> Content Writer: <input type="text" placeholder="author name"> </template> <!-- html template tag ends here --> <p>End of the example of template tag</p> </body></html> Output: HTML template tag Example 3: This example illustrates the uses of JavaScript to display the template tag content. HTML <!DOCTYPE html><html><body> <h1>GeeksforGeeks</h1> <h3>HTML template tag</h3> <p> Click the button to get the content from a template, and display it in the web page. </p> <button onclick="myGeeks()"> Show content </button> <!-- Html template tag starts here --> <template> <h2>GeeksforGeeks: A computer science portal</h2> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20210922100958/gfg3-300x300.png"> <br> Content Writer: <input type="text" placeholder="author name"> </template> <!-- Html template tag ends here --> <!-- Script to display the content of template tag --> <script> function myGeeks() { var t = document.getElementsByTagName("template")[0]; var clone = t.content.cloneNode(true); document.body.appendChild(clone); } </script></body></html> Output: HTML template tag Supported Browsers: Google Chrome 93.0 & above Microsoft Edge 93.0 Firefox 92.0 & above Safari 14.1 Opera 79.0 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. arorakashish0911 shubhamyadav4 bhaskargeeksforgeeks HTML-Tags HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments REST API (Introduction) Design a web page using HTML and CSS Angular File Upload Form validation using jQuery How to auto-resize an image to fit a div container using CSS? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript How to calculate the number of days between two dates in javascript?
[ { "code": null, "e": 24919, "s": 24891, "text": "\n15 Dec, 2021" }, { "code": null, "e": 25249, "s": 24919, "text": "The <template> tag in HTML is used to store the HTML code fragments, which can be cloned and inserted in an HTML document. The content of the tag is hidden from clients being stored on the client-side. It is inserted until activated using JavaScript. Use JavaScript to get the content from a template, and add it to the web page." }, { "code": null, "e": 25257, "s": 25249, "text": "Syntax:" }, { "code": null, "e": 25289, "s": 25257, "text": "<template> Contents </template>" }, { "code": null, "e": 25332, "s": 25289, "text": "Note: The <template> tag is new in HTML 5." }, { "code": null, "e": 25393, "s": 25332, "text": "Attributes: This tag supports the global attributes in HTML." }, { "code": null, "e": 25527, "s": 25393, "text": "Example 1: In this example, we have an unordered list of the courses that we have hidden to display using the <template> tag in HTML." }, { "code": null, "e": 25532, "s": 25527, "text": "HTML" }, { "code": "<!DOCTYPE html><html><body> <h1>GeeksforGeeks</h1> <h3>HTML template tag</h3> <p> Content inside a template tag will be hidden from the client. </p> <!-- Html script tag starts here --> <template> <h2>GeeksforGeeks: A computer science portal</h2> <h4>GeeksforGeeks Offline Courses</h4> <ul> <li>DSA</li> <li>Placement & Interview Preparation</li> <li>Web Development</li> <li>Algorithms & basic programming</li> </ul> </template> <!-- Html template tag ends here --> <p>End of the example of template tag</p></body></html>", "e": 26175, "s": 25532, "text": null }, { "code": null, "e": 26184, "s": 26175, "text": " Output:" }, { "code": null, "e": 26202, "s": 26184, "text": "HTML template tag" }, { "code": null, "e": 26297, "s": 26202, "text": "Example 2: This example uses a template tag, and it hides the content within the template tag." }, { "code": null, "e": 26302, "s": 26297, "text": "HTML" }, { "code": "<!DOCTYPE html><html><body> <h1>GeeksforGeeks</h1> <h3>HTML template tag</h3> <p> Content inside a template tag is hidden from the client. </p> <!-- html script tag starts here --> <template> <h2>GeeksforGeeks: A computer science portal</h2> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210922100958/gfg3-300x300.png\"> Content Writer: <input type=\"text\" placeholder=\"author name\"> </template> <!-- html template tag ends here --> <p>End of the example of template tag</p> </body></html>", "e": 26912, "s": 26302, "text": null }, { "code": null, "e": 26920, "s": 26912, "text": "Output:" }, { "code": null, "e": 26938, "s": 26920, "text": "HTML template tag" }, { "code": null, "e": 27034, "s": 26938, "text": "Example 3: This example illustrates the uses of JavaScript to display the template tag content." }, { "code": null, "e": 27039, "s": 27034, "text": "HTML" }, { "code": "<!DOCTYPE html><html><body> <h1>GeeksforGeeks</h1> <h3>HTML template tag</h3> <p> Click the button to get the content from a template, and display it in the web page. </p> <button onclick=\"myGeeks()\"> Show content </button> <!-- Html template tag starts here --> <template> <h2>GeeksforGeeks: A computer science portal</h2> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210922100958/gfg3-300x300.png\"> <br> Content Writer: <input type=\"text\" placeholder=\"author name\"> </template> <!-- Html template tag ends here --> <!-- Script to display the content of template tag --> <script> function myGeeks() { var t = document.getElementsByTagName(\"template\")[0]; var clone = t.content.cloneNode(true); document.body.appendChild(clone); } </script></body></html>", "e": 27957, "s": 27039, "text": null }, { "code": null, "e": 27965, "s": 27957, "text": "Output:" }, { "code": null, "e": 27983, "s": 27965, "text": "HTML template tag" }, { "code": null, "e": 28004, "s": 27983, "text": "Supported Browsers: " }, { "code": null, "e": 28031, "s": 28004, "text": "Google Chrome 93.0 & above" }, { "code": null, "e": 28051, "s": 28031, "text": "Microsoft Edge 93.0" }, { "code": null, "e": 28072, "s": 28051, "text": "Firefox 92.0 & above" }, { "code": null, "e": 28084, "s": 28072, "text": "Safari 14.1" }, { "code": null, "e": 28095, "s": 28084, "text": "Opera 79.0" }, { "code": null, "e": 28232, "s": 28095, "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": 28249, "s": 28232, "text": "arorakashish0911" }, { "code": null, "e": 28263, "s": 28249, "text": "shubhamyadav4" }, { "code": null, "e": 28284, "s": 28263, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 28294, "s": 28284, "text": "HTML-Tags" }, { "code": null, "e": 28299, "s": 28294, "text": "HTML" }, { "code": null, "e": 28316, "s": 28299, "text": "Web Technologies" }, { "code": null, "e": 28321, "s": 28316, "text": "HTML" }, { "code": null, "e": 28419, "s": 28321, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28428, "s": 28419, "text": "Comments" }, { "code": null, "e": 28441, "s": 28428, "text": "Old Comments" }, { "code": null, "e": 28465, "s": 28441, "text": "REST API (Introduction)" }, { "code": null, "e": 28502, "s": 28465, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28522, "s": 28502, "text": "Angular File Upload" }, { "code": null, "e": 28551, "s": 28522, "text": "Form validation using jQuery" }, { "code": null, "e": 28613, "s": 28551, "text": "How to auto-resize an image to fit a div container using CSS?" }, { "code": null, "e": 28655, "s": 28613, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28688, "s": 28655, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28731, "s": 28688, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28776, "s": 28731, "text": "Convert a string to an integer in JavaScript" } ]
Minimum Sum of Euclidean Distances to all given Points - GeeksforGeeks
11 May, 2021 Given a matrix mat[][] consisting of N pairs of the form {x, y} each denoting coordinates of N points, the task is to find the minimum sum of the Euclidean distances to all points. Examples: Input: mat[][] = { { 0, 1}, { 1, 0 }, { 1, 2 }, { 2, 1 }} Output: 4 Explanation: Average of the set of points, i.e. Centroid = ((0+1+1+2)/4, (1+0+2+1)/4) = (1, 1). Euclidean distance of each point from the centroid are {1, 1, 1, 1} Sum of all distances = 1 + 1 + 1 + 1 = 4Input: mat[][] = { { 1, 1}, { 3, 3 }} Output: 2.82843 Approach: Since the task is to minimize the Euclidean Distance to all points, the idea is to calculate the Median of all the points. Geometric Median generalizes the concept of median to higher dimensions Follow the steps below to solve the problem: Calculate the centroid of all the given coordinates, by getting the average of the points. Find the Euclidean distance of all points from the centroid. Calculate the sum of these distance and print as the answer. Below is the implementation of above approach: C++ Java Python3 C# Javascript // C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate Euclidean distancedouble find(double x, double y, vector<vector<int> >& p){ double mind = 0; for (int i = 0; i < p.size(); i++) { double a = p[i][0], b = p[i][1]; mind += sqrt((x - a) * (x - a) + (y - b) * (y - b)); } return mind;} // Function to calculate the minimum sum// of the euclidean distances to all pointsdouble getMinDistSum(vector<vector<int> >& p){ // Calculate the centroid double x = 0, y = 0; for (int i = 0; i < p.size(); i++) { x += p[i][0]; y += p[i][1]; } x = x / p.size(); y = y / p.size(); // Calculate distance of all // points double mind = find(x, y, p); return mind;} // Driver Codeint main(){ // Initializing the points vector<vector<int> > vec = { { 0, 1 }, { 1, 0 }, { 1, 2 }, { 2, 1 } }; double d = getMinDistSum(vec); cout << d << endl; return 0;} // Java program to implement// the above approachclass GFG{ // Function to calculate Euclidean distancestatic double find(double x, double y, int [][] p){ double mind = 0; for(int i = 0; i < p.length; i++) { double a = p[i][0], b = p[i][1]; mind += Math.sqrt((x - a) * (x - a) + (y - b) * (y - b)); } return mind;} // Function to calculate the minimum sum// of the euclidean distances to all pointsstatic double getMinDistSum(int [][]p){ // Calculate the centroid double x = 0, y = 0; for(int i = 0; i < p.length; i++) { x += p[i][0]; y += p[i][1]; } x = x / p.length; y = y / p.length; // Calculate distance of all // points double mind = find(x, y, p); return mind;} // Driver Codepublic static void main(String[] args){ // Initializing the points int [][]vec = { { 0, 1 }, { 1, 0 }, { 1, 2 }, { 2, 1 } }; double d = getMinDistSum(vec); System.out.print(d + "\n");}} // This code is contributed by Amit Katiyar # Python3 program to implement# the above approachfrom math import sqrt # Function to calculate Euclidean distancedef find(x, y, p): mind = 0 for i in range(len(p)): a = p[i][0] b = p[i][1] mind += sqrt((x - a) * (x - a) + (y - b) * (y - b)) return mind # Function to calculate the minimum sum# of the euclidean distances to all pointsdef getMinDistSum(p): # Calculate the centroid x = 0 y = 0 for i in range(len(p)): x += p[i][0] y += p[i][1] x = x // len(p) y = y // len(p) # Calculate distance of all # points mind = find(x, y, p) return mind # Driver Codeif __name__ == '__main__': # Initializing the points vec = [ [ 0, 1 ], [ 1, 0 ], [ 1, 2 ], [ 2, 1 ] ] d = getMinDistSum(vec) print(int(d)) # This code is contributed by mohit kumar 29 // C# program to implement// the above approachusing System;class GFG{ // Function to calculate Euclidean distancestatic double find(double x, double y, int [,] p){ double mind = 0; for(int i = 0; i < p.GetLength(0); i++) { double a = p[i,0], b = p[i,1]; mind += Math.Sqrt((x - a) * (x - a) + (y - b) * (y - b)); } return mind;} // Function to calculate the minimum sum// of the euclidean distances to all pointsstatic double getMinDistSum(int [,]p){ // Calculate the centroid double x = 0, y = 0; for(int i = 0; i < p.GetLength(0); i++) { x += p[i,0]; y += p[i,1]; } x = x / p.Length; y = y / p.Length; // Calculate distance of all // points double mind = find(x, y, p); return mind;} // Driver Codepublic static void Main(String[] args){ // Initializing the points int [,]vec = { { 0, 1 }, { 1, 0 }, { 1, 2 }, { 2, 1 } }; int d = (int)getMinDistSum(vec); Console.Write(d + "\n");}} // This code is contributed by Rohit_ranjan <script> // JavaScript program for the above approach // Function to calculate Euclidean distancefunction find(x, y, p){ let mind = 0; for(let i = 0; i < p.length; i++) { let a = p[i][0], b = p[i][1]; mind += Math.sqrt((x - a) * (x - a) + (y - b) * (y - b)); } return mind;} // Function to calculate the minimum sum// of the euclidean distances to all poletsfunction getMinDistSum(p){ // Calculate the centroid let x = 0, y = 0; for(let i = 0; i < p.length; i++) { x += p[i][0]; y += p[i][1]; } x = x / p.length; y = y / p.length; // Calculate distance of all // polets let mind = find(x, y, p); return mind;} // Driver Code // Initializing the points let vec = [[ 0, 1 ], [ 1, 0 ], [ 1, 2 ], [ 2, 1 ]]; let d = getMinDistSum(vec); document.write(d); </script> 4 Time Complexity: O(N) Auxiliary Space: O(1) amit143katiyar Rohit_ranjan mohit kumar 29 sanjoy_62 median-finding Arrays Geometric Mathematical Arrays Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Window Sliding Technique Program to find sum of elements in a given array Move all negative numbers to beginning and positive to end with constant extra space Reversal algorithm for array rotation Find duplicates in O(n) time and O(1) extra space | Set 1 Closest Pair of Points using Divide and Conquer algorithm How to check if two given line segments intersect? How to check if a given point lies inside or outside a polygon? Program for distance between two points on earth Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)
[ { "code": null, "e": 24822, "s": 24794, "text": "\n11 May, 2021" }, { "code": null, "e": 25003, "s": 24822, "text": "Given a matrix mat[][] consisting of N pairs of the form {x, y} each denoting coordinates of N points, the task is to find the minimum sum of the Euclidean distances to all points." }, { "code": null, "e": 25013, "s": 25003, "text": "Examples:" }, { "code": null, "e": 25339, "s": 25013, "text": "Input: mat[][] = { { 0, 1}, { 1, 0 }, { 1, 2 }, { 2, 1 }} Output: 4 Explanation: Average of the set of points, i.e. Centroid = ((0+1+1+2)/4, (1+0+2+1)/4) = (1, 1). Euclidean distance of each point from the centroid are {1, 1, 1, 1} Sum of all distances = 1 + 1 + 1 + 1 = 4Input: mat[][] = { { 1, 1}, { 3, 3 }} Output: 2.82843" }, { "code": null, "e": 25544, "s": 25339, "text": "Approach: Since the task is to minimize the Euclidean Distance to all points, the idea is to calculate the Median of all the points. Geometric Median generalizes the concept of median to higher dimensions" }, { "code": null, "e": 25589, "s": 25544, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 25680, "s": 25589, "text": "Calculate the centroid of all the given coordinates, by getting the average of the points." }, { "code": null, "e": 25741, "s": 25680, "text": "Find the Euclidean distance of all points from the centroid." }, { "code": null, "e": 25802, "s": 25741, "text": "Calculate the sum of these distance and print as the answer." }, { "code": null, "e": 25849, "s": 25802, "text": "Below is the implementation of above approach:" }, { "code": null, "e": 25853, "s": 25849, "text": "C++" }, { "code": null, "e": 25858, "s": 25853, "text": "Java" }, { "code": null, "e": 25866, "s": 25858, "text": "Python3" }, { "code": null, "e": 25869, "s": 25866, "text": "C#" }, { "code": null, "e": 25880, "s": 25869, "text": "Javascript" }, { "code": "// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate Euclidean distancedouble find(double x, double y, vector<vector<int> >& p){ double mind = 0; for (int i = 0; i < p.size(); i++) { double a = p[i][0], b = p[i][1]; mind += sqrt((x - a) * (x - a) + (y - b) * (y - b)); } return mind;} // Function to calculate the minimum sum// of the euclidean distances to all pointsdouble getMinDistSum(vector<vector<int> >& p){ // Calculate the centroid double x = 0, y = 0; for (int i = 0; i < p.size(); i++) { x += p[i][0]; y += p[i][1]; } x = x / p.size(); y = y / p.size(); // Calculate distance of all // points double mind = find(x, y, p); return mind;} // Driver Codeint main(){ // Initializing the points vector<vector<int> > vec = { { 0, 1 }, { 1, 0 }, { 1, 2 }, { 2, 1 } }; double d = getMinDistSum(vec); cout << d << endl; return 0;}", "e": 26909, "s": 25880, "text": null }, { "code": "// Java program to implement// the above approachclass GFG{ // Function to calculate Euclidean distancestatic double find(double x, double y, int [][] p){ double mind = 0; for(int i = 0; i < p.length; i++) { double a = p[i][0], b = p[i][1]; mind += Math.sqrt((x - a) * (x - a) + (y - b) * (y - b)); } return mind;} // Function to calculate the minimum sum// of the euclidean distances to all pointsstatic double getMinDistSum(int [][]p){ // Calculate the centroid double x = 0, y = 0; for(int i = 0; i < p.length; i++) { x += p[i][0]; y += p[i][1]; } x = x / p.length; y = y / p.length; // Calculate distance of all // points double mind = find(x, y, p); return mind;} // Driver Codepublic static void main(String[] args){ // Initializing the points int [][]vec = { { 0, 1 }, { 1, 0 }, { 1, 2 }, { 2, 1 } }; double d = getMinDistSum(vec); System.out.print(d + \"\\n\");}} // This code is contributed by Amit Katiyar", "e": 28000, "s": 26909, "text": null }, { "code": "# Python3 program to implement# the above approachfrom math import sqrt # Function to calculate Euclidean distancedef find(x, y, p): mind = 0 for i in range(len(p)): a = p[i][0] b = p[i][1] mind += sqrt((x - a) * (x - a) + (y - b) * (y - b)) return mind # Function to calculate the minimum sum# of the euclidean distances to all pointsdef getMinDistSum(p): # Calculate the centroid x = 0 y = 0 for i in range(len(p)): x += p[i][0] y += p[i][1] x = x // len(p) y = y // len(p) # Calculate distance of all # points mind = find(x, y, p) return mind # Driver Codeif __name__ == '__main__': # Initializing the points vec = [ [ 0, 1 ], [ 1, 0 ], [ 1, 2 ], [ 2, 1 ] ] d = getMinDistSum(vec) print(int(d)) # This code is contributed by mohit kumar 29", "e": 28902, "s": 28000, "text": null }, { "code": "// C# program to implement// the above approachusing System;class GFG{ // Function to calculate Euclidean distancestatic double find(double x, double y, int [,] p){ double mind = 0; for(int i = 0; i < p.GetLength(0); i++) { double a = p[i,0], b = p[i,1]; mind += Math.Sqrt((x - a) * (x - a) + (y - b) * (y - b)); } return mind;} // Function to calculate the minimum sum// of the euclidean distances to all pointsstatic double getMinDistSum(int [,]p){ // Calculate the centroid double x = 0, y = 0; for(int i = 0; i < p.GetLength(0); i++) { x += p[i,0]; y += p[i,1]; } x = x / p.Length; y = y / p.Length; // Calculate distance of all // points double mind = find(x, y, p); return mind;} // Driver Codepublic static void Main(String[] args){ // Initializing the points int [,]vec = { { 0, 1 }, { 1, 0 }, { 1, 2 }, { 2, 1 } }; int d = (int)getMinDistSum(vec); Console.Write(d + \"\\n\");}} // This code is contributed by Rohit_ranjan", "e": 30008, "s": 28902, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to calculate Euclidean distancefunction find(x, y, p){ let mind = 0; for(let i = 0; i < p.length; i++) { let a = p[i][0], b = p[i][1]; mind += Math.sqrt((x - a) * (x - a) + (y - b) * (y - b)); } return mind;} // Function to calculate the minimum sum// of the euclidean distances to all poletsfunction getMinDistSum(p){ // Calculate the centroid let x = 0, y = 0; for(let i = 0; i < p.length; i++) { x += p[i][0]; y += p[i][1]; } x = x / p.length; y = y / p.length; // Calculate distance of all // polets let mind = find(x, y, p); return mind;} // Driver Code // Initializing the points let vec = [[ 0, 1 ], [ 1, 0 ], [ 1, 2 ], [ 2, 1 ]]; let d = getMinDistSum(vec); document.write(d); </script>", "e": 30969, "s": 30008, "text": null }, { "code": null, "e": 30971, "s": 30969, "text": "4" }, { "code": null, "e": 31015, "s": 30971, "text": "Time Complexity: O(N) Auxiliary Space: O(1)" }, { "code": null, "e": 31030, "s": 31015, "text": "amit143katiyar" }, { "code": null, "e": 31043, "s": 31030, "text": "Rohit_ranjan" }, { "code": null, "e": 31058, "s": 31043, "text": "mohit kumar 29" }, { "code": null, "e": 31068, "s": 31058, "text": "sanjoy_62" }, { "code": null, "e": 31083, "s": 31068, "text": "median-finding" }, { "code": null, "e": 31090, "s": 31083, "text": "Arrays" }, { "code": null, "e": 31100, "s": 31090, "text": "Geometric" }, { "code": null, "e": 31113, "s": 31100, "text": "Mathematical" }, { "code": null, "e": 31120, "s": 31113, "text": "Arrays" }, { "code": null, "e": 31133, "s": 31120, "text": "Mathematical" }, { "code": null, "e": 31143, "s": 31133, "text": "Geometric" }, { "code": null, "e": 31241, "s": 31143, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31250, "s": 31241, "text": "Comments" }, { "code": null, "e": 31263, "s": 31250, "text": "Old Comments" }, { "code": null, "e": 31288, "s": 31263, "text": "Window Sliding Technique" }, { "code": null, "e": 31337, "s": 31288, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 31422, "s": 31337, "text": "Move all negative numbers to beginning and positive to end with constant extra space" }, { "code": null, "e": 31460, "s": 31422, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 31518, "s": 31460, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 31576, "s": 31518, "text": "Closest Pair of Points using Divide and Conquer algorithm" }, { "code": null, "e": 31627, "s": 31576, "text": "How to check if two given line segments intersect?" }, { "code": null, "e": 31691, "s": 31627, "text": "How to check if a given point lies inside or outside a polygon?" }, { "code": null, "e": 31740, "s": 31691, "text": "Program for distance between two points on earth" } ]
Python - Custom Lower bound a List - GeeksforGeeks
11 Oct, 2020 Given a list, assign a custom lower-bound value to it. Input : test_list = [5, 7, 8, 2, 3, 5, 1], K = 3 Output : [5, 7, 8, 3, 3, 5, 3] Explanation : All elements less than 3, assigned 3. Input : test_list = [5, 7, 8, 2, 3, 5, 1], K = 5 Output : [5, 7, 8, 5, 5, 5, 5] Explanation : All elements less than 5, assigned 5. Method #1: Using list comprehension In this, we check for each element if it’s lower than lower-bound, if yes, then assign the decided lower-bound to that element. Python3 # Python3 code to demonstrate working of # Custom Lowerbound a List# Using list comprehension # initializing listtest_list = [5, 7, 8, 2, 3, 5, 1] # printing original listprint("The original list is : " + str(test_list)) # initializing LowerboundK = 4 # checking for elements and assigning Lowerboundsres = [ele if ele >= K else K for ele in test_list] # printing result print("List with Lowerbounds : " + str(res)) The original list is : [5, 7, 8, 2, 3, 5, 1] List with Lowerbounds : [5, 7, 8, 4, 4, 5, 4] Method #2 : Using list comprehension + max() In this, we perform comparison using max(), assign max of the element, or the lower-bound as decided. Python3 # Python3 code to demonstrate working of # Custom Lowerbound a List# Using list comprehension + max() # initializing listtest_list = [5, 7, 8, 2, 3, 5, 1] # printing original listprint("The original list is : " + str(test_list)) # initializing LowerboundK = 4 # max() is used to compare for Lowerboundres = [max(ele, K) for ele in test_list] # printing result print("List with Lowerbounds : " + str(res)) The original list is : [5, 7, 8, 2, 3, 5, 1] List with Lowerbounds : [5, 7, 8, 4, 4, 5, 4] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25012, "s": 24984, "text": "\n11 Oct, 2020" }, { "code": null, "e": 25067, "s": 25012, "text": "Given a list, assign a custom lower-bound value to it." }, { "code": null, "e": 25199, "s": 25067, "text": "Input : test_list = [5, 7, 8, 2, 3, 5, 1], K = 3 Output : [5, 7, 8, 3, 3, 5, 3] Explanation : All elements less than 3, assigned 3." }, { "code": null, "e": 25332, "s": 25199, "text": "Input : test_list = [5, 7, 8, 2, 3, 5, 1], K = 5 Output : [5, 7, 8, 5, 5, 5, 5] Explanation : All elements less than 5, assigned 5. " }, { "code": null, "e": 25368, "s": 25332, "text": "Method #1: Using list comprehension" }, { "code": null, "e": 25496, "s": 25368, "text": "In this, we check for each element if it’s lower than lower-bound, if yes, then assign the decided lower-bound to that element." }, { "code": null, "e": 25504, "s": 25496, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Custom Lowerbound a List# Using list comprehension # initializing listtest_list = [5, 7, 8, 2, 3, 5, 1] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing LowerboundK = 4 # checking for elements and assigning Lowerboundsres = [ele if ele >= K else K for ele in test_list] # printing result print(\"List with Lowerbounds : \" + str(res))", "e": 25926, "s": 25504, "text": null }, { "code": null, "e": 26018, "s": 25926, "text": "The original list is : [5, 7, 8, 2, 3, 5, 1]\nList with Lowerbounds : [5, 7, 8, 4, 4, 5, 4]\n" }, { "code": null, "e": 26063, "s": 26018, "text": "Method #2 : Using list comprehension + max()" }, { "code": null, "e": 26165, "s": 26063, "text": "In this, we perform comparison using max(), assign max of the element, or the lower-bound as decided." }, { "code": null, "e": 26173, "s": 26165, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Custom Lowerbound a List# Using list comprehension + max() # initializing listtest_list = [5, 7, 8, 2, 3, 5, 1] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing LowerboundK = 4 # max() is used to compare for Lowerboundres = [max(ele, K) for ele in test_list] # printing result print(\"List with Lowerbounds : \" + str(res))", "e": 26584, "s": 26173, "text": null }, { "code": null, "e": 26676, "s": 26584, "text": "The original list is : [5, 7, 8, 2, 3, 5, 1]\nList with Lowerbounds : [5, 7, 8, 4, 4, 5, 4]\n" }, { "code": null, "e": 26697, "s": 26676, "text": "Python list-programs" }, { "code": null, "e": 26704, "s": 26697, "text": "Python" }, { "code": null, "e": 26720, "s": 26704, "text": "Python Programs" }, { "code": null, "e": 26818, "s": 26720, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26827, "s": 26818, "text": "Comments" }, { "code": null, "e": 26840, "s": 26827, "text": "Old Comments" }, { "code": null, "e": 26858, "s": 26840, "text": "Python Dictionary" }, { "code": null, "e": 26893, "s": 26858, "text": "Read a file line by line in Python" }, { "code": null, "e": 26915, "s": 26893, "text": "Enumerate() in Python" }, { "code": null, "e": 26947, "s": 26915, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26989, "s": 26947, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27011, "s": 26989, "text": "Defaultdict in Python" }, { "code": null, "e": 27050, "s": 27011, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27096, "s": 27050, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27134, "s": 27096, "text": "Python | Convert a list to dictionary" } ]
Merge two BST 's | Practice | GeeksforGeeks
Given two BSTs, return elements of both BSTs in sorted form. Example 1: Input: BST1: 5 / \ 3 6 / \ 2 4 BST2: 2 / \ 1 3 \ 7 / 6 Output: 1 2 2 3 3 4 5 6 6 7 Explanation: After merging and sorting the two BST we get 1 2 2 3 3 4 5 6 6 7. Example 2: Input: BST1: 12 / 9 / \ 6 11 BST2: 8 / \ 5 10 / 2 Output: 2 5 6 8 9 10 11 12 Explanation: After merging and sorting the two BST we get 2 5 6 8 9 10 11 12. Your Task: You don't need to read input or print anything. Your task is to complete the function merge() which takes roots of both the BSTs as its input and returns an array of integers denoting the node values of both the BSTs in a sorted order. Expected Time Complexity: O(M+N) where M and N are the sizes if the two BSTs. Expected Auxiliary Space: O(Height of BST1 + Height of BST2). Constraints: 1 ≤ Number of Nodes ≤ 105 0 subhanshukumar6314 days ago void inorder(Node* root,multiset<int> &st){ if(root==NULL) return; inorder(root->left,st); st.insert(root->data); inorder(root->right,st); } vector<int> merge(Node *root1, Node *root2) { multiset<int> ans; inorder(root1,ans); inorder(root2,ans); vector<int> res; for(auto i:ans){ res.push_back(i); } return res; } +1 sarafraj019995 days ago PYTHON EASY SOLUSION <=> (h1+h2) space and (n1+n2) time complexity class Solution: def merge(self, root1, root2): def leftTravel(stak, root): if not root: return stak.append(root) leftTravel(stak, root.left) res = [] stak1, stak2 = [], [] leftTravel(stak1, root1) leftTravel(stak2, root2) while stak1 and stak2: if stak1[-1].data < stak2[-1].data: temp = stak1.pop() res.append(temp.data) leftTravel(stak1, temp.right) elif stak2[-1].data < stak1[-1].data: temp = stak2.pop() res.append(temp.data) leftTravel(stak2, temp.right) else: temp1 = stak1.pop() temp2 = stak2.pop() res.append(temp1.data) res.append(temp2.data) leftTravel(stak1, temp1.right) leftTravel(stak2, temp2.right) while stak1: temp = stak1.pop() res.append(temp.data) leftTravel(stak1, temp.right) while stak2: temp = stak2.pop() res.append(temp.data) leftTravel(stak2, temp.right) return res 0 joyrockok1 week ago class Solution{ PriorityQueue<Integer> queue; //Function to return a list of integers denoting the node //values of both the BST in a sorted order. public List<Integer> merge(Node root1,Node root2) { queue = new PriorityQueue<Integer>(); // Write your code here getMerge(root1, queue); getMerge(root2, queue); List<Integer> ansList = new ArrayList<Integer>(); while(queue.isEmpty() == false) { ansList.add(queue.poll()); } return ansList; } public void getMerge(Node node, PriorityQueue queue) { if(node == null) return; if(node.left == null) { queue.add(node.data); } else { getMerge(node.left, queue); queue.add(node.data); } if(node.right != null) { getMerge(node.right, queue); } }} 0 amarrajsmart1972 weeks ago void inorder(Node* root,vector<int> &v) { if(!root) { return ; } inorder(root->left,v); v.push_back(root->data); inorder(root->right,v); } vector<int> merge(Node *root1, Node *root2) { //Your code here vector<int> v; inorder(root1,v); inorder(root2,v); sort(v.begin(),v.end()); return v; } 0 subhamk472 weeks ago class Solution{ //Function to return a list of integers denoting the node //values of both the BST in a sorted order. public List<Integer> merge(Node root1,Node root2) { Queue<Integer> q1 = new LinkedList<>(); Queue<Integer> q2 = new LinkedList<>(); inOrder(root1,q1); inOrder(root2,q2); List<Integer> result = new ArrayList<Integer>(); while(!q1.isEmpty() || !q2.isEmpty()){ if(q1.peek()<q2.peek() ){ result.add(q1.poll()); }else{ result.add(q2.poll()); } if(q1.isEmpty()) while(!q2.isEmpty()) result.add(q2.poll()); if(q2.isEmpty()) while(!q1.isEmpty()) result.add(q1.poll()); } return result; } public void inOrder(Node root, Queue<Integer> q){ if(root==null) return; inOrder(root.left,q); q.offer(root.data); inOrder(root.right,q); }} 0 amishasahu3282 weeks ago TC→ O(n+m) SC→ O(h1 +h2) class Solution { void BSTtoDLL(Node *root, Node* &head) { if(!root) return; BSTtoDLL(root->right, head); root->right = head; if(head != NULL) head->left = root; head = root; BSTtoDLL(root->left, head); } Node *mergeSortedDLL(Node *head1, Node *head2) { if(!head1) return head2; if(!head2) return head1; Node *head = NULL; Node *tail = NULL; while(head1 != NULL && head2 != NULL) { if(head1->data < head2->data) { if(head == NULL) { head = tail = head1; head1 = head1->right; } else { tail->right = head1; head1->left = tail; tail = head1; head1 = head1->right; } } else { if(head == NULL) { head = tail = head2; head2 = head2->right; } else { tail->right = head2; head2->left = tail; tail = head2; head2 = head2->right; } } } while(head1) { tail->right = head1; head1->left = tail; tail = head1; head1 = head1->right; } while(head2) { tail->right = head2; head2->left = tail; tail = head2; head2 = head2->right; } return head; } int countNodes(Node *&head) { int count = 0; Node *curr = head; while(curr) { count++; curr = curr->right; } return count; } vector<int> DLLtoInorder(Node *&head) { vector<int> inorder; if(!head) return inorder; while(head) { inorder.push_back(head->data); head = head->right; } return inorder; } public: //Function to return a list of integers denoting the node //values of both the BST in a sorted order. vector<int> merge(Node *root1, Node *root2) { // Step1: convert BST to DLL Node * head1 = NULL, *head2 = NULL; BSTtoDLL(root1, head1); head1->left = NULL; BSTtoDLL(root2, head2); head2->left = NULL; // Step2: merge two DLL Node *mergedDLL = mergeSortedDLL(head1, head2); // Step3: convert sorted DLL to vector return DLLtoInorder(mergedDLL); } }; 0 amishasahu328 This comment was deleted. -1 tanashah3 weeks ago 0 chhitizgoyal3 weeks ago Java Solution. void inorder1(Node root1, ArrayList<Integer> list){ if(root1!=null){ inorder1(root1.left, list); list.add(root1.data); inorder1(root1.right, list); } } void inorder2(Node root2, ArrayList<Integer> list){ if(root2!=null){ inorder2(root2.left, list); list.add(root2.data); inorder2(root2.right, list); } } public List<Integer> merge(Node root1,Node root2) { ArrayList<Integer> list = new ArrayList<Integer>(); if(root1==null && root2==null){ return list; } inorder1(root1, list); inorder2(root2, list); Collections.sort(list); return list; } 0 jaydhurat3 weeks ago class Solution { //Function to return a list of integers denoting the node //values of both the BST in a sorted order. public List<Integer> merge(Node root1,Node root2) { List<Integer> a = new ArrayList<>(); check1(root1,a); check2(root2,a); Collections.sort(a); return a; } public void check1(Node root,List<Integer> a) { if(root==null) { return; } check1(root.left,a); if(root!=null){ a.add(root.data); } check1(root.right,a); } public void check2(Node root,List<Integer> a) { if(root==null) { return; } check2(root.left,a); if(root!=null){ a.add(root.data); } check2(root.right,a); } } 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": 299, "s": 238, "text": "Given two BSTs, return elements of both BSTs in sorted form." }, { "code": null, "e": 311, "s": 299, "text": "\nExample 1:" }, { "code": null, "e": 579, "s": 311, "text": "Input:\nBST1:\n 5\n / \\\n 3 6\n / \\\n 2 4 \nBST2:\n 2\n / \\\n 1 3\n \\\n 7\n /\n 6\nOutput: 1 2 2 3 3 4 5 6 6 7\nExplanation: \nAfter merging and sorting the\ntwo BST we get 1 2 2 3 3 4 5 6 6 7.\n" }, { "code": null, "e": 590, "s": 579, "text": "Example 2:" }, { "code": null, "e": 796, "s": 590, "text": "Input:\nBST1:\n 12\n / \n 9\n / \\ \n 6 11\nBST2:\n 8\n / \\\n 5 10\n /\n 2\nOutput: 2 5 6 8 9 10 11 12\nExplanation: \nAfter merging and sorting the\ntwo BST we get 2 5 6 8 9 10 11 12." }, { "code": null, "e": 1044, "s": 796, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function merge() which takes roots of both the BSTs as its input and returns an array of integers denoting the node values of both the BSTs in a sorted order." }, { "code": null, "e": 1185, "s": 1044, "text": "\nExpected Time Complexity: O(M+N) where M and N are the sizes if the two BSTs.\nExpected Auxiliary Space: O(Height of BST1 + Height of BST2)." }, { "code": null, "e": 1225, "s": 1185, "text": "\nConstraints:\n1 ≤ Number of Nodes ≤ 105" }, { "code": null, "e": 1227, "s": 1225, "text": "0" }, { "code": null, "e": 1255, "s": 1227, "text": "subhanshukumar6314 days ago" }, { "code": null, "e": 1646, "s": 1255, "text": " void inorder(Node* root,multiset<int> &st){ if(root==NULL) return; inorder(root->left,st); st.insert(root->data); inorder(root->right,st); } vector<int> merge(Node *root1, Node *root2) { multiset<int> ans; inorder(root1,ans); inorder(root2,ans); vector<int> res; for(auto i:ans){ res.push_back(i); } return res; }" }, { "code": null, "e": 1649, "s": 1646, "text": "+1" }, { "code": null, "e": 1673, "s": 1649, "text": "sarafraj019995 days ago" }, { "code": null, "e": 1701, "s": 1673, "text": "PYTHON EASY SOLUSION <=> " }, { "code": null, "e": 1744, "s": 1701, "text": "(h1+h2) space and (n1+n2) time complexity " }, { "code": null, "e": 3045, "s": 1746, "text": "class Solution:\n def merge(self, root1, root2):\n \n def leftTravel(stak, root):\n if not root:\n return \n stak.append(root)\n leftTravel(stak, root.left)\n\n res = []\n stak1, stak2 = [], []\n leftTravel(stak1, root1)\n leftTravel(stak2, root2)\n \n while stak1 and stak2:\n if stak1[-1].data < stak2[-1].data:\n temp = stak1.pop()\n res.append(temp.data)\n leftTravel(stak1, temp.right)\n \n elif stak2[-1].data < stak1[-1].data:\n temp = stak2.pop()\n res.append(temp.data)\n leftTravel(stak2, temp.right)\n \n else:\n temp1 = stak1.pop()\n temp2 = stak2.pop()\n res.append(temp1.data)\n res.append(temp2.data)\n leftTravel(stak1, temp1.right)\n leftTravel(stak2, temp2.right)\n \n while stak1:\n temp = stak1.pop()\n res.append(temp.data)\n leftTravel(stak1, temp.right)\n \n while stak2:\n temp = stak2.pop()\n res.append(temp.data)\n leftTravel(stak2, temp.right)\n \n return res" }, { "code": null, "e": 3047, "s": 3045, "text": "0" }, { "code": null, "e": 3067, "s": 3047, "text": "joyrockok1 week ago" }, { "code": null, "e": 3878, "s": 3067, "text": "class Solution{ PriorityQueue<Integer> queue; //Function to return a list of integers denoting the node //values of both the BST in a sorted order. public List<Integer> merge(Node root1,Node root2) { queue = new PriorityQueue<Integer>(); // Write your code here getMerge(root1, queue); getMerge(root2, queue); List<Integer> ansList = new ArrayList<Integer>(); while(queue.isEmpty() == false) { ansList.add(queue.poll()); } return ansList; } public void getMerge(Node node, PriorityQueue queue) { if(node == null) return; if(node.left == null) { queue.add(node.data); } else { getMerge(node.left, queue); queue.add(node.data); } if(node.right != null) { getMerge(node.right, queue); } }} " }, { "code": null, "e": 3880, "s": 3878, "text": "0" }, { "code": null, "e": 3907, "s": 3880, "text": "amarrajsmart1972 weeks ago" }, { "code": null, "e": 4287, "s": 3907, "text": " void inorder(Node* root,vector<int> &v) { if(!root) { return ; } inorder(root->left,v); v.push_back(root->data); inorder(root->right,v); } vector<int> merge(Node *root1, Node *root2) { //Your code here vector<int> v; inorder(root1,v); inorder(root2,v); sort(v.begin(),v.end()); return v; }" }, { "code": null, "e": 4289, "s": 4287, "text": "0" }, { "code": null, "e": 4310, "s": 4289, "text": "subhamk472 weeks ago" }, { "code": null, "e": 5215, "s": 4310, "text": "class Solution{ //Function to return a list of integers denoting the node //values of both the BST in a sorted order. public List<Integer> merge(Node root1,Node root2) { Queue<Integer> q1 = new LinkedList<>(); Queue<Integer> q2 = new LinkedList<>(); inOrder(root1,q1); inOrder(root2,q2); List<Integer> result = new ArrayList<Integer>(); while(!q1.isEmpty() || !q2.isEmpty()){ if(q1.peek()<q2.peek() ){ result.add(q1.poll()); }else{ result.add(q2.poll()); } if(q1.isEmpty()) while(!q2.isEmpty()) result.add(q2.poll()); if(q2.isEmpty()) while(!q1.isEmpty()) result.add(q1.poll()); } return result; } public void inOrder(Node root, Queue<Integer> q){ if(root==null) return; inOrder(root.left,q); q.offer(root.data); inOrder(root.right,q); }} " }, { "code": null, "e": 5217, "s": 5215, "text": "0" }, { "code": null, "e": 5242, "s": 5217, "text": "amishasahu3282 weeks ago" }, { "code": null, "e": 5253, "s": 5242, "text": "TC→ O(n+m)" }, { "code": null, "e": 5267, "s": 5253, "text": "SC→ O(h1 +h2)" }, { "code": null, "e": 7588, "s": 5267, "text": "class Solution\n{\n void BSTtoDLL(Node *root, Node* &head)\n {\n \tif(!root) return;\n \tBSTtoDLL(root->right, head);\n \troot->right = head;\n \tif(head != NULL)\n \t\thead->left = root;\n \thead = root;\n \tBSTtoDLL(root->left, head);\n }\n \n Node *mergeSortedDLL(Node *head1, Node *head2)\n {\n \tif(!head1) return head2;\n \tif(!head2) return head1;\n \tNode *head = NULL;\n \tNode *tail = NULL;\n \t\n \twhile(head1 != NULL && head2 != NULL)\n \t{\n \t\tif(head1->data < head2->data)\n \t\t{\n \t\t\tif(head == NULL)\n \t\t\t{\n \t\t\t\thead = tail = head1;\n \t\t\t\thead1 = head1->right;\n \t\t\t}\n \t\t\telse\n \t\t\t{\n \t\t\t\ttail->right = head1;\n \t\t\t\thead1->left = tail;\n \t\t\t\ttail = head1;\n \t\t\t\thead1 = head1->right;\n \t\t\t}\n \t\t}\n \t\telse\n \t\t{\n \t\t\tif(head == NULL)\n \t\t\t{\n \t\t\t\thead = tail = head2;\n \t\t\t\thead2 = head2->right;\n \t\t\t}\n \t\t\telse\n \t\t\t{\n \t\t\t\ttail->right = head2;\n \t\t\t\thead2->left = tail;\n \t\t\t\ttail = head2;\n \t\t\t\thead2 = head2->right;\n \t\t\t}\n \t\t}\n \t}\n \twhile(head1)\n \t{\n \t\ttail->right = head1;\n \t\thead1->left = tail;\n \t\ttail = head1;\n \t\thead1 = head1->right;\n \t}\n \twhile(head2)\n \t{\n \t\ttail->right = head2;\n \t\thead2->left = tail;\n \t\ttail = head2;\n \t\thead2 = head2->right;\n \t}\n \t\n \treturn head;\n }\n int countNodes(Node *&head)\n {\n \tint count = 0;\n \tNode *curr = head;\n \twhile(curr)\n \t{\n \t\tcount++;\n \t\tcurr = curr->right;\n \t}\n \treturn count;\n }\n vector<int> DLLtoInorder(Node *&head)\n {\n vector<int> inorder;\n if(!head) return inorder;\n while(head)\n {\n inorder.push_back(head->data);\n head = head->right;\n }\n return inorder;\n }\n public:\n //Function to return a list of integers denoting the node \n //values of both the BST in a sorted order.\n vector<int> merge(Node *root1, Node *root2)\n {\n // Step1: convert BST to DLL\n \tNode * head1 = NULL, *head2 = NULL;\n \tBSTtoDLL(root1, head1);\n \thead1->left = NULL;\n \tBSTtoDLL(root2, head2);\n \thead2->left = NULL;\n \t\n \t// Step2: merge two DLL\n \tNode *mergedDLL = mergeSortedDLL(head1, head2);\n \t\n \t// Step3: convert sorted DLL to vector\n \treturn DLLtoInorder(mergedDLL);\n }\n};" }, { "code": null, "e": 7590, "s": 7588, "text": "0" }, { "code": null, "e": 7604, "s": 7590, "text": "amishasahu328" }, { "code": null, "e": 7630, "s": 7604, "text": "This comment was deleted." }, { "code": null, "e": 7633, "s": 7630, "text": "-1" }, { "code": null, "e": 7653, "s": 7633, "text": "tanashah3 weeks ago" }, { "code": null, "e": 7655, "s": 7653, "text": "0" }, { "code": null, "e": 7679, "s": 7655, "text": "chhitizgoyal3 weeks ago" }, { "code": null, "e": 7694, "s": 7679, "text": "Java Solution." }, { "code": null, "e": 8383, "s": 7694, "text": " void inorder1(Node root1, ArrayList<Integer> list){ if(root1!=null){ inorder1(root1.left, list); list.add(root1.data); inorder1(root1.right, list); } } void inorder2(Node root2, ArrayList<Integer> list){ if(root2!=null){ inorder2(root2.left, list); list.add(root2.data); inorder2(root2.right, list); } } public List<Integer> merge(Node root1,Node root2) { ArrayList<Integer> list = new ArrayList<Integer>(); if(root1==null && root2==null){ return list; } inorder1(root1, list); inorder2(root2, list); Collections.sort(list); return list; }" }, { "code": null, "e": 8385, "s": 8383, "text": "0" }, { "code": null, "e": 8406, "s": 8385, "text": "jaydhurat3 weeks ago" }, { "code": null, "e": 9200, "s": 8406, "text": "class Solution\n{\n //Function to return a list of integers denoting the node \n //values of both the BST in a sorted order.\n public List<Integer> merge(Node root1,Node root2)\n {\n List<Integer> a = new ArrayList<>();\n check1(root1,a);\n check2(root2,a);\n Collections.sort(a);\n return a;\n }\n public void check1(Node root,List<Integer> a)\n {\n if(root==null)\n {\n return;\n }\n check1(root.left,a);\n if(root!=null){\n a.add(root.data);\n }\n check1(root.right,a);\n }\n public void check2(Node root,List<Integer> a)\n {\n if(root==null)\n {\n return;\n }\n check2(root.left,a);\n if(root!=null){\n a.add(root.data);\n }\n check2(root.right,a);\n }\n}\n" }, { "code": null, "e": 9346, "s": 9200, "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": 9382, "s": 9346, "text": " Login to access your submissions. " }, { "code": null, "e": 9392, "s": 9382, "text": "\nProblem\n" }, { "code": null, "e": 9402, "s": 9392, "text": "\nContest\n" }, { "code": null, "e": 9465, "s": 9402, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 9613, "s": 9465, "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": 9821, "s": 9613, "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": 9927, "s": 9821, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Amazing hacks of Python - GeeksforGeeks
27 Dec, 2021 Python is indeed one of the smart and most trending languages. Here are some cool hacks that make python superb among all other languages. List comprehensions: List comprehension is the best and efficient technique to get rid of writing unnecessary lines of code. Read Article to know more. Printing a list: The list is not printed according to the user’s requirement. They are always printed in unwanted square brackets and single quotes. But there is a trivial solution to print the list efficiently by using the string’s join method. The join method turns the list into a string by casting each item into a string and connecting them with the string that joins was called on. Python # Declaring the list geekgeek = ['Geeks', 'Programming', 'Algorithm', 'Article'] # Directly printing the listprint ("Simple List:", geek) # Printing the list by join methodprint ('List by using join method: %s' % ', ' .join(geek)) # Direct use of join methodprint ('Direct apply the join method:',(", " .join(geek))) Output: Simple List: ['Geeks', 'Programming', 'Algorithm', 'Article'] List by using join method: Geeks, Programming, Algorithm, Article Direct apply the join method: Geeks, Programming, Algorithm, Article Cool Zip tricks Transpose a matrix: You can Read Here about this. Partition a list into N groups: We used iter() as an iterator over a sequence. Python3 # Declaring the list geekgeek = ['Sun', 'Flowers', 'Peoples', 'Animals', 'Day', 'Night'] partition = list(zip (*[iter(geek)] * 2))print (partition) Output: [('Sun', 'Flowers'), ('Peoples', 'Animals'), ('Day', 'Night')] Explanation: [iter(geek)] * 2 produces a list containing 2 items of geek[] list, i.e. a list of length 2. *arg unpacks a sequence into arguments for a function call. Therefore we are passing the same iterator 2 times to zip(). Printing more than one list’s items simultaneously Python list1 = [1, 3, 5, 7]list2 = [2, 4, 6, 8] # Here zip() function takes two equal length list and merges them# together in pairsfor a, b in zip(list1,list2): print (a, b) Output: 1 2 3 4 5 6 7 8 Take the string as input and convert it into the list: Python3 # Reads a string from input and type case them to int# after splitting to white-spaces formatted_list = list(map(int, input().split()))print(formatted_list) Input: 2 4 5 6 Output: [2, 4, 5, 6] Convert the list of list into a single list Python3 # import the itertoolsimport itertools # Declaring the list geekgeek = [[1, 2], [3, 4], [5, 6]] # chain.from_iterable() function returns the# elements of nested list# and iterate from first list# of iterable till the last# end of the list lst = list(itertools.chain.from_iterable(geek))print(lst) Output: [1, 2, 3, 4, 5, 6] Printing the repeated characters: The task is to print the pattern like this Geeeeekkkkss. So we can easily print this pattern without using it for a loop. Python # + used for string concatenation# To repeat the character n times, just multiply n # with that character print ("G" + "e"*5 + "k"*4 + "s"*2) Output: Geeeeekkkkss Read More: 10 interesting facts about Python Reference: https://www.quora.com/What-are-some-cool-Python-tricks This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. punamsingh628700 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Check if element exists in list in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 25859, "s": 25831, "text": "\n27 Dec, 2021" }, { "code": null, "e": 25999, "s": 25859, "text": "Python is indeed one of the smart and most trending languages. Here are some cool hacks that make python superb among all other languages. " }, { "code": null, "e": 26152, "s": 25999, "text": "List comprehensions: List comprehension is the best and efficient technique to get rid of writing unnecessary lines of code. Read Article to know more. " }, { "code": null, "e": 26541, "s": 26152, "text": "Printing a list: The list is not printed according to the user’s requirement. They are always printed in unwanted square brackets and single quotes. But there is a trivial solution to print the list efficiently by using the string’s join method. The join method turns the list into a string by casting each item into a string and connecting them with the string that joins was called on. " }, { "code": null, "e": 26548, "s": 26541, "text": "Python" }, { "code": "# Declaring the list geekgeek = ['Geeks', 'Programming', 'Algorithm', 'Article'] # Directly printing the listprint (\"Simple List:\", geek) # Printing the list by join methodprint ('List by using join method: %s' % ', ' .join(geek)) # Direct use of join methodprint ('Direct apply the join method:',(\", \" .join(geek)))", "e": 26871, "s": 26548, "text": null }, { "code": null, "e": 27077, "s": 26871, "text": "Output: \nSimple List: ['Geeks', 'Programming', 'Algorithm', 'Article']\nList by using join method: Geeks, Programming, Algorithm, Article\nDirect apply the join method: Geeks, Programming, Algorithm, Article" }, { "code": null, "e": 27093, "s": 27077, "text": "Cool Zip tricks" }, { "code": null, "e": 27143, "s": 27093, "text": "Transpose a matrix: You can Read Here about this." }, { "code": null, "e": 27223, "s": 27143, "text": "Partition a list into N groups: We used iter() as an iterator over a sequence. " }, { "code": null, "e": 27231, "s": 27223, "text": "Python3" }, { "code": "# Declaring the list geekgeek = ['Sun', 'Flowers', 'Peoples', 'Animals', 'Day', 'Night'] partition = list(zip (*[iter(geek)] * 2))print (partition)", "e": 27379, "s": 27231, "text": null }, { "code": null, "e": 27451, "s": 27379, "text": "Output: \n[('Sun', 'Flowers'), ('Peoples', 'Animals'), ('Day', 'Night')]" }, { "code": null, "e": 27679, "s": 27451, "text": "Explanation: [iter(geek)] * 2 produces a list containing 2 items of geek[] list, i.e. a list of length 2. *arg unpacks a sequence into arguments for a function call. Therefore we are passing the same iterator 2 times to zip(). " }, { "code": null, "e": 27731, "s": 27679, "text": "Printing more than one list’s items simultaneously " }, { "code": null, "e": 27738, "s": 27731, "text": "Python" }, { "code": "list1 = [1, 3, 5, 7]list2 = [2, 4, 6, 8] # Here zip() function takes two equal length list and merges them# together in pairsfor a, b in zip(list1,list2): print (a, b)", "e": 27909, "s": 27738, "text": null }, { "code": null, "e": 27934, "s": 27909, "text": "Output: \n1 2\n3 4\n5 6\n7 8" }, { "code": null, "e": 27990, "s": 27934, "text": "Take the string as input and convert it into the list: " }, { "code": null, "e": 27998, "s": 27990, "text": "Python3" }, { "code": "# Reads a string from input and type case them to int# after splitting to white-spaces formatted_list = list(map(int, input().split()))print(formatted_list)", "e": 28155, "s": 27998, "text": null }, { "code": null, "e": 28192, "s": 28155, "text": "Input:\n2 4 5 6\nOutput:\n[2, 4, 5, 6] " }, { "code": null, "e": 28237, "s": 28192, "text": "Convert the list of list into a single list " }, { "code": null, "e": 28245, "s": 28237, "text": "Python3" }, { "code": "# import the itertoolsimport itertools # Declaring the list geekgeek = [[1, 2], [3, 4], [5, 6]] # chain.from_iterable() function returns the# elements of nested list# and iterate from first list# of iterable till the last# end of the list lst = list(itertools.chain.from_iterable(geek))print(lst)", "e": 28542, "s": 28245, "text": null }, { "code": null, "e": 28570, "s": 28542, "text": "Output: \n[1, 2, 3, 4, 5, 6]" }, { "code": null, "e": 28727, "s": 28570, "text": "Printing the repeated characters: The task is to print the pattern like this Geeeeekkkkss. So we can easily print this pattern without using it for a loop. " }, { "code": null, "e": 28734, "s": 28727, "text": "Python" }, { "code": "# + used for string concatenation# To repeat the character n times, just multiply n # with that character print (\"G\" + \"e\"*5 + \"k\"*4 + \"s\"*2)", "e": 28877, "s": 28734, "text": null }, { "code": null, "e": 28898, "s": 28877, "text": "Output:\nGeeeeekkkkss" }, { "code": null, "e": 29009, "s": 28898, "text": "Read More: 10 interesting facts about Python Reference: https://www.quora.com/What-are-some-cool-Python-tricks" }, { "code": null, "e": 29432, "s": 29009, "text": "This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 29449, "s": 29432, "text": "punamsingh628700" }, { "code": null, "e": 29456, "s": 29449, "text": "Python" }, { "code": null, "e": 29554, "s": 29456, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29572, "s": 29554, "text": "Python Dictionary" }, { "code": null, "e": 29607, "s": 29572, "text": "Read a file line by line in Python" }, { "code": null, "e": 29639, "s": 29607, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29681, "s": 29639, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29707, "s": 29681, "text": "Python String | replace()" }, { "code": null, "e": 29736, "s": 29707, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29780, "s": 29736, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29817, "s": 29780, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29859, "s": 29817, "text": "Check if element exists in list in Python" } ]
Can we override a protected method in Java?
Yes, the protected method of a superclass can be overridden by a subclass. If the superclass method is protected, the subclass overridden method can have protected or public (but not default or private) which means the subclass overridden method can not have a weaker access specifier. class A { protected void protectedMethod() { System.out.println("superclass protected method"); } } class B extends A { protected void protectedMethod() { System.out.println("subclass protected method"); } } public class Test { public static void main(String args[]) { B b = new B(); b.protectedMethod(); } } subclass protected method
[ { "code": null, "e": 1348, "s": 1062, "text": "Yes, the protected method of a superclass can be overridden by a subclass. If the superclass method is protected, the subclass overridden method can have protected or public (but not default or private) which means the subclass overridden method can not have a weaker access specifier." }, { "code": null, "e": 1699, "s": 1348, "text": "class A {\n protected void protectedMethod() {\n System.out.println(\"superclass protected method\");\n }\n}\nclass B extends A {\n protected void protectedMethod() {\n System.out.println(\"subclass protected method\");\n }\n}\npublic class Test {\n public static void main(String args[]) {\n B b = new B();\n b.protectedMethod();\n }\n}" }, { "code": null, "e": 1725, "s": 1699, "text": "subclass protected method" } ]
Check if the bracket sequence can be balanced with at most one change in the position of a bracket - GeeksforGeeks
26 Jul, 2021 Given an unbalanced bracket sequence as a string str, the task is to find whether the given string can be balanced by moving at most one bracket from its original place in the sequence to any other position.Examples: Input: str = “)(()” Output: Yes As by moving s[0] to the end will make it valid. “(())”Input: str = “()))(()” Output: No Approach: Consider X as a valid bracket then definitely (X) is also valid. If X is not valid and can be balanced with just one change of position in some bracket then it must be of type X = “)(“ where ‘)’ has been placed before ‘(‘. Now, X can be replaced with (X) as it will not affect the balanced nature of X. The new string becomes X = “()()” which is balanced. Hence, if (X) is balanced then we can say that X can be balanced with at most one change in the position of some bracket.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // CPP implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if the sequence// can be balanced by changing the// position of at most one bracketbool canBeBalanced(string s, int n){ // Odd length string can // never be balanced if (n % 2 == 1) return false; // Add '(' in the beginning and ')' // in the end of the string string k = "("; k += s + ")"; vector<string> d; int cnt = 0; for (int i = 0; i < k.length(); i++) { // If its an opening bracket then // append it to the temp string if (k[i] == '(') d.push_back("("); // If its a closing bracket else { // There was an opening bracket // to match it with if (d.size() != 0) d.pop_back(); // No opening bracket to // match it with else return false; } } // Sequence is balanced if (d.empty()) return true; return false;} // Driver Codeint main(int argc, char const *argv[]){ string s = ")(()"; int n = s.length(); (canBeBalanced(s, n)) ? cout << "Yes" << endl : cout << "No" << endl; return 0;} // This code is contributed by// sanjeev2552 // Java implementation of the approachimport java.util.Vector; class GFG{ // Function that returns true if the sequence // can be balanced by changing the // position of at most one bracket static boolean canBeBalanced(String s, int n) { // Odd length string can // never be balanced if (n % 2 == 1) return false; // Add '(' in the beginning and ')' // in the end of the string String k = "("; k += s + ")"; Vector<String> d = new Vector<>(); for (int i = 0; i < k.length(); i++) { // If its an opening bracket then // append it to the temp string if (k.charAt(i) == '(') d.add("("); // If its a closing bracket else { // There was an opening bracket // to match it with if (d.size() != 0) d.remove(d.size() - 1); // No opening bracket to // match it with else return false; } } // Sequence is balanced if (d.isEmpty()) return true; return false; } // Driver Code public static void main(String[] args) { String s = ")(()"; int n = s.length(); if (canBeBalanced(s, n)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by// sanjeev2552 # Python3 implementation of the approach # Function that returns true if the sequence# can be balanced by changing the# position of at most one bracketdef canBeBalanced(s, n): # Odd length string can # never be balanced if n % 2 == 1: return False # Add '(' in the beginning and ')' # in the end of the string k = "(" k = k + s+")" d = [] count = 0 for i in range(len(k)): # If its an opening bracket then # append it to the temp string if k[i] == "(": d.append("(") # If its a closing bracket else: # There was an opening bracket # to match it with if len(d)!= 0: d.pop() # No opening bracket to # match it with else: return False # Sequence is balanced if len(d) == 0: return True return False # Driver codeS = ")(()"n = len(S)if(canBeBalanced(S, n)): print("Yes")else: print("No") // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function that returns true if the sequence // can be balanced by changing the // position of at most one bracket static bool canBeBalanced(string s, int n) { // Odd length string can // never be balanced if (n % 2 == 1) return false; // Add '(' in the beginning and ')' // in the end of the string string k = "("; k += s + ")"; List<string> d = new List<string>(); for (int i = 0; i < k.Length; i++) { // If its an opening bracket then // append it to the temp string if (k[i] == '(') d.Add("("); // If its a closing bracket else { // There was an opening bracket // to match it with if (d.Count != 0) d.RemoveAt(d.Count - 1); // No opening bracket to // match it with else return false; } } // Sequence is balanced if (d.Count == 0) return true; return false; } // Driver Code public static void Main() { string s = ")(()"; int n = s.Length; if (canBeBalanced(s, n)) Console.Write("Yes"); else Console.Write("No"); }} // This code is contributed by// mohit kumar 29 <script> // JavaScript implementation of the approach // Function that returns true if the sequence // can be balanced by changing the // position of at most one bracketfunction canBeBalanced(s,n){ // Odd length string can // never be balanced if (n % 2 == 1) return false; // Add '(' in the beginning and ')' // in the end of the string let k = "("; k += s + ")"; let d = []; for (let i = 0; i < k.length; i++) { // If its an opening bracket then // append it to the temp string if (k[i] == '(') d.push("("); // If its a closing bracket else { // There was an opening bracket // to match it with if (d.length != 0) d.pop(); // No opening bracket to // match it with else return false; } } // Sequence is balanced if (d.length==0) return true; return false;} // Driver Codelet s = ")(()"; let n = s.length; if (canBeBalanced(s, n)) document.write("Yes"); else document.write("No"); // This code is contributed by unknown2108 </script> Yes sanjeev2552 mohit kumar 29 unknown2108 surinderdawra388 Constructive Algorithms Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 50 String Coding Problems for Interviews Hill Cipher Naive algorithm for Pattern Searching How to Append a Character to a String in C Vigenère Cipher Convert character array to string in C++ sprintf() in C Reverse words in a given String in Python Converting Roman Numerals to Decimal lying between 1 to 3999 Iterate over characters of a string in C++
[ { "code": null, "e": 24772, "s": 24744, "text": "\n26 Jul, 2021" }, { "code": null, "e": 24991, "s": 24772, "text": "Given an unbalanced bracket sequence as a string str, the task is to find whether the given string can be balanced by moving at most one bracket from its original place in the sequence to any other position.Examples: " }, { "code": null, "e": 25114, "s": 24991, "text": "Input: str = “)(()” Output: Yes As by moving s[0] to the end will make it valid. “(())”Input: str = “()))(()” Output: No " }, { "code": null, "e": 25655, "s": 25116, "text": "Approach: Consider X as a valid bracket then definitely (X) is also valid. If X is not valid and can be balanced with just one change of position in some bracket then it must be of type X = “)(“ where ‘)’ has been placed before ‘(‘. Now, X can be replaced with (X) as it will not affect the balanced nature of X. The new string becomes X = “()()” which is balanced. Hence, if (X) is balanced then we can say that X can be balanced with at most one change in the position of some bracket.Below is the implementation of the above approach: " }, { "code": null, "e": 25659, "s": 25655, "text": "C++" }, { "code": null, "e": 25664, "s": 25659, "text": "Java" }, { "code": null, "e": 25672, "s": 25664, "text": "Python3" }, { "code": null, "e": 25675, "s": 25672, "text": "C#" }, { "code": null, "e": 25686, "s": 25675, "text": "Javascript" }, { "code": "// CPP implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if the sequence// can be balanced by changing the// position of at most one bracketbool canBeBalanced(string s, int n){ // Odd length string can // never be balanced if (n % 2 == 1) return false; // Add '(' in the beginning and ')' // in the end of the string string k = \"(\"; k += s + \")\"; vector<string> d; int cnt = 0; for (int i = 0; i < k.length(); i++) { // If its an opening bracket then // append it to the temp string if (k[i] == '(') d.push_back(\"(\"); // If its a closing bracket else { // There was an opening bracket // to match it with if (d.size() != 0) d.pop_back(); // No opening bracket to // match it with else return false; } } // Sequence is balanced if (d.empty()) return true; return false;} // Driver Codeint main(int argc, char const *argv[]){ string s = \")(()\"; int n = s.length(); (canBeBalanced(s, n)) ? cout << \"Yes\" << endl : cout << \"No\" << endl; return 0;} // This code is contributed by// sanjeev2552", "e": 26981, "s": 25686, "text": null }, { "code": "// Java implementation of the approachimport java.util.Vector; class GFG{ // Function that returns true if the sequence // can be balanced by changing the // position of at most one bracket static boolean canBeBalanced(String s, int n) { // Odd length string can // never be balanced if (n % 2 == 1) return false; // Add '(' in the beginning and ')' // in the end of the string String k = \"(\"; k += s + \")\"; Vector<String> d = new Vector<>(); for (int i = 0; i < k.length(); i++) { // If its an opening bracket then // append it to the temp string if (k.charAt(i) == '(') d.add(\"(\"); // If its a closing bracket else { // There was an opening bracket // to match it with if (d.size() != 0) d.remove(d.size() - 1); // No opening bracket to // match it with else return false; } } // Sequence is balanced if (d.isEmpty()) return true; return false; } // Driver Code public static void main(String[] args) { String s = \")(()\"; int n = s.length(); if (canBeBalanced(s, n)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by// sanjeev2552", "e": 28487, "s": 26981, "text": null }, { "code": "# Python3 implementation of the approach # Function that returns true if the sequence# can be balanced by changing the# position of at most one bracketdef canBeBalanced(s, n): # Odd length string can # never be balanced if n % 2 == 1: return False # Add '(' in the beginning and ')' # in the end of the string k = \"(\" k = k + s+\")\" d = [] count = 0 for i in range(len(k)): # If its an opening bracket then # append it to the temp string if k[i] == \"(\": d.append(\"(\") # If its a closing bracket else: # There was an opening bracket # to match it with if len(d)!= 0: d.pop() # No opening bracket to # match it with else: return False # Sequence is balanced if len(d) == 0: return True return False # Driver codeS = \")(()\"n = len(S)if(canBeBalanced(S, n)): print(\"Yes\")else: print(\"No\")", "e": 29483, "s": 28487, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function that returns true if the sequence // can be balanced by changing the // position of at most one bracket static bool canBeBalanced(string s, int n) { // Odd length string can // never be balanced if (n % 2 == 1) return false; // Add '(' in the beginning and ')' // in the end of the string string k = \"(\"; k += s + \")\"; List<string> d = new List<string>(); for (int i = 0; i < k.Length; i++) { // If its an opening bracket then // append it to the temp string if (k[i] == '(') d.Add(\"(\"); // If its a closing bracket else { // There was an opening bracket // to match it with if (d.Count != 0) d.RemoveAt(d.Count - 1); // No opening bracket to // match it with else return false; } } // Sequence is balanced if (d.Count == 0) return true; return false; } // Driver Code public static void Main() { string s = \")(()\"; int n = s.Length; if (canBeBalanced(s, n)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} // This code is contributed by// mohit kumar 29", "e": 30978, "s": 29483, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Function that returns true if the sequence // can be balanced by changing the // position of at most one bracketfunction canBeBalanced(s,n){ // Odd length string can // never be balanced if (n % 2 == 1) return false; // Add '(' in the beginning and ')' // in the end of the string let k = \"(\"; k += s + \")\"; let d = []; for (let i = 0; i < k.length; i++) { // If its an opening bracket then // append it to the temp string if (k[i] == '(') d.push(\"(\"); // If its a closing bracket else { // There was an opening bracket // to match it with if (d.length != 0) d.pop(); // No opening bracket to // match it with else return false; } } // Sequence is balanced if (d.length==0) return true; return false;} // Driver Codelet s = \")(()\"; let n = s.length; if (canBeBalanced(s, n)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by unknown2108 </script>", "e": 32323, "s": 30978, "text": null }, { "code": null, "e": 32327, "s": 32323, "text": "Yes" }, { "code": null, "e": 32341, "s": 32329, "text": "sanjeev2552" }, { "code": null, "e": 32356, "s": 32341, "text": "mohit kumar 29" }, { "code": null, "e": 32368, "s": 32356, "text": "unknown2108" }, { "code": null, "e": 32385, "s": 32368, "text": "surinderdawra388" }, { "code": null, "e": 32409, "s": 32385, "text": "Constructive Algorithms" }, { "code": null, "e": 32417, "s": 32409, "text": "Strings" }, { "code": null, "e": 32425, "s": 32417, "text": "Strings" }, { "code": null, "e": 32523, "s": 32425, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32532, "s": 32523, "text": "Comments" }, { "code": null, "e": 32545, "s": 32532, "text": "Old Comments" }, { "code": null, "e": 32590, "s": 32545, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 32602, "s": 32590, "text": "Hill Cipher" }, { "code": null, "e": 32640, "s": 32602, "text": "Naive algorithm for Pattern Searching" }, { "code": null, "e": 32683, "s": 32640, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 32700, "s": 32683, "text": "Vigenère Cipher" }, { "code": null, "e": 32741, "s": 32700, "text": "Convert character array to string in C++" }, { "code": null, "e": 32756, "s": 32741, "text": "sprintf() in C" }, { "code": null, "e": 32798, "s": 32756, "text": "Reverse words in a given String in Python" }, { "code": null, "e": 32859, "s": 32798, "text": "Converting Roman Numerals to Decimal lying between 1 to 3999" } ]
What are member functions of a class in C#?
A member function of a class is a function that has its definition or its prototype within the class definition similar to any other variable. It operates on an object of the class of which it is a member, and has access to all the members of a class for that object. The following is an example of a member function − public void setLength( double len ) { length = len; } public void setBreadth( double bre ) { breadth = bre; } The following is an example showing how to access member functions in C#. Live Demo using System; namespace BoxApplication { class Box { private double length; // Length of a box private double breadth; // Breadth of a box private double height; // Height of a box public void setLength( double len ) { length = len; } public void setBreadth( double bre ) { breadth = bre; } public void setHeight( double hei ) { height = hei; } public double getVolume() { return length * breadth * height; } } class Boxtester { static void Main(string[] args) { Box Box1 = new Box(); // Declare Box1 of type Box Box Box2 = new Box(); double volume; // Declare Box2 of type Box // box 1 specification Box1.setLength(8.0); Box1.setBreadth(9.0); Box1.setHeight(7.0); // box 2 specification Box2.setLength(18.0); Box2.setBreadth(20.0); Box2.setHeight(17.0); // volume of box 1 volume = Box1.getVolume(); Console.WriteLine("Volume of Box1 : {0}" ,volume); // volume of box 2 volume = Box2.getVolume(); Console.WriteLine("Volume of Box2 : {0}", volume); Console.ReadKey(); } } } Volume of Box1 : 504 Volume of Box2 : 6120
[ { "code": null, "e": 1330, "s": 1062, "text": "A member function of a class is a function that has its definition or its prototype within the class definition similar to any other variable. It operates on an object of the class of which it is a member, and has access to all the members of a class for that object." }, { "code": null, "e": 1381, "s": 1330, "text": "The following is an example of a member function −" }, { "code": null, "e": 1497, "s": 1381, "text": "public void setLength( double len ) {\n length = len;\n}\npublic void setBreadth( double bre ) {\n breadth = bre;\n}" }, { "code": null, "e": 1571, "s": 1497, "text": "The following is an example showing how to access member functions in C#." }, { "code": null, "e": 1582, "s": 1571, "text": " Live Demo" }, { "code": null, "e": 2864, "s": 1582, "text": "using System;\n\nnamespace BoxApplication {\n class Box {\n private double length; // Length of a box\n private double breadth; // Breadth of a box\n private double height; // Height of a box\n\n public void setLength( double len ) {\n length = len;\n }\n\n public void setBreadth( double bre ) {\n breadth = bre;\n }\n\n public void setHeight( double hei ) {\n height = hei;\n }\n\n public double getVolume() {\n return length * breadth * height;\n }\n }\n\n class Boxtester {\n static void Main(string[] args) {\n Box Box1 = new Box(); // Declare Box1 of type Box\n Box Box2 = new Box();\n double volume;\n\n // Declare Box2 of type Box\n // box 1 specification\n Box1.setLength(8.0);\n Box1.setBreadth(9.0);\n Box1.setHeight(7.0);\n\n // box 2 specification\n Box2.setLength(18.0);\n Box2.setBreadth(20.0);\n Box2.setHeight(17.0);\n\n // volume of box 1\n volume = Box1.getVolume();\n Console.WriteLine(\"Volume of Box1 : {0}\" ,volume);\n\n // volume of box 2\n volume = Box2.getVolume();\n Console.WriteLine(\"Volume of Box2 : {0}\", volume);\n\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 2907, "s": 2864, "text": "Volume of Box1 : 504\nVolume of Box2 : 6120" } ]
Complexity Cheat Sheet for Python Operations - GeeksforGeeks
24 Feb, 2022 Prerequisite: List, Dictionaries, Sets Python built-in data structures like list, sets, dictionaries provide a large number of operations making it easier to write concise code but not being aware of their complexity can result in unexpected slow behavior of your python code. For example: A simple dictionary lookup Operation can be done by either : if key in d: or if dict.get(key) The first has a time complexity of O(N) for Python2, O(1) for Python3 and the latter has O(1) which can create a lot of difference in nested statements. Important points: Lists are similar to arrays with bidirectional adding and deleting capability.Dictionaries and Set use Hash Tables for insertion/deletion and lookup operations. Lists are similar to arrays with bidirectional adding and deleting capability. Dictionaries and Set use Hash Tables for insertion/deletion and lookup operations. This Cheat sheet can be referred for choosing operations that are efficient with respect to time. For more information, refer to Internal working of list in Python. Note: Tuples have the same operations (non-mutable) and complexities. Note: Defaultdict has operations same as dict with same time complexity as it inherits from dict. For more information, refer to Internal working of Set in Python Note: Frozen sets have the same operations (non-mutable) and complexities. kk773572498 kvtoraman python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | 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": 25579, "s": 25551, "text": "\n24 Feb, 2022" }, { "code": null, "e": 25619, "s": 25579, "text": "Prerequisite: List, Dictionaries, Sets " }, { "code": null, "e": 25858, "s": 25619, "text": "Python built-in data structures like list, sets, dictionaries provide a large number of operations making it easier to write concise code but not being aware of their complexity can result in unexpected slow behavior of your python code. " }, { "code": null, "e": 25872, "s": 25858, "text": "For example: " }, { "code": null, "e": 25935, "s": 25872, "text": "A simple dictionary lookup Operation can be done by either : " }, { "code": null, "e": 25948, "s": 25935, "text": "if key in d:" }, { "code": null, "e": 25951, "s": 25948, "text": "or" }, { "code": null, "e": 25968, "s": 25951, "text": "if dict.get(key)" }, { "code": null, "e": 26122, "s": 25968, "text": "The first has a time complexity of O(N) for Python2, O(1) for Python3 and the latter has O(1) which can create a lot of difference in nested statements. " }, { "code": null, "e": 26142, "s": 26122, "text": "Important points: " }, { "code": null, "e": 26303, "s": 26142, "text": "Lists are similar to arrays with bidirectional adding and deleting capability.Dictionaries and Set use Hash Tables for insertion/deletion and lookup operations." }, { "code": null, "e": 26382, "s": 26303, "text": "Lists are similar to arrays with bidirectional adding and deleting capability." }, { "code": null, "e": 26465, "s": 26382, "text": "Dictionaries and Set use Hash Tables for insertion/deletion and lookup operations." }, { "code": null, "e": 26564, "s": 26465, "text": "This Cheat sheet can be referred for choosing operations that are efficient with respect to time. " }, { "code": null, "e": 26634, "s": 26566, "text": "For more information, refer to Internal working of list in Python. " }, { "code": null, "e": 26705, "s": 26634, "text": "Note: Tuples have the same operations (non-mutable) and complexities. " }, { "code": null, "e": 26806, "s": 26707, "text": "Note: Defaultdict has operations same as dict with same time complexity as it inherits from dict. " }, { "code": null, "e": 26876, "s": 26810, "text": "For more information, refer to Internal working of Set in Python " }, { "code": null, "e": 26952, "s": 26876, "text": "Note: Frozen sets have the same operations (non-mutable) and complexities. " }, { "code": null, "e": 26966, "s": 26954, "text": "kk773572498" }, { "code": null, "e": 26976, "s": 26966, "text": "kvtoraman" }, { "code": null, "e": 26991, "s": 26976, "text": "python-utility" }, { "code": null, "e": 26998, "s": 26991, "text": "Python" }, { "code": null, "e": 27096, "s": 26998, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27128, "s": 27096, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27170, "s": 27128, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27212, "s": 27170, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27268, "s": 27212, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27295, "s": 27268, "text": "Python Classes and Objects" }, { "code": null, "e": 27326, "s": 27295, "text": "Python | os.path.join() method" }, { "code": null, "e": 27365, "s": 27326, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27394, "s": 27365, "text": "Create a directory in Python" }, { "code": null, "e": 27416, "s": 27394, "text": "Defaultdict in Python" } ]
Span<T>.Enumerator Struct in C# - GeeksforGeeks
23 Mar, 2022 Span<T> is a new feature introduced with C# 7.2 and supported in the .NET Core 2.1. It provides a type-safe access to a contiguous area of memory. This memory can be located on the heap, stack or formed a unallocated memory. Span<T> is defined as a ref struct, which means it is limited to being allocated only on the Stack. The main reason for the ref struct design is to ensure that when using of Span<T> it causes no additional heap allocations. Span<T> improves execution speed and reducing memory allocations in existing code. Here, Span<T> references some contiguous memory(colored blocks) that has already been allocated.Span<T>.Enumerator struct provides an enumerator for the elements of a Span<T>. Where Span<T> provides a type and memory safe representation of a contiguous region of arbitrary memory. Syntax: public struct Span<T>.Enumerator Parameter: Here the parameter is T, where T is the type of items in the Span<T>.Example: csharp // C# program to demonstrate Span<T>.Enumerator Structusing System;using System.Threading.Tasks; class GFG { // a array "arr" type of byte private static byte[] arr = new byte[4]; // main method static void Main() { // randomly fillup the array "arr" new Random(30).NextBytes(arr); // implicitly cast the array // "arr" to span<byte> Span<byte> sp = arr; // Task.Run() method executes // the clear() method // to clear the array for // each thread operations Task.Run(() => clear()); // call the function "print" print(sp); } public static void clear() { // delay for 10ms Task.Delay(10).Wait(); lock(arr) // defines that one thread // executes one task at one time { Array.Clear(arr, 0, arr.Length); } } // print function public static void print(Span<byte> span) { foreach(byte e in span) { Console.WriteLine(e); Task.Delay(10).Wait(); } }} Output: 52 239 0 0 Properties: Current: It is used to get a reference to the item at the current position of the enumerator. Methods: MoveNext(): It advances the enumerator to the next item of the Span<T>. Important Points: Span<T> provides a type-safe access to a contiguous area of memory. It cannot be used within asynchronous methods. It does not implement the IEnumerator or IEnumerator<T> interface, because Span<T> enumerator is a ref struct. It does not include a Reset method. For use the Reset() method, it must be implemented as part of the interface. It does not include additional heap allocation. It cannot be used as a generic type argument. Span<T> provides read-write access to the memory. ReadOnlySpan<T> provides read-only access to a memory. Akanksha_Rai sumitgumber28 simmytarika5 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 Partial Classes in C# C# | Inheritance C# | Generics - Introduction Switch Statement in C# Top 50 C# Interview Questions & Answers Lambda Expressions in C# C# | How to insert an element in an Array? Convert String to Character Array in C#
[ { "code": null, "e": 26098, "s": 26070, "text": "\n23 Mar, 2022" }, { "code": null, "e": 26631, "s": 26098, "text": "Span<T> is a new feature introduced with C# 7.2 and supported in the .NET Core 2.1. It provides a type-safe access to a contiguous area of memory. This memory can be located on the heap, stack or formed a unallocated memory. Span<T> is defined as a ref struct, which means it is limited to being allocated only on the Stack. The main reason for the ref struct design is to ensure that when using of Span<T> it causes no additional heap allocations. Span<T> improves execution speed and reducing memory allocations in existing code. " }, { "code": null, "e": 26922, "s": 26631, "text": "Here, Span<T> references some contiguous memory(colored blocks) that has already been allocated.Span<T>.Enumerator struct provides an enumerator for the elements of a Span<T>. Where Span<T> provides a type and memory safe representation of a contiguous region of arbitrary memory. Syntax: " }, { "code": null, "e": 26955, "s": 26922, "text": "public struct Span<T>.Enumerator" }, { "code": null, "e": 27045, "s": 26955, "text": "Parameter: Here the parameter is T, where T is the type of items in the Span<T>.Example: " }, { "code": null, "e": 27052, "s": 27045, "text": "csharp" }, { "code": "// C# program to demonstrate Span<T>.Enumerator Structusing System;using System.Threading.Tasks; class GFG { // a array \"arr\" type of byte private static byte[] arr = new byte[4]; // main method static void Main() { // randomly fillup the array \"arr\" new Random(30).NextBytes(arr); // implicitly cast the array // \"arr\" to span<byte> Span<byte> sp = arr; // Task.Run() method executes // the clear() method // to clear the array for // each thread operations Task.Run(() => clear()); // call the function \"print\" print(sp); } public static void clear() { // delay for 10ms Task.Delay(10).Wait(); lock(arr) // defines that one thread // executes one task at one time { Array.Clear(arr, 0, arr.Length); } } // print function public static void print(Span<byte> span) { foreach(byte e in span) { Console.WriteLine(e); Task.Delay(10).Wait(); } }}", "e": 28149, "s": 27052, "text": null }, { "code": null, "e": 28159, "s": 28149, "text": "Output: " }, { "code": null, "e": 28170, "s": 28159, "text": "52\n239\n0\n0" }, { "code": null, "e": 28186, "s": 28172, "text": "Properties: " }, { "code": null, "e": 28280, "s": 28186, "text": "Current: It is used to get a reference to the item at the current position of the enumerator." }, { "code": null, "e": 28291, "s": 28280, "text": "Methods: " }, { "code": null, "e": 28363, "s": 28291, "text": "MoveNext(): It advances the enumerator to the next item of the Span<T>." }, { "code": null, "e": 28382, "s": 28363, "text": "Important Points: " }, { "code": null, "e": 28450, "s": 28382, "text": "Span<T> provides a type-safe access to a contiguous area of memory." }, { "code": null, "e": 28497, "s": 28450, "text": "It cannot be used within asynchronous methods." }, { "code": null, "e": 28608, "s": 28497, "text": "It does not implement the IEnumerator or IEnumerator<T> interface, because Span<T> enumerator is a ref struct." }, { "code": null, "e": 28644, "s": 28608, "text": "It does not include a Reset method." }, { "code": null, "e": 28721, "s": 28644, "text": "For use the Reset() method, it must be implemented as part of the interface." }, { "code": null, "e": 28769, "s": 28721, "text": "It does not include additional heap allocation." }, { "code": null, "e": 28815, "s": 28769, "text": "It cannot be used as a generic type argument." }, { "code": null, "e": 28865, "s": 28815, "text": "Span<T> provides read-write access to the memory." }, { "code": null, "e": 28920, "s": 28865, "text": "ReadOnlySpan<T> provides read-only access to a memory." }, { "code": null, "e": 28935, "s": 28922, "text": "Akanksha_Rai" }, { "code": null, "e": 28949, "s": 28935, "text": "sumitgumber28" }, { "code": null, "e": 28962, "s": 28949, "text": "simmytarika5" }, { "code": null, "e": 28965, "s": 28962, "text": "C#" }, { "code": null, "e": 29063, "s": 28965, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29086, "s": 29063, "text": "Extension Method in C#" }, { "code": null, "e": 29114, "s": 29086, "text": "HashSet in C# with Examples" }, { "code": null, "e": 29136, "s": 29114, "text": "Partial Classes in C#" }, { "code": null, "e": 29153, "s": 29136, "text": "C# | Inheritance" }, { "code": null, "e": 29182, "s": 29153, "text": "C# | Generics - Introduction" }, { "code": null, "e": 29205, "s": 29182, "text": "Switch Statement in C#" }, { "code": null, "e": 29245, "s": 29205, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 29270, "s": 29245, "text": "Lambda Expressions in C#" }, { "code": null, "e": 29313, "s": 29270, "text": "C# | How to insert an element in an Array?" } ]
OpenCV - Alpha blending and masking of images - GeeksforGeeks
16 Mar, 2021 Alpha blending is the process of overlaying a foreground image on a background image. We take these two images to blend : gfg.png apple.jpeg Steps : First, we will import OpenCV. We read the two images that we want to blend. The images are displayed. We have a while loop that runs while the choice is 1. Enter an alpha value. Use cv2.addWeighted() to add the weighted images. We display and save the image as alpha_{image}.png. To continue and try out more alpha values, press 1. Else press 0 to exit. Python3 import cv2 img1 = cv2.imread('gfg.png')img2 = cv2.imread('apple.jpeg') img2 = cv2.resize(img2, img1.shape[1::-1]) cv2.imshow("img 1",img1) cv2.waitKey(0) cv2.imshow("img 2",img2) cv2.waitKey(0) choice = 1 while (choice) : alpha = float(input("Enter alpha value")) dst = cv2.addWeighted(img1, alpha , img2, 1-alpha, 0) cv2.imwrite('alpha_mask_.png', dst) img3 = cv2.imread('alpha_mask_.png') cv2.imshow("alpha blending 1",img3) cv2.waitKey(0) choice = int(input("Enter 1 to continue and 0 to exit")) Outputs: alpha = 0.8 alpha = 0.5 Alpha masking: We can create a black and white mask from an image with a transparent background. Python3 import cv2im = cv2.imread("spectacles.png", cv2.IMREAD_UNCHANGED)_, mask = cv2.threshold(im[:, :, 3], 0, 255, cv2.THRESH_BINARY)cv2.imwrite('mask.jpg', mask) Output: OpenCV Picked Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | os.path.join() method Defaultdict in Python Create a directory in Python Python Classes and Objects
[ { "code": null, "e": 24238, "s": 24210, "text": "\n16 Mar, 2021" }, { "code": null, "e": 24324, "s": 24238, "text": "Alpha blending is the process of overlaying a foreground image on a background image." }, { "code": null, "e": 24360, "s": 24324, "text": "We take these two images to blend :" }, { "code": null, "e": 24368, "s": 24360, "text": "gfg.png" }, { "code": null, "e": 24379, "s": 24368, "text": "apple.jpeg" }, { "code": null, "e": 24387, "s": 24379, "text": "Steps :" }, { "code": null, "e": 24417, "s": 24387, "text": "First, we will import OpenCV." }, { "code": null, "e": 24463, "s": 24417, "text": "We read the two images that we want to blend." }, { "code": null, "e": 24489, "s": 24463, "text": "The images are displayed." }, { "code": null, "e": 24543, "s": 24489, "text": "We have a while loop that runs while the choice is 1." }, { "code": null, "e": 24565, "s": 24543, "text": "Enter an alpha value." }, { "code": null, "e": 24615, "s": 24565, "text": "Use cv2.addWeighted() to add the weighted images." }, { "code": null, "e": 24667, "s": 24615, "text": "We display and save the image as alpha_{image}.png." }, { "code": null, "e": 24741, "s": 24667, "text": "To continue and try out more alpha values, press 1. Else press 0 to exit." }, { "code": null, "e": 24749, "s": 24741, "text": "Python3" }, { "code": "import cv2 img1 = cv2.imread('gfg.png')img2 = cv2.imread('apple.jpeg') img2 = cv2.resize(img2, img1.shape[1::-1]) cv2.imshow(\"img 1\",img1) cv2.waitKey(0) cv2.imshow(\"img 2\",img2) cv2.waitKey(0) choice = 1 while (choice) : alpha = float(input(\"Enter alpha value\")) dst = cv2.addWeighted(img1, alpha , img2, 1-alpha, 0) cv2.imwrite('alpha_mask_.png', dst) img3 = cv2.imread('alpha_mask_.png') cv2.imshow(\"alpha blending 1\",img3) cv2.waitKey(0) choice = int(input(\"Enter 1 to continue and 0 to exit\"))", "e": 25291, "s": 24749, "text": null }, { "code": null, "e": 25300, "s": 25291, "text": "Outputs:" }, { "code": null, "e": 25312, "s": 25300, "text": "alpha = 0.8" }, { "code": null, "e": 25324, "s": 25312, "text": "alpha = 0.5" }, { "code": null, "e": 25339, "s": 25324, "text": "Alpha masking:" }, { "code": null, "e": 25421, "s": 25339, "text": "We can create a black and white mask from an image with a transparent background." }, { "code": null, "e": 25429, "s": 25421, "text": "Python3" }, { "code": "import cv2im = cv2.imread(\"spectacles.png\", cv2.IMREAD_UNCHANGED)_, mask = cv2.threshold(im[:, :, 3], 0, 255, cv2.THRESH_BINARY)cv2.imwrite('mask.jpg', mask)", "e": 25587, "s": 25429, "text": null }, { "code": null, "e": 25595, "s": 25587, "text": "Output:" }, { "code": null, "e": 25602, "s": 25595, "text": "OpenCV" }, { "code": null, "e": 25609, "s": 25602, "text": "Picked" }, { "code": null, "e": 25623, "s": 25609, "text": "Python-OpenCV" }, { "code": null, "e": 25630, "s": 25623, "text": "Python" }, { "code": null, "e": 25728, "s": 25630, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25737, "s": 25728, "text": "Comments" }, { "code": null, "e": 25750, "s": 25737, "text": "Old Comments" }, { "code": null, "e": 25782, "s": 25750, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25837, "s": 25782, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 25893, "s": 25837, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25932, "s": 25893, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25974, "s": 25932, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26016, "s": 25974, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26047, "s": 26016, "text": "Python | os.path.join() method" }, { "code": null, "e": 26069, "s": 26047, "text": "Defaultdict in Python" }, { "code": null, "e": 26098, "s": 26069, "text": "Create a directory in Python" } ]
User defined Functions in C - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorial, we are going to learn about the User defined functions in C. User-defined functions are the functions that are defined by the user at the time of writing the program. Functions are made for code re-usability and for saving time and space. In C, main() is the user-defined function and first calling function in any program. main() is a special function that tells the compiler to start the execution of a C program from the beginning of the function main(). An identifier other than keywords followed by parenthesis is recognized as a function name by the compiler. To make use of the user-defined function the programmer must be able to know the following 3 concepts. Define a Function (or) Function Definition Function Prototype (or) Function Declaration Calling a Function (or) Invoke a Function Define a Function (or) Function Definition Function Prototype (or) Function Declaration Calling a Function (or) Invoke a Function A function definition describes what a function does, how its actions are achieved, and how it is used. It consists of a function header and a function body. The general format of defining a function is return_type function_name(parameters list) { //Local variable declarations //Executable statements return(expression); } The first line which heads the function is known as the function header. The function header should not end with a semicolon (;) in defining a function. The function body follows the function header and it is always enclosed in braces. The body of the function is a combination of local variable declarations and executable statements. Here the statements describe the actions to be performed by the function. The body of function definition is also known as a block or compound statement. The elements specified within the parenthesis of the function name are known as parameters or arguments. The general format of defining a function is return_type function_name(parameters list) { //Local variable declarations //Executable statements return(expression); } The return_type specifies the data type of the value returned by the function. The return_value may be of the primitive data type or empty data type. If return_type is omitted then the default return_type of any function is int. A void is specified in the place of return_type if the function returns no value. function_name is any valid identifier. It can’t begin with an underscore because such names are reserved for the use of the C library. The arguments in the parameter_list are known as formal parameters. Zero or more parameters may be used. Each parameter must be preceded by its data type. More than one parameter must be separated by commas. Parameters are used to pass the values into the function definition. For parameterless functions, the keyword void is placed within the parenthesis of the function name. It consists of the keyword return followed by an expression within the block and it returns only a single value to the calling function when the function returns a value. A value or an expression may follow a return if the function returns a value; otherwise, nothing follows return. The syntax of the return statement is return(expression); (Or) return expression; The following points must be kept in mind while defining a function. A function cannot be defined more than once in a program. One function cannot be defined within another function definition. Function definitions may appear in any order. Built-in functions are predefined and they are available in the C library that is supplied along with the compiler. Whenever a function is invoked within another function it must be declared before use. Such declaration is known as function declaration or function prototype. Function declaration always ends with a semicolon (;). The general format of the function prototype is return_type function_name(parameter_list); In the above function declaration, the parameter names in the parameter_list are optional. Hence, it is possible to have the data type of each parameter without mentioning the parameter name as shown below. return_type function_name(data_type, data_type, data_type,...., data_type); A parameterless function is declared by using void inside the parenthesis as return_type function_name(void); For user understandability, all the function declarations are specified before the main() function. A function is invoked to make use of it. The general format of a function call is function_name(var_1, var_2 .... var_n); Where var_1, var_2,..., var_n are argument expressions. For a parameterless function, there is no argument in the function call also. The arguments var_1, var_2,..., var_n in a function call is called actual arguments. If a function returns a value, the function call may appear in any expression, and the returned value used as an operand in the evaluation of the expression. gnu – C functions gnu – Function Definitions C Program Structure Happy Learning 🙂 C – Derived and User Defined Data Types Functions in C PHP Functions Example Tutorials user defined exceptions in Java User defined Exceptions in Python User defined sorting with Java 8 Comparator Python Decorators – Classes and Functions JQuery Callback Functions Example Tutorial Hello World Java Program Example PHP String functions Example Tutorials Different ways to use Lambdas in Python C – Header Files & Preprocessor Directives C – Type Conversions What are Python default function parameters ? Java Class Example Tutorials C – Derived and User Defined Data Types Functions in C PHP Functions Example Tutorials user defined exceptions in Java User defined Exceptions in Python User defined sorting with Java 8 Comparator Python Decorators – Classes and Functions JQuery Callback Functions Example Tutorial Hello World Java Program Example PHP String functions Example Tutorials Different ways to use Lambdas in Python C – Header Files & Preprocessor Directives C – Type Conversions What are Python default function parameters ? Java Class Example Tutorials Δ C – Introduction C – Features C – Variables & Keywords C – Program Structure C – Comment Lines & Tokens C – Number System C – Local and Global Variables C – Scope & Lifetime of Variables C – Data Types C – Integer Data Types C – Floating Data Types C – Derived, Defined Data Types C – Type Conversions C – Arithmetic Operators C – Bitwise Operators C – Logical Operators C – Comma and sizeof Operators C – Operator Precedence and Associativity C – Relational Operators C Flow Control – if, if-else, nested if-else, if-else-if C – Switch Case C Iterative – for, while, dowhile loops C Unconditional – break, continue, goto statements C – Expressions and Statements C – Header Files & Preprocessor Directives C – One Dimensional Arrays C – Multi Dimensional Arrays C – Pointers Basics C – Pointers with Arrays C – Functions C – How to Pass Arrays to Functions C – Categories of Functions C – User defined Functions C – Formal and Actual Arguments C – Recursion functions C – Structures Part -1 C – Structures Part -2 C – Unions C – File Handling C – File Operations C – Dynamic Memory Allocation C Program – Fibonacci Series C Program – Prime or Not C Program – Factorial of Number C Program – Even or Odd C Program – Sum of digits till Single Digit C Program – Sum of digits C Program – Reverse of a number C Program – Armstrong Numbers C Program – Print prime Numbers C Program – GCD of two Numbers C Program – Number Palindrome or Not C Program – Find Largest and Smallest number in an Array C Program – Add elements of an Array C Program – Addition of Matrices C Program – Multiplication of Matrices C Program – Reverse of an Array C Program – Bubble Sort C Program – Add and Sub without using + –
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 477, "s": 398, "text": "In this tutorial, we are going to learn about the User defined functions in C." }, { "code": null, "e": 655, "s": 477, "text": "User-defined functions are the functions that are defined by the user at the time of writing the program. Functions are made for code re-usability and for saving time and space." }, { "code": null, "e": 874, "s": 655, "text": "In C, main() is the user-defined function and first calling function in any program. main() is a special function that tells the compiler to start the execution of a C program from the beginning of the function main()." }, { "code": null, "e": 982, "s": 874, "text": "An identifier other than keywords followed by parenthesis is recognized as a function name by the compiler." }, { "code": null, "e": 1085, "s": 982, "text": "To make use of the user-defined function the programmer must be able to know the following 3 concepts." }, { "code": null, "e": 1217, "s": 1085, "text": "\nDefine a Function (or) Function Definition\nFunction Prototype (or) Function Declaration\nCalling a Function (or) Invoke a Function\n" }, { "code": null, "e": 1260, "s": 1217, "text": "Define a Function (or) Function Definition" }, { "code": null, "e": 1305, "s": 1260, "text": "Function Prototype (or) Function Declaration" }, { "code": null, "e": 1347, "s": 1305, "text": "Calling a Function (or) Invoke a Function" }, { "code": null, "e": 1505, "s": 1347, "text": "A function definition describes what a function does, how its actions are achieved, and how it is used. It consists of a function header and a function body." }, { "code": null, "e": 1550, "s": 1505, "text": "The general format of defining a function is" }, { "code": null, "e": 1677, "s": 1550, "text": "return_type function_name(parameters list) {\n //Local variable declarations\n //Executable statements\n return(expression);\n}" }, { "code": null, "e": 1830, "s": 1677, "text": "The first line which heads the function is known as the function header. The function header should not end with a semicolon (;) in defining a function." }, { "code": null, "e": 2013, "s": 1830, "text": "The function body follows the function header and it is always enclosed in braces. The body of the function is a combination of local variable declarations and executable statements." }, { "code": null, "e": 2272, "s": 2013, "text": "Here the statements describe the actions to be performed by the function. The body of function definition is also known as a block or compound statement. The elements specified within the parenthesis of the function name are known as parameters or arguments." }, { "code": null, "e": 2317, "s": 2272, "text": "The general format of defining a function is" }, { "code": null, "e": 2444, "s": 2317, "text": "return_type function_name(parameters list) {\n //Local variable declarations\n //Executable statements\n return(expression);\n}" }, { "code": null, "e": 2594, "s": 2444, "text": "The return_type specifies the data type of the value returned by the function. The return_value may be of the primitive data type or empty data type." }, { "code": null, "e": 2890, "s": 2594, "text": "If return_type is omitted then the default return_type of any function is int. A void is specified in the place of return_type if the function returns no value. function_name is any valid identifier. It can’t begin with an underscore because such names are reserved for the use of the C library." }, { "code": null, "e": 3045, "s": 2890, "text": "The arguments in the parameter_list are known as formal parameters. Zero or more parameters may be used. Each parameter must be preceded by its data type." }, { "code": null, "e": 3439, "s": 3045, "text": "More than one parameter must be separated by commas. Parameters are used to pass the values into the function definition. For parameterless functions, the keyword void is placed within the parenthesis of the function name. It consists of the keyword return followed by an expression within the block and it returns only a single value to the calling function when the function returns a value." }, { "code": null, "e": 3590, "s": 3439, "text": "A value or an expression may follow a return if the function returns a value; otherwise, nothing follows return. The syntax of the return statement is" }, { "code": null, "e": 3634, "s": 3590, "text": "return(expression); (Or) return expression;" }, { "code": null, "e": 3703, "s": 3634, "text": "The following points must be kept in mind while defining a function." }, { "code": null, "e": 3761, "s": 3703, "text": "A function cannot be defined more than once in a program." }, { "code": null, "e": 3828, "s": 3761, "text": "One function cannot be defined within another function definition." }, { "code": null, "e": 3874, "s": 3828, "text": "Function definitions may appear in any order." }, { "code": null, "e": 3990, "s": 3874, "text": "Built-in functions are predefined and they are available in the C library that is supplied along with the compiler." }, { "code": null, "e": 4150, "s": 3990, "text": "Whenever a function is invoked within another function it must be declared before use. Such declaration is known as function declaration or function prototype." }, { "code": null, "e": 4253, "s": 4150, "text": "Function declaration always ends with a semicolon (;). The general format of the function prototype is" }, { "code": null, "e": 4296, "s": 4253, "text": "return_type function_name(parameter_list);" }, { "code": null, "e": 4503, "s": 4296, "text": "In the above function declaration, the parameter names in the parameter_list are optional.\nHence, it is possible to have the data type of each parameter without mentioning the parameter name as shown below." }, { "code": null, "e": 4580, "s": 4503, "text": "return_type function_name(data_type, data_type, data_type,...., data_type);\n" }, { "code": null, "e": 4657, "s": 4580, "text": "A parameterless function is declared by using void inside the parenthesis as" }, { "code": null, "e": 4690, "s": 4657, "text": "return_type function_name(void);" }, { "code": null, "e": 4872, "s": 4690, "text": "For user understandability, all the function declarations are specified before the main() function. A function is invoked to make use of it. The general format of a function call is" }, { "code": null, "e": 4912, "s": 4872, "text": "function_name(var_1, var_2 .... var_n);" }, { "code": null, "e": 5046, "s": 4912, "text": "Where var_1, var_2,..., var_n are argument expressions. For a parameterless function, there is no argument in the function call also." }, { "code": null, "e": 5131, "s": 5046, "text": "The arguments var_1, var_2,..., var_n in a function call is called actual arguments." }, { "code": null, "e": 5289, "s": 5131, "text": "If a function returns a value, the function call may appear in any expression, and the returned value used as an operand in the evaluation of the expression." }, { "code": null, "e": 5307, "s": 5289, "text": "gnu – C functions" }, { "code": null, "e": 5334, "s": 5307, "text": "gnu – Function Definitions" }, { "code": null, "e": 5354, "s": 5334, "text": "C Program Structure" }, { "code": null, "e": 5371, "s": 5354, "text": "Happy Learning 🙂" }, { "code": null, "e": 5906, "s": 5371, "text": "\nC – Derived and User Defined Data Types\nFunctions in C\nPHP Functions Example Tutorials\nuser defined exceptions in Java\nUser defined Exceptions in Python\nUser defined sorting with Java 8 Comparator\nPython Decorators – Classes and Functions\nJQuery Callback Functions Example Tutorial\nHello World Java Program Example\nPHP String functions Example Tutorials\nDifferent ways to use Lambdas in Python\nC – Header Files & Preprocessor Directives\nC – Type Conversions\nWhat are Python default function parameters ?\nJava Class Example Tutorials\n" }, { "code": null, "e": 5946, "s": 5906, "text": "C – Derived and User Defined Data Types" }, { "code": null, "e": 5961, "s": 5946, "text": "Functions in C" }, { "code": null, "e": 5993, "s": 5961, "text": "PHP Functions Example Tutorials" }, { "code": null, "e": 6025, "s": 5993, "text": "user defined exceptions in Java" }, { "code": null, "e": 6059, "s": 6025, "text": "User defined Exceptions in Python" }, { "code": null, "e": 6103, "s": 6059, "text": "User defined sorting with Java 8 Comparator" }, { "code": null, "e": 6145, "s": 6103, "text": "Python Decorators – Classes and Functions" }, { "code": null, "e": 6188, "s": 6145, "text": "JQuery Callback Functions Example Tutorial" }, { "code": null, "e": 6221, "s": 6188, "text": "Hello World Java Program Example" }, { "code": null, "e": 6260, "s": 6221, "text": "PHP String functions Example Tutorials" }, { "code": null, "e": 6300, "s": 6260, "text": "Different ways to use Lambdas in Python" }, { "code": null, "e": 6343, "s": 6300, "text": "C – Header Files & Preprocessor Directives" }, { "code": null, "e": 6364, "s": 6343, "text": "C – Type Conversions" }, { "code": null, "e": 6410, "s": 6364, "text": "What are Python default function parameters ?" }, { "code": null, "e": 6439, "s": 6410, "text": "Java Class Example Tutorials" }, { "code": null, "e": 6445, "s": 6443, "text": "Δ" }, { "code": null, "e": 6463, "s": 6445, "text": " C – Introduction" }, { "code": null, "e": 6477, "s": 6463, "text": " C – Features" }, { "code": null, "e": 6503, "s": 6477, "text": " C – Variables & Keywords" }, { "code": null, "e": 6526, "s": 6503, "text": " C – Program Structure" }, { "code": null, "e": 6555, "s": 6526, "text": " C – Comment Lines & Tokens" }, { "code": null, "e": 6574, "s": 6555, "text": " C – Number System" }, { "code": null, "e": 6606, "s": 6574, "text": " C – Local and Global Variables" }, { "code": null, "e": 6641, "s": 6606, "text": " C – Scope & Lifetime of Variables" }, { "code": null, "e": 6657, "s": 6641, "text": " C – Data Types" }, { "code": null, "e": 6681, "s": 6657, "text": " C – Integer Data Types" }, { "code": null, "e": 6706, "s": 6681, "text": " C – Floating Data Types" }, { "code": null, "e": 6739, "s": 6706, "text": " C – Derived, Defined Data Types" }, { "code": null, "e": 6761, "s": 6739, "text": " C – Type Conversions" }, { "code": null, "e": 6787, "s": 6761, "text": " C – Arithmetic Operators" }, { "code": null, "e": 6810, "s": 6787, "text": " C – Bitwise Operators" }, { "code": null, "e": 6833, "s": 6810, "text": " C – Logical Operators" }, { "code": null, "e": 6866, "s": 6833, "text": " C – Comma and sizeof Operators" }, { "code": null, "e": 6909, "s": 6866, "text": " C – Operator Precedence and Associativity" }, { "code": null, "e": 6935, "s": 6909, "text": " C – Relational Operators" }, { "code": null, "e": 6993, "s": 6935, "text": " C Flow Control – if, if-else, nested if-else, if-else-if" }, { "code": null, "e": 7010, "s": 6993, "text": " C – Switch Case" }, { "code": null, "e": 7051, "s": 7010, "text": " C Iterative – for, while, dowhile loops" }, { "code": null, "e": 7103, "s": 7051, "text": " C Unconditional – break, continue, goto statements" }, { "code": null, "e": 7135, "s": 7103, "text": " C – Expressions and Statements" }, { "code": null, "e": 7179, "s": 7135, "text": " C – Header Files & Preprocessor Directives" }, { "code": null, "e": 7207, "s": 7179, "text": " C – One Dimensional Arrays" }, { "code": null, "e": 7237, "s": 7207, "text": " C – Multi Dimensional Arrays" }, { "code": null, "e": 7258, "s": 7237, "text": " C – Pointers Basics" }, { "code": null, "e": 7284, "s": 7258, "text": " C – Pointers with Arrays" }, { "code": null, "e": 7299, "s": 7284, "text": " C – Functions" }, { "code": null, "e": 7336, "s": 7299, "text": " C – How to Pass Arrays to Functions" }, { "code": null, "e": 7365, "s": 7336, "text": " C – Categories of Functions" }, { "code": null, "e": 7393, "s": 7365, "text": " C – User defined Functions" }, { "code": null, "e": 7426, "s": 7393, "text": " C – Formal and Actual Arguments" }, { "code": null, "e": 7451, "s": 7426, "text": " C – Recursion functions" }, { "code": null, "e": 7475, "s": 7451, "text": " C – Structures Part -1" }, { "code": null, "e": 7499, "s": 7475, "text": " C – Structures Part -2" }, { "code": null, "e": 7511, "s": 7499, "text": " C – Unions" }, { "code": null, "e": 7530, "s": 7511, "text": " C – File Handling" }, { "code": null, "e": 7551, "s": 7530, "text": " C – File Operations" }, { "code": null, "e": 7582, "s": 7551, "text": " C – Dynamic Memory Allocation" }, { "code": null, "e": 7612, "s": 7582, "text": " C Program – Fibonacci Series" }, { "code": null, "e": 7638, "s": 7612, "text": " C Program – Prime or Not" }, { "code": null, "e": 7671, "s": 7638, "text": " C Program – Factorial of Number" }, { "code": null, "e": 7696, "s": 7671, "text": " C Program – Even or Odd" }, { "code": null, "e": 7741, "s": 7696, "text": " C Program – Sum of digits till Single Digit" }, { "code": null, "e": 7768, "s": 7741, "text": " C Program – Sum of digits" }, { "code": null, "e": 7801, "s": 7768, "text": " C Program – Reverse of a number" }, { "code": null, "e": 7832, "s": 7801, "text": " C Program – Armstrong Numbers" }, { "code": null, "e": 7865, "s": 7832, "text": " C Program – Print prime Numbers" }, { "code": null, "e": 7897, "s": 7865, "text": " C Program – GCD of two Numbers" }, { "code": null, "e": 7935, "s": 7897, "text": " C Program – Number Palindrome or Not" }, { "code": null, "e": 7993, "s": 7935, "text": " C Program – Find Largest and Smallest number in an Array" }, { "code": null, "e": 8031, "s": 7993, "text": " C Program – Add elements of an Array" }, { "code": null, "e": 8065, "s": 8031, "text": " C Program – Addition of Matrices" }, { "code": null, "e": 8105, "s": 8065, "text": " C Program – Multiplication of Matrices" }, { "code": null, "e": 8138, "s": 8105, "text": " C Program – Reverse of an Array" }, { "code": null, "e": 8163, "s": 8138, "text": " C Program – Bubble Sort" } ]
Class getEnclosingMethod() method in Java with Examples - GeeksforGeeks
27 Jan, 2022 The getEnclosingMethod() method of java.lang.Class class is used to get the enclosing methods of this class. The method returns the enclosing methods of this class if this class is a local class or anonymous class declared in that method. Else this method returns null.Syntax: public Method getEnclosingMethod() Parameter: This method does not accept any parameter.Return Value: This method returns the enclosing methods of this class if this class is a local class or anonymous class declared in that method. Else this method returns null.Exception This method throws SecurityException if a security manager is present and the security conditions are not met.Below programs demonstrate the getEnclosingMethod() method.Example 1: Java // Java program to demonstrate getEnclosingMethod() method import java.util.*; public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); // Get the enclosing methods of myClass // using getEnclosingMethod() method System.out.println("EnclosingMethod of myClass: " + myClass.getEnclosingMethod()); }} Class represented by myClass: class Test EnclosingMethod of myClass: null Example 2: Java // Java program to demonstrate getEnclosingMethod() method import java.util.*; class Main { public Object obj; public Object func() { class Arr { }; return new Arr(); } public static void main(String[] args) throws ClassNotFoundException { Main t = new Main(); // returns the Class object Class myClass = t.func().getClass(); // Get the enclosing constructors of myClass // using getEnclosingConstructor() constructor System.out.println("getEnclosingMethod of myClass: " + myClass.getEnclosingMethod()); }} EnclosingConstructor of myClass: public java.lang.Object Main.func() Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getEnclosingMethod– saurabh1990aror Java-Functions Java-lang package Java.lang.Class Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Initialize an ArrayList in Java HashMap in Java with Examples Object Oriented Programming (OOPs) Concept in Java ArrayList in Java How to iterate any Map in Java Multidimensional Arrays in Java Stack Class in Java Singleton Class in Java Set in Java Overriding in Java
[ { "code": null, "e": 24346, "s": 24318, "text": "\n27 Jan, 2022" }, { "code": null, "e": 24625, "s": 24346, "text": "The getEnclosingMethod() method of java.lang.Class class is used to get the enclosing methods of this class. The method returns the enclosing methods of this class if this class is a local class or anonymous class declared in that method. Else this method returns null.Syntax: " }, { "code": null, "e": 24660, "s": 24625, "text": "public Method getEnclosingMethod()" }, { "code": null, "e": 25079, "s": 24660, "text": "Parameter: This method does not accept any parameter.Return Value: This method returns the enclosing methods of this class if this class is a local class or anonymous class declared in that method. Else this method returns null.Exception This method throws SecurityException if a security manager is present and the security conditions are not met.Below programs demonstrate the getEnclosingMethod() method.Example 1: " }, { "code": null, "e": 25084, "s": 25079, "text": "Java" }, { "code": "// Java program to demonstrate getEnclosingMethod() method import java.util.*; public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); // Get the enclosing methods of myClass // using getEnclosingMethod() method System.out.println(\"EnclosingMethod of myClass: \" + myClass.getEnclosingMethod()); }}", "e": 25687, "s": 25084, "text": null }, { "code": null, "e": 25761, "s": 25687, "text": "Class represented by myClass: class Test\nEnclosingMethod of myClass: null" }, { "code": null, "e": 25775, "s": 25763, "text": "Example 2: " }, { "code": null, "e": 25780, "s": 25775, "text": "Java" }, { "code": "// Java program to demonstrate getEnclosingMethod() method import java.util.*; class Main { public Object obj; public Object func() { class Arr { }; return new Arr(); } public static void main(String[] args) throws ClassNotFoundException { Main t = new Main(); // returns the Class object Class myClass = t.func().getClass(); // Get the enclosing constructors of myClass // using getEnclosingConstructor() constructor System.out.println(\"getEnclosingMethod of myClass: \" + myClass.getEnclosingMethod()); }}", "e": 26409, "s": 25780, "text": null }, { "code": null, "e": 26478, "s": 26409, "text": "EnclosingConstructor of myClass: public java.lang.Object Main.func()" }, { "code": null, "e": 26575, "s": 26480, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getEnclosingMethod– " }, { "code": null, "e": 26591, "s": 26575, "text": "saurabh1990aror" }, { "code": null, "e": 26606, "s": 26591, "text": "Java-Functions" }, { "code": null, "e": 26624, "s": 26606, "text": "Java-lang package" }, { "code": null, "e": 26640, "s": 26624, "text": "Java.lang.Class" }, { "code": null, "e": 26645, "s": 26640, "text": "Java" }, { "code": null, "e": 26650, "s": 26645, "text": "Java" }, { "code": null, "e": 26748, "s": 26650, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26780, "s": 26748, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26810, "s": 26780, "text": "HashMap in Java with Examples" }, { "code": null, "e": 26861, "s": 26810, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 26879, "s": 26861, "text": "ArrayList in Java" }, { "code": null, "e": 26910, "s": 26879, "text": "How to iterate any Map in Java" }, { "code": null, "e": 26942, "s": 26910, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 26962, "s": 26942, "text": "Stack Class in Java" }, { "code": null, "e": 26986, "s": 26962, "text": "Singleton Class in Java" }, { "code": null, "e": 26998, "s": 26986, "text": "Set in Java" } ]
C++ Program for Longest Increasing Subsequence - GeeksforGeeks
15 Sep, 2021 The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order. For example, the length of LIS for {10, 22, 9, 33, 21, 50, 41, 60, 80} is 6 and LIS is {10, 22, 33, 50, 60, 80}. Examples: Input : arr[] = {3, 10, 2, 1, 20} Output : Length of LIS = 3 The longest increasing subsequence is 3, 10, 20 Input : arr[] = {3, 2} Output : Length of LIS = 1 The longest increasing subsequences are {3} and {2} Input : arr[] = {50, 3, 10, 7, 40, 80} Output : Length of LIS = 4 The longest increasing subsequence is {3, 7, 40, 80} Overlapping Subproblems: Considering the above implementation, the following is a recursion tree for an array of size 4. lis(n) gives us the length of LIS for arr[]. lis(4) / | lis(3) lis(2) lis(1) / / lis(2) lis(1) lis(1) / lis(1) We can see that there are many subproblems that are solved again and again. So this problem has Overlapping Substructure property and recomputation of same subproblems can be avoided by either using Memoization or Tabulation. Following is a tabulated implementation for the LIS problem. C++ C Java Python3 C# Javascript /* Dynamic Programming C/C++ implementation of LIS problem */#include <iostream>using namespace std; /* lis() returns the length of the longest increasing subsequence in arr[] of size n */int lis(int arr[], int n){ int *lis, i, j, max = 0; lis = (int*)malloc(sizeof(int) * n); /* Initialize LIS values for all indexes */ for (i = 0; i < n; i++) lis[i] = 1; /* Compute optimized LIS values in bottom up manner */ for (i = 1; i < n; i++) for (j = 0; j < i; j++) if (arr[i] > arr[j] && lis[i] < lis[j] + 1) lis[i] = lis[j] + 1; /* Pick maximum of all LIS values */ for (i = 0; i < n; i++) if (max < lis[i]) max = lis[i]; /* Free memory to avoid memory leak */ free(lis); return max;} /* Driver program to test above function */int main(){ int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 }; int n = sizeof(arr) / sizeof(arr[0]); cout <<"Length of lis is "<< lis(arr, n); return 0;} // this code is contributed by shivanisinghss2110 /* Dynamic Programming C/C++ implementation of LIS problem */#include <stdio.h>#include <stdlib.h> /* lis() returns the length of the longest increasing subsequence in arr[] of size n */int lis(int arr[], int n){ int *lis, i, j, max = 0; lis = (int*)malloc(sizeof(int) * n); /* Initialize LIS values for all indexes */ for (i = 0; i < n; i++) lis[i] = 1; /* Compute optimized LIS values in bottom up manner */ for (i = 1; i < n; i++) for (j = 0; j < i; j++) if (arr[i] > arr[j] && lis[i] < lis[j] + 1) lis[i] = lis[j] + 1; /* Pick maximum of all LIS values */ for (i = 0; i < n; i++) if (max < lis[i]) max = lis[i]; /* Free memory to avoid memory leak */ free(lis); return max;} /* Driver program to test above function */int main(){ int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 }; int n = sizeof(arr) / sizeof(arr[0]); printf("Length of lis is %d\n", lis(arr, n)); return 0;} /* Dynamic Programming Java implementationof LIS problem */import java.util.*; class GFG{ /* * lis() returns the length of the longest * increasing subsequence in arr[] of size n */ static int lis(int[] arr, int n) { int max = 0; int[] lst = new int[n]; // initialize LIS values for all indexes Arrays.fill(lst, 1); /* Compute optimized LIS values in bottom up manner */ for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (arr[i] > arr[j] && lst[i] < lst[j] + 1) lst[i] = lst[j] + 1; } } /* Pick maximum of all LIS values */ for (int i = 0; i < n; i++) if (max < lst[i]) max = lst[i]; return max; } // Driver Code public static void main(String[] args) { int[] arr = { 10, 22, 9, 33, 21, 50, 41, 60 }; int n = arr.length; System.out.println("Length of lis is " + lis(arr, n)); }} // This code is contributed by// sanjeev2552 # Dynamic Programming python3# implementation of LIS problem # lis() returns the length of the# longest increasing subsequence# in arr[] of size ndef lis(arr, n): i, j, maxm = 0, 0, 0 # initialize LIS values for all indexes lst = [1 for s in range(n)] for i in range(1, n): for j in range(0, i): if (arr[i] > arr[j] and lst[i] < lst[j] + 1): lst[i] = lst[j] + 1 # Pick maximum of all LIS values for i in range(0, n): if maxm < lst[i]: maxm = lst[i] return maxm # Driver Codearr = [10, 22, 9, 33, 21, 50, 41, 60]n = len(arr)print("Length of lst is", lis(arr, n)) # This code is contributed# by Mohit kumar 29 /* Dynamic Programming Java implementationof LIS problem */using System;public class GFG{ /* * lis() returns the length of the longest * increasing subsequence in arr[] of size n */ static int lis(int[] arr, int n) { int max = 0; int[] lst = new int[n]; // initialize LIS values for all indexes Array.Fill(lst, 1); /* Compute optimized LIS values in bottom up manner */ for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (arr[i] > arr[j] && lst[i] < lst[j] + 1) { lst[i] = lst[j] + 1; } } } /* Pick maximum of all LIS values */ for (int i = 0; i < n; i++) if (max < lst[i]) max = lst[i]; return max; } // Driver code static public void Main () { int[] arr = { 10, 22, 9, 33, 21, 50, 41, 60 }; int n = arr.Length; Console.WriteLine("Length of lis is " + lis(arr, n)); }} // This code is contributed by avanitrachhadiya2155 <script>/* Dynamic Programming Javascript implementationof LIS problem */ /* * lis() returns the length of the longest * increasing subsequence in arr[] of size n */ function lis(arr,n) { let max = 0; let lst = new Array(n); // initialize LIS values for all indexes for(let i=0;i<lst.length;i++) { lst[i]=1; } /* Compute optimized LIS values in bottom up manner */ for (let i = 1; i < n; i++) { for (let j = 0; j < i; j++) { if (arr[i] > arr[j] && lst[i] < lst[j] + 1) lst[i] = lst[j] + 1; } } /* Pick maximum of all LIS values */ for (let i = 0; i < n; i++) if (max < lst[i]) max = lst[i]; return max; } // Driver Code let arr=[10, 22, 9, 33, 21, 50, 41, 60 ]; let n = arr.length; document.write("Length of lis is " + lis(arr, n)); // This code is contributed by patel2127</script> Length of lis is 5 Please refer complete article on Dynamic Programming | Set 3 (Longest Increasing Subsequence) for more details! Method 2 : Lower Bound based approach Algorithm : 1. Iterate the array. 2. Declare a new array ans to add the newly constructed increasing subsequence. 2. For every index, if lower_bound is points to the ending of the array ans, push it into a vector ans. 3. Return the ans array size. C++ #include <bits/stdc++.h>using namespace std;int longest_increasing_subsequence(vector<int>& arr){ vector<int> ans; int n = arr.size(); for (int i = 0; i < n; i++) { auto it = lower_bound(ans.begin(), ans.end(), arr[i]); if (it == ans.end()) { ans.push_back(arr[i]); } else { *it = arr[i]; } } return ans.size();}int main(){ vector<int> a = { 10, 22, 9, 33, 21, 50, 41, 60 }; int ans = longest_increasing_subsequence(a); cout << ans; return 0;} 5 mohit kumar 29 sanjeev2552 avanitrachhadiya2155 patel2127 adityamutharia sweetyty shivanisinghss2110 LIS C++ Programs Dynamic Programming Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Passing a function as a parameter in C++ Const keyword in C++ Program to implement Singly Linked List in C++ using class cout in C++ Dynamic _Cast in C++ 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Largest Sum Contiguous Subarray Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23
[ { "code": null, "e": 24632, "s": 24604, "text": "\n15 Sep, 2021" }, { "code": null, "e": 24938, "s": 24632, "text": "The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order. For example, the length of LIS for {10, 22, 9, 33, 21, 50, 41, 60, 80} is 6 and LIS is {10, 22, 33, 50, 60, 80}. " }, { "code": null, "e": 24949, "s": 24938, "text": "Examples: " }, { "code": null, "e": 25283, "s": 24949, "text": "Input : arr[] = {3, 10, 2, 1, 20}\nOutput : Length of LIS = 3\nThe longest increasing subsequence is 3, 10, 20\n\nInput : arr[] = {3, 2}\nOutput : Length of LIS = 1\nThe longest increasing subsequences are {3} and {2}\n\nInput : arr[] = {50, 3, 10, 7, 40, 80}\nOutput : Length of LIS = 4\nThe longest increasing subsequence is {3, 7, 40, 80}" }, { "code": null, "e": 25451, "s": 25283, "text": "Overlapping Subproblems: Considering the above implementation, the following is a recursion tree for an array of size 4. lis(n) gives us the length of LIS for arr[]. " }, { "code": null, "e": 25583, "s": 25451, "text": " lis(4)\n / | \n lis(3) lis(2) lis(1)\n / /\n lis(2) lis(1) lis(1)\n /\nlis(1)" }, { "code": null, "e": 25871, "s": 25583, "text": "We can see that there are many subproblems that are solved again and again. So this problem has Overlapping Substructure property and recomputation of same subproblems can be avoided by either using Memoization or Tabulation. Following is a tabulated implementation for the LIS problem. " }, { "code": null, "e": 25875, "s": 25871, "text": "C++" }, { "code": null, "e": 25877, "s": 25875, "text": "C" }, { "code": null, "e": 25882, "s": 25877, "text": "Java" }, { "code": null, "e": 25890, "s": 25882, "text": "Python3" }, { "code": null, "e": 25893, "s": 25890, "text": "C#" }, { "code": null, "e": 25904, "s": 25893, "text": "Javascript" }, { "code": "/* Dynamic Programming C/C++ implementation of LIS problem */#include <iostream>using namespace std; /* lis() returns the length of the longest increasing subsequence in arr[] of size n */int lis(int arr[], int n){ int *lis, i, j, max = 0; lis = (int*)malloc(sizeof(int) * n); /* Initialize LIS values for all indexes */ for (i = 0; i < n; i++) lis[i] = 1; /* Compute optimized LIS values in bottom up manner */ for (i = 1; i < n; i++) for (j = 0; j < i; j++) if (arr[i] > arr[j] && lis[i] < lis[j] + 1) lis[i] = lis[j] + 1; /* Pick maximum of all LIS values */ for (i = 0; i < n; i++) if (max < lis[i]) max = lis[i]; /* Free memory to avoid memory leak */ free(lis); return max;} /* Driver program to test above function */int main(){ int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 }; int n = sizeof(arr) / sizeof(arr[0]); cout <<\"Length of lis is \"<< lis(arr, n); return 0;} // this code is contributed by shivanisinghss2110", "e": 26938, "s": 25904, "text": null }, { "code": "/* Dynamic Programming C/C++ implementation of LIS problem */#include <stdio.h>#include <stdlib.h> /* lis() returns the length of the longest increasing subsequence in arr[] of size n */int lis(int arr[], int n){ int *lis, i, j, max = 0; lis = (int*)malloc(sizeof(int) * n); /* Initialize LIS values for all indexes */ for (i = 0; i < n; i++) lis[i] = 1; /* Compute optimized LIS values in bottom up manner */ for (i = 1; i < n; i++) for (j = 0; j < i; j++) if (arr[i] > arr[j] && lis[i] < lis[j] + 1) lis[i] = lis[j] + 1; /* Pick maximum of all LIS values */ for (i = 0; i < n; i++) if (max < lis[i]) max = lis[i]; /* Free memory to avoid memory leak */ free(lis); return max;} /* Driver program to test above function */int main(){ int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 }; int n = sizeof(arr) / sizeof(arr[0]); printf(\"Length of lis is %d\\n\", lis(arr, n)); return 0;}", "e": 27923, "s": 26938, "text": null }, { "code": "/* Dynamic Programming Java implementationof LIS problem */import java.util.*; class GFG{ /* * lis() returns the length of the longest * increasing subsequence in arr[] of size n */ static int lis(int[] arr, int n) { int max = 0; int[] lst = new int[n]; // initialize LIS values for all indexes Arrays.fill(lst, 1); /* Compute optimized LIS values in bottom up manner */ for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (arr[i] > arr[j] && lst[i] < lst[j] + 1) lst[i] = lst[j] + 1; } } /* Pick maximum of all LIS values */ for (int i = 0; i < n; i++) if (max < lst[i]) max = lst[i]; return max; } // Driver Code public static void main(String[] args) { int[] arr = { 10, 22, 9, 33, 21, 50, 41, 60 }; int n = arr.length; System.out.println(\"Length of lis is \" + lis(arr, n)); }} // This code is contributed by// sanjeev2552", "e": 29050, "s": 27923, "text": null }, { "code": "# Dynamic Programming python3# implementation of LIS problem # lis() returns the length of the# longest increasing subsequence# in arr[] of size ndef lis(arr, n): i, j, maxm = 0, 0, 0 # initialize LIS values for all indexes lst = [1 for s in range(n)] for i in range(1, n): for j in range(0, i): if (arr[i] > arr[j] and lst[i] < lst[j] + 1): lst[i] = lst[j] + 1 # Pick maximum of all LIS values for i in range(0, n): if maxm < lst[i]: maxm = lst[i] return maxm # Driver Codearr = [10, 22, 9, 33, 21, 50, 41, 60]n = len(arr)print(\"Length of lst is\", lis(arr, n)) # This code is contributed# by Mohit kumar 29", "e": 29765, "s": 29050, "text": null }, { "code": "/* Dynamic Programming Java implementationof LIS problem */using System;public class GFG{ /* * lis() returns the length of the longest * increasing subsequence in arr[] of size n */ static int lis(int[] arr, int n) { int max = 0; int[] lst = new int[n]; // initialize LIS values for all indexes Array.Fill(lst, 1); /* Compute optimized LIS values in bottom up manner */ for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (arr[i] > arr[j] && lst[i] < lst[j] + 1) { lst[i] = lst[j] + 1; } } } /* Pick maximum of all LIS values */ for (int i = 0; i < n; i++) if (max < lst[i]) max = lst[i]; return max; } // Driver code static public void Main () { int[] arr = { 10, 22, 9, 33, 21, 50, 41, 60 }; int n = arr.Length; Console.WriteLine(\"Length of lis is \" + lis(arr, n)); }} // This code is contributed by avanitrachhadiya2155", "e": 30734, "s": 29765, "text": null }, { "code": "<script>/* Dynamic Programming Javascript implementationof LIS problem */ /* * lis() returns the length of the longest * increasing subsequence in arr[] of size n */ function lis(arr,n) { let max = 0; let lst = new Array(n); // initialize LIS values for all indexes for(let i=0;i<lst.length;i++) { lst[i]=1; } /* Compute optimized LIS values in bottom up manner */ for (let i = 1; i < n; i++) { for (let j = 0; j < i; j++) { if (arr[i] > arr[j] && lst[i] < lst[j] + 1) lst[i] = lst[j] + 1; } } /* Pick maximum of all LIS values */ for (let i = 0; i < n; i++) if (max < lst[i]) max = lst[i]; return max; } // Driver Code let arr=[10, 22, 9, 33, 21, 50, 41, 60 ]; let n = arr.length; document.write(\"Length of lis is \" + lis(arr, n)); // This code is contributed by patel2127</script>", "e": 31833, "s": 30734, "text": null }, { "code": null, "e": 31852, "s": 31833, "text": "Length of lis is 5" }, { "code": null, "e": 31967, "s": 31854, "text": "Please refer complete article on Dynamic Programming | Set 3 (Longest Increasing Subsequence) for more details! " }, { "code": null, "e": 32005, "s": 31967, "text": "Method 2 : Lower Bound based approach" }, { "code": null, "e": 32017, "s": 32005, "text": "Algorithm :" }, { "code": null, "e": 32039, "s": 32017, "text": "1. Iterate the array." }, { "code": null, "e": 32119, "s": 32039, "text": "2. Declare a new array ans to add the newly constructed increasing subsequence." }, { "code": null, "e": 32223, "s": 32119, "text": "2. For every index, if lower_bound is points to the ending of the array ans, push it into a vector ans." }, { "code": null, "e": 32253, "s": 32223, "text": "3. Return the ans array size." }, { "code": null, "e": 32257, "s": 32253, "text": "C++" }, { "code": "#include <bits/stdc++.h>using namespace std;int longest_increasing_subsequence(vector<int>& arr){ vector<int> ans; int n = arr.size(); for (int i = 0; i < n; i++) { auto it = lower_bound(ans.begin(), ans.end(), arr[i]); if (it == ans.end()) { ans.push_back(arr[i]); } else { *it = arr[i]; } } return ans.size();}int main(){ vector<int> a = { 10, 22, 9, 33, 21, 50, 41, 60 }; int ans = longest_increasing_subsequence(a); cout << ans; return 0;}", "e": 32796, "s": 32257, "text": null }, { "code": null, "e": 32798, "s": 32796, "text": "5" }, { "code": null, "e": 32813, "s": 32798, "text": "mohit kumar 29" }, { "code": null, "e": 32825, "s": 32813, "text": "sanjeev2552" }, { "code": null, "e": 32846, "s": 32825, "text": "avanitrachhadiya2155" }, { "code": null, "e": 32856, "s": 32846, "text": "patel2127" }, { "code": null, "e": 32871, "s": 32856, "text": "adityamutharia" }, { "code": null, "e": 32880, "s": 32871, "text": "sweetyty" }, { "code": null, "e": 32899, "s": 32880, "text": "shivanisinghss2110" }, { "code": null, "e": 32903, "s": 32899, "text": "LIS" }, { "code": null, "e": 32916, "s": 32903, "text": "C++ Programs" }, { "code": null, "e": 32936, "s": 32916, "text": "Dynamic Programming" }, { "code": null, "e": 32956, "s": 32936, "text": "Dynamic Programming" }, { "code": null, "e": 33054, "s": 32956, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33095, "s": 33054, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 33116, "s": 33095, "text": "Const keyword in C++" }, { "code": null, "e": 33175, "s": 33116, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 33187, "s": 33175, "text": "cout in C++" }, { "code": null, "e": 33208, "s": 33187, "text": "Dynamic _Cast in C++" }, { "code": null, "e": 33237, "s": 33208, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 33267, "s": 33237, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 33299, "s": 33267, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 33333, "s": 33299, "text": "Longest Common Subsequence | DP-4" } ]
Lazy Loading in ReactJS
In this article, we will learn how to lazily load the pages of our application to make our React application more optimized. React apps are bundled with the preinstalled bundlers like webpack before making the React application to be production ready. When this bundled project is loaded, it loads the whole source code at once, even those pages which are rarely visited by the user. So, to prevent the entire loading of the application at once, we use the concept of lazy loading to decrease the DOM load time and to increase the speed of the application. const OtherComponent = React.lazy(() => import('./OtherComponent')); Here, OtherComponent is the component which is going to be lazily loaded. In this example, we will build a Routing application which lazily loads the component. App.jsx import React, { Suspense, lazy } from 'react'; import { BrowserRouter as Router, Route, Switch } from 'react -router-dom'; const About = lazy(() => import('./About')); const App = () => ( <Router> <Suspense fallback={<div>Loading...</div>}> <Switch> <Route path="/about" component={About} /> <Route path="/" exact render={() => ( <div> <h1>This is the main page</h1> <a href="/about">Click here</a> </div> )} /> </Switch> </Suspense> </Router> ); export default App; About.js import React from 'react'; const About = () => { return ( <div> <h1>This is the about section</h1> </div> ); }; export default About; In the above example, when the user clicks on the 'click here' button. the about.js script is lazily loaded and the DOM is updated accordingly. This will produce the following result.
[ { "code": null, "e": 1187, "s": 1062, "text": "In this article, we will learn how to lazily load the pages of our application to make our React application more optimized." }, { "code": null, "e": 1619, "s": 1187, "text": "React apps are bundled with the preinstalled bundlers like webpack before making the React application to be production ready. When this bundled project is loaded, it loads the whole source code at once, even those pages which are rarely visited by the user. So, to prevent the entire loading of the application at once, we use the concept of lazy loading to decrease the DOM load time and to increase the speed of the application." }, { "code": null, "e": 1688, "s": 1619, "text": "const OtherComponent = React.lazy(() => import('./OtherComponent'));" }, { "code": null, "e": 1762, "s": 1688, "text": "Here, OtherComponent is the component which is going to be lazily loaded." }, { "code": null, "e": 1849, "s": 1762, "text": "In this example, we will build a Routing application which lazily loads the component." }, { "code": null, "e": 1857, "s": 1849, "text": "App.jsx" }, { "code": null, "e": 2407, "s": 1857, "text": "import React, { Suspense, lazy } from 'react';\nimport { BrowserRouter as Router, Route, Switch } from 'react -router-dom';\n\nconst About = lazy(() => import('./About'));\n\nconst App = () => (\n <Router>\n <Suspense fallback={<div>Loading...</div>}>\n <Switch>\n <Route path=\"/about\" component={About} />\n <Route\n path=\"/\"\n exact\n render={() => (\n <div>\n <h1>This is the main page</h1>\n <a href=\"/about\">Click here</a>\n </div>\n )}\n />\n </Switch>\n </Suspense>\n </Router>\n);\nexport default App;" }, { "code": null, "e": 2416, "s": 2407, "text": "About.js" }, { "code": null, "e": 2578, "s": 2416, "text": "import React from 'react';\n\nconst About = () => {\n return (\n <div>\n <h1>This is the about section</h1>\n </div>\n );\n};\nexport default About;" }, { "code": null, "e": 2722, "s": 2578, "text": "In the above example, when the user clicks on the 'click here' button. the about.js script is lazily loaded and the DOM is updated accordingly." }, { "code": null, "e": 2762, "s": 2722, "text": "This will produce the following result." } ]
Masked-Language Modeling With BERT | by James Briggs | Towards Data Science
BERT, everyone’s favorite transformer costs Google ~$7K to train [1] (and who knows how much in R&D costs). From there, we write a couple of lines of code to use the same model — all for free. BERT has enjoyed unparalleled success in NLP thanks to two unique training approaches, masked-language modeling (MLM), and next sentence prediction (NSP). In many cases, we might be able to take the pre-trained BERT model out-of-the-box and apply it successfully to our own language tasks. But often, we might need to fine-tune the model. Further training with MLM allows us to fine-tune BERT to better understand the particular use of language in a more specific domain. Out-of-the-box BERT — great for general purpose use. Fine-tuned with MLM BERT — great for domain-specific use. In this article, we’ll go into depth about what MLM is, how it works, and how we can improve our models with it. MLM consists of giving BERT a sentence and optimizing the weights inside BERT to output the same sentence on the other side. So we input a sentence and ask that BERT outputs the same sentence. However, before we actually give BERT that input sentence — we mask a few tokens. So we’re actually inputting an incomplete sentence and asking BERT to complete it for us. What is the effect of this? Well, it’s like those questions many of us were given in school — where, given a sentence, we had to fill in the gaps. In Autumn the ______ fall from the trees. Do you know the answer? Most likely you do, and you do because you have considered the context of the sentence. We see the words fall and trees — we know that the missing word is something that falls from trees. A lot of things fall from trees, acorns, branches, leaves — but we have another condition, in Autumn — that narrows down our search, the most probable thing to fall from a tree in Autumn are leaves. As humans, we use a mix of general world knowledge, and linguistic understanding to come to that conclusion. For BERT, this guess will come from reading a lot — and learning linguistic patterns incredibly well. BERT may not know what Autumn, trees, and leaves are — but it does know that given linguistic patterns, and the context of these words, the answer is most likely to be leaves. The outcome of this process — for BERT — is an improved comprehension of the style of language being used. So we understand what MLM is doing, but how does this actually work? What are the logical steps that we’ll need to follow in code? 1.We tokenize our text. Just like we usually would with transformers, we begin with text tokenization. From tokenization we will receive three different tensors: input_ids token_type_ids attention_mask We don’t need token_type_ids for MLM — and in this example attention_mask is not so important. For us, the input_ids tensor is most important. Here, we will have a tokenized representation of our text — which is what we will be modifying moving forwards. 2.Create a labels tensor. We’re training our model here, so we need a labels tensor to calculate loss against — and optimize towards. The labels tensor is simply input_ids — so all we need to do is make a copy. 3.Mask tokens in input_ids. Now that we’ve created a copy of input_ids for labels, we can go ahead and mask a random selection of tokens. The BERT paper uses a 15% probability of masking each token during model pre-training, with a few additional rules — we’ll use a simplified version of this and assign a 15% probability of each word being masked. 4.Calculate loss. We process the input_ids and labels tensors through our BERT model and calculate the loss between them both. Using this loss, we calculate the required gradient changes with BERT — and optimize our model weights. The loss is calculated as the difference between the output probability distributions for each output ‘token’, and the true one-hot encoded labels. Okay, that’s all great, but how can we demonstrate MLM in code? We’ll be using HuggingFace’s transformers and PyTorch, alongside the bert-base-uncased model. So, let’s import and initialize everything first: from transformers import BertTokenizer, BertForMaskedLM import torch tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') model = BertForMaskedLM.from_pretrained('bert-base-uncased') text = ("After Abraham Lincoln won the November 1860 presidential " "election on an anti-slavery platform, an initial seven " "slave states declared their secession from the country " "to form the Confederacy. War broke out in April 1861 " "when secessionist forces attacked Fort Sumter in South " "Carolina, just over a month after Lincoln's " "inauguration.") Some weights of the model checkpoint at bert-base-uncased were not used when initializing BertForMaskedLM: ['cls.seq_relationship.weight', 'cls.seq_relationship.bias'] - This IS expected if you are initializing BertForMaskedLM from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model). - This IS NOT expected if you are initializing BertForMaskedLM from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model). And now we move into each one of our logical steps, starting with: 1.Tokenization — tokenization is simple, we’ve already initialized a BertTokenizer, all we do now is tokenize our input text. inputs = tokenizer(text, return_tensors='pt') inputs.keys() dict_keys(['input_ids', 'token_type_ids', 'attention_mask']) inputs {'input_ids': tensor([[ 101, 2044, 8181, 5367, 2180, 1996, 2281, 7313, 4883, 2602, 2006, 2019, 3424, 1011, 8864, 4132, 1010, 2019, 3988, 2698, 6658, 2163, 4161, 2037, 22965, 2013, 1996, 2406, 2000, 2433, 1996, 18179, 1012, 2162, 3631, 2041, 1999, 2258, 6863, 2043, 22965, 2923, 2749, 4457, 3481, 7680, 3334, 1999, 2148, 3792, 1010, 2074, 2058, 1037, 3204, 2044, 5367, 1005, 1055, 17331, 1012, 102]]), 'token_type_ids': tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]), 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])} We won’t worry about padding/truncation for now. What we should be aware of are the three tensors described earlier — token_type_ids and attention_mask don’t need any attention from us — but input_ids does. 2.Create labels — The next step is easy, all we need to do here is clone our input_ids tensor into a new labels tensor. We’ll store this within the inputs variable too. 3.Masking — Now we need to mask a random selection of tokens in our input_ids tensor. To create our 15% probability of masking any one token, we can use torch.rand alongside a condition of each value < 0.15. Together, these will produce our masking array mask_arr. Now, we use mask_arr to select where to place our MASK tokens — but we don’t want to place a MASK token over other special tokens such as CLS or SEP tokens (101 and 102 respectively). So, we need to add an additional condition. A check for positions containing the token ids 101 or 102. Now that is our masking tensor, to apply it we will first extract the index positions where we find a True value — then use this selection to set values in these positions to 103 (the MASK token id). Now we can see our MASK tokens represented by 103 in the input_ids tensor above. 4.Calculate Loss — Our final step here no different from the typical model training process. With both input_ids and labels tensors inside our inputs dictionary, we can pass this to our model and return the model loss. Cool, we’ve run through all of the essentials — but how would all of this look when fine-tuning a model? There are two ways, (1) we implement our own version of the training function using everything we have learned so far, or (2) we use HuggingFace’s Trainer. Trainer is clearly the way to go for an optimized, easy-to-use solution. And we’ll take a look at how we can use it — but first, let’s try implementing it ourselves. After learning all of this, it would be a waste to not give implementing our own training function a go. First, we need data. Because we’re just randomly masking a selection of tokens — we can use almost any text. We don’t need labeled or special data. Here, we’ll use Meditations by Marcus Aurelius, sourced from here and preprocessed a little (clean version). First, we’ll import/initialize and load our text data. Then we tokenize — this time we do truncate and pad each sequence — as we have many sequences of different lengths. Now we clone the input_ids to create our labels tensor. Next is our masking code, which is a little different this time for two reasons: Our mask should not include PAD tokens (as before with CLS and SEP). We have many sequences — not just one. We can see the value 103 assigned in the same position as the True value is found in the mask_arr tensor. The inputs tensors are now ready — and we can begin setting them up to be fed into our model during training. During training, we’ll be using a PyTorch DataLoader to load our data. To use this, we’ll need to format our data into a PyTorch Dataset object. Now we’re ready to move onto our training loop. Before starting our loop we need to set up three things: Move the model to GPU/CPU (GPU if available). Activate model training mode. Initialize an Adam with weighted decay optimizer. Now we’re finally set up — we can begin training! We format this as a typical training loop in PyTorch. And with that we’re done — we’ve implemented our own MLM fine-tuning script. Switching across to our Trainer implementation — we’ll still need to do everything we did before up to to point that we created our dataset — as Trainer will be expecting this as input for training. We’ll first define our training arguments, initialize the Trainer — then train! So the Trainer approach is certainly much simpler — and allows us to implement checkpoints and other features by simply specifying them at initialization time. Okay, so that’s everything we really need to know to get started with fine-tuning our models using MLM. There’s a lot to MLM, but the concept and implementations are not too complex — and incredibly powerful. Using what we’ve learned here, we can take the best models in NLP and fine-tune them to our more domain-specific language use-cases — needing nothing more than unlabelled text — often an easy data source to find. I hope you enjoyed this article! If you have any questions, let me know via Twitter or in the comments below. If you’d like more content like this, I post on YouTube too. Thanks for reading! [1] The Staggering Cost of Training SOTA AI Models (2019), Synced Review 🤖 NLP With Transformers Course *All images are by the author except where stated otherwise
[ { "code": null, "e": 365, "s": 172, "text": "BERT, everyone’s favorite transformer costs Google ~$7K to train [1] (and who knows how much in R&D costs). From there, we write a couple of lines of code to use the same model — all for free." }, { "code": null, "e": 520, "s": 365, "text": "BERT has enjoyed unparalleled success in NLP thanks to two unique training approaches, masked-language modeling (MLM), and next sentence prediction (NSP)." }, { "code": null, "e": 655, "s": 520, "text": "In many cases, we might be able to take the pre-trained BERT model out-of-the-box and apply it successfully to our own language tasks." }, { "code": null, "e": 704, "s": 655, "text": "But often, we might need to fine-tune the model." }, { "code": null, "e": 837, "s": 704, "text": "Further training with MLM allows us to fine-tune BERT to better understand the particular use of language in a more specific domain." }, { "code": null, "e": 948, "s": 837, "text": "Out-of-the-box BERT — great for general purpose use. Fine-tuned with MLM BERT — great for domain-specific use." }, { "code": null, "e": 1061, "s": 948, "text": "In this article, we’ll go into depth about what MLM is, how it works, and how we can improve our models with it." }, { "code": null, "e": 1186, "s": 1061, "text": "MLM consists of giving BERT a sentence and optimizing the weights inside BERT to output the same sentence on the other side." }, { "code": null, "e": 1254, "s": 1186, "text": "So we input a sentence and ask that BERT outputs the same sentence." }, { "code": null, "e": 1336, "s": 1254, "text": "However, before we actually give BERT that input sentence — we mask a few tokens." }, { "code": null, "e": 1426, "s": 1336, "text": "So we’re actually inputting an incomplete sentence and asking BERT to complete it for us." }, { "code": null, "e": 1573, "s": 1426, "text": "What is the effect of this? Well, it’s like those questions many of us were given in school — where, given a sentence, we had to fill in the gaps." }, { "code": null, "e": 1615, "s": 1573, "text": "In Autumn the ______ fall from the trees." }, { "code": null, "e": 1727, "s": 1615, "text": "Do you know the answer? Most likely you do, and you do because you have considered the context of the sentence." }, { "code": null, "e": 1827, "s": 1727, "text": "We see the words fall and trees — we know that the missing word is something that falls from trees." }, { "code": null, "e": 2026, "s": 1827, "text": "A lot of things fall from trees, acorns, branches, leaves — but we have another condition, in Autumn — that narrows down our search, the most probable thing to fall from a tree in Autumn are leaves." }, { "code": null, "e": 2237, "s": 2026, "text": "As humans, we use a mix of general world knowledge, and linguistic understanding to come to that conclusion. For BERT, this guess will come from reading a lot — and learning linguistic patterns incredibly well." }, { "code": null, "e": 2413, "s": 2237, "text": "BERT may not know what Autumn, trees, and leaves are — but it does know that given linguistic patterns, and the context of these words, the answer is most likely to be leaves." }, { "code": null, "e": 2520, "s": 2413, "text": "The outcome of this process — for BERT — is an improved comprehension of the style of language being used." }, { "code": null, "e": 2651, "s": 2520, "text": "So we understand what MLM is doing, but how does this actually work? What are the logical steps that we’ll need to follow in code?" }, { "code": null, "e": 2754, "s": 2651, "text": "1.We tokenize our text. Just like we usually would with transformers, we begin with text tokenization." }, { "code": null, "e": 2813, "s": 2754, "text": "From tokenization we will receive three different tensors:" }, { "code": null, "e": 2823, "s": 2813, "text": "input_ids" }, { "code": null, "e": 2838, "s": 2823, "text": "token_type_ids" }, { "code": null, "e": 2853, "s": 2838, "text": "attention_mask" }, { "code": null, "e": 2948, "s": 2853, "text": "We don’t need token_type_ids for MLM — and in this example attention_mask is not so important." }, { "code": null, "e": 3108, "s": 2948, "text": "For us, the input_ids tensor is most important. Here, we will have a tokenized representation of our text — which is what we will be modifying moving forwards." }, { "code": null, "e": 3242, "s": 3108, "text": "2.Create a labels tensor. We’re training our model here, so we need a labels tensor to calculate loss against — and optimize towards." }, { "code": null, "e": 3319, "s": 3242, "text": "The labels tensor is simply input_ids — so all we need to do is make a copy." }, { "code": null, "e": 3457, "s": 3319, "text": "3.Mask tokens in input_ids. Now that we’ve created a copy of input_ids for labels, we can go ahead and mask a random selection of tokens." }, { "code": null, "e": 3669, "s": 3457, "text": "The BERT paper uses a 15% probability of masking each token during model pre-training, with a few additional rules — we’ll use a simplified version of this and assign a 15% probability of each word being masked." }, { "code": null, "e": 3796, "s": 3669, "text": "4.Calculate loss. We process the input_ids and labels tensors through our BERT model and calculate the loss between them both." }, { "code": null, "e": 3900, "s": 3796, "text": "Using this loss, we calculate the required gradient changes with BERT — and optimize our model weights." }, { "code": null, "e": 4048, "s": 3900, "text": "The loss is calculated as the difference between the output probability distributions for each output ‘token’, and the true one-hot encoded labels." }, { "code": null, "e": 4112, "s": 4048, "text": "Okay, that’s all great, but how can we demonstrate MLM in code?" }, { "code": null, "e": 4256, "s": 4112, "text": "We’ll be using HuggingFace’s transformers and PyTorch, alongside the bert-base-uncased model. So, let’s import and initialize everything first:" }, { "code": null, "e": 4326, "s": 4256, "text": "from transformers import BertTokenizer, BertForMaskedLM\nimport torch\n" }, { "code": null, "e": 4862, "s": 4326, "text": "tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\nmodel = BertForMaskedLM.from_pretrained('bert-base-uncased')\n\ntext = (\"After Abraham Lincoln won the November 1860 presidential \"\n \"election on an anti-slavery platform, an initial seven \"\n \"slave states declared their secession from the country \"\n \"to form the Confederacy. War broke out in April 1861 \"\n \"when secessionist forces attacked Fort Sumter in South \"\n \"Carolina, just over a month after Lincoln's \"\n \"inauguration.\")\n" }, { "code": null, "e": 5496, "s": 4862, "text": "Some weights of the model checkpoint at bert-base-uncased were not used when initializing BertForMaskedLM: ['cls.seq_relationship.weight', 'cls.seq_relationship.bias']\n- This IS expected if you are initializing BertForMaskedLM from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).\n- This IS NOT expected if you are initializing BertForMaskedLM from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).\n" }, { "code": null, "e": 5563, "s": 5496, "text": "And now we move into each one of our logical steps, starting with:" }, { "code": null, "e": 5689, "s": 5563, "text": "1.Tokenization — tokenization is simple, we’ve already initialized a BertTokenizer, all we do now is tokenize our input text." }, { "code": null, "e": 5736, "s": 5689, "text": "inputs = tokenizer(text, return_tensors='pt')\n" }, { "code": null, "e": 5751, "s": 5736, "text": "inputs.keys()\n" }, { "code": null, "e": 5812, "s": 5751, "text": "dict_keys(['input_ids', 'token_type_ids', 'attention_mask'])" }, { "code": null, "e": 5820, "s": 5812, "text": "inputs\n" }, { "code": null, "e": 6802, "s": 5820, "text": "{'input_ids': tensor([[ 101, 2044, 8181, 5367, 2180, 1996, 2281, 7313, 4883, 2602,\n 2006, 2019, 3424, 1011, 8864, 4132, 1010, 2019, 3988, 2698,\n 6658, 2163, 4161, 2037, 22965, 2013, 1996, 2406, 2000, 2433,\n 1996, 18179, 1012, 2162, 3631, 2041, 1999, 2258, 6863, 2043,\n 22965, 2923, 2749, 4457, 3481, 7680, 3334, 1999, 2148, 3792,\n 1010, 2074, 2058, 1037, 3204, 2044, 5367, 1005, 1055, 17331,\n 1012, 102]]), 'token_type_ids': tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]), 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])}" }, { "code": null, "e": 7009, "s": 6802, "text": "We won’t worry about padding/truncation for now. What we should be aware of are the three tensors described earlier — token_type_ids and attention_mask don’t need any attention from us — but input_ids does." }, { "code": null, "e": 7178, "s": 7009, "text": "2.Create labels — The next step is easy, all we need to do here is clone our input_ids tensor into a new labels tensor. We’ll store this within the inputs variable too." }, { "code": null, "e": 7264, "s": 7178, "text": "3.Masking — Now we need to mask a random selection of tokens in our input_ids tensor." }, { "code": null, "e": 7443, "s": 7264, "text": "To create our 15% probability of masking any one token, we can use torch.rand alongside a condition of each value < 0.15. Together, these will produce our masking array mask_arr." }, { "code": null, "e": 7627, "s": 7443, "text": "Now, we use mask_arr to select where to place our MASK tokens — but we don’t want to place a MASK token over other special tokens such as CLS or SEP tokens (101 and 102 respectively)." }, { "code": null, "e": 7730, "s": 7627, "text": "So, we need to add an additional condition. A check for positions containing the token ids 101 or 102." }, { "code": null, "e": 7930, "s": 7730, "text": "Now that is our masking tensor, to apply it we will first extract the index positions where we find a True value — then use this selection to set values in these positions to 103 (the MASK token id)." }, { "code": null, "e": 8011, "s": 7930, "text": "Now we can see our MASK tokens represented by 103 in the input_ids tensor above." }, { "code": null, "e": 8104, "s": 8011, "text": "4.Calculate Loss — Our final step here no different from the typical model training process." }, { "code": null, "e": 8230, "s": 8104, "text": "With both input_ids and labels tensors inside our inputs dictionary, we can pass this to our model and return the model loss." }, { "code": null, "e": 8335, "s": 8230, "text": "Cool, we’ve run through all of the essentials — but how would all of this look when fine-tuning a model?" }, { "code": null, "e": 8491, "s": 8335, "text": "There are two ways, (1) we implement our own version of the training function using everything we have learned so far, or (2) we use HuggingFace’s Trainer." }, { "code": null, "e": 8657, "s": 8491, "text": "Trainer is clearly the way to go for an optimized, easy-to-use solution. And we’ll take a look at how we can use it — but first, let’s try implementing it ourselves." }, { "code": null, "e": 8762, "s": 8657, "text": "After learning all of this, it would be a waste to not give implementing our own training function a go." }, { "code": null, "e": 8910, "s": 8762, "text": "First, we need data. Because we’re just randomly masking a selection of tokens — we can use almost any text. We don’t need labeled or special data." }, { "code": null, "e": 9019, "s": 8910, "text": "Here, we’ll use Meditations by Marcus Aurelius, sourced from here and preprocessed a little (clean version)." }, { "code": null, "e": 9074, "s": 9019, "text": "First, we’ll import/initialize and load our text data." }, { "code": null, "e": 9190, "s": 9074, "text": "Then we tokenize — this time we do truncate and pad each sequence — as we have many sequences of different lengths." }, { "code": null, "e": 9246, "s": 9190, "text": "Now we clone the input_ids to create our labels tensor." }, { "code": null, "e": 9327, "s": 9246, "text": "Next is our masking code, which is a little different this time for two reasons:" }, { "code": null, "e": 9396, "s": 9327, "text": "Our mask should not include PAD tokens (as before with CLS and SEP)." }, { "code": null, "e": 9435, "s": 9396, "text": "We have many sequences — not just one." }, { "code": null, "e": 9541, "s": 9435, "text": "We can see the value 103 assigned in the same position as the True value is found in the mask_arr tensor." }, { "code": null, "e": 9651, "s": 9541, "text": "The inputs tensors are now ready — and we can begin setting them up to be fed into our model during training." }, { "code": null, "e": 9796, "s": 9651, "text": "During training, we’ll be using a PyTorch DataLoader to load our data. To use this, we’ll need to format our data into a PyTorch Dataset object." }, { "code": null, "e": 9901, "s": 9796, "text": "Now we’re ready to move onto our training loop. Before starting our loop we need to set up three things:" }, { "code": null, "e": 9947, "s": 9901, "text": "Move the model to GPU/CPU (GPU if available)." }, { "code": null, "e": 9977, "s": 9947, "text": "Activate model training mode." }, { "code": null, "e": 10027, "s": 9977, "text": "Initialize an Adam with weighted decay optimizer." }, { "code": null, "e": 10131, "s": 10027, "text": "Now we’re finally set up — we can begin training! We format this as a typical training loop in PyTorch." }, { "code": null, "e": 10208, "s": 10131, "text": "And with that we’re done — we’ve implemented our own MLM fine-tuning script." }, { "code": null, "e": 10407, "s": 10208, "text": "Switching across to our Trainer implementation — we’ll still need to do everything we did before up to to point that we created our dataset — as Trainer will be expecting this as input for training." }, { "code": null, "e": 10487, "s": 10407, "text": "We’ll first define our training arguments, initialize the Trainer — then train!" }, { "code": null, "e": 10647, "s": 10487, "text": "So the Trainer approach is certainly much simpler — and allows us to implement checkpoints and other features by simply specifying them at initialization time." }, { "code": null, "e": 10751, "s": 10647, "text": "Okay, so that’s everything we really need to know to get started with fine-tuning our models using MLM." }, { "code": null, "e": 10856, "s": 10751, "text": "There’s a lot to MLM, but the concept and implementations are not too complex — and incredibly powerful." }, { "code": null, "e": 11069, "s": 10856, "text": "Using what we’ve learned here, we can take the best models in NLP and fine-tune them to our more domain-specific language use-cases — needing nothing more than unlabelled text — often an easy data source to find." }, { "code": null, "e": 11240, "s": 11069, "text": "I hope you enjoyed this article! If you have any questions, let me know via Twitter or in the comments below. If you’d like more content like this, I post on YouTube too." }, { "code": null, "e": 11260, "s": 11240, "text": "Thanks for reading!" }, { "code": null, "e": 11333, "s": 11260, "text": "[1] The Staggering Cost of Training SOTA AI Models (2019), Synced Review" }, { "code": null, "e": 11364, "s": 11333, "text": "🤖 NLP With Transformers Course" } ]
Java Program to check whether a file exists or not
The method java.io.File.exists() is used to check whether a file exists or not. This method returns true if the file specified by the abstract path name exists and false if it does not exist. A program that demonstrates this is given as follows − Live Demo import java.io.File; public class Demo { public static void main(String[] args) { try { File file = new File("demo1.txt"); file.createNewFile(); System.out.println("File exists? " + file.exists()); } catch(Exception e) { e.printStackTrace(); } } } The output of the above program is as follows − File exists? true Now let us understand the above program. The method java.io.File.exists() is used to check whether the file exists or not and the boolean value that is returned by the method is printed. A code snippet that demonstrates this is given as follows − try { File file = new File("demo1.txt"); file.createNewFile(); System.out.println("File exists? " + file.exists()); } catch(Exception e) { e.printStackTrace(); }
[ { "code": null, "e": 1254, "s": 1062, "text": "The method java.io.File.exists() is used to check whether a file exists or not. This method returns true if the file specified by the abstract path name exists and false if it does not exist." }, { "code": null, "e": 1309, "s": 1254, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1320, "s": 1309, "text": " Live Demo" }, { "code": null, "e": 1628, "s": 1320, "text": "import java.io.File;\npublic class Demo {\n public static void main(String[] args) {\n try {\n File file = new File(\"demo1.txt\");\n file.createNewFile();\n System.out.println(\"File exists? \" + file.exists());\n } catch(Exception e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 1676, "s": 1628, "text": "The output of the above program is as follows −" }, { "code": null, "e": 1694, "s": 1676, "text": "File exists? true" }, { "code": null, "e": 1735, "s": 1694, "text": "Now let us understand the above program." }, { "code": null, "e": 1941, "s": 1735, "text": "The method java.io.File.exists() is used to check whether the file exists or not and the boolean value that is returned by the method is printed. A code snippet that demonstrates this is given as follows −" }, { "code": null, "e": 2115, "s": 1941, "text": "try {\n File file = new File(\"demo1.txt\");\n file.createNewFile();\n System.out.println(\"File exists? \" + file.exists());\n} catch(Exception e) {\n e.printStackTrace();\n}" } ]
Tryit Editor v3.7
Tryit: HTML image
[]
Replace every element with the least greater element on its right - GeeksforGeeks
18 Apr, 2022 Given an array of integers, replace every element with the least greater element on its right side in the array. If there are no greater elements on the right side, replace it with -1. Examples: Input: [8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28] Output: [18, 63, 80, 25, 32, 43, 80, 93, 80, 25, 93, -1, 28, -1, -1] A naive method is to run two loops. The outer loop will one by one pick array elements from left to right. The inner loop will find the smallest element greater than the picked element on its right side. Finally, the outer loop will replace the picked element with the element found by inner loop. The time complexity of this method will be O(n2). A tricky solution would be to use Binary Search Trees. We start scanning the array from right to left and insert each element into the BST. For each inserted element, we replace it in the array by its inorder successor in BST. If the element inserted is the maximum so far (i.e. its inorder successor doesn’t exist), we replace it by -1. Below is the implementation of the above idea – C++ Java Python3 C# Javascript // C++ program to replace every element with the// least greater element on its right#include <bits/stdc++.h>using namespace std; // A binary Tree nodestruct Node { int data; Node *left, *right;}; // A utility function to create a new BST nodeNode* newNode(int item){ Node* temp = new Node; temp->data = item; temp->left = temp->right = NULL; return temp;} /* A utility function to insert a new node with given data in BST and find its successor */Node* insert(Node* node, int data, Node*& succ){ /* If the tree is empty, return a new node */ if (node == NULL) return node = newNode(data); // If key is smaller than root's key, go to left // subtree and set successor as current node if (data < node->data) { succ = node; node->left = insert(node->left, data, succ); } // go to right subtree else if (data > node->data) node->right = insert(node->right, data, succ); return node;} // Function to replace every element with the// least greater element on its rightvoid replace(int arr[], int n){ Node* root = NULL; // start from right to left for (int i = n - 1; i >= 0; i--) { Node* succ = NULL; // insert current element into BST and // find its inorder successor root = insert(root, arr[i], succ); // replace element by its inorder // successor in BST if (succ) arr[i] = succ->data; else // No inorder successor arr[i] = -1; }} // Driver Program to test above functionsint main(){ int arr[] = { 8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28 }; int n = sizeof(arr) / sizeof(arr[0]); replace(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0;} // Java program to replace every element with// the least greater element on its rightimport java.io.*; class BinarySearchTree{ // A binary Tree nodeclass Node{ int data; Node left, right; Node(int d) { data = d; left = right = null; }} // Root of BSTstatic Node root;static Node succ; // ConstructorBinarySearchTree(){ root = null; succ = null;} // A utility function to insert a new node with// given data in BST and find its successorNode insert(Node node, int data){ // If the tree is empty, return a new node if (node == null) { node = new Node(data); } // If key is smaller than root's key, // go to left subtree and set successor // as current node if (data < node.data) { succ = node; node.left = insert(node.left, data); } // Go to right subtree else if (data > node.data) node.right = insert(node.right, data); return node;} // Function to replace every element with the// least greater element on its rightstatic void replace(int arr[], int n){ BinarySearchTree tree = new BinarySearchTree(); // start from right to left for(int i = n - 1; i >= 0; i--) { succ = null; // Insert current element into BST and // find its inorder successor root = tree.insert(root, arr[i]); // Replace element by its inorder // successor in BST if (succ != null) arr[i] = succ.data; // No inorder successor else arr[i] = -1; }} // Driver codepublic static void main(String[] args){ int arr[] = new int[] { 8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28 }; int n = arr.length; replace(arr, n); for(int i = 0; i < n; i++) System.out.print(arr[i] + " ");}} // The code is contributed by Tushar Bansal # Python3 program to replace every element# with the least greater element on its right # A binary Tree nodeclass Node: def __init__(self, d): self.data = d self.left = None self.right = None # A utility function to insert a new node with# given data in BST and find its successordef insert(node, data): global succ # If the tree is empty, return a new node root = node if (node == None): return Node(data) # If key is smaller than root's key, go to left # subtree and set successor as current node if (data < node.data): #print("1") succ = node root.left = insert(node.left, data) # Go to right subtree elif (data > node.data): root.right = insert(node.right, data) return root # Function to replace every element with the# least greater element on its rightdef replace(arr, n): global succ root = None # Start from right to left for i in range(n - 1, -1, -1): succ = None # Insert current element into BST and # find its inorder successor root = insert(root, arr[i]) # Replace element by its inorder # successor in BST if (succ): arr[i] = succ.data # No inorder successor else: arr[i] = -1 return arr # Driver codeif __name__ == '__main__': arr = [ 8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28 ] n = len(arr) succ = None arr = replace(arr, n) print(*arr) # This code is contributed by mohit kumar 29 // C# program to replace every element with// the least greater element on its rightusing System; class BinarySearchTree{ // A binary Tree nodepublic class Node{ public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} // Root of BSTpublic static Node root;public static Node succ; // Constructorpublic BinarySearchTree(){ root = null; succ = null;} // A utility function to insert a new node with// given data in BST and find its successorpublic static Node insert(Node node, int data){ // If the tree is empty, return a new node if (node == null) { node = new Node(data); } // If key is smaller than root's key, // go to left subtree and set successor // as current node if (data < node.data) { succ = node; node.left = insert(node.left, data); } // Go to right subtree else if (data > node.data) { node.right = insert(node.right, data); } return node;} // Function to replace every element with the// least greater element on its rightpublic static void replace(int[] arr, int n){ //BinarySearchTree tree = new BinarySearchTree(); // Start from right to left for(int i = n - 1; i >= 0; i--) { succ = null; // Insert current element into BST and // find its inorder successor root = BinarySearchTree.insert(root, arr[i]); // Replace element by its inorder // successor in BST if (succ != null) { arr[i] = succ.data; } // No inorder successor else { arr[i] = -1; } }} // Driver codestatic public void Main(){ int[] arr = { 8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28 }; int n = arr.Length; replace(arr, n); for(int i = 0; i < n; i++) { Console.Write(arr[i]+" "); }}} // This code is contributed by rag2127 <script> // Javascript program to// replace every element with// the least greater element// on its right // A binary Tree node class Node{ constructor(d) { this.data=d; this.left=this.right=null; } } // Root of BST let root=null; let succ=null; // A utility function to insert a new node with // given data in BST and find its successor function insert(node,data) { // If the tree is empty, return a new node if (node == null) { node = new Node(data); } // If key is smaller than root's key, // go to left subtree and set successor // as current node if (data < node.data) { succ = node; node.left = insert(node.left, data); } // Go to right subtree else if (data > node.data) node.right = insert(node.right, data); return node; } // Function to replace every element with the // least greater element on its right function replace(arr,n) { // start from right to left for(let i = n - 1; i >= 0; i--) { succ = null; // Insert current element into BST and // find its inorder successor root = insert(root, arr[i]); // Replace element by its inorder // successor in BST if (succ != null) arr[i] = succ.data; // No inorder successor else arr[i] = -1; } } // Driver code let arr=[8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28 ]; let n = arr.length; replace(arr, n); for(let i = 0; i < n; i++) document.write(arr[i] + " "); // This code is contributed by unknown2108 </script> 18 63 80 25 32 43 80 93 80 25 93 -1 28 -1 -1 The worst-case time complexity of the above solution is also O(n2) as it uses BST. The worst-case will happen when array is sorted in ascending or descending order. The complexity can easily be reduced to O(nlogn) by using balanced trees like red-black trees. Another Approach: We can use the Next Greater Element using stack algorithm to solve this problem in O(Nlog(N)) time and O(N) space. Algorithm: First, we take an array of pairs namely temp, and store each element and its index in this array,i.e. temp[i] will be storing {arr[i],i}.Sort the array according to the array elements.Now get the next greater index for each and every index of the temp array in an array namely index by using Next Greater Element using stack.Now index[i] stores the index of the next least greater element of the element temp[i].first and if index[i] is -1, then it means that there is no least greater element of the element temp[i].second at its right side.Now take a result array where result[i] will be equal to a[indexes[temp[i].second]] if index[i] is not -1 otherwise result[i] will be equal to -1. First, we take an array of pairs namely temp, and store each element and its index in this array,i.e. temp[i] will be storing {arr[i],i}. Sort the array according to the array elements. Now get the next greater index for each and every index of the temp array in an array namely index by using Next Greater Element using stack. Now index[i] stores the index of the next least greater element of the element temp[i].first and if index[i] is -1, then it means that there is no least greater element of the element temp[i].second at its right side. Now take a result array where result[i] will be equal to a[indexes[temp[i].second]] if index[i] is not -1 otherwise result[i] will be equal to -1. Below is the implementation of the above approach C++ Python3 #include <bits/stdc++.h>using namespace std;// function to get the next least greater index for each and// every temp.second of the temp array using stack this// function is similar to the Next Greater element for each// and every element of an array using stack difference is// we are finding the next greater index not value and the// indexes are stored in the temp[i].second for all ivector<int> nextGreaterIndex(vector<pair<int, int> >& temp){ int n = temp.size(); // initially result[i] for all i is -1 vector<int> res(n, -1); stack<int> stack; for (int i = 0; i < n; i++) { // if the stack is empty or this index is smaller // than the index stored at top of the stack then we // push this index to the stack if (stack.empty() || temp[i].second < stack.top()) stack.push( temp[i].second); // notice temp[i].second is // the index // else this index (i.e. temp[i].second) is greater // than the index stored at top of the stack we pop // all the indexes stored at stack's top and for all // these indexes we make this index i.e. // temp[i].second as their next greater index else { while (!stack.empty() && temp[i].second > stack.top()) { res[stack.top()] = temp[i].second; stack.pop(); } // after that push the current index to the stack stack.push(temp[i].second); } } // now res will store the next least greater indexes for // each and every indexes stored at temp[i].second for // all i return res;}// now we will be using above function for finding the next// greater index for each and every indexes stored at// temp[i].secondvector<int> replaceByLeastGreaterUsingStack(int arr[], int n){ // first of all in temp we store the pairs of {arr[i].i} vector<pair<int, int> > temp; for (int i = 0; i < n; i++) { temp.push_back({ arr[i], i }); } // we sort the temp according to the first of the pair // i.e value sort(temp.begin(), temp.end()); // now indexes vector will store the next greater index // for each temp[i].second index vector<int> indexes = nextGreaterIndex(temp); // we initialize a result vector with all -1 vector<int> res(n, -1); for (int i = 0; i < n; i++) { // now if there is no next greater index after the // index temp[i].second the result will be -1 // otherwise the result will be the element of the // array arr at index indexes[temp[i].second] if (indexes[temp[i].second] != -1) res[temp[i].second] = arr[indexes[temp[i].second]]; } // return the res which will store the least greater // element of each and every element in the array at its // right side return res;}// driver codeint main(){ int arr[] = { 8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28 }; int n = sizeof(arr) / sizeof(int); auto res = replaceByLeastGreaterUsingStack(arr, n); cout << "Least Greater elements on the right side are " << endl; for (int i : res) cout << i << ' '; cout << endl; return 0;} // this code is contributed by Dipti Prakash Sinha # function to get the next least greater index for each and# every temp[1] of the temp array using stack this# function is similar to the Next Greater element for each# and every element of an array using stack difference is# we are finding the next greater index not value and the# indexes are stored in the temp[i][1] for all idef nextGreaterIndex(temp): n = len(temp) # initially result[i] for all i is -1 res = [-1 for i in range(n)] stack = [] for i in range(n): # if the stack is empty or this index is smaller # than the index stored at top of the stack then we # append this index to the stack if (len(stack)==0 or temp[i][1] < stack[-1]): stack.append(temp[i][1]); # notice temp[i][1] is # the index # else this index (i.e. temp[i][1]) is greater # than the index stored at top of the stack we pop # all the indexes stored at stack's top and for all # these indexes we make this index i.e. # temp[i][1] as their next greater index else: while (len(stack)>0 and temp[i][1] > stack[-1]): res[stack[-1]] = temp[i][1] stack.pop() # after that append the current index to the stack stack.append(temp[i][1]) # now res will store the next least greater indexes for # each and every indexes stored at temp[i][1] for # all i return res # now we will be using above function for finding the next# greater index for each and every indexes stored at# temp[i][1]def replaceByLeastGreaterUsingStack(arr, n): # first of all in temp we store the pairs of {arr[i].i} temp = [] for i in range(n): temp.append([ arr[i], i ]) # we sort the temp according to the first of the pair # i.e value temp.sort() # now indexes vector will store the next greater index # for each temp[i][1] index indexes = nextGreaterIndex(temp) # we initialize a result vector with all -1 res = [-1 for i in range(n)] for i in range(n): # now if there is no next greater index after the # index temp[i][1] the result will be -1 # otherwise the result will be the element of the # array arr at index indexes[temp[i][1]] if (indexes[temp[i][1]] != -1): res[temp[i][1]] = arr[indexes[temp[i][1]]] # return the res which will store the least greater # element of each and every element in the array at its # right side return res # driver code arr = [ 8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28 ]n = len(arr)res = replaceByLeastGreaterUsingStack(arr, n)print("Least Greater elements on the right side are ")for i in res: print(i,end = ' ')print() # this code is contributed by shinjanpatra Least Greater elements on the right side are 18 63 80 25 32 43 80 93 80 25 93 -1 28 -1 -1 Another approach with set A different way to think about the problem is listing our requirements and then thinking over it to find a solution. If we traverse the array from backwards, we need a data structure(ds) to support: 1. Insert an element into our ds in sorted order (so at any point of time the elements in our ds are sorted) 2. Finding the upper bound of the current element (upper bound will give just greater element from our ds if present) Carefully observing at our requirements, a set is what comes in mind. Why not multiset? Well we can use a multiset but there is no need to store an element more than once. Let’s code our approach Time and space complexity: We insert each element in our set and find upper bound for each element using a loop so its time complexity is O(n*log(n)). We are storing each element in our set so space complexity is O(n) C++ #include <iostream>#include <vector>#include <set> using namespace std; void solve(vector<int>& arr) { set<int> s; vector<int> ans(arr.size()); for(int i=arr.size()-1;i>=0;i--) { //traversing the array backwards s.insert(arr[i]); // inserting the element into set auto it = s.upper_bound(arr[i]); // finding upper bound if(it == s.end()) arr[i] = -1; // if upper_bound does not exist then -1 else arr[i] = *it; // if upper_bound exists, lets take it }} void printArray(vector<int>& arr) { for(int i : arr) cout << i << " "; cout << "\n";} int main() { vector<int> arr = {8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28}; printArray(arr); solve(arr); printArray(arr); return 0;} 8 58 71 18 31 32 63 92 43 3 91 93 25 80 28 18 63 80 25 32 43 80 93 80 25 93 -1 28 -1 -1 This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. mysticpeaks mohit kumar 29 rag2127 arpitprasad928 unknown2108 sinhadiptiprakash anikaseth98 abhishek0719kadiyan shobhittewari Arrays Binary Search Tree Arrays Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Next Greater Element Window Sliding Technique Count pairs with given sum Program to find sum of elements in a given array Reversal algorithm for array rotation Binary Search Tree | Set 1 (Search and Insertion) AVL Tree | Set 1 (Insertion) Binary Search Tree | Set 2 (Delete) A program to check if a binary tree is BST or not Construct BST from given preorder traversal | Set 1
[ { "code": null, "e": 24429, "s": 24401, "text": "\n18 Apr, 2022" }, { "code": null, "e": 24614, "s": 24429, "text": "Given an array of integers, replace every element with the least greater element on its right side in the array. If there are no greater elements on the right side, replace it with -1." }, { "code": null, "e": 24625, "s": 24614, "text": "Examples: " }, { "code": null, "e": 24780, "s": 24625, "text": "Input: [8, 58, 71, 18, 31, 32, 63, 92, \n 43, 3, 91, 93, 25, 80, 28]\nOutput: [18, 63, 80, 25, 32, 43, 80, 93, \n 80, 25, 93, -1, 28, -1, -1]" }, { "code": null, "e": 25128, "s": 24780, "text": "A naive method is to run two loops. The outer loop will one by one pick array elements from left to right. The inner loop will find the smallest element greater than the picked element on its right side. Finally, the outer loop will replace the picked element with the element found by inner loop. The time complexity of this method will be O(n2)." }, { "code": null, "e": 25466, "s": 25128, "text": "A tricky solution would be to use Binary Search Trees. We start scanning the array from right to left and insert each element into the BST. For each inserted element, we replace it in the array by its inorder successor in BST. If the element inserted is the maximum so far (i.e. its inorder successor doesn’t exist), we replace it by -1." }, { "code": null, "e": 25515, "s": 25466, "text": "Below is the implementation of the above idea – " }, { "code": null, "e": 25519, "s": 25515, "text": "C++" }, { "code": null, "e": 25524, "s": 25519, "text": "Java" }, { "code": null, "e": 25532, "s": 25524, "text": "Python3" }, { "code": null, "e": 25535, "s": 25532, "text": "C#" }, { "code": null, "e": 25546, "s": 25535, "text": "Javascript" }, { "code": "// C++ program to replace every element with the// least greater element on its right#include <bits/stdc++.h>using namespace std; // A binary Tree nodestruct Node { int data; Node *left, *right;}; // A utility function to create a new BST nodeNode* newNode(int item){ Node* temp = new Node; temp->data = item; temp->left = temp->right = NULL; return temp;} /* A utility function to insert a new node with given data in BST and find its successor */Node* insert(Node* node, int data, Node*& succ){ /* If the tree is empty, return a new node */ if (node == NULL) return node = newNode(data); // If key is smaller than root's key, go to left // subtree and set successor as current node if (data < node->data) { succ = node; node->left = insert(node->left, data, succ); } // go to right subtree else if (data > node->data) node->right = insert(node->right, data, succ); return node;} // Function to replace every element with the// least greater element on its rightvoid replace(int arr[], int n){ Node* root = NULL; // start from right to left for (int i = n - 1; i >= 0; i--) { Node* succ = NULL; // insert current element into BST and // find its inorder successor root = insert(root, arr[i], succ); // replace element by its inorder // successor in BST if (succ) arr[i] = succ->data; else // No inorder successor arr[i] = -1; }} // Driver Program to test above functionsint main(){ int arr[] = { 8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28 }; int n = sizeof(arr) / sizeof(arr[0]); replace(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << \" \"; return 0;}", "e": 27340, "s": 25546, "text": null }, { "code": "// Java program to replace every element with// the least greater element on its rightimport java.io.*; class BinarySearchTree{ // A binary Tree nodeclass Node{ int data; Node left, right; Node(int d) { data = d; left = right = null; }} // Root of BSTstatic Node root;static Node succ; // ConstructorBinarySearchTree(){ root = null; succ = null;} // A utility function to insert a new node with// given data in BST and find its successorNode insert(Node node, int data){ // If the tree is empty, return a new node if (node == null) { node = new Node(data); } // If key is smaller than root's key, // go to left subtree and set successor // as current node if (data < node.data) { succ = node; node.left = insert(node.left, data); } // Go to right subtree else if (data > node.data) node.right = insert(node.right, data); return node;} // Function to replace every element with the// least greater element on its rightstatic void replace(int arr[], int n){ BinarySearchTree tree = new BinarySearchTree(); // start from right to left for(int i = n - 1; i >= 0; i--) { succ = null; // Insert current element into BST and // find its inorder successor root = tree.insert(root, arr[i]); // Replace element by its inorder // successor in BST if (succ != null) arr[i] = succ.data; // No inorder successor else arr[i] = -1; }} // Driver codepublic static void main(String[] args){ int arr[] = new int[] { 8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28 }; int n = arr.length; replace(arr, n); for(int i = 0; i < n; i++) System.out.print(arr[i] + \" \");}} // The code is contributed by Tushar Bansal", "e": 29261, "s": 27340, "text": null }, { "code": "# Python3 program to replace every element# with the least greater element on its right # A binary Tree nodeclass Node: def __init__(self, d): self.data = d self.left = None self.right = None # A utility function to insert a new node with# given data in BST and find its successordef insert(node, data): global succ # If the tree is empty, return a new node root = node if (node == None): return Node(data) # If key is smaller than root's key, go to left # subtree and set successor as current node if (data < node.data): #print(\"1\") succ = node root.left = insert(node.left, data) # Go to right subtree elif (data > node.data): root.right = insert(node.right, data) return root # Function to replace every element with the# least greater element on its rightdef replace(arr, n): global succ root = None # Start from right to left for i in range(n - 1, -1, -1): succ = None # Insert current element into BST and # find its inorder successor root = insert(root, arr[i]) # Replace element by its inorder # successor in BST if (succ): arr[i] = succ.data # No inorder successor else: arr[i] = -1 return arr # Driver codeif __name__ == '__main__': arr = [ 8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28 ] n = len(arr) succ = None arr = replace(arr, n) print(*arr) # This code is contributed by mohit kumar 29", "e": 30874, "s": 29261, "text": null }, { "code": "// C# program to replace every element with// the least greater element on its rightusing System; class BinarySearchTree{ // A binary Tree nodepublic class Node{ public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} // Root of BSTpublic static Node root;public static Node succ; // Constructorpublic BinarySearchTree(){ root = null; succ = null;} // A utility function to insert a new node with// given data in BST and find its successorpublic static Node insert(Node node, int data){ // If the tree is empty, return a new node if (node == null) { node = new Node(data); } // If key is smaller than root's key, // go to left subtree and set successor // as current node if (data < node.data) { succ = node; node.left = insert(node.left, data); } // Go to right subtree else if (data > node.data) { node.right = insert(node.right, data); } return node;} // Function to replace every element with the// least greater element on its rightpublic static void replace(int[] arr, int n){ //BinarySearchTree tree = new BinarySearchTree(); // Start from right to left for(int i = n - 1; i >= 0; i--) { succ = null; // Insert current element into BST and // find its inorder successor root = BinarySearchTree.insert(root, arr[i]); // Replace element by its inorder // successor in BST if (succ != null) { arr[i] = succ.data; } // No inorder successor else { arr[i] = -1; } }} // Driver codestatic public void Main(){ int[] arr = { 8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28 }; int n = arr.Length; replace(arr, n); for(int i = 0; i < n; i++) { Console.Write(arr[i]+\" \"); }}} // This code is contributed by rag2127", "e": 32890, "s": 30874, "text": null }, { "code": "<script> // Javascript program to// replace every element with// the least greater element// on its right // A binary Tree node class Node{ constructor(d) { this.data=d; this.left=this.right=null; } } // Root of BST let root=null; let succ=null; // A utility function to insert a new node with // given data in BST and find its successor function insert(node,data) { // If the tree is empty, return a new node if (node == null) { node = new Node(data); } // If key is smaller than root's key, // go to left subtree and set successor // as current node if (data < node.data) { succ = node; node.left = insert(node.left, data); } // Go to right subtree else if (data > node.data) node.right = insert(node.right, data); return node; } // Function to replace every element with the // least greater element on its right function replace(arr,n) { // start from right to left for(let i = n - 1; i >= 0; i--) { succ = null; // Insert current element into BST and // find its inorder successor root = insert(root, arr[i]); // Replace element by its inorder // successor in BST if (succ != null) arr[i] = succ.data; // No inorder successor else arr[i] = -1; } } // Driver code let arr=[8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28 ]; let n = arr.length; replace(arr, n); for(let i = 0; i < n; i++) document.write(arr[i] + \" \"); // This code is contributed by unknown2108 </script>", "e": 34656, "s": 32890, "text": null }, { "code": null, "e": 34702, "s": 34656, "text": "18 63 80 25 32 43 80 93 80 25 93 -1 28 -1 -1 " }, { "code": null, "e": 34962, "s": 34702, "text": "The worst-case time complexity of the above solution is also O(n2) as it uses BST. The worst-case will happen when array is sorted in ascending or descending order. The complexity can easily be reduced to O(nlogn) by using balanced trees like red-black trees." }, { "code": null, "e": 34980, "s": 34962, "text": "Another Approach:" }, { "code": null, "e": 35095, "s": 34980, "text": "We can use the Next Greater Element using stack algorithm to solve this problem in O(Nlog(N)) time and O(N) space." }, { "code": null, "e": 35106, "s": 35095, "text": "Algorithm:" }, { "code": null, "e": 35795, "s": 35106, "text": "First, we take an array of pairs namely temp, and store each element and its index in this array,i.e. temp[i] will be storing {arr[i],i}.Sort the array according to the array elements.Now get the next greater index for each and every index of the temp array in an array namely index by using Next Greater Element using stack.Now index[i] stores the index of the next least greater element of the element temp[i].first and if index[i] is -1, then it means that there is no least greater element of the element temp[i].second at its right side.Now take a result array where result[i] will be equal to a[indexes[temp[i].second]] if index[i] is not -1 otherwise result[i] will be equal to -1." }, { "code": null, "e": 35933, "s": 35795, "text": "First, we take an array of pairs namely temp, and store each element and its index in this array,i.e. temp[i] will be storing {arr[i],i}." }, { "code": null, "e": 35981, "s": 35933, "text": "Sort the array according to the array elements." }, { "code": null, "e": 36123, "s": 35981, "text": "Now get the next greater index for each and every index of the temp array in an array namely index by using Next Greater Element using stack." }, { "code": null, "e": 36341, "s": 36123, "text": "Now index[i] stores the index of the next least greater element of the element temp[i].first and if index[i] is -1, then it means that there is no least greater element of the element temp[i].second at its right side." }, { "code": null, "e": 36488, "s": 36341, "text": "Now take a result array where result[i] will be equal to a[indexes[temp[i].second]] if index[i] is not -1 otherwise result[i] will be equal to -1." }, { "code": null, "e": 36538, "s": 36488, "text": "Below is the implementation of the above approach" }, { "code": null, "e": 36542, "s": 36538, "text": "C++" }, { "code": null, "e": 36550, "s": 36542, "text": "Python3" }, { "code": "#include <bits/stdc++.h>using namespace std;// function to get the next least greater index for each and// every temp.second of the temp array using stack this// function is similar to the Next Greater element for each// and every element of an array using stack difference is// we are finding the next greater index not value and the// indexes are stored in the temp[i].second for all ivector<int> nextGreaterIndex(vector<pair<int, int> >& temp){ int n = temp.size(); // initially result[i] for all i is -1 vector<int> res(n, -1); stack<int> stack; for (int i = 0; i < n; i++) { // if the stack is empty or this index is smaller // than the index stored at top of the stack then we // push this index to the stack if (stack.empty() || temp[i].second < stack.top()) stack.push( temp[i].second); // notice temp[i].second is // the index // else this index (i.e. temp[i].second) is greater // than the index stored at top of the stack we pop // all the indexes stored at stack's top and for all // these indexes we make this index i.e. // temp[i].second as their next greater index else { while (!stack.empty() && temp[i].second > stack.top()) { res[stack.top()] = temp[i].second; stack.pop(); } // after that push the current index to the stack stack.push(temp[i].second); } } // now res will store the next least greater indexes for // each and every indexes stored at temp[i].second for // all i return res;}// now we will be using above function for finding the next// greater index for each and every indexes stored at// temp[i].secondvector<int> replaceByLeastGreaterUsingStack(int arr[], int n){ // first of all in temp we store the pairs of {arr[i].i} vector<pair<int, int> > temp; for (int i = 0; i < n; i++) { temp.push_back({ arr[i], i }); } // we sort the temp according to the first of the pair // i.e value sort(temp.begin(), temp.end()); // now indexes vector will store the next greater index // for each temp[i].second index vector<int> indexes = nextGreaterIndex(temp); // we initialize a result vector with all -1 vector<int> res(n, -1); for (int i = 0; i < n; i++) { // now if there is no next greater index after the // index temp[i].second the result will be -1 // otherwise the result will be the element of the // array arr at index indexes[temp[i].second] if (indexes[temp[i].second] != -1) res[temp[i].second] = arr[indexes[temp[i].second]]; } // return the res which will store the least greater // element of each and every element in the array at its // right side return res;}// driver codeint main(){ int arr[] = { 8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28 }; int n = sizeof(arr) / sizeof(int); auto res = replaceByLeastGreaterUsingStack(arr, n); cout << \"Least Greater elements on the right side are \" << endl; for (int i : res) cout << i << ' '; cout << endl; return 0;} // this code is contributed by Dipti Prakash Sinha", "e": 39895, "s": 36550, "text": null }, { "code": "# function to get the next least greater index for each and# every temp[1] of the temp array using stack this# function is similar to the Next Greater element for each# and every element of an array using stack difference is# we are finding the next greater index not value and the# indexes are stored in the temp[i][1] for all idef nextGreaterIndex(temp): n = len(temp) # initially result[i] for all i is -1 res = [-1 for i in range(n)] stack = [] for i in range(n): # if the stack is empty or this index is smaller # than the index stored at top of the stack then we # append this index to the stack if (len(stack)==0 or temp[i][1] < stack[-1]): stack.append(temp[i][1]); # notice temp[i][1] is # the index # else this index (i.e. temp[i][1]) is greater # than the index stored at top of the stack we pop # all the indexes stored at stack's top and for all # these indexes we make this index i.e. # temp[i][1] as their next greater index else: while (len(stack)>0 and temp[i][1] > stack[-1]): res[stack[-1]] = temp[i][1] stack.pop() # after that append the current index to the stack stack.append(temp[i][1]) # now res will store the next least greater indexes for # each and every indexes stored at temp[i][1] for # all i return res # now we will be using above function for finding the next# greater index for each and every indexes stored at# temp[i][1]def replaceByLeastGreaterUsingStack(arr, n): # first of all in temp we store the pairs of {arr[i].i} temp = [] for i in range(n): temp.append([ arr[i], i ]) # we sort the temp according to the first of the pair # i.e value temp.sort() # now indexes vector will store the next greater index # for each temp[i][1] index indexes = nextGreaterIndex(temp) # we initialize a result vector with all -1 res = [-1 for i in range(n)] for i in range(n): # now if there is no next greater index after the # index temp[i][1] the result will be -1 # otherwise the result will be the element of the # array arr at index indexes[temp[i][1]] if (indexes[temp[i][1]] != -1): res[temp[i][1]] = arr[indexes[temp[i][1]]] # return the res which will store the least greater # element of each and every element in the array at its # right side return res # driver code arr = [ 8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28 ]n = len(arr)res = replaceByLeastGreaterUsingStack(arr, n)print(\"Least Greater elements on the right side are \")for i in res: print(i,end = ' ')print() # this code is contributed by shinjanpatra", "e": 42757, "s": 39895, "text": null }, { "code": null, "e": 42849, "s": 42757, "text": "Least Greater elements on the right side are \n18 63 80 25 32 43 80 93 80 25 93 -1 28 -1 -1 " }, { "code": null, "e": 42875, "s": 42849, "text": "Another approach with set" }, { "code": null, "e": 43075, "s": 42875, "text": "A different way to think about the problem is listing our requirements and then thinking over it to find a solution. If we traverse the array from backwards, we need a data structure(ds) to support:" }, { "code": null, "e": 43184, "s": 43075, "text": "1. Insert an element into our ds in sorted order (so at any point of time the elements in our ds are sorted)" }, { "code": null, "e": 43302, "s": 43184, "text": "2. Finding the upper bound of the current element (upper bound will give just greater element from our ds if present)" }, { "code": null, "e": 43373, "s": 43302, "text": "Carefully observing at our requirements, a set is what comes in mind. " }, { "code": null, "e": 43475, "s": 43373, "text": "Why not multiset? Well we can use a multiset but there is no need to store an element more than once." }, { "code": null, "e": 43499, "s": 43475, "text": "Let’s code our approach" }, { "code": null, "e": 43717, "s": 43499, "text": "Time and space complexity: We insert each element in our set and find upper bound for each element using a loop so its time complexity is O(n*log(n)). We are storing each element in our set so space complexity is O(n)" }, { "code": null, "e": 43721, "s": 43717, "text": "C++" }, { "code": "#include <iostream>#include <vector>#include <set> using namespace std; void solve(vector<int>& arr) { set<int> s; vector<int> ans(arr.size()); for(int i=arr.size()-1;i>=0;i--) { //traversing the array backwards s.insert(arr[i]); // inserting the element into set auto it = s.upper_bound(arr[i]); // finding upper bound if(it == s.end()) arr[i] = -1; // if upper_bound does not exist then -1 else arr[i] = *it; // if upper_bound exists, lets take it }} void printArray(vector<int>& arr) { for(int i : arr) cout << i << \" \"; cout << \"\\n\";} int main() { vector<int> arr = {8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28}; printArray(arr); solve(arr); printArray(arr); return 0;}", "e": 44469, "s": 43721, "text": null }, { "code": null, "e": 44559, "s": 44469, "text": "8 58 71 18 31 32 63 92 43 3 91 93 25 80 28 \n18 63 80 25 32 43 80 93 80 25 93 -1 28 -1 -1 " }, { "code": null, "e": 44978, "s": 44559, "text": "This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 44990, "s": 44978, "text": "mysticpeaks" }, { "code": null, "e": 45005, "s": 44990, "text": "mohit kumar 29" }, { "code": null, "e": 45013, "s": 45005, "text": "rag2127" }, { "code": null, "e": 45028, "s": 45013, "text": "arpitprasad928" }, { "code": null, "e": 45040, "s": 45028, "text": "unknown2108" }, { "code": null, "e": 45058, "s": 45040, "text": "sinhadiptiprakash" }, { "code": null, "e": 45070, "s": 45058, "text": "anikaseth98" }, { "code": null, "e": 45090, "s": 45070, "text": "abhishek0719kadiyan" }, { "code": null, "e": 45104, "s": 45090, "text": "shobhittewari" }, { "code": null, "e": 45111, "s": 45104, "text": "Arrays" }, { "code": null, "e": 45130, "s": 45111, "text": "Binary Search Tree" }, { "code": null, "e": 45137, "s": 45130, "text": "Arrays" }, { "code": null, "e": 45156, "s": 45137, "text": "Binary Search Tree" }, { "code": null, "e": 45254, "s": 45156, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45263, "s": 45254, "text": "Comments" }, { "code": null, "e": 45276, "s": 45263, "text": "Old Comments" }, { "code": null, "e": 45297, "s": 45276, "text": "Next Greater Element" }, { "code": null, "e": 45322, "s": 45297, "text": "Window Sliding Technique" }, { "code": null, "e": 45349, "s": 45322, "text": "Count pairs with given sum" }, { "code": null, "e": 45398, "s": 45349, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 45436, "s": 45398, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 45486, "s": 45436, "text": "Binary Search Tree | Set 1 (Search and Insertion)" }, { "code": null, "e": 45515, "s": 45486, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 45551, "s": 45515, "text": "Binary Search Tree | Set 2 (Delete)" }, { "code": null, "e": 45601, "s": 45551, "text": "A program to check if a binary tree is BST or not" } ]
Select a row of series or dataframe by given integer index - GeeksforGeeks
28 Jul, 2020 Dataframe.iloc[] is used to select a row of series/dataframe by given integer index. Let’s Create a Data Frame: Code: Python3 # import pandas libraryimport pandas as pd # Create the dataframe df = pd.DataFrame({'ID': ['114', '345', '157788', '5626'], 'Product': ['shirt', 'trousers', 'tie', 'belt'], 'Price': [1200, 1500, 600, 352], 'Color': ['White','Black', 'Red', 'Brown'], 'Discount': [10, 10, 10, 10]}) # Show the dataframedf Output: Now, Selecting a row of series/dataframe by a given integer index:Example 1: Selecting the first row only. Python3 # select first row # from the dataframedf.iloc[0] Output: Example 2: Selecting 0,1,2 rows. Python3 # select 0, 1, 2 rows#from the dataframedf.iloc[0 : 3] Output: Example 3: Selecting rows from 0 to 2 and columns 0 to 1. Python3 # selecting rows from 0 to# 2 and columns 0 to 1df.iloc[0 : 3, 0 : 2] Output: Example 4: Selecting all rows and columns from 0 to 3. Python3 # selecting all rows and # columns from 0 to 3df.iloc[ : , 0 : 4] Output: Example 5: Selecting all rows and 2nd column. Python3 # selecting all rows and # 3rd columndf.iloc[ : , 2] Output: Python pandas-dataFrame Python pandas-series Python-pandas Python 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 Bar Plot in Matplotlib Python | Get dictionary keys as a list Python | Convert set into a list Ways to filter Pandas DataFrame by column values Python - Call function from another file loops in python Multithreading in Python | Set 2 (Synchronization) Python Dictionary keys() method Python Lambda Functions
[ { "code": null, "e": 23901, "s": 23873, "text": "\n28 Jul, 2020" }, { "code": null, "e": 24014, "s": 23901, "text": "Dataframe.iloc[] is used to select a row of series/dataframe by given integer index. Let’s Create a Data Frame:" }, { "code": null, "e": 24020, "s": 24014, "text": "Code:" }, { "code": null, "e": 24028, "s": 24020, "text": "Python3" }, { "code": "# import pandas libraryimport pandas as pd # Create the dataframe df = pd.DataFrame({'ID': ['114', '345', '157788', '5626'], 'Product': ['shirt', 'trousers', 'tie', 'belt'], 'Price': [1200, 1500, 600, 352], 'Color': ['White','Black', 'Red', 'Brown'], 'Discount': [10, 10, 10, 10]}) # Show the dataframedf", "e": 24527, "s": 24028, "text": null }, { "code": null, "e": 24535, "s": 24527, "text": "Output:" }, { "code": null, "e": 24642, "s": 24535, "text": "Now, Selecting a row of series/dataframe by a given integer index:Example 1: Selecting the first row only." }, { "code": null, "e": 24650, "s": 24642, "text": "Python3" }, { "code": "# select first row # from the dataframedf.iloc[0]", "e": 24700, "s": 24650, "text": null }, { "code": null, "e": 24710, "s": 24700, "text": "Output: " }, { "code": null, "e": 24745, "s": 24710, "text": "Example 2: Selecting 0,1,2 rows." }, { "code": null, "e": 24753, "s": 24745, "text": "Python3" }, { "code": "# select 0, 1, 2 rows#from the dataframedf.iloc[0 : 3]", "e": 24808, "s": 24753, "text": null }, { "code": null, "e": 24817, "s": 24808, "text": "Output: " }, { "code": null, "e": 24875, "s": 24817, "text": "Example 3: Selecting rows from 0 to 2 and columns 0 to 1." }, { "code": null, "e": 24883, "s": 24875, "text": "Python3" }, { "code": "# selecting rows from 0 to# 2 and columns 0 to 1df.iloc[0 : 3, 0 : 2]", "e": 24953, "s": 24883, "text": null }, { "code": null, "e": 24963, "s": 24953, "text": "Output: " }, { "code": null, "e": 25019, "s": 24963, "text": "Example 4: Selecting all rows and columns from 0 to 3. " }, { "code": null, "e": 25027, "s": 25019, "text": "Python3" }, { "code": "# selecting all rows and # columns from 0 to 3df.iloc[ : , 0 : 4]", "e": 25093, "s": 25027, "text": null }, { "code": null, "e": 25102, "s": 25093, "text": "Output: " }, { "code": null, "e": 25148, "s": 25102, "text": "Example 5: Selecting all rows and 2nd column." }, { "code": null, "e": 25156, "s": 25148, "text": "Python3" }, { "code": "# selecting all rows and # 3rd columndf.iloc[ : , 2]", "e": 25209, "s": 25156, "text": null }, { "code": null, "e": 25218, "s": 25209, "text": "Output: " }, { "code": null, "e": 25242, "s": 25218, "text": "Python pandas-dataFrame" }, { "code": null, "e": 25263, "s": 25242, "text": "Python pandas-series" }, { "code": null, "e": 25277, "s": 25263, "text": "Python-pandas" }, { "code": null, "e": 25284, "s": 25277, "text": "Python" }, { "code": null, "e": 25382, "s": 25284, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25391, "s": 25382, "text": "Comments" }, { "code": null, "e": 25404, "s": 25391, "text": "Old Comments" }, { "code": null, "e": 25440, "s": 25404, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 25463, "s": 25440, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 25502, "s": 25463, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 25535, "s": 25502, "text": "Python | Convert set into a list" }, { "code": null, "e": 25584, "s": 25535, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 25625, "s": 25584, "text": "Python - Call function from another file" }, { "code": null, "e": 25641, "s": 25625, "text": "loops in python" }, { "code": null, "e": 25692, "s": 25641, "text": "Multithreading in Python | Set 2 (Synchronization)" }, { "code": null, "e": 25724, "s": 25692, "text": "Python Dictionary keys() method" } ]
How do we print a variable at the MongoDB command prompt?
In order to print a variable at the MongoDB command prompt, use the following syntax //Declaring and Initializing a variable. var anyVariableName=yourValue; //To print the above variable. yourVariableName; Or print(yourVariableName); Following is how you can declare and initialize a variable at the MongoDB command prompt > var myIntegerValue=20; Print a variable at the MongoDB command prompt: > myIntegerValue This will produce the following output 20 You can also use print(). Following is the query > print(myIntegerValue); This will produce the following output 20 Let us see another example. Following is the query to declare and initialize a string variable at MongoDB shell. > var myStringValue="Hello MongoDB!!!"; Following is the query to print a variable at the MongoDB command prompt. > myStringValue This will produce the following output Hello MongoDB!!! You can also use print(). Following is the query > print(myStringValue); This will produce the following output Hello MongoDB!!!
[ { "code": null, "e": 1147, "s": 1062, "text": "In order to print a variable at the MongoDB command prompt, use the following syntax" }, { "code": null, "e": 1296, "s": 1147, "text": "//Declaring and Initializing a variable.\nvar anyVariableName=yourValue;\n//To print the above variable.\nyourVariableName;\nOr\nprint(yourVariableName);" }, { "code": null, "e": 1385, "s": 1296, "text": "Following is how you can declare and initialize a variable at the MongoDB command prompt" }, { "code": null, "e": 1410, "s": 1385, "text": "> var myIntegerValue=20;" }, { "code": null, "e": 1458, "s": 1410, "text": "Print a variable at the MongoDB command prompt:" }, { "code": null, "e": 1475, "s": 1458, "text": "> myIntegerValue" }, { "code": null, "e": 1514, "s": 1475, "text": "This will produce the following output" }, { "code": null, "e": 1517, "s": 1514, "text": "20" }, { "code": null, "e": 1566, "s": 1517, "text": "You can also use print(). Following is the query" }, { "code": null, "e": 1591, "s": 1566, "text": "> print(myIntegerValue);" }, { "code": null, "e": 1630, "s": 1591, "text": "This will produce the following output" }, { "code": null, "e": 1633, "s": 1630, "text": "20" }, { "code": null, "e": 1746, "s": 1633, "text": "Let us see another example. Following is the query to declare and initialize a string variable at MongoDB shell." }, { "code": null, "e": 1786, "s": 1746, "text": "> var myStringValue=\"Hello MongoDB!!!\";" }, { "code": null, "e": 1860, "s": 1786, "text": "Following is the query to print a variable at the MongoDB command prompt." }, { "code": null, "e": 1876, "s": 1860, "text": "> myStringValue" }, { "code": null, "e": 1915, "s": 1876, "text": "This will produce the following output" }, { "code": null, "e": 1932, "s": 1915, "text": "Hello MongoDB!!!" }, { "code": null, "e": 1981, "s": 1932, "text": "You can also use print(). Following is the query" }, { "code": null, "e": 2005, "s": 1981, "text": "> print(myStringValue);" }, { "code": null, "e": 2044, "s": 2005, "text": "This will produce the following output" }, { "code": null, "e": 2061, "s": 2044, "text": "Hello MongoDB!!!" } ]
GATE | GATE-CS-2007 | Question 45 - GeeksforGeeks
28 Jun, 2021 What is the time complexity of the following recursive function: int DoSomething (int n) { if (n <= 2) return 1; else return (DoSomething (floor(sqrt(n))) + n);} (A) (n)(B) (nlogn)(C) (logn)(D) (loglogn)(A) A(B) B(C) C(D) DAnswer: (D)Explanation: See Question 5 of https://www.geeksforgeeks.org/data-structures-and-algorithms-set-11/Quiz of this Question GATE-CS-2007 GATE-GATE-CS-2007 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE-CS-2006 | Question 47 GATE | GATE MOCK 2017 | Question 24 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25695, "s": 25667, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25760, "s": 25695, "text": "What is the time complexity of the following recursive function:" }, { "code": "int DoSomething (int n) { if (n <= 2) return 1; else return (DoSomething (floor(sqrt(n))) + n);}", "e": 25867, "s": 25760, "text": null }, { "code": null, "e": 26060, "s": 25867, "text": "(A) (n)(B) (nlogn)(C) (logn)(D) (loglogn)(A) A(B) B(C) C(D) DAnswer: (D)Explanation: See Question 5 of https://www.geeksforgeeks.org/data-structures-and-algorithms-set-11/Quiz of this Question" }, { "code": null, "e": 26073, "s": 26060, "text": "GATE-CS-2007" }, { "code": null, "e": 26091, "s": 26073, "text": "GATE-GATE-CS-2007" }, { "code": null, "e": 26096, "s": 26091, "text": "GATE" }, { "code": null, "e": 26194, "s": 26096, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26228, "s": 26194, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 26262, "s": 26228, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 26296, "s": 26262, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 26329, "s": 26296, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 26365, "s": 26329, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 26399, "s": 26365, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 26435, "s": 26399, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 26469, "s": 26435, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 26503, "s": 26469, "text": "GATE | GATE-CS-2009 | Question 38" } ]
PositiveSmallIntegerField - Django Models - GeeksforGeeks
12 Feb, 2020 PositiveSmallIntegerField is a integer number represented in Python by a int instance. This field is like a PositiveIntegerField. The default form widget for this field is a NumberInput when localize is False or TextInput otherwise. It supports values from 0 to 32767 in all databases supported by Django.It uses MinValueValidator and MaxValueValidator to validate the input based on the values that the default database supports. Syntax: field_name = models.PositiveSmallIntegerField(**options) Illustration of PositiveSmallIntegerField using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Enter the following code into models.py file of geeks app. from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.PositiveSmallIntegerField() Add the geeks app to INSTALLED_APPS # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',] Now when we run makemigrations command from the terminal, Python manage.py makemigrations A new folder named migrations would be created in geeks directory with a file named 0001_initial.py # Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField( auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.PositiveSmallIntegerField()), ], ), ] Now run, Python manage.py migrate Thus, an geeks_field PositiveSmallIntegerField is created when you run migrations on the project. It is a field to store positive integer numbers. PositiveSmallIntegerField is used for storing a integer number represented in Python by a int instance. To know more about int, visit Python | int() function. Let’s try to save a positive number in PositiveSmallIntegerField. # importing the model# from geeks appfrom geeks.models import GeeksModel # creating an instance of# intd = int(2189) # creating a instance of # GeeksModelgeek_object = GeeksModel.objects.create(geeks_field = d)geek_object.save() Now let’s check it in admin server. We have created an instance of GeeksModel. Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to PositiveSmallIntegerField will enable it to store empty values for that table in relational database.Here are the field options and attributes that an PositiveSmallIntegerField can use. NaveenArora Django-models Python Django 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 ? Different ways to create Pandas Dataframe Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Convert integer to string in Python Check if element exists in list in Python Create a Pandas DataFrame from Lists sum() function in Python
[ { "code": null, "e": 25559, "s": 25531, "text": "\n12 Feb, 2020" }, { "code": null, "e": 25990, "s": 25559, "text": "PositiveSmallIntegerField is a integer number represented in Python by a int instance. This field is like a PositiveIntegerField. The default form widget for this field is a NumberInput when localize is False or TextInput otherwise. It supports values from 0 to 32767 in all databases supported by Django.It uses MinValueValidator and MaxValueValidator to validate the input based on the values that the default database supports." }, { "code": null, "e": 25998, "s": 25990, "text": "Syntax:" }, { "code": null, "e": 26055, "s": 25998, "text": "field_name = models.PositiveSmallIntegerField(**options)" }, { "code": null, "e": 26181, "s": 26055, "text": "Illustration of PositiveSmallIntegerField using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 26268, "s": 26181, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 26319, "s": 26268, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 26352, "s": 26319, "text": "How to Create an App in Django ?" }, { "code": null, "e": 26411, "s": 26352, "text": "Enter the following code into models.py file of geeks app." }, { "code": "from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.PositiveSmallIntegerField()", "e": 26578, "s": 26411, "text": null }, { "code": null, "e": 26614, "s": 26578, "text": "Add the geeks app to INSTALLED_APPS" }, { "code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]", "e": 26852, "s": 26614, "text": null }, { "code": null, "e": 26910, "s": 26852, "text": "Now when we run makemigrations command from the terminal," }, { "code": null, "e": 26942, "s": 26910, "text": "Python manage.py makemigrations" }, { "code": null, "e": 27042, "s": 26942, "text": "A new folder named migrations would be created in geeks directory with a file named 0001_initial.py" }, { "code": "# Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField( auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.PositiveSmallIntegerField()), ], ), ]", "e": 27662, "s": 27042, "text": null }, { "code": null, "e": 27671, "s": 27662, "text": "Now run," }, { "code": null, "e": 27696, "s": 27671, "text": "Python manage.py migrate" }, { "code": null, "e": 27843, "s": 27696, "text": "Thus, an geeks_field PositiveSmallIntegerField is created when you run migrations on the project. It is a field to store positive integer numbers." }, { "code": null, "e": 28068, "s": 27843, "text": "PositiveSmallIntegerField is used for storing a integer number represented in Python by a int instance. To know more about int, visit Python | int() function. Let’s try to save a positive number in PositiveSmallIntegerField." }, { "code": "# importing the model# from geeks appfrom geeks.models import GeeksModel # creating an instance of# intd = int(2189) # creating a instance of # GeeksModelgeek_object = GeeksModel.objects.create(geeks_field = d)geek_object.save()", "e": 28299, "s": 28068, "text": null }, { "code": null, "e": 28378, "s": 28299, "text": "Now let’s check it in admin server. We have created an instance of GeeksModel." }, { "code": null, "e": 28756, "s": 28378, "text": "Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to PositiveSmallIntegerField will enable it to store empty values for that table in relational database.Here are the field options and attributes that an PositiveSmallIntegerField can use." }, { "code": null, "e": 28768, "s": 28756, "text": "NaveenArora" }, { "code": null, "e": 28782, "s": 28768, "text": "Django-models" }, { "code": null, "e": 28796, "s": 28782, "text": "Python Django" }, { "code": null, "e": 28803, "s": 28796, "text": "Python" }, { "code": null, "e": 28901, "s": 28803, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28919, "s": 28901, "text": "Python Dictionary" }, { "code": null, "e": 28951, "s": 28919, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28993, "s": 28951, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29019, "s": 28993, "text": "Python String | replace()" }, { "code": null, "e": 29063, "s": 29019, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29092, "s": 29063, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29128, "s": 29092, "text": "Convert integer to string in Python" }, { "code": null, "e": 29170, "s": 29128, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29207, "s": 29170, "text": "Create a Pandas DataFrame from Lists" } ]
HTML DOM Range insertNode() Method - GeeksforGeeks
07 Jul, 2020 The insertNode() method inserts a node at the start of the Range. The updated Range consists of new inserted node before the Range of the last Range content. Syntax: range.insertNode( newNode ); Parameters: This method accepts single parameter as mentioned above and described below: newNode: The Node to be inserted at the starting of the range. Return value: This method does not return any value. Example: This example shows how to insert a node before the range content using insertNode() method. To Clarify, changes in range content, we had console logged the new range in string text using toString() method. HTML <!DOCTYPE html><html> <head> <title> HTML DOM range insertNode() method </title></head> <body> <h1>GeeksforGeeks</h1> <p>Range Content</p> <button onclick="insert()"> Click Here to insert the Node </button> <p id="element">Node element </p> <script> var range = document.createRange(); range.selectNode(document .getElementsByTagName("p").item(0)); const element = document .getElementById('element'); console.log("Before Button Click:", range.toString()); function insert() { range.insertNode(element); console.log("After Button Click:", range.toString()); } </script></body> </html> Output: Before Click the Button: Before Click the Button: After Click the Button: After Click the Button: Supported Browsers: Google Chrome Edge Firefox Safari Opera Internet Explorer Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-DOM HTML-Methods HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload 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 calculate the number of days between two dates in javascript?
[ { "code": null, "e": 26139, "s": 26111, "text": "\n07 Jul, 2020" }, { "code": null, "e": 26205, "s": 26139, "text": "The insertNode() method inserts a node at the start of the Range." }, { "code": null, "e": 26297, "s": 26205, "text": "The updated Range consists of new inserted node before the Range of the last Range content." }, { "code": null, "e": 26305, "s": 26297, "text": "Syntax:" }, { "code": null, "e": 26334, "s": 26305, "text": "range.insertNode( newNode );" }, { "code": null, "e": 26423, "s": 26334, "text": "Parameters: This method accepts single parameter as mentioned above and described below:" }, { "code": null, "e": 26486, "s": 26423, "text": "newNode: The Node to be inserted at the starting of the range." }, { "code": null, "e": 26539, "s": 26486, "text": "Return value: This method does not return any value." }, { "code": null, "e": 26754, "s": 26539, "text": "Example: This example shows how to insert a node before the range content using insertNode() method. To Clarify, changes in range content, we had console logged the new range in string text using toString() method." }, { "code": null, "e": 26759, "s": 26754, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML DOM range insertNode() method </title></head> <body> <h1>GeeksforGeeks</h1> <p>Range Content</p> <button onclick=\"insert()\"> Click Here to insert the Node </button> <p id=\"element\">Node element </p> <script> var range = document.createRange(); range.selectNode(document .getElementsByTagName(\"p\").item(0)); const element = document .getElementById('element'); console.log(\"Before Button Click:\", range.toString()); function insert() { range.insertNode(element); console.log(\"After Button Click:\", range.toString()); } </script></body> </html>", "e": 27557, "s": 26759, "text": null }, { "code": null, "e": 27565, "s": 27557, "text": "Output:" }, { "code": null, "e": 27590, "s": 27565, "text": "Before Click the Button:" }, { "code": null, "e": 27615, "s": 27590, "text": "Before Click the Button:" }, { "code": null, "e": 27639, "s": 27615, "text": "After Click the Button:" }, { "code": null, "e": 27663, "s": 27639, "text": "After Click the Button:" }, { "code": null, "e": 27683, "s": 27663, "text": "Supported Browsers:" }, { "code": null, "e": 27697, "s": 27683, "text": "Google Chrome" }, { "code": null, "e": 27702, "s": 27697, "text": "Edge" }, { "code": null, "e": 27710, "s": 27702, "text": "Firefox" }, { "code": null, "e": 27717, "s": 27710, "text": "Safari" }, { "code": null, "e": 27723, "s": 27717, "text": "Opera" }, { "code": null, "e": 27741, "s": 27723, "text": "Internet Explorer" }, { "code": null, "e": 27878, "s": 27741, "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": 27887, "s": 27878, "text": "HTML-DOM" }, { "code": null, "e": 27900, "s": 27887, "text": "HTML-Methods" }, { "code": null, "e": 27905, "s": 27900, "text": "HTML" }, { "code": null, "e": 27916, "s": 27905, "text": "JavaScript" }, { "code": null, "e": 27933, "s": 27916, "text": "Web Technologies" }, { "code": null, "e": 27938, "s": 27933, "text": "HTML" }, { "code": null, "e": 28036, "s": 27938, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28060, "s": 28036, "text": "REST API (Introduction)" }, { "code": null, "e": 28101, "s": 28060, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 28138, "s": 28101, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28167, "s": 28138, "text": "Form validation using jQuery" }, { "code": null, "e": 28187, "s": 28167, "text": "Angular File Upload" }, { "code": null, "e": 28227, "s": 28187, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28272, "s": 28227, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28333, "s": 28272, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28405, "s": 28333, "text": "Differences between Functional Components and Class Components in React" } ]
Peterson's Algorithm for Mutual Exclusion | Set 2 (CPU Cycles and Memory Fence) - GeeksforGeeks
07 Aug, 2021 Problem: Given 2 process i and j, you need to write a program that can guarantee mutual exclusion between the two without any additional hardware support. We strongly recommend to refer below basic solution discussed in previous article. Peterson’s Algorithm for Mutual Exclusion | Set 1We would be resolving 2 issues in the previous algorithm. In layman terms, when a thread was waiting for its turn, it ended in a long while loop which tested the condition millions of times per second thus doing unnecessary computation. There is a better way to wait, and it is known as “yield”. To understand what it does, we need to dig deep into how the Process scheduler works in Linux. The idea mentioned here is a simplified version of the scheduler, the actual implementation has lots of complications. Consider the following example, There are three processes, P1, P2 and P3. Process P3 is such that it has a while loop similar to the one in our code, doing not so useful computation, and it exists from the loop only when P2 finishes its execution. The scheduler puts all of them in a round robin queue. Now, say the clock speed of processor is 1000000/sec, and it allocates 100 clocks to each process in each iteration. Then, first P1 will be run for 100 clocks (0.0001 seconds), then P2(0.0001 seconds) followed by P3(0.0001 seconds), now since there are no more processes, this cycle repeats until P2 ends and then followed by P3’s execution and eventually its termination. This is a complete waste of the 100 CPU clock cycles. To avoid this, we mutually give up the CPU time slice, i.e. yield, which essentially ends this time slice and the scheduler picks up the next process to run. Now, we test our condition once, then we give up the CPU. Considering our test takes 25 clock cycles, we save 75% of our computation in a time slice. To put this graphically, Considering the processor clock speed as 1MHz this is a lot of saving!. Different distributions provide different function to achieve this functionality. Linux provides sched_yield(). C void lock(int self){ flag[self] = 1; turn = 1-self; while (flag[1-self] == 1 && turn == 1-self) // Only change is the addition of // sched_yield() call sched_yield();} The code in earlier tutorial might have worked on most systems, but is was not 100% correct. The logic was perfect, but most modern CPUs employ performance optimizations that can result in out-of-order execution. This reordering of memory operations (loads and stores) normally goes unnoticed within a single thread of execution, but can cause unpredictable behaviour in concurrent programs.Consider this example, C while (f == 0); // Memory fence required hereprint x; In the above example, the compiler considers the 2 statements as independent of each other and thus tries to increase the code efficiency by re-ordering them, which can lead to problems for concurrent programs. To avoid this we place a memory fence to give hint to the compiler about the possible relationship between the statements across the barrier. So the order of statements, flag[self] = 1; turn = 1-self; while (turn condition check) yield(); has to be exactly the same in order for the lock to work, otherwise it will end up in a deadlock condition. To ensure this, compilers provide a instruction that prevent ordering of statements across this barrier. In case of gcc, its __sync_synchronize().So the modified code becomes, Full Implementation in C: C // Filename: peterson_yieldlock_memoryfence.c// Use below command to compile:// gcc -pthread peterson_yieldlock_memoryfence.c -o peterson_yieldlock_memoryfence #include<stdio.h>#include<pthread.h>#include "mythreads.h" int flag[2];int turn;const int MAX = 1e9;int ans = 0; void lock_init(){ // Initialize lock by reseting the desire of // both the threads to acquire the locks. // And, giving turn to one of them. flag[0] = flag[1] = 0; turn = 0;} // Executed before entering critical sectionvoid lock(int self){ // Set flag[self] = 1 saying you want // to acquire lock flag[self]=1; // But, first give the other thread the // chance to acquire lock turn = 1-self; // Memory fence to prevent the reordering // of instructions beyond this barrier. __sync_synchronize(); // Wait until the other thread loses the // desire to acquire lock or it is your // turn to get the lock. while (flag[1-self]==1 && turn==1-self) // Yield to avoid wastage of resources. sched_yield();} // Executed after leaving critical sectionvoid unlock(int self){ // You do not desire to acquire lock in future. // This will allow the other thread to acquire // the lock. flag[self]=0;} // A Sample function run by two threads created// in main()void* func(void *s){ int i = 0; int self = (int *)s; printf("Thread Entered: %d\n",self); lock(self); // Critical section (Only one thread // can enter here at a time) for (i=0; i<MAX; i++) ans++; unlock(self);} // Driver codeint main(){ pthread_t p1, p2; // Initialize the lock lock_init(); // Create two threads (both run func) Pthread_create(&p1, NULL, func, (void*)0); Pthread_create(&p2, NULL, func, (void*)1); // Wait for the threads to end. Pthread_join(p1, NULL); Pthread_join(p2, NULL); printf("Actual Count: %d | Expected Count:" " %d\n",ans,MAX*2); return 0;} C // mythread.h (A wrapper header file with assert// statements)#ifndef __MYTHREADS_h__#define __MYTHREADS_h__ #include <pthread.h>#include <assert.h>#include <sched.h> void Pthread_mutex_lock(pthread_mutex_t *m){ int rc = pthread_mutex_lock(m); assert(rc == 0);} void Pthread_mutex_unlock(pthread_mutex_t *m){ int rc = pthread_mutex_unlock(m); assert(rc == 0);} void Pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg){ int rc = pthread_create(thread, attr, start_routine, arg); assert(rc == 0);} void Pthread_join(pthread_t thread, void **value_ptr){ int rc = pthread_join(thread, value_ptr); assert(rc == 0);} #endif // __MYTHREADS_h__ Output: Thread Entered: 1 Thread Entered: 0 Actual Count: 2000000000 | Expected Count: 2000000000 This article is contributed by Pinkesh Badjatiya . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. arorakashish0911 Process Synchronization Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Page Replacement Algorithms in Operating Systems Program for FCFS CPU Scheduling | Set 1 Paging in Operating System Program for Round Robin scheduling | Set 1 Introduction of Operating System - Set 1 Semaphores in Process Synchronization Inter Process Communication (IPC) Disk Scheduling Algorithms CPU Scheduling in Operating Systems Preemptive and Non-Preemptive Scheduling
[ { "code": null, "e": 25857, "s": 25829, "text": "\n07 Aug, 2021" }, { "code": null, "e": 26012, "s": 25857, "text": "Problem: Given 2 process i and j, you need to write a program that can guarantee mutual exclusion between the two without any additional hardware support." }, { "code": null, "e": 26203, "s": 26012, "text": "We strongly recommend to refer below basic solution discussed in previous article. Peterson’s Algorithm for Mutual Exclusion | Set 1We would be resolving 2 issues in the previous algorithm. " }, { "code": null, "e": 26441, "s": 26203, "text": "In layman terms, when a thread was waiting for its turn, it ended in a long while loop which tested the condition millions of times per second thus doing unnecessary computation. There is a better way to wait, and it is known as “yield”." }, { "code": null, "e": 26655, "s": 26441, "text": "To understand what it does, we need to dig deep into how the Process scheduler works in Linux. The idea mentioned here is a simplified version of the scheduler, the actual implementation has lots of complications." }, { "code": null, "e": 27331, "s": 26655, "text": "Consider the following example, There are three processes, P1, P2 and P3. Process P3 is such that it has a while loop similar to the one in our code, doing not so useful computation, and it exists from the loop only when P2 finishes its execution. The scheduler puts all of them in a round robin queue. Now, say the clock speed of processor is 1000000/sec, and it allocates 100 clocks to each process in each iteration. Then, first P1 will be run for 100 clocks (0.0001 seconds), then P2(0.0001 seconds) followed by P3(0.0001 seconds), now since there are no more processes, this cycle repeats until P2 ends and then followed by P3’s execution and eventually its termination." }, { "code": null, "e": 27719, "s": 27331, "text": "This is a complete waste of the 100 CPU clock cycles. To avoid this, we mutually give up the CPU time slice, i.e. yield, which essentially ends this time slice and the scheduler picks up the next process to run. Now, we test our condition once, then we give up the CPU. Considering our test takes 25 clock cycles, we save 75% of our computation in a time slice. To put this graphically, " }, { "code": null, "e": 27903, "s": 27719, "text": "Considering the processor clock speed as 1MHz this is a lot of saving!. Different distributions provide different function to achieve this functionality. Linux provides sched_yield()." }, { "code": null, "e": 27905, "s": 27903, "text": "C" }, { "code": "void lock(int self){ flag[self] = 1; turn = 1-self; while (flag[1-self] == 1 && turn == 1-self) // Only change is the addition of // sched_yield() call sched_yield();}", "e": 28116, "s": 27905, "text": null }, { "code": null, "e": 28531, "s": 28116, "text": "The code in earlier tutorial might have worked on most systems, but is was not 100% correct. The logic was perfect, but most modern CPUs employ performance optimizations that can result in out-of-order execution. This reordering of memory operations (loads and stores) normally goes unnoticed within a single thread of execution, but can cause unpredictable behaviour in concurrent programs.Consider this example, " }, { "code": null, "e": 28533, "s": 28531, "text": "C" }, { "code": "while (f == 0); // Memory fence required hereprint x;", "e": 28587, "s": 28533, "text": null }, { "code": null, "e": 28940, "s": 28587, "text": "In the above example, the compiler considers the 2 statements as independent of each other and thus tries to increase the code efficiency by re-ordering them, which can lead to problems for concurrent programs. To avoid this we place a memory fence to give hint to the compiler about the possible relationship between the statements across the barrier." }, { "code": null, "e": 28970, "s": 28940, "text": "So the order of statements, " }, { "code": null, "e": 29041, "s": 28970, "text": "flag[self] = 1; turn = 1-self; while (turn condition check) yield(); " }, { "code": null, "e": 29149, "s": 29041, "text": "has to be exactly the same in order for the lock to work, otherwise it will end up in a deadlock condition." }, { "code": null, "e": 29351, "s": 29149, "text": "To ensure this, compilers provide a instruction that prevent ordering of statements across this barrier. In case of gcc, its __sync_synchronize().So the modified code becomes, Full Implementation in C:" }, { "code": null, "e": 29353, "s": 29351, "text": "C" }, { "code": "// Filename: peterson_yieldlock_memoryfence.c// Use below command to compile:// gcc -pthread peterson_yieldlock_memoryfence.c -o peterson_yieldlock_memoryfence #include<stdio.h>#include<pthread.h>#include \"mythreads.h\" int flag[2];int turn;const int MAX = 1e9;int ans = 0; void lock_init(){ // Initialize lock by reseting the desire of // both the threads to acquire the locks. // And, giving turn to one of them. flag[0] = flag[1] = 0; turn = 0;} // Executed before entering critical sectionvoid lock(int self){ // Set flag[self] = 1 saying you want // to acquire lock flag[self]=1; // But, first give the other thread the // chance to acquire lock turn = 1-self; // Memory fence to prevent the reordering // of instructions beyond this barrier. __sync_synchronize(); // Wait until the other thread loses the // desire to acquire lock or it is your // turn to get the lock. while (flag[1-self]==1 && turn==1-self) // Yield to avoid wastage of resources. sched_yield();} // Executed after leaving critical sectionvoid unlock(int self){ // You do not desire to acquire lock in future. // This will allow the other thread to acquire // the lock. flag[self]=0;} // A Sample function run by two threads created// in main()void* func(void *s){ int i = 0; int self = (int *)s; printf(\"Thread Entered: %d\\n\",self); lock(self); // Critical section (Only one thread // can enter here at a time) for (i=0; i<MAX; i++) ans++; unlock(self);} // Driver codeint main(){ pthread_t p1, p2; // Initialize the lock lock_init(); // Create two threads (both run func) Pthread_create(&p1, NULL, func, (void*)0); Pthread_create(&p2, NULL, func, (void*)1); // Wait for the threads to end. Pthread_join(p1, NULL); Pthread_join(p2, NULL); printf(\"Actual Count: %d | Expected Count:\" \" %d\\n\",ans,MAX*2); return 0;}", "e": 31312, "s": 29353, "text": null }, { "code": null, "e": 31314, "s": 31312, "text": "C" }, { "code": "// mythread.h (A wrapper header file with assert// statements)#ifndef __MYTHREADS_h__#define __MYTHREADS_h__ #include <pthread.h>#include <assert.h>#include <sched.h> void Pthread_mutex_lock(pthread_mutex_t *m){ int rc = pthread_mutex_lock(m); assert(rc == 0);} void Pthread_mutex_unlock(pthread_mutex_t *m){ int rc = pthread_mutex_unlock(m); assert(rc == 0);} void Pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg){ int rc = pthread_create(thread, attr, start_routine, arg); assert(rc == 0);} void Pthread_join(pthread_t thread, void **value_ptr){ int rc = pthread_join(thread, value_ptr); assert(rc == 0);} #endif // __MYTHREADS_h__", "e": 32201, "s": 31314, "text": null }, { "code": null, "e": 32210, "s": 32201, "text": "Output: " }, { "code": null, "e": 32300, "s": 32210, "text": "Thread Entered: 1\nThread Entered: 0\nActual Count: 2000000000 | Expected Count: 2000000000" }, { "code": null, "e": 32727, "s": 32300, "text": "This article is contributed by Pinkesh Badjatiya . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 32744, "s": 32727, "text": "arorakashish0911" }, { "code": null, "e": 32768, "s": 32744, "text": "Process Synchronization" }, { "code": null, "e": 32786, "s": 32768, "text": "Operating Systems" }, { "code": null, "e": 32804, "s": 32786, "text": "Operating Systems" }, { "code": null, "e": 32902, "s": 32804, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32951, "s": 32902, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 32991, "s": 32951, "text": "Program for FCFS CPU Scheduling | Set 1" }, { "code": null, "e": 33018, "s": 32991, "text": "Paging in Operating System" }, { "code": null, "e": 33061, "s": 33018, "text": "Program for Round Robin scheduling | Set 1" }, { "code": null, "e": 33102, "s": 33061, "text": "Introduction of Operating System - Set 1" }, { "code": null, "e": 33140, "s": 33102, "text": "Semaphores in Process Synchronization" }, { "code": null, "e": 33174, "s": 33140, "text": "Inter Process Communication (IPC)" }, { "code": null, "e": 33201, "s": 33174, "text": "Disk Scheduling Algorithms" }, { "code": null, "e": 33237, "s": 33201, "text": "CPU Scheduling in Operating Systems" } ]
Phonenumbers module in Python - GeeksforGeeks
05 Sep, 2020 Python is a very powerful language and also very rich in libraries. phonenumbers is one of the modules that provides numerous features like providing basic information of a phone number, validation of a phone number etc. Here, we will learn how to use phonenumbers module just by writing simple Python programs. This is a Python port of Google’s libphonenumber library. Install the phonenumbers module by typing the following command in command prompt. pip install phonenumbers 1. Convert String to phonenumber format: To explore the features of phonenumbers module, we need to take the phone number of a user in phonenumber format. Here we will see how to convert the user phone number to phonenumber format. Input must be of string type and country code must be added before phone number. Python3 # Program to convert input to# phonenumber format import phonenumbers # Parsing String to Phone number# Phone number format: (+Countrycode)xxxxxxxxxxphoneNumber = phonenumbers.parse("+919876543210") # This will print the phone number and # it's basic details.print(phoneNumber) Output: Country Code: 91 National Number: 9876543210 2. Get Timezone: Here is the simple Python program to get the timezone of a phone number using phonenumbers module. First, we do parse the string input to phonenumber format, and then we use an inbuilt function to get the timezone of a user. It gives the output for valid numbers only. Python3 # Program to get timezone a phone number import phonenumbersfrom phonenumbers import timezone # Parsing String to Phone numberphoneNumber = phonenumbers.parse("+919876543210") # Pass the parsed phone number in below functiontimeZone = timezone.time_zones_for_number(phoneNumber) # It print the timezone of a phonenumberprint(timeZone) Output: ('Asia/Calcutta',) 3. Extract phone numbers from text: We can extract phone numbers that are present in a text/paragraph using this module. You can iterate over it to retrieve a sequence of phone numbers. For this, PhoneNumberMatcher object provides the relevant function. Python3 # Program to extract phone numbers from a textimport phonenumbers # Text Inputtext = "Contact us at +919876543210 or +14691234567" # Pass the text and country code to the below functionnumbers = phonenumbers.PhoneNumberMatcher(text, "IN") # Printing the phone numbers matched with country code# and also the indexes of the phone numbers in the string inputfor number in numbers: print(number) Output: PhoneNumberMatch [14,27) +919876543210 4. Carrier and Region of a Phone Number: Here we will learn how to find the carrier and region of a phone number using the geocoder and carrier functions of this module. Python3 # Program to find carrier and region# of a phone numberimport phonenumbersfrom phonenumbers import geocoder, carrier # Parsing String to Phone numberphoneNumber = phonenumbers.parse("+919876543210") # Getting carrier of a phone numberCarrier = carrier.name_for_number(phoneNumber, 'en') # Getting region informationRegion = geocoder.description_for_number(phoneNumber, 'en') # Printing the carrier and region of a phone numberprint(Carrier)print(Region) Output: Airtel India 5. Validation of a phone number: A simple python program, to check whether a given phone number is valid or not (e.g. it’s in an assigned exchange), and to check whether a given phone number is possible or not (e.g. it has the right number of digits). Python3 # Program to check whether a phone number is# valid or notimport phonenumbers # Parsing String to Phone numberphone_number = phonenumbers.parse("+91987654321") # Validating a phone numbervalid = phonenumbers.is_valid_number(phone_number) # Checking possibility of a numberpossible = phonenumbers.is_possible_number(phone_number) # Printing the outputprint(valid)print(possible) Output: False True python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25849, "s": 25821, "text": "\n05 Sep, 2020" }, { "code": null, "e": 26219, "s": 25849, "text": "Python is a very powerful language and also very rich in libraries. phonenumbers is one of the modules that provides numerous features like providing basic information of a phone number, validation of a phone number etc. Here, we will learn how to use phonenumbers module just by writing simple Python programs. This is a Python port of Google’s libphonenumber library." }, { "code": null, "e": 26302, "s": 26219, "text": "Install the phonenumbers module by typing the following command in command prompt." }, { "code": null, "e": 26328, "s": 26302, "text": "pip install phonenumbers\n" }, { "code": null, "e": 26641, "s": 26328, "text": "1. Convert String to phonenumber format: To explore the features of phonenumbers module, we need to take the phone number of a user in phonenumber format. Here we will see how to convert the user phone number to phonenumber format. Input must be of string type and country code must be added before phone number." }, { "code": null, "e": 26649, "s": 26641, "text": "Python3" }, { "code": "# Program to convert input to# phonenumber format import phonenumbers # Parsing String to Phone number# Phone number format: (+Countrycode)xxxxxxxxxxphoneNumber = phonenumbers.parse(\"+919876543210\") # This will print the phone number and # it's basic details.print(phoneNumber)", "e": 26930, "s": 26649, "text": null }, { "code": null, "e": 26938, "s": 26930, "text": "Output:" }, { "code": null, "e": 26984, "s": 26938, "text": "Country Code: 91 National Number: 9876543210\n" }, { "code": null, "e": 27270, "s": 26984, "text": "2. Get Timezone: Here is the simple Python program to get the timezone of a phone number using phonenumbers module. First, we do parse the string input to phonenumber format, and then we use an inbuilt function to get the timezone of a user. It gives the output for valid numbers only." }, { "code": null, "e": 27278, "s": 27270, "text": "Python3" }, { "code": "# Program to get timezone a phone number import phonenumbersfrom phonenumbers import timezone # Parsing String to Phone numberphoneNumber = phonenumbers.parse(\"+919876543210\") # Pass the parsed phone number in below functiontimeZone = timezone.time_zones_for_number(phoneNumber) # It print the timezone of a phonenumberprint(timeZone)", "e": 27617, "s": 27278, "text": null }, { "code": null, "e": 27625, "s": 27617, "text": "Output:" }, { "code": null, "e": 27645, "s": 27625, "text": "('Asia/Calcutta',)\n" }, { "code": null, "e": 27899, "s": 27645, "text": "3. Extract phone numbers from text: We can extract phone numbers that are present in a text/paragraph using this module. You can iterate over it to retrieve a sequence of phone numbers. For this, PhoneNumberMatcher object provides the relevant function." }, { "code": null, "e": 27907, "s": 27899, "text": "Python3" }, { "code": "# Program to extract phone numbers from a textimport phonenumbers # Text Inputtext = \"Contact us at +919876543210 or +14691234567\" # Pass the text and country code to the below functionnumbers = phonenumbers.PhoneNumberMatcher(text, \"IN\") # Printing the phone numbers matched with country code# and also the indexes of the phone numbers in the string inputfor number in numbers: print(number)", "e": 28306, "s": 27907, "text": null }, { "code": null, "e": 28314, "s": 28306, "text": "Output:" }, { "code": null, "e": 28354, "s": 28314, "text": "PhoneNumberMatch [14,27) +919876543210\n" }, { "code": null, "e": 28524, "s": 28354, "text": "4. Carrier and Region of a Phone Number: Here we will learn how to find the carrier and region of a phone number using the geocoder and carrier functions of this module." }, { "code": null, "e": 28532, "s": 28524, "text": "Python3" }, { "code": "# Program to find carrier and region# of a phone numberimport phonenumbersfrom phonenumbers import geocoder, carrier # Parsing String to Phone numberphoneNumber = phonenumbers.parse(\"+919876543210\") # Getting carrier of a phone numberCarrier = carrier.name_for_number(phoneNumber, 'en') # Getting region informationRegion = geocoder.description_for_number(phoneNumber, 'en') # Printing the carrier and region of a phone numberprint(Carrier)print(Region)", "e": 28990, "s": 28532, "text": null }, { "code": null, "e": 28998, "s": 28990, "text": "Output:" }, { "code": null, "e": 29012, "s": 28998, "text": "Airtel\nIndia\n" }, { "code": null, "e": 29264, "s": 29012, "text": "5. Validation of a phone number: A simple python program, to check whether a given phone number is valid or not (e.g. it’s in an assigned exchange), and to check whether a given phone number is possible or not (e.g. it has the right number of digits)." }, { "code": null, "e": 29272, "s": 29264, "text": "Python3" }, { "code": "# Program to check whether a phone number is# valid or notimport phonenumbers # Parsing String to Phone numberphone_number = phonenumbers.parse(\"+91987654321\") # Validating a phone numbervalid = phonenumbers.is_valid_number(phone_number) # Checking possibility of a numberpossible = phonenumbers.is_possible_number(phone_number) # Printing the outputprint(valid)print(possible)", "e": 29654, "s": 29272, "text": null }, { "code": null, "e": 29662, "s": 29654, "text": "Output:" }, { "code": null, "e": 29673, "s": 29662, "text": "False\nTrue" }, { "code": null, "e": 29688, "s": 29673, "text": "python-modules" }, { "code": null, "e": 29695, "s": 29688, "text": "Python" }, { "code": null, "e": 29793, "s": 29695, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29811, "s": 29793, "text": "Python Dictionary" }, { "code": null, "e": 29846, "s": 29811, "text": "Read a file line by line in Python" }, { "code": null, "e": 29878, "s": 29846, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29900, "s": 29878, "text": "Enumerate() in Python" }, { "code": null, "e": 29942, "s": 29900, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29972, "s": 29942, "text": "Iterate over a list in Python" }, { "code": null, "e": 29998, "s": 29972, "text": "Python String | replace()" }, { "code": null, "e": 30027, "s": 29998, "text": "*args and **kwargs in Python" }, { "code": null, "e": 30071, "s": 30027, "text": "Reading and Writing to text files in Python" } ]
Java | Exception Handling | Question 4 - GeeksforGeeks
28 Jun, 2021 class Base extends Exception {}class Derived extends Base {} public class Main { public static void main(String args[]) { // some other stuff try { // Some monitored code throw new Derived(); } catch(Base b) { System.out.println("Caught base class exception"); } catch(Derived d) { System.out.println("Caught derived class exception"); } }} (A) Caught base class exception(B) Caught derived class exception(C) Compiler Error because derived is not throwable(D) Compiler Error because base class exception is caught before derived classAnswer: (D)Explanation: See Catching base and derived classes as exceptions Following is the error in below program Main.java:12: error: exception Derived has already been caught catch(Derived d) { System.out.println("Caught derived class exception"); } Quiz of this Question Exception Handling Java-Exception Handling Java Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Java | Constructors | Question 5 Java | Functions | Question 1 Java | final keyword | Question 1 Java | Inheritance | Question 8 Java | Arrays | Question 1 Java | Operators | Question 1 Java | Operators | Question 3 Java | Inheritance | Question 7 Java | Functions | Question 4 Java | Inheritance | Question 5
[ { "code": null, "e": 25658, "s": 25630, "text": "\n28 Jun, 2021" }, { "code": "class Base extends Exception {}class Derived extends Base {} public class Main { public static void main(String args[]) { // some other stuff try { // Some monitored code throw new Derived(); } catch(Base b) { System.out.println(\"Caught base class exception\"); } catch(Derived d) { System.out.println(\"Caught derived class exception\"); } }} ", "e": 26056, "s": 25658, "text": null }, { "code": null, "e": 26326, "s": 26056, "text": "(A) Caught base class exception(B) Caught derived class exception(C) Compiler Error because derived is not throwable(D) Compiler Error because base class exception is caught before derived classAnswer: (D)Explanation: See Catching base and derived classes as exceptions" }, { "code": null, "e": 26366, "s": 26326, "text": "Following is the error in below program" }, { "code": null, "e": 26510, "s": 26366, "text": "Main.java:12: error: exception Derived has already been caught\n catch(Derived d) { System.out.println(\"Caught derived class exception\"); } " }, { "code": null, "e": 26532, "s": 26510, "text": "Quiz of this Question" }, { "code": null, "e": 26551, "s": 26532, "text": "Exception Handling" }, { "code": null, "e": 26575, "s": 26551, "text": "Java-Exception Handling" }, { "code": null, "e": 26585, "s": 26575, "text": "Java Quiz" }, { "code": null, "e": 26683, "s": 26585, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26716, "s": 26683, "text": "Java | Constructors | Question 5" }, { "code": null, "e": 26746, "s": 26716, "text": "Java | Functions | Question 1" }, { "code": null, "e": 26780, "s": 26746, "text": "Java | final keyword | Question 1" }, { "code": null, "e": 26812, "s": 26780, "text": "Java | Inheritance | Question 8" }, { "code": null, "e": 26839, "s": 26812, "text": "Java | Arrays | Question 1" }, { "code": null, "e": 26869, "s": 26839, "text": "Java | Operators | Question 1" }, { "code": null, "e": 26899, "s": 26869, "text": "Java | Operators | Question 3" }, { "code": null, "e": 26931, "s": 26899, "text": "Java | Inheritance | Question 7" }, { "code": null, "e": 26961, "s": 26931, "text": "Java | Functions | Question 4" } ]
Print all words matching a pattern in CamelCase Notation Dictionary - GeeksforGeeks
08 Jul, 2021 Given a dictionary of words where each word follows CamelCase notation, print all words in the dictionary that match with a given pattern consisting of uppercase characters only.CamelCase is the practice of writing compound words or phrases such that each word or abbreviation begins with a capital letter. Common examples include: “PowerPoint” and “WikiPedia”, “GeeksForGeeks”, “CodeBlocks”, etc.Examples: Input: dict[] = ["Hi", "Hello", "HelloWorld", "HiTech", "HiGeek", "HiTechWorld", "HiTechCity", "HiTechLab"] For pattern "HT", Output: ["HiTech", "HiTechWorld", "HiTechCity", "HiTechLab"] For pattern "H", Output: ["Hi", "Hello", "HelloWorld", "HiTech", "HiGeek", "HiTechWorld", "HiTechCity", "HiTechLab"] For pattern "HTC", Output: ["HiTechCity"] Input: dict[] = ["WelcomeGeek","WelcomeToGeeksForGeeks", "GeeksForGeeks"] For pattern "WTG", Output: ["WelcomeToGeeksForGeeks"] For pattern "GFG", Output: [GeeksForGeeks] For pattern "GG", Output: No match found The idea is to insert all dictionary keys into the Trie one by one. Here key refers to only Uppercase characters in original word in CamelCase notation. If we encounter the key for the first time, we need to mark the last node as leaf node and insert the complete word for that key into the vector associated with the leaf node. If we encounter a key that is already in the trie, we update the vector associated with the leaf node with current word. After all dictionary words are processed, we search for the pattern in the trie and print all words that matches the pattern.Below is the implementation of above idea – C++ Java C# // C++ program to print all words in the CamelCase// dictionary that matches with a given pattern#include <bits/stdc++.h>using namespace std; // Alphabet size (# of upper-Case characters)#define ALPHABET_SIZE 26 // A Trie nodestruct TrieNode{ TrieNode* children[ALPHABET_SIZE]; // isLeaf is true if the node represents // end of a word bool isLeaf; // vector to store list of complete words // in leaf node list<string> word;}; // Returns new Trie node (initialized to NULLs)TrieNode* getNewTrieNode(void){ TrieNode* pNode = new TrieNode; if (pNode) { pNode->isLeaf = false; for (int i = 0; i < ALPHABET_SIZE; i++) pNode->children[i] = NULL; } return pNode;} // Function to insert word into the Trievoid insert(TrieNode* root, string word){ int index; TrieNode* pCrawl = root; for (int level = 0; level < word.length(); level++) { // consider only uppercase characters if (islower(word[level])) continue; // get current character position index = int(word[level]) - 'A'; if (!pCrawl->children[index]) pCrawl->children[index] = getNewTrieNode(); pCrawl = pCrawl->children[index]; } // mark last node as leaf pCrawl->isLeaf = true; // push word into vector associated with leaf node (pCrawl->word).push_back(word);} // Function to print all children of Trie node rootvoid printAllWords(TrieNode* root){ // if current node is leaf if (root->isLeaf) { for(string str : root->word) cout << str << endl; } // recurse for all children of root node for (int i = 0; i < ALPHABET_SIZE; i++) { TrieNode* child = root->children[i]; if (child) printAllWords(child); }} // search for pattern in Trie and print all words// matching that patternbool search(TrieNode* root, string pattern){ int index; TrieNode* pCrawl = root; for (int level = 0; level < pattern.length(); level++) { index = int(pattern[level]) - 'A'; // Invalid pattern if (!pCrawl->children[index]) return false; pCrawl = pCrawl->children[index]; } // print all words matching that pattern printAllWords(pCrawl); return true;} // Main function to print all words in the CamelCase// dictionary that matches with a given patternvoid findAllWords(vector<string> dict, string pattern){ // construct Trie root node TrieNode* root = getNewTrieNode(); // Construct Trie from given dict for (string word : dict) insert(root, word); // search for pattern in Trie if (!search(root, pattern)) cout << "No match found";} // Driver functionint main(){ // dictionary of words where each word follows // CamelCase notation vector<string> dict = { "Hi", "Hello", "HelloWorld", "HiTech", "HiGeek", "HiTechWorld", "HiTechCity", "HiTechLab" }; // pattern consisting of uppercase characters only string pattern = "HT"; findAllWords(dict, pattern); return 0;} // Java program to print all words in the CamelCase// dictionary that matches with a given patternimport java.util.ArrayList;import java.util.Arrays;import java.util.List;public class CamelCase { // Alphabet size (# of upper-Case characters) static final int ALPHABET_SIZE = 26; // A Trie node static class TrieNode { TrieNode[] children = new TrieNode[ALPHABET_SIZE]; // isLeaf is true if the node represents // end of a word boolean isLeaf; // vector to store list of complete words // in leaf node List<String> word; public TrieNode() { isLeaf = false; for (int i = 0; i < ALPHABET_SIZE; i++) children[i] = null; word = new ArrayList<String>(); } } static TrieNode root; // Function to insert word into the Trie static void insert(String word) { int index; TrieNode pCrawl = root; for (int level = 0; level < word.length(); level++) { // consider only uppercase characters if (Character.isLowerCase(word.charAt(level))) continue; // get current character position index = word.charAt(level) - 'A'; if (pCrawl.children[index] == null) pCrawl.children[index] = new TrieNode(); pCrawl = pCrawl.children[index]; } // mark last node as leaf pCrawl.isLeaf = true; // push word into vector associated with leaf node (pCrawl.word).add(word); } // Function to print all children of Trie node root static void printAllWords(TrieNode root) { // if current node is leaf if (root.isLeaf) { for (String str : root.word) System.out.println(str); } // recurse for all children of root node for (int i = 0; i < ALPHABET_SIZE; i++) { TrieNode child = root.children[i]; if (child != null) printAllWords(child); } } // search for pattern in Trie and print all words // matching that pattern static boolean search(String pattern) { int index; TrieNode pCrawl = root; for (int level = 0; level < pattern.length(); level++) { index = pattern.charAt(level) - 'A'; // Invalid pattern if (pCrawl.children[index] == null) return false; pCrawl = pCrawl.children[index]; } // print all words matching that pattern printAllWords(pCrawl); return true; } // Main function to print all words in the CamelCase // dictionary that matches with a given pattern static void findAllWords(List<String> dict, String pattern) { // construct Trie root node root = new TrieNode(); // Construct Trie from given dict for (String word : dict) insert(word); // search for pattern in Trie if (!search(pattern)) System.out.println("No match found"); } // Driver function public static void main(String args[]) { // dictionary of words where each word follows // CamelCase notation List<String> dict = Arrays.asList("Hi", "Hello", "HelloWorld", "HiTech", "HiGeek", "HiTechWorld", "HiTechCity", "HiTechLab"); // pattern consisting of uppercase characters only String pattern = "HT"; findAllWords(dict, pattern); }}// This code is contributed by Sumit Ghosh // C# program to print all words in// the CamelCase dictionary that// matches with a given patternusing System;using System.Collections.Generic; class GFG{ // Alphabet size (# of upper-Case characters) static int ALPHABET_SIZE = 26; // A Trie node public class TrieNode { public TrieNode[] children = new TrieNode[ALPHABET_SIZE]; // isLeaf is true if the node represents // end of a word public bool isLeaf; // vector to store list of complete words // in leaf node public List<String> word; public TrieNode() { isLeaf = false; for (int i = 0; i < ALPHABET_SIZE; i++) children[i] = null; word = new List<String>(); } } static TrieNode root; // Function to insert word into the Trie static void insert(String word) { int index; TrieNode pCrawl = root; for (int level = 0; level < word.Length; level++) { // consider only uppercase characters if (char.IsLower(word[level])) continue; // get current character position index = word[level] - 'A'; if (pCrawl.children[index] == null) pCrawl.children[index] = new TrieNode(); pCrawl = pCrawl.children[index]; } // mark last node as leaf pCrawl.isLeaf = true; // push word into vector // associated with leaf node (pCrawl.word).Add(word); } // Function to print all children // of Trie node root static void printAllWords(TrieNode root) { // if current node is leaf if (root.isLeaf) { foreach (String str in root.word) Console.WriteLine(str); } // recurse for all children of root node for (int i = 0; i < ALPHABET_SIZE; i++) { TrieNode child = root.children[i]; if (child != null) printAllWords(child); } } // search for pattern in Trie and // print all words matching that pattern static bool search(String pattern) { int index; TrieNode pCrawl = root; for (int level = 0; level < pattern.Length; level++) { index = pattern[level] - 'A'; // Invalid pattern if (pCrawl.children[index] == null) return false; pCrawl = pCrawl.children[index]; } // print all words matching that pattern printAllWords(pCrawl); return true; } // Main function to print all words // in the CamelCase dictionary that // matches with a given pattern static void findAllWords(List<String> dict, String pattern) { // construct Trie root node root = new TrieNode(); // Construct Trie from given dict foreach (String word in dict) insert(word); // search for pattern in Trie if (!search(pattern)) Console.WriteLine("No match found"); } // Driver Code public static void Main(String []args) { // dictionary of words where each word follows // CamelCase notation List<String> dict = new List<String>{"Hi", "Hello", "HelloWorld", "HiTech", "HiGeek", "HiTechWorld", "HiTechCity", "HiTechLab"}; // pattern consisting of // uppercase characters only String pattern = "HT"; findAllWords(dict, pattern); }} // This code is contributed by Princi Singh Output: HiTech HiTechCity HiTechLab HiTechWorld This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. princi singh surindertarika1234 Trie Advanced Data Structure Strings Strings Trie Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ordered Set and GNU C++ PBDS Disjoint Set Data Structures Binary Indexed Tree or Fenwick Tree Insert Operation in B-Tree Design a data structure that supports insert, delete, search and getRandom in constant time Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Longest Common Subsequence | DP-4
[ { "code": null, "e": 25801, "s": 25773, "text": "\n08 Jul, 2021" }, { "code": null, "e": 26210, "s": 25801, "text": "Given a dictionary of words where each word follows CamelCase notation, print all words in the dictionary that match with a given pattern consisting of uppercase characters only.CamelCase is the practice of writing compound words or phrases such that each word or abbreviation begins with a capital letter. Common examples include: “PowerPoint” and “WikiPedia”, “GeeksForGeeks”, “CodeBlocks”, etc.Examples: " }, { "code": null, "e": 26786, "s": 26210, "text": "Input: \ndict[] = [\"Hi\", \"Hello\", \"HelloWorld\", \"HiTech\", \"HiGeek\", \n\"HiTechWorld\", \"HiTechCity\", \"HiTechLab\"]\n\nFor pattern \"HT\",\nOutput: [\"HiTech\", \"HiTechWorld\", \"HiTechCity\", \"HiTechLab\"]\n\nFor pattern \"H\",\nOutput: [\"Hi\", \"Hello\", \"HelloWorld\", \"HiTech\", \"HiGeek\", \n \"HiTechWorld\", \"HiTechCity\", \"HiTechLab\"]\n\nFor pattern \"HTC\",\nOutput: [\"HiTechCity\"]\n\n\nInput: \ndict[] = [\"WelcomeGeek\",\"WelcomeToGeeksForGeeks\", \"GeeksForGeeks\"]\n\nFor pattern \"WTG\",\nOutput: [\"WelcomeToGeeksForGeeks\"]\n\nFor pattern \"GFG\",\nOutput: [GeeksForGeeks]\n\nFor pattern \"GG\",\nOutput: No match found" }, { "code": null, "e": 27409, "s": 26788, "text": "The idea is to insert all dictionary keys into the Trie one by one. Here key refers to only Uppercase characters in original word in CamelCase notation. If we encounter the key for the first time, we need to mark the last node as leaf node and insert the complete word for that key into the vector associated with the leaf node. If we encounter a key that is already in the trie, we update the vector associated with the leaf node with current word. After all dictionary words are processed, we search for the pattern in the trie and print all words that matches the pattern.Below is the implementation of above idea – " }, { "code": null, "e": 27413, "s": 27409, "text": "C++" }, { "code": null, "e": 27418, "s": 27413, "text": "Java" }, { "code": null, "e": 27421, "s": 27418, "text": "C#" }, { "code": "// C++ program to print all words in the CamelCase// dictionary that matches with a given pattern#include <bits/stdc++.h>using namespace std; // Alphabet size (# of upper-Case characters)#define ALPHABET_SIZE 26 // A Trie nodestruct TrieNode{ TrieNode* children[ALPHABET_SIZE]; // isLeaf is true if the node represents // end of a word bool isLeaf; // vector to store list of complete words // in leaf node list<string> word;}; // Returns new Trie node (initialized to NULLs)TrieNode* getNewTrieNode(void){ TrieNode* pNode = new TrieNode; if (pNode) { pNode->isLeaf = false; for (int i = 0; i < ALPHABET_SIZE; i++) pNode->children[i] = NULL; } return pNode;} // Function to insert word into the Trievoid insert(TrieNode* root, string word){ int index; TrieNode* pCrawl = root; for (int level = 0; level < word.length(); level++) { // consider only uppercase characters if (islower(word[level])) continue; // get current character position index = int(word[level]) - 'A'; if (!pCrawl->children[index]) pCrawl->children[index] = getNewTrieNode(); pCrawl = pCrawl->children[index]; } // mark last node as leaf pCrawl->isLeaf = true; // push word into vector associated with leaf node (pCrawl->word).push_back(word);} // Function to print all children of Trie node rootvoid printAllWords(TrieNode* root){ // if current node is leaf if (root->isLeaf) { for(string str : root->word) cout << str << endl; } // recurse for all children of root node for (int i = 0; i < ALPHABET_SIZE; i++) { TrieNode* child = root->children[i]; if (child) printAllWords(child); }} // search for pattern in Trie and print all words// matching that patternbool search(TrieNode* root, string pattern){ int index; TrieNode* pCrawl = root; for (int level = 0; level < pattern.length(); level++) { index = int(pattern[level]) - 'A'; // Invalid pattern if (!pCrawl->children[index]) return false; pCrawl = pCrawl->children[index]; } // print all words matching that pattern printAllWords(pCrawl); return true;} // Main function to print all words in the CamelCase// dictionary that matches with a given patternvoid findAllWords(vector<string> dict, string pattern){ // construct Trie root node TrieNode* root = getNewTrieNode(); // Construct Trie from given dict for (string word : dict) insert(root, word); // search for pattern in Trie if (!search(root, pattern)) cout << \"No match found\";} // Driver functionint main(){ // dictionary of words where each word follows // CamelCase notation vector<string> dict = { \"Hi\", \"Hello\", \"HelloWorld\", \"HiTech\", \"HiGeek\", \"HiTechWorld\", \"HiTechCity\", \"HiTechLab\" }; // pattern consisting of uppercase characters only string pattern = \"HT\"; findAllWords(dict, pattern); return 0;}", "e": 30484, "s": 27421, "text": null }, { "code": "// Java program to print all words in the CamelCase// dictionary that matches with a given patternimport java.util.ArrayList;import java.util.Arrays;import java.util.List;public class CamelCase { // Alphabet size (# of upper-Case characters) static final int ALPHABET_SIZE = 26; // A Trie node static class TrieNode { TrieNode[] children = new TrieNode[ALPHABET_SIZE]; // isLeaf is true if the node represents // end of a word boolean isLeaf; // vector to store list of complete words // in leaf node List<String> word; public TrieNode() { isLeaf = false; for (int i = 0; i < ALPHABET_SIZE; i++) children[i] = null; word = new ArrayList<String>(); } } static TrieNode root; // Function to insert word into the Trie static void insert(String word) { int index; TrieNode pCrawl = root; for (int level = 0; level < word.length(); level++) { // consider only uppercase characters if (Character.isLowerCase(word.charAt(level))) continue; // get current character position index = word.charAt(level) - 'A'; if (pCrawl.children[index] == null) pCrawl.children[index] = new TrieNode(); pCrawl = pCrawl.children[index]; } // mark last node as leaf pCrawl.isLeaf = true; // push word into vector associated with leaf node (pCrawl.word).add(word); } // Function to print all children of Trie node root static void printAllWords(TrieNode root) { // if current node is leaf if (root.isLeaf) { for (String str : root.word) System.out.println(str); } // recurse for all children of root node for (int i = 0; i < ALPHABET_SIZE; i++) { TrieNode child = root.children[i]; if (child != null) printAllWords(child); } } // search for pattern in Trie and print all words // matching that pattern static boolean search(String pattern) { int index; TrieNode pCrawl = root; for (int level = 0; level < pattern.length(); level++) { index = pattern.charAt(level) - 'A'; // Invalid pattern if (pCrawl.children[index] == null) return false; pCrawl = pCrawl.children[index]; } // print all words matching that pattern printAllWords(pCrawl); return true; } // Main function to print all words in the CamelCase // dictionary that matches with a given pattern static void findAllWords(List<String> dict, String pattern) { // construct Trie root node root = new TrieNode(); // Construct Trie from given dict for (String word : dict) insert(word); // search for pattern in Trie if (!search(pattern)) System.out.println(\"No match found\"); } // Driver function public static void main(String args[]) { // dictionary of words where each word follows // CamelCase notation List<String> dict = Arrays.asList(\"Hi\", \"Hello\", \"HelloWorld\", \"HiTech\", \"HiGeek\", \"HiTechWorld\", \"HiTechCity\", \"HiTechLab\"); // pattern consisting of uppercase characters only String pattern = \"HT\"; findAllWords(dict, pattern); }}// This code is contributed by Sumit Ghosh", "e": 34060, "s": 30484, "text": null }, { "code": "// C# program to print all words in// the CamelCase dictionary that// matches with a given patternusing System;using System.Collections.Generic; class GFG{ // Alphabet size (# of upper-Case characters) static int ALPHABET_SIZE = 26; // A Trie node public class TrieNode { public TrieNode[] children = new TrieNode[ALPHABET_SIZE]; // isLeaf is true if the node represents // end of a word public bool isLeaf; // vector to store list of complete words // in leaf node public List<String> word; public TrieNode() { isLeaf = false; for (int i = 0; i < ALPHABET_SIZE; i++) children[i] = null; word = new List<String>(); } } static TrieNode root; // Function to insert word into the Trie static void insert(String word) { int index; TrieNode pCrawl = root; for (int level = 0; level < word.Length; level++) { // consider only uppercase characters if (char.IsLower(word[level])) continue; // get current character position index = word[level] - 'A'; if (pCrawl.children[index] == null) pCrawl.children[index] = new TrieNode(); pCrawl = pCrawl.children[index]; } // mark last node as leaf pCrawl.isLeaf = true; // push word into vector // associated with leaf node (pCrawl.word).Add(word); } // Function to print all children // of Trie node root static void printAllWords(TrieNode root) { // if current node is leaf if (root.isLeaf) { foreach (String str in root.word) Console.WriteLine(str); } // recurse for all children of root node for (int i = 0; i < ALPHABET_SIZE; i++) { TrieNode child = root.children[i]; if (child != null) printAllWords(child); } } // search for pattern in Trie and // print all words matching that pattern static bool search(String pattern) { int index; TrieNode pCrawl = root; for (int level = 0; level < pattern.Length; level++) { index = pattern[level] - 'A'; // Invalid pattern if (pCrawl.children[index] == null) return false; pCrawl = pCrawl.children[index]; } // print all words matching that pattern printAllWords(pCrawl); return true; } // Main function to print all words // in the CamelCase dictionary that // matches with a given pattern static void findAllWords(List<String> dict, String pattern) { // construct Trie root node root = new TrieNode(); // Construct Trie from given dict foreach (String word in dict) insert(word); // search for pattern in Trie if (!search(pattern)) Console.WriteLine(\"No match found\"); } // Driver Code public static void Main(String []args) { // dictionary of words where each word follows // CamelCase notation List<String> dict = new List<String>{\"Hi\", \"Hello\", \"HelloWorld\", \"HiTech\", \"HiGeek\", \"HiTechWorld\", \"HiTechCity\", \"HiTechLab\"}; // pattern consisting of // uppercase characters only String pattern = \"HT\"; findAllWords(dict, pattern); }} // This code is contributed by Princi Singh", "e": 37805, "s": 34060, "text": null }, { "code": null, "e": 37815, "s": 37805, "text": "Output: " }, { "code": null, "e": 37855, "s": 37815, "text": "HiTech\nHiTechCity\nHiTechLab\nHiTechWorld" }, { "code": null, "e": 38275, "s": 37855, "text": "This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 38288, "s": 38275, "text": "princi singh" }, { "code": null, "e": 38307, "s": 38288, "text": "surindertarika1234" }, { "code": null, "e": 38312, "s": 38307, "text": "Trie" }, { "code": null, "e": 38336, "s": 38312, "text": "Advanced Data Structure" }, { "code": null, "e": 38344, "s": 38336, "text": "Strings" }, { "code": null, "e": 38352, "s": 38344, "text": "Strings" }, { "code": null, "e": 38357, "s": 38352, "text": "Trie" }, { "code": null, "e": 38455, "s": 38357, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38484, "s": 38455, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 38513, "s": 38484, "text": "Disjoint Set Data Structures" }, { "code": null, "e": 38549, "s": 38513, "text": "Binary Indexed Tree or Fenwick Tree" }, { "code": null, "e": 38576, "s": 38549, "text": "Insert Operation in B-Tree" }, { "code": null, "e": 38668, "s": 38576, "text": "Design a data structure that supports insert, delete, search and getRandom in constant time" }, { "code": null, "e": 38714, "s": 38668, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 38739, "s": 38714, "text": "Reverse a string in Java" }, { "code": null, "e": 38799, "s": 38739, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 38814, "s": 38799, "text": "C++ Data Types" } ]
Python PIL | Image.histogram() - GeeksforGeeks
12 Dec, 2021 PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.Image.histogram() Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an “RGB” image contains 768 values).A bi-level image (mode “1”) is treated as a grayscale (“L”) image by this method. If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode “1”) or a grayscale image (“L”). Syntax: Image.histogram(mask=None, extrema=None)Parameters: mask – An optional mask.Returns: A list containing pixel counts. Image Used: Python3 from PIL import Image img = Image.open(r"C:\Users\System-Pc\Desktop\tree.jpg")r, g, b = img.split()len(r.histogram())### 256 ### r.histogram() Output: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 3, 1, 2, 3, 4, 3, 2, 3, 10, 7, 6, 7, 13, 14, 6, 22, 9, 19, 23, 21, 29, 23, 36, 42, 32, 46, 59, 51, 53, 69, 49, 61, 64, 79, 69, 55, 66, 73, 78, 64, 82, 84, 83, 67, 85, 87, 91, 84, 87, 63, 79, 86, 86, 77, 75, 78, 85, 77, 78, 92, 83, 78, 86, 90, 97, 96, 94, 90, 94, 76, 99, 97, 113, 108, 92, 120, 124, 110, 140, 121, 124, 132, 144, 132, 145, 151, 163, 145, 147, 184, 151, 161, 177, 199, 200, 205, 218, 223, 274, 237, 245, 254, 260, 281, 299, 301, 354, 361, 335, 392, 365, 375, 389, 367, 396, 387, 415, 398, 404, 417, 404, 405, 447, 483, 493, 484, 470, 440, 473, 472, 441, 462, 467, 461, 468, 474, 438, 449, 451, 431, 468, 470, 415, 452, 407, 379, 411, 358, 383, 418, 375, 414, 376, 375, 341, 361, 340, 350, 354, 293, 318, 325, 297, 316, 287, 326, 287, 307, 289, 314, 296, 275, 262, 281, 262, 278, 268, 320, 254, 288, 279, 280, 259, 252, 257, 257, 245, 227, 231, 254, 282, 263, 248, 218, 250, 246, 232, 244, 237, 208, 217, 215, 226, 205, 223, 212, 227, 220, 213, 198, 197, 224, 193, 200, 173, 190, 184, 190, 183, 3263] Another Example:Here used another image.Image Used: Python3 from PIL import Image img = Image.open(r"C:\Users\System-Pc\Desktop\tree.jpg")r, g, b = img.split()len(r.histogram())### 256 ### r.histogram() Output: [970, 228, 158, 207, 258, 217, 257, 260, 256, 252, 224, 277, 247, 293, 294, 305, 303, 309, 318, 321, 343, 326, 313, 295, 346, 292, 356, 340, 305, 311, 360, 373, 350, 357, 384, 356, 325, 380, 373, 389, 355, 336, 328, 349, 364, 335, 390, 340, 343, 382, 343, 339, 351, 329, 364, 350, 356, 362, 381, 349, 386, 366, 351, 345, 357, 353, 339, 359, 387, 346, 371, 359, 319, 330, 321, 311, 300, 313, 325, 338, 322, 330, 303, 354, 335, 321, 313, 289, 286, 286, 264, 279, 267, 255, 277, 266, 297, 261, 282, 267, 254, 269, 246, 244, 265, 240, 231, 250, 210, 227, 202, 200, 217, 191, 187, 217, 199, 171, 180, 152, 195, 172, 158, 170, 177, 159, 151, 152, 143, 159, 183, 138, 169, 162, 145, 161, 147, 150, 160, 186, 163, 153, 139, 153, 149, 144, 148, 143, 167, 144, 184, 154, 160, 134, 130, 144, 176, 118, 140, 132, 115, 119, 130, 130, 120, 125, 121, 133, 105, 123, 105, 106, 92, 114, 101, 112, 103, 106, 98, 118, 110, 111, 99, 99, 107, 74, 109, 83, 94, 97, 87, 85, 88, 77, 77, 92, 94, 69, 91, 97, 71, 100, 83, 80, 83, 53, 89, 72, 68, 70, 58, 74, 67, 69, 64, 80, 81, 68, 57, 47, 60, 53, 59, 53, 64, 63, 69, 52, 48, 46, 51, 52, 41, 49, 45, 43, 41, 32, 43, 42, 47, 46, 34, 38, 39, 34, 33, 31, 21, 23, 28, 25, 15, 15, 24, 148] adnanirshad158 Python-pil 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": "\n12 Dec, 2021" }, { "code": null, "e": 26489, "s": 25537, "text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.Image.histogram() Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an “RGB” image contains 768 values).A bi-level image (mode “1”) is treated as a grayscale (“L”) image by this method. If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode “1”) or a grayscale image (“L”). " }, { "code": null, "e": 26615, "s": 26489, "text": "Syntax: Image.histogram(mask=None, extrema=None)Parameters: mask – An optional mask.Returns: A list containing pixel counts. " }, { "code": null, "e": 26628, "s": 26615, "text": "Image Used: " }, { "code": null, "e": 26638, "s": 26630, "text": "Python3" }, { "code": "from PIL import Image img = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\tree.jpg\")r, g, b = img.split()len(r.histogram())### 256 ### r.histogram()", "e": 26781, "s": 26638, "text": null }, { "code": null, "e": 26790, "s": 26781, "text": "Output: " }, { "code": null, "e": 27915, "s": 26790, "text": "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 3, 1, 2, 3, 4, 3, 2, 3, 10, 7, 6, 7, 13, 14, 6, 22, 9, 19, 23, 21, 29, 23, 36, 42, 32, 46, 59, 51, 53, 69, 49, 61, 64, 79, 69, 55, 66, 73, 78, 64, 82, 84, 83, 67, 85, 87, 91, 84, 87, 63, 79, 86, 86, 77, 75, 78, 85, 77, 78, 92, 83, 78, 86, 90, 97, 96, 94, 90, 94, 76, 99, 97, 113, 108, 92, 120, 124, 110, 140, 121, 124, 132, 144, 132, 145, 151, 163, 145, 147, 184, 151, 161, 177, 199, 200, 205, 218, 223, 274, 237, 245, 254, 260, 281, 299, 301, 354, 361, 335, 392, 365, 375, 389, 367, 396, 387, 415, 398, 404, 417, 404, 405, 447, 483, 493, 484, 470, 440, 473, 472, 441, 462, 467, 461, 468, 474, 438, 449, 451, 431, 468, 470, 415, 452, 407, 379, 411, 358, 383, 418, 375, 414, 376, 375, 341, 361, 340, 350, 354, 293, 318, 325, 297, 316, 287, 326, 287, 307, 289, 314, 296, 275, 262, 281, 262, 278, 268, 320, 254, 288, 279, 280, 259, 252, 257, 257, 245, 227, 231, 254, 282, 263, 248, 218, 250, 246, 232, 244, 237, 208, 217, 215, 226, 205, 223, 212, 227, 220, 213, 198, 197, 224, 193, 200, 173, 190, 184, 190, 183, 3263] " }, { "code": null, "e": 27968, "s": 27915, "text": "Another Example:Here used another image.Image Used: " }, { "code": null, "e": 27978, "s": 27970, "text": "Python3" }, { "code": "from PIL import Image img = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\tree.jpg\")r, g, b = img.split()len(r.histogram())### 256 ### r.histogram()", "e": 28121, "s": 27978, "text": null }, { "code": null, "e": 28130, "s": 28121, "text": "Output: " }, { "code": null, "e": 29339, "s": 28130, "text": "[970, 228, 158, 207, 258, 217, 257, 260, 256, 252, 224, 277, 247, 293, 294, 305, 303, 309, 318, 321, 343, 326, 313, 295, 346, 292, 356, 340, 305, 311, 360, 373, 350, 357, 384, 356, 325, 380, 373, 389, 355, 336, 328, 349, 364, 335, 390, 340, 343, 382, 343, 339, 351, 329, 364, 350, 356, 362, 381, 349, 386, 366, 351, 345, 357, 353, 339, 359, 387, 346, 371, 359, 319, 330, 321, 311, 300, 313, 325, 338, 322, 330, 303, 354, 335, 321, 313, 289, 286, 286, 264, 279, 267, 255, 277, 266, 297, 261, 282, 267, 254, 269, 246, 244, 265, 240, 231, 250, 210, 227, 202, 200, 217, 191, 187, 217, 199, 171, 180, 152, 195, 172, 158, 170, 177, 159, 151, 152, 143, 159, 183, 138, 169, 162, 145, 161, 147, 150, 160, 186, 163, 153, 139, 153, 149, 144, 148, 143, 167, 144, 184, 154, 160, 134, 130, 144, 176, 118, 140, 132, 115, 119, 130, 130, 120, 125, 121, 133, 105, 123, 105, 106, 92, 114, 101, 112, 103, 106, 98, 118, 110, 111, 99, 99, 107, 74, 109, 83, 94, 97, 87, 85, 88, 77, 77, 92, 94, 69, 91, 97, 71, 100, 83, 80, 83, 53, 89, 72, 68, 70, 58, 74, 67, 69, 64, 80, 81, 68, 57, 47, 60, 53, 59, 53, 64, 63, 69, 52, 48, 46, 51, 52, 41, 49, 45, 43, 41, 32, 43, 42, 47, 46, 34, 38, 39, 34, 33, 31, 21, 23, 28, 25, 15, 15, 24, 148]" }, { "code": null, "e": 29354, "s": 29339, "text": "adnanirshad158" }, { "code": null, "e": 29365, "s": 29354, "text": "Python-pil" }, { "code": null, "e": 29372, "s": 29365, "text": "Python" }, { "code": null, "e": 29470, "s": 29372, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29502, "s": 29470, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29544, "s": 29502, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29586, "s": 29544, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29613, "s": 29586, "text": "Python Classes and Objects" }, { "code": null, "e": 29669, "s": 29613, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29691, "s": 29669, "text": "Defaultdict in Python" }, { "code": null, "e": 29730, "s": 29691, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29761, "s": 29730, "text": "Python | os.path.join() method" }, { "code": null, "e": 29790, "s": 29761, "text": "Create a directory in Python" } ]
How to write a running C code without main()?
Here we will see, one program can be written without main or not? The answer is yes. We can write program, that has no main() function. In many places, we have seen that the main() is the entry point of a program execution. Just from the programmers perspective this is true. From the system’s perspective it is not true. So the system at first calls the _start(), this sets up the environment, then main is called. To execute this program we have to use this option ‘-nostartfiles’. #include <stdio.h> extern void _exit(register int); int _start() { printf("Program without main\n"); _exit(0); } soumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$ gcc test_prog.c -nostartfiles soumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$ ./a.out Program without main soumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$
[ { "code": null, "e": 1198, "s": 1062, "text": "Here we will see, one program can be written without main or not? The answer is yes. We can write program, that has no main() function." }, { "code": null, "e": 1478, "s": 1198, "text": "In many places, we have seen that the main() is the entry point of a program execution. Just from the programmers perspective this is true. From the system’s perspective it is not true. So the system at first calls the _start(), this sets up the environment, then main is called." }, { "code": null, "e": 1546, "s": 1478, "text": "To execute this program we have to use this option ‘-nostartfiles’." }, { "code": null, "e": 1668, "s": 1546, "text": "#include <stdio.h>\nextern void _exit(register int);\nint _start() {\n printf(\"Program without main\\n\");\n _exit(0);\n}" }, { "code": null, "e": 1865, "s": 1668, "text": "soumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$ gcc test_prog.c -nostartfiles\nsoumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$ ./a.out\nProgram without main\nsoumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$" } ]
How can I remove items out of a Python tuple?
Tuples in python are immutable. If you want to remove items out of a Python tuple, you can use index slicing to leave out a particular index. For example, a = (1, 2, 3, 4, 5) b = a[:2] + a[3:] print(b) This will give the output: (1, 2, 4, 5) Or you can convert it to a list, remove the item and convert back to a tuple. For example, a = (1, 2, 3, 4, 5) ls_a = list(a) del ls_a[2] b = tuple(ls_a) print(b) This will give the output: (1, 2, 4, 5)
[ { "code": null, "e": 1217, "s": 1062, "text": "Tuples in python are immutable. If you want to remove items out of a Python tuple, you can use index slicing to leave out a particular index. For example," }, { "code": null, "e": 1264, "s": 1217, "text": "a = (1, 2, 3, 4, 5)\nb = a[:2] + a[3:]\nprint(b)" }, { "code": null, "e": 1291, "s": 1264, "text": "This will give the output:" }, { "code": null, "e": 1304, "s": 1291, "text": "(1, 2, 4, 5)" }, { "code": null, "e": 1395, "s": 1304, "text": "Or you can convert it to a list, remove the item and convert back to a tuple. For example," }, { "code": null, "e": 1468, "s": 1395, "text": "a = (1, 2, 3, 4, 5)\nls_a = list(a)\ndel ls_a[2]\n\nb = tuple(ls_a)\nprint(b)" }, { "code": null, "e": 1495, "s": 1468, "text": "This will give the output:" }, { "code": null, "e": 1508, "s": 1495, "text": "(1, 2, 4, 5)" } ]
GATE CS 2021 | Set 2 - GeeksforGeeks
18 Oct, 2021 Pen : Write :: Knife : _______ From the above graph we obtained following information- Year Cost/Unit Cost Price Number of Units 1 3 300 100 2 2 400 200 3 1 300 300 Let selling price of year 2 = SP2 and Selling price of year3 = SP3 Given that- Taxes for year 2 = 13% of SP2 = 0.13SP2 Taxes for year 3 = 15% of SP3 = 0.15SP3 Cost per unit of year 3 = 1 (Cost per unit of year 2)/2 = 1 So now Cost / unit of year 2 = 2*1 = 2 Net profit formula now = Selling Price - (Cost Price + (Tax% x selling price ) For year 2 296 = SP2- (200*2 + 0.13*SP2) SP2 = 696*100/87 SP2 = 800 For year 3 210 = SP3 - (300*1+0.15*SP3) SP3 = 510*100/85 SP3 = 600 Required Ratio 800/600= 4/3 (Correct Option A) Observation I: S is taller than R. Observation II: Q is the shortest of all. Observation III: U is taller than only one student. Observation IV: T is taller than S but is not the tallest. __ __ __ __ U Q P T S R U Q Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Coding Questions for Product Based Companies Difference between var, let and const keywords in JavaScript Array of Objects in C++ with Examples How to Replace Values in Column Based on Condition in Pandas? C Program to read contents of Whole File Hash Functions and list/types of Hash functions How to Replace Values in a List in Python? Spring - REST Controller How to Read Text Files with Pandas? Python Data Structures and Algorithms
[ { "code": null, "e": 27610, "s": 27582, "text": "\n18 Oct, 2021" }, { "code": null, "e": 27642, "s": 27610, "text": "Pen : Write :: Knife : _______ " }, { "code": null, "e": 27699, "s": 27642, "text": "From the above graph we obtained following information- " }, { "code": null, "e": 27896, "s": 27699, "text": "Year Cost/Unit Cost Price Number of Units\n1 3 300 100\n2 2 400 200\n3 1 300 300" }, { "code": null, "e": 27963, "s": 27896, "text": "Let selling price of year 2 = SP2 and Selling price of year3 = SP3" }, { "code": null, "e": 27975, "s": 27963, "text": "Given that-" }, { "code": null, "e": 28154, "s": 27975, "text": "Taxes for year 2 = 13% of SP2 = 0.13SP2\nTaxes for year 3 = 15% of SP3 = 0.15SP3\nCost per unit of year 3 = 1\n(Cost per unit of year 2)/2 = 1\nSo now Cost / unit of year 2 = 2*1 = 2" }, { "code": null, "e": 28233, "s": 28154, "text": "Net profit formula now = Selling Price - (Cost Price + (Tax% x selling price )" }, { "code": null, "e": 28244, "s": 28233, "text": "For year 2" }, { "code": null, "e": 28301, "s": 28244, "text": "296 = SP2- (200*2 + 0.13*SP2)\nSP2 = 696*100/87\nSP2 = 800" }, { "code": null, "e": 28312, "s": 28301, "text": "For year 3" }, { "code": null, "e": 28368, "s": 28312, "text": "210 = SP3 - (300*1+0.15*SP3)\nSP3 = 510*100/85\nSP3 = 600" }, { "code": null, "e": 28415, "s": 28368, "text": "Required Ratio 800/600= 4/3 (Correct Option A)" }, { "code": null, "e": 28450, "s": 28415, "text": "Observation I: S is taller than R." }, { "code": null, "e": 28492, "s": 28450, "text": "Observation II: Q is the shortest of all." }, { "code": null, "e": 28544, "s": 28492, "text": "Observation III: U is taller than only one student." }, { "code": null, "e": 28603, "s": 28544, "text": "Observation IV: T is taller than S but is not the tallest." }, { "code": null, "e": 28621, "s": 28603, "text": " __ __ __ __ U Q " }, { "code": null, "e": 28634, "s": 28621, "text": "P T S R U Q " }, { "code": null, "e": 28732, "s": 28634, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 28785, "s": 28732, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 28846, "s": 28785, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28884, "s": 28846, "text": "Array of Objects in C++ with Examples" }, { "code": null, "e": 28946, "s": 28884, "text": "How to Replace Values in Column Based on Condition in Pandas?" }, { "code": null, "e": 28987, "s": 28946, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 29035, "s": 28987, "text": "Hash Functions and list/types of Hash functions" }, { "code": null, "e": 29078, "s": 29035, "text": "How to Replace Values in a List in Python?" }, { "code": null, "e": 29103, "s": 29078, "text": "Spring - REST Controller" }, { "code": null, "e": 29139, "s": 29103, "text": "How to Read Text Files with Pandas?" } ]
Java Examples - Display text in different fonts
How to display text in different fonts? Following example demonstrates how to display text in different fonts using setFont() method of Font class. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Main extends JPanel { String[] type = { "Serif","SansSerif"}; int[] styles = { Font.PLAIN, Font.ITALIC, Font.BOLD, Font.ITALIC + Font.BOLD }; String[] stylenames = { "Plain", "Italic", "Bold", "Bold & Italic" }; public void paint(Graphics g) { for (int f = 0; f < type.length; f++) { for (int s = 0; s < styles.length; s++) { Font font = new Font(type[f], styles[s], 18); g.setFont(font); String name = type[f] + " " + stylenames[s]; g.drawString(name, 20, (f * 4 + s + 1) * 20); } } } public static void main(String[] a) { JFrame f = new JFrame(); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); f.setContentPane(new Main()); f.setSize(400,400); f.setVisible(true); } } The above code sample will produce the following result. Different font names are displayed in a frame. The following is an another sample example to display text in different fonts import java.awt.*; import javax.swing.*; public class Main extends JComponent { String[] dfonts; Font[] font; static final int IN = 15; public Main() { dfonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames(); font = new Font[dfonts.length]; } public void paintComponent(Graphics g) { for (int j = 0; j < dfonts.length; j += 1) { if (font[j] == null) { font[j] = new Font(dfonts[j], Font.PLAIN, 16); } g.setFont(font[j]); int p = 15; int q = 15+ (IN * j); g.drawString(dfonts[j],p,q); } } public static void main(String[] args) { JFrame frame = new JFrame("Different Fonts"); frame.getContentPane().add(new JScrollPane(new Main())); frame.setSize(350, 650); frame.setVisible(true); } } Print Add Notes Bookmark this page
[ { "code": null, "e": 2108, "s": 2068, "text": "How to display text in different fonts?" }, { "code": null, "e": 2216, "s": 2108, "text": "Following example demonstrates how to display text in different fonts using setFont() method of Font class." }, { "code": null, "e": 3200, "s": 2216, "text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\n\npublic class Main extends JPanel {\n String[] type = { \"Serif\",\"SansSerif\"}; \n int[] styles = { Font.PLAIN, Font.ITALIC, Font.BOLD, Font.ITALIC + Font.BOLD };\n String[] stylenames = { \"Plain\", \"Italic\", \"Bold\", \"Bold & Italic\" };\n \n public void paint(Graphics g) {\n for (int f = 0; f < type.length; f++) { \n for (int s = 0; s < styles.length; s++) { \n Font font = new Font(type[f], styles[s], 18);\n g.setFont(font); \n String name = type[f] + \" \" + stylenames[s];\n g.drawString(name, 20, (f * 4 + s + 1) * 20); \n }\n }\n }\n public static void main(String[] a) {\n JFrame f = new JFrame();\n f.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent e) {\n System.exit(0);\n }\n });\n f.setContentPane(new Main());\n f.setSize(400,400);\n f.setVisible(true);\n }\n}" }, { "code": null, "e": 3257, "s": 3200, "text": "The above code sample will produce the following result." }, { "code": null, "e": 3305, "s": 3257, "text": "Different font names are displayed in a frame.\n" }, { "code": null, "e": 3383, "s": 3305, "text": "The following is an another sample example to display text in different fonts" }, { "code": null, "e": 4247, "s": 3383, "text": "import java.awt.*;\nimport javax.swing.*;\n\npublic class Main extends JComponent {\n String[] dfonts;\n Font[] font;\n static final int IN = 15;\n public Main() {\n dfonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();\n font = new Font[dfonts.length];\n }\n public void paintComponent(Graphics g) {\n for (int j = 0; j < dfonts.length; j += 1) {\n if (font[j] == null) {\n font[j] = new Font(dfonts[j], Font.PLAIN, 16);\n } \n g.setFont(font[j]);\n int p = 15;\n int q = 15+ (IN * j);\n g.drawString(dfonts[j],p,q);\n } \n }\n public static void main(String[] args) {\n JFrame frame = new JFrame(\"Different Fonts\");\n frame.getContentPane().add(new JScrollPane(new Main()));\n frame.setSize(350, 650);\n frame.setVisible(true);\n }\n} " }, { "code": null, "e": 4254, "s": 4247, "text": " Print" }, { "code": null, "e": 4265, "s": 4254, "text": " Add Notes" } ]
Frequency of vowels and consonants in JavaScript
We are required to write a JavaScript function that takes in a string which contains English alphabets. The function should return an object containing the count of vowels and consonants in the string. Therefore, let’s write the code for this function − The code for this will be − const str = 'This is a sample string, will be used to collect some data'; const countAlpha = str => { return str.split('').reduce((acc, val) => { const legend = 'aeiou'; let { vowels, consonants } = acc; if(val.toLowerCase() === val.toUpperCase()){ return acc; }; if(legend.includes(val.toLowerCase())){ vowels++; }else{ consonants++; }; return { vowels, consonants }; }, { vowels: 0, consonants: 0 }); }; console.log(countAlpha(str)); The output in the console will be − { vowels: 17, consonants: 29 }
[ { "code": null, "e": 1264, "s": 1062, "text": "We are required to write a JavaScript function that takes in a string which contains English\nalphabets. The function should return an object containing the count of vowels and consonants\nin the string." }, { "code": null, "e": 1316, "s": 1264, "text": "Therefore, let’s write the code for this function −" }, { "code": null, "e": 1344, "s": 1316, "text": "The code for this will be −" }, { "code": null, "e": 1876, "s": 1344, "text": "const str = 'This is a sample string, will be used to collect some data';\nconst countAlpha = str => {\n return str.split('').reduce((acc, val) => {\n const legend = 'aeiou';\n let { vowels, consonants } = acc;\n if(val.toLowerCase() === val.toUpperCase()){\n return acc;\n };\n if(legend.includes(val.toLowerCase())){\n vowels++;\n }else{\n consonants++;\n };\n return { vowels, consonants };\n }, {\n vowels: 0,\n consonants: 0\n });\n};\nconsole.log(countAlpha(str));" }, { "code": null, "e": 1912, "s": 1876, "text": "The output in the console will be −" }, { "code": null, "e": 1943, "s": 1912, "text": "{ vowels: 17, consonants: 29 }" } ]
Python | Print diagonals of 2D list - GeeksforGeeks
30 Aug, 2021 Given a 2D list (with equal length of sublists), write a Python program to print both the diagonals of the given 2D list. Examples: Input : [[1, 2, 3], [4, 5, 6], [7, 8, 9]] Output : Diagonal 1 - [1, 5, 9] Diagonal 2 - [3, 5, 7] Input : [['a', 'b'], ['c', 'd']] Output : Diagonal 1 - ['a', 'd'] Diagonal 2 - ['b', 'c'] Approach #1 : Using Python xrange()We can use one-liner list comprehension along with xrange() function. xrange() is used to iterate a certain number of times in for loops. Thus, we print the element at [i][i] position in every iteration of loop. [Works in Python2] Python # Python2 program to print diagonals in 2D list def printDiagonal(lst): # To print Primary Diagonal print('Diagonal 1 -'), print([lst[i][i] for i in xrange(len(lst))]) # To print Secondary Diagonal print('Diagonal 2 -'), print([lst[i][len(lst)-1-i] for i in xrange(len(lst))]) # Driver codelst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] printDiagonal(lst) Diagonal 1 - [1, 5, 9] Diagonal 2 - [3, 5, 7] Approach #2 : Using range()This method is similar to Approach #1. The advantage of range() is that it works for both the versions of Python i.e. Python2 and Python3. Python3 # Python3 program to print diagonals in 2D list def printDiagonal(lst): # To print Primary Diagonal print('Diagonal 1 - ', end ="") print([lst[i][i] for i in range(len(lst))]) # To print Secondary Diagonal print('Diagonal 2 - ', end ="") print([lst[i][len(lst)-i-1] for i in range(len(lst))]) # Driver codelst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]printDiagonal(lst) Diagonal 1 - [1, 5, 9] Diagonal 2 - [3, 5, 7] Approach #3 : Using enumerate()Python enumerate() is also an alternative to above mentioned methods. It uses two variable ‘i’ and ‘r’ two traverse through enumerate(lst) and simply return the ith element of ‘r’. Python3 # Python3 program to print diagonals in 2D list def printDiagonal(lst): # To print Primary Diagonal print('Diagonal 1 - ', end ="") print([r[i] for i, r in enumerate(lst)]) # To print Secondary Diagonal print('Diagonal 2 - ', end ="") print([r[~i] for i, r in enumerate(lst)]) # Driver codelst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]printDiagonal(lst) Diagonal 1 - [1, 5, 9] Diagonal 2 - [3, 5, 7] gabaa406 ruhelaa48 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25468, "s": 25440, "text": "\n30 Aug, 2021" }, { "code": null, "e": 25590, "s": 25468, "text": "Given a 2D list (with equal length of sublists), write a Python program to print both the diagonals of the given 2D list." }, { "code": null, "e": 25601, "s": 25590, "text": "Examples: " }, { "code": null, "e": 25807, "s": 25601, "text": "Input : [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\nOutput : Diagonal 1 - [1, 5, 9]\n Diagonal 2 - [3, 5, 7]\n\nInput : [['a', 'b'], ['c', 'd']]\nOutput : Diagonal 1 - ['a', 'd']\n Diagonal 2 - ['b', 'c']" }, { "code": null, "e": 26074, "s": 25807, "text": "Approach #1 : Using Python xrange()We can use one-liner list comprehension along with xrange() function. xrange() is used to iterate a certain number of times in for loops. Thus, we print the element at [i][i] position in every iteration of loop. [Works in Python2] " }, { "code": null, "e": 26081, "s": 26074, "text": "Python" }, { "code": "# Python2 program to print diagonals in 2D list def printDiagonal(lst): # To print Primary Diagonal print('Diagonal 1 -'), print([lst[i][i] for i in xrange(len(lst))]) # To print Secondary Diagonal print('Diagonal 2 -'), print([lst[i][len(lst)-1-i] for i in xrange(len(lst))]) # Driver codelst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] printDiagonal(lst)", "e": 26466, "s": 26081, "text": null }, { "code": null, "e": 26512, "s": 26466, "text": "Diagonal 1 - [1, 5, 9]\nDiagonal 2 - [3, 5, 7]" }, { "code": null, "e": 26681, "s": 26512, "text": " Approach #2 : Using range()This method is similar to Approach #1. The advantage of range() is that it works for both the versions of Python i.e. Python2 and Python3. " }, { "code": null, "e": 26689, "s": 26681, "text": "Python3" }, { "code": "# Python3 program to print diagonals in 2D list def printDiagonal(lst): # To print Primary Diagonal print('Diagonal 1 - ', end =\"\") print([lst[i][i] for i in range(len(lst))]) # To print Secondary Diagonal print('Diagonal 2 - ', end =\"\") print([lst[i][len(lst)-i-1] for i in range(len(lst))]) # Driver codelst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]printDiagonal(lst)", "e": 27081, "s": 26689, "text": null }, { "code": null, "e": 27127, "s": 27081, "text": "Diagonal 1 - [1, 5, 9]\nDiagonal 2 - [3, 5, 7]" }, { "code": null, "e": 27342, "s": 27127, "text": " Approach #3 : Using enumerate()Python enumerate() is also an alternative to above mentioned methods. It uses two variable ‘i’ and ‘r’ two traverse through enumerate(lst) and simply return the ith element of ‘r’. " }, { "code": null, "e": 27350, "s": 27342, "text": "Python3" }, { "code": "# Python3 program to print diagonals in 2D list def printDiagonal(lst): # To print Primary Diagonal print('Diagonal 1 - ', end =\"\") print([r[i] for i, r in enumerate(lst)]) # To print Secondary Diagonal print('Diagonal 2 - ', end =\"\") print([r[~i] for i, r in enumerate(lst)]) # Driver codelst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]printDiagonal(lst)", "e": 27726, "s": 27350, "text": null }, { "code": null, "e": 27772, "s": 27726, "text": "Diagonal 1 - [1, 5, 9]\nDiagonal 2 - [3, 5, 7]" }, { "code": null, "e": 27781, "s": 27772, "text": "gabaa406" }, { "code": null, "e": 27791, "s": 27781, "text": "ruhelaa48" }, { "code": null, "e": 27812, "s": 27791, "text": "Python list-programs" }, { "code": null, "e": 27819, "s": 27812, "text": "Python" }, { "code": null, "e": 27835, "s": 27819, "text": "Python Programs" }, { "code": null, "e": 27933, "s": 27835, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27965, "s": 27933, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27987, "s": 27965, "text": "Enumerate() in Python" }, { "code": null, "e": 28029, "s": 27987, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28055, "s": 28029, "text": "Python String | replace()" }, { "code": null, "e": 28084, "s": 28055, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28106, "s": 28084, "text": "Defaultdict in Python" }, { "code": null, "e": 28145, "s": 28106, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28191, "s": 28145, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28229, "s": 28191, "text": "Python | Convert a list to dictionary" } ]
Python - API.update_status() in Tweepy - GeeksforGeeks
05 Jun, 2020 Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication. The API.update_status() method of the API class in Tweepy module is used to update the authenticated user’s current status or in simple words, tweeting. Syntax : API.update_status(parameters) Parameters : status : The text of the tweet / status update. in_reply_to_status_id : The ID of the tweet that the new tweet is being replied to. attachment_url : This provides a URL as a tweet attachment. media_ids : A list of media_ids to be associated with the tweet. possibly_sensitive : Set it to True if the tweet might contain sensitive data. lat : The latitude of the tweet. long : The longitude of the tweet. place_id : The name of the place of the tweet. display_coordinates : Set this value to True if the exact coordinates of the tweet have to be displayed. Returns : an object of the class Status Example 1 :Using the update_status() method with only the text and no other parameter. # import the moduleimport tweepy # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = "" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the text to be tweetedstatus = "This is a tweet." # posting the tweetapi.update_status(status) Output : Example 2 :Using the update_status() method with in_reply_to_status_id parameter to reply to the previous tweet. # the text to be tweetedstatus = "This is a tweet is a reply." # the ID of the tweet to be replied toin_reply_to_status_id = "" # posting the tweetapi.update_status(status, in_reply_to_status_id) Output : Python-Tweepy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25677, "s": 25649, "text": "\n05 Jun, 2020" }, { "code": null, "e": 26077, "s": 25677, "text": "Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication." }, { "code": null, "e": 26230, "s": 26077, "text": "The API.update_status() method of the API class in Tweepy module is used to update the authenticated user’s current status or in simple words, tweeting." }, { "code": null, "e": 26269, "s": 26230, "text": "Syntax : API.update_status(parameters)" }, { "code": null, "e": 26282, "s": 26269, "text": "Parameters :" }, { "code": null, "e": 26330, "s": 26282, "text": "status : The text of the tweet / status update." }, { "code": null, "e": 26414, "s": 26330, "text": "in_reply_to_status_id : The ID of the tweet that the new tweet is being replied to." }, { "code": null, "e": 26474, "s": 26414, "text": "attachment_url : This provides a URL as a tweet attachment." }, { "code": null, "e": 26539, "s": 26474, "text": "media_ids : A list of media_ids to be associated with the tweet." }, { "code": null, "e": 26618, "s": 26539, "text": "possibly_sensitive : Set it to True if the tweet might contain sensitive data." }, { "code": null, "e": 26651, "s": 26618, "text": "lat : The latitude of the tweet." }, { "code": null, "e": 26686, "s": 26651, "text": "long : The longitude of the tweet." }, { "code": null, "e": 26733, "s": 26686, "text": "place_id : The name of the place of the tweet." }, { "code": null, "e": 26838, "s": 26733, "text": "display_coordinates : Set this value to True if the exact coordinates of the tweet have to be displayed." }, { "code": null, "e": 26878, "s": 26838, "text": "Returns : an object of the class Status" }, { "code": null, "e": 26965, "s": 26878, "text": "Example 1 :Using the update_status() method with only the text and no other parameter." }, { "code": "# import the moduleimport tweepy # assign the values accordinglyconsumer_key = \"\"consumer_secret = \"\"access_token = \"\"access_token_secret = \"\" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the text to be tweetedstatus = \"This is a tweet.\" # posting the tweetapi.update_status(status)", "e": 27470, "s": 26965, "text": null }, { "code": null, "e": 27479, "s": 27470, "text": "Output :" }, { "code": null, "e": 27592, "s": 27479, "text": "Example 2 :Using the update_status() method with in_reply_to_status_id parameter to reply to the previous tweet." }, { "code": "# the text to be tweetedstatus = \"This is a tweet is a reply.\" # the ID of the tweet to be replied toin_reply_to_status_id = \"\" # posting the tweetapi.update_status(status, in_reply_to_status_id)", "e": 27790, "s": 27592, "text": null }, { "code": null, "e": 27799, "s": 27790, "text": "Output :" }, { "code": null, "e": 27813, "s": 27799, "text": "Python-Tweepy" }, { "code": null, "e": 27820, "s": 27813, "text": "Python" }, { "code": null, "e": 27918, "s": 27820, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27936, "s": 27918, "text": "Python Dictionary" }, { "code": null, "e": 27971, "s": 27936, "text": "Read a file line by line in Python" }, { "code": null, "e": 28003, "s": 27971, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28025, "s": 28003, "text": "Enumerate() in Python" }, { "code": null, "e": 28067, "s": 28025, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28097, "s": 28067, "text": "Iterate over a list in Python" }, { "code": null, "e": 28123, "s": 28097, "text": "Python String | replace()" }, { "code": null, "e": 28152, "s": 28123, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28196, "s": 28152, "text": "Reading and Writing to text files in Python" } ]
Implementation of lower_bound() and upper_bound() in Array of Pairs in C++ - GeeksforGeeks
01 Aug, 2020 In this article we will discuss the implementation of the lower_bound() and upper_bound() in an array of pairs. lower_bound(): It returns an iterator pointing to the first element in the range [first, last) which has a value greater than or equals to the given value “val”. But in Array of Pairs lower_bound() for pair(x, y) will return an iterator pointing to the position of pair whose the first value is greater than or equals x and second value is greater than equals to y.If the above-mentioned criteria are not met, then it returns an iterator to the index which out of the array of pairs. upper_bound(): It returns an iterator pointing to the first element in the range [first, last) which has a value greater than the given value “val”. But in Array of Pairs upper_bound() for pair(x, y) will return an iterator pointing to the position of pair whose the first value is greater than x and second value is greater than y.If the above-mentioned criteria are not met, then it returns an iterator to the index which out of the array of pairs. Syntax: // For lower boundlower_bound(array_name, array_name + array_size, value, comparator_function); // For upper boundupper_bound(array_name, array_name + array_size, value, comparator_function); Parameters: The function lower_bound() and upper_bound() in array of pairs accepts the following parameters: array_name & array_size: The name and size of the array which represents the interval between [start, end).value: Value of the lower_bound()/upper_bound() to be searched in the range.comparator_function: Binary function that accepts two arguments as its input, namely an element of type pair from the array, and the second is the value for which lower_bound()/upper_bound() has to be found and returns a boolean value. array_name & array_size: The name and size of the array which represents the interval between [start, end). value: Value of the lower_bound()/upper_bound() to be searched in the range. comparator_function: Binary function that accepts two arguments as its input, namely an element of type pair from the array, and the second is the value for which lower_bound()/upper_bound() has to be found and returns a boolean value. Return Type: It returns an iterator pointing to the first element of the array whose first parameter is greater than or equal to the value. Below is the program to demonstrate lower_bound() and upper_bound() in array of pairs: C++ // C++ program to demonstrate lower_bound()// and upper_bound() in Array of Pairs#include <bits/stdc++.h>using namespace std; // Function to implement lower_bound()void findLowerBound(pair<int, int> arr[], pair<int, int>& p, int n){ // Given iterator points to the // lower_bound() of given pair auto low = lower_bound(arr, arr + n, p); cout << "lower_bound() for {2, 5}" << " is at index: " << low - arr << endl;} // Function to implement upper_bound()void findUpperBound(pair<int, int> arr[], pair<int, int>& p, int n){ // Given iterator points to the // lower_bound() of given pair auto up = upper_bound(arr, arr + n, p); cout << "upper_bound() for {2, 5}" << " is at index: " << up - arr << endl;} // Driver Codeint main(){ // Given sorted array of Pairs pair<int, int> arr[] = { { 1, 3 }, { 1, 7 }, { 2, 4 }, { 2, 5 }, { 3, 8 }, { 8, 6 } }; // Given pair {2, 5} pair<int, int> p = { 2, 5 }; // Size of array int n = sizeof(arr) / sizeof(arr[0]); // Function Call to find lower_bound // of pair p in arr findLowerBound(arr, p, n); // Function Call to find upper_bound // of pair p in arr findUpperBound(arr, p, n); return 0;} lower_bound() for {2, 5} is at index: 3 upper_bound() for {2, 5} is at index: 4 cpp-array cpp-pair Arrays C++ Programs Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Header files in C/C++ and its uses Program to print ASCII Value of a character How to return multiple values from a function in C or C++? C++ Program for QuickSort Sorting a Map by value in C++ STL
[ { "code": null, "e": 26041, "s": 26013, "text": "\n01 Aug, 2020" }, { "code": null, "e": 26153, "s": 26041, "text": "In this article we will discuss the implementation of the lower_bound() and upper_bound() in an array of pairs." }, { "code": null, "e": 26637, "s": 26153, "text": "lower_bound(): It returns an iterator pointing to the first element in the range [first, last) which has a value greater than or equals to the given value “val”. But in Array of Pairs lower_bound() for pair(x, y) will return an iterator pointing to the position of pair whose the first value is greater than or equals x and second value is greater than equals to y.If the above-mentioned criteria are not met, then it returns an iterator to the index which out of the array of pairs." }, { "code": null, "e": 27088, "s": 26637, "text": "upper_bound(): It returns an iterator pointing to the first element in the range [first, last) which has a value greater than the given value “val”. But in Array of Pairs upper_bound() for pair(x, y) will return an iterator pointing to the position of pair whose the first value is greater than x and second value is greater than y.If the above-mentioned criteria are not met, then it returns an iterator to the index which out of the array of pairs." }, { "code": null, "e": 27096, "s": 27088, "text": "Syntax:" }, { "code": null, "e": 27192, "s": 27096, "text": "// For lower boundlower_bound(array_name, array_name + array_size, value, comparator_function);" }, { "code": null, "e": 27288, "s": 27192, "text": "// For upper boundupper_bound(array_name, array_name + array_size, value, comparator_function);" }, { "code": null, "e": 27397, "s": 27288, "text": "Parameters: The function lower_bound() and upper_bound() in array of pairs accepts the following parameters:" }, { "code": null, "e": 27816, "s": 27397, "text": "array_name & array_size: The name and size of the array which represents the interval between [start, end).value: Value of the lower_bound()/upper_bound() to be searched in the range.comparator_function: Binary function that accepts two arguments as its input, namely an element of type pair from the array, and the second is the value for which lower_bound()/upper_bound() has to be found and returns a boolean value." }, { "code": null, "e": 27924, "s": 27816, "text": "array_name & array_size: The name and size of the array which represents the interval between [start, end)." }, { "code": null, "e": 28001, "s": 27924, "text": "value: Value of the lower_bound()/upper_bound() to be searched in the range." }, { "code": null, "e": 28237, "s": 28001, "text": "comparator_function: Binary function that accepts two arguments as its input, namely an element of type pair from the array, and the second is the value for which lower_bound()/upper_bound() has to be found and returns a boolean value." }, { "code": null, "e": 28377, "s": 28237, "text": "Return Type: It returns an iterator pointing to the first element of the array whose first parameter is greater than or equal to the value." }, { "code": null, "e": 28464, "s": 28377, "text": "Below is the program to demonstrate lower_bound() and upper_bound() in array of pairs:" }, { "code": null, "e": 28468, "s": 28464, "text": "C++" }, { "code": "// C++ program to demonstrate lower_bound()// and upper_bound() in Array of Pairs#include <bits/stdc++.h>using namespace std; // Function to implement lower_bound()void findLowerBound(pair<int, int> arr[], pair<int, int>& p, int n){ // Given iterator points to the // lower_bound() of given pair auto low = lower_bound(arr, arr + n, p); cout << \"lower_bound() for {2, 5}\" << \" is at index: \" << low - arr << endl;} // Function to implement upper_bound()void findUpperBound(pair<int, int> arr[], pair<int, int>& p, int n){ // Given iterator points to the // lower_bound() of given pair auto up = upper_bound(arr, arr + n, p); cout << \"upper_bound() for {2, 5}\" << \" is at index: \" << up - arr << endl;} // Driver Codeint main(){ // Given sorted array of Pairs pair<int, int> arr[] = { { 1, 3 }, { 1, 7 }, { 2, 4 }, { 2, 5 }, { 3, 8 }, { 8, 6 } }; // Given pair {2, 5} pair<int, int> p = { 2, 5 }; // Size of array int n = sizeof(arr) / sizeof(arr[0]); // Function Call to find lower_bound // of pair p in arr findLowerBound(arr, p, n); // Function Call to find upper_bound // of pair p in arr findUpperBound(arr, p, n); return 0;}", "e": 29802, "s": 28468, "text": null }, { "code": null, "e": 29883, "s": 29802, "text": "lower_bound() for {2, 5} is at index: 3\nupper_bound() for {2, 5} is at index: 4\n" }, { "code": null, "e": 29893, "s": 29883, "text": "cpp-array" }, { "code": null, "e": 29902, "s": 29893, "text": "cpp-pair" }, { "code": null, "e": 29909, "s": 29902, "text": "Arrays" }, { "code": null, "e": 29922, "s": 29909, "text": "C++ Programs" }, { "code": null, "e": 29929, "s": 29922, "text": "Arrays" }, { "code": null, "e": 30027, "s": 29929, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30054, "s": 30027, "text": "Count pairs with given sum" }, { "code": null, "e": 30085, "s": 30054, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 30110, "s": 30085, "text": "Window Sliding Technique" }, { "code": null, "e": 30148, "s": 30110, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 30169, "s": 30148, "text": "Next Greater Element" }, { "code": null, "e": 30204, "s": 30169, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 30248, "s": 30204, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 30307, "s": 30248, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 30333, "s": 30307, "text": "C++ Program for QuickSort" } ]
K difference permutation - GeeksforGeeks
20 May, 2021 Given two integers n and k. Consider first permutation of natural n numbers, P = “1 2 3 ... n”, print a permutation “Result” such that abs(Resulti – Pi) = k where Pi denotes the position of i in permutation P. The value of Pi varies from 1 to n. If there are multiple possible results, then print the lexicographically smallest one. Input: n = 6 k = 3 Output: 4 5 6 1 2 3 Explanation: P = 1 2 3 4 5 6 Result = 4 5 6 1 2 3 We can notice that the difference between individual numbers (at same positions) of P and result is 3 and "4 5 6 1 2 3" is lexicographically smallest such permutation. Other greater permutations could be Input : n = 6 k = 2 Output : Not possible Explanation: No permutation is possible with difference is k Naive approach is to generate all the permutation from 1 to n and pick the smallest one which satisfy the condition of absolute difference k. Time complexity of this approach is Ω(n!) which will definitely time out for large value of n.The Efficient approach is to observe the pattern at each position of index. For each position of index i, there can only exist two candidate i.e., i + k and i – k. As we need to find lexicographically smallest permutation so we will first look for i – k candidate(if possible) and then for i + k candidate. Illustration: n = 8, k = 2 P : 1 2 3 4 5 6 7 8 For any ith position we will check which candidate is possible i.e., i + k or i - k 1st pos = 1 + 2 = 3 (1 - 2 not possible) 2nd pos = 2 + 2 = 4 (2 - 2 not possible) 3rd pos = 3 - 2 = 1 (possible) 4th pos = 4 - 2 = 2 (possible) 5th pos = 5 + 2 = 7 (5 - 2 already placed, not possible) 6th pos = 6 + 2 = 8 (6 - 2 already placed, not possible) 7th pos = 7 - 2 = 5 (possible) 8th pos = 8 - 2 = 6 (possible) Note: If we observe above illustration then we will find that i + k and i – k are alternating after kth consecutive interval. Another observation is that the whole permutation is only when n is even such that n can be divided into two parts where each part must be divisible by k. C++ Java Python3 C# PHP Javascript // C++ program to find k absolute difference// permutation#include<bits/stdc++.h>using namespace std; void kDifferencePermutation(int n, int k){ // If k is 0 then we just print the // permutation from 1 to n if (!k) { for (int i = 0; i < n; ++i) cout << i + 1 << " "; } // Check whether permutation is feasible or not else if (n % (2 * k) != 0) cout <<"Not Possible"; else { for (int i = 0; i < n; ++i) { // Put i + k + 1 candidate if position is // feasible, otherwise put the i - k - 1 // candidate if ((i / k) % 2 == 0) cout << i + k + 1 << " "; else cout << i - k + 1 << " "; } } cout << "\n";} // Driver codeint main(){ int n = 6 , k = 3; kDifferencePermutation(n, k); n = 6 , k = 2; kDifferencePermutation(n, k); n = 8 , k = 2; kDifferencePermutation(n, k); return 0;} // Java program to find k absolute// difference permutationimport java.io.*; class GFG { static void kDifferencePermutation(int n, int k) { // If k is 0 then we just print the // permutation from 1 to n if (!(k > 0)) { for (int i = 0; i < n; ++i) System.out.print( i + 1 + " "); } // Check whether permutation is // feasible or not else if (n % (2 * k) != 0) System.out.print("Not Possible"); else { for (int i = 0; i < n; ++i) { // Put i + k + 1 candidate // if position is feasible, // otherwise put the // i - k - 1 candidate if ((i / k) % 2 == 0) System.out.print( i + k + 1 + " "); else System.out.print( i - k + 1 + " "); } } System.out.println() ; } // Driver code static public void main (String[] args) { int n = 6 , k = 3; kDifferencePermutation(n, k); n = 6 ; k = 2; kDifferencePermutation(n, k); n = 8 ; k = 2; kDifferencePermutation(n, k); }} // This code is contributed by anuj_67. # Python 3 program to find k# absolute difference permutationdef kDifferencePermutation(n, k): # If k is 0 then we just print the # permutation from 1 to n if (k == 0): for i in range(n): print(i + 1, end = " ") # Check whether permutation # is feasible or not elif (n % (2 * k) != 0): print("Not Possible", end = "") else: for i in range(n): # Put i + k + 1 candidate if position is # feasible, otherwise put the i - k - 1 # candidate if (int(i / k) % 2 == 0): print(i + k + 1, end = " ") else: print(i - k + 1, end = " ") print("\n", end = "") # Driver codeif __name__ == '__main__': n = 6 k = 3 kDifferencePermutation(n, k) n = 6 k = 2 kDifferencePermutation(n, k) n = 8 k = 2 kDifferencePermutation(n, k) # This code is contributed by# Surendra_Gangwar // C# program to find k absolute// difference permutationusing System; class GFG { static void kDifferencePermutation(int n, int k) { // If k is 0 then we just print the // permutation from 1 to n if (!(k > 0)) { for (int i = 0; i < n; ++i) Console.Write( i + 1 + " "); } // Check whether permutation is // feasible or not else if (n % (2 * k) != 0) Console.Write("Not Possible"); else { for (int i = 0; i < n; ++i) { // Put i + k + 1 candidate // if position is feasible, // otherwise put the // i - k - 1 candidate if ((i / k) % 2 == 0) Console.Write( i + k + 1 + " "); else Console.Write( i - k + 1 + " "); } } Console.WriteLine() ; } // Driver code static public void Main () { int n = 6 , k = 3; kDifferencePermutation(n, k); n = 6 ; k = 2; kDifferencePermutation(n, k); n = 8 ; k = 2; kDifferencePermutation(n, k); }} // This code is contributed by anuj_67. <?php// PHP program to find k absolute// difference permutation function kDifferencePermutation( $n, $k){ // If k is 0 then we just print the // permutation from 1 to n if (!$k) { for($i = 0; $i < $n; ++$i) echo $i + 1 ," "; } // Check whether permutation // is feasible or not else if ($n % (2 * $k) != 0) echo"Not Possible"; else { for($i = 0; $i < $n; ++$i) { // Put i + k + 1 candidate // if position is feasible, // otherwise put the i - k - 1 // candidate if (($i / $k) % 2 == 0) echo $i + $k + 1 , " "; else echo $i - $k + 1 , " "; } } echo "\n";} // Driver Code $n = 6 ; $k = 3; kDifferencePermutation($n, $k); $n = 6 ; $k = 2; kDifferencePermutation($n, $k); $n = 8 ;$k = 2; kDifferencePermutation($n, $k); // This code is contributed by anuj_67.?> <script> // Javascript program to find k absolute difference permutation function kDifferencePermutation(n, k) { // If k is 0 then we just print the // permutation from 1 to n if (!(k > 0)) { for (let i = 0; i < n; ++i) document.write( i + 1 + " "); } // Check whether permutation is // feasible or not else if (n % (2 * k) != 0) document.write("Not Possible"); else { for (let i = 0; i < n; ++i) { // Put i + k + 1 candidate // if position is feasible, // otherwise put the // i - k - 1 candidate if (parseInt(i / k, 10) % 2 == 0) document.write( i + k + 1 + " "); else document.write( i - k + 1 + " "); } } document.write("</br>") ; } let n = 6 , k = 3; kDifferencePermutation(n, k); n = 6 ; k = 2; kDifferencePermutation(n, k); n = 8 ; k = 2; kDifferencePermutation(n, k); // This code is contributed by rameshtravel07.</script> Output: 4 5 6 1 2 3 Not Possible 3 4 1 2 7 8 5 6 Time complexity: O(n) Auxiliary space: O(1)This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m SURENDRA_GANGWAR rameshtravel07 permutation Combinatorial permutation Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ways to sum to N using Natural Numbers up to K with repetitions allowed Generate all possible combinations of K numbers that sums to N Combinations with repetitions Generate all possible combinations of at most X characters from a given array Given number of matches played, find number of teams in tournament Print all possible permutations of an array with duplicates using Backtracking Print all permutations with repetition of characters Number of ways to form a heap with n distinct integers Print all Strong numbers less than or equal to N Largest substring with same Characters
[ { "code": null, "e": 26723, "s": 26695, "text": "\n20 May, 2021" }, { "code": null, "e": 27057, "s": 26723, "text": "Given two integers n and k. Consider first permutation of natural n numbers, P = “1 2 3 ... n”, print a permutation “Result” such that abs(Resulti – Pi) = k where Pi denotes the position of i in permutation P. The value of Pi varies from 1 to n. If there are multiple possible results, then print the lexicographically smallest one. " }, { "code": null, "e": 27465, "s": 27057, "text": "Input: n = 6 k = 3\nOutput: 4 5 6 1 2 3\nExplanation:\n P = 1 2 3 4 5 6\nResult = 4 5 6 1 2 3\nWe can notice that the difference between\nindividual numbers (at same positions) of \nP and result is 3 and \"4 5 6 1 2 3\" is \nlexicographically smallest such permutation.\nOther greater permutations could be \n\nInput : n = 6 k = 2\nOutput : Not possible\nExplanation: No permutation is possible \nwith difference is k " }, { "code": null, "e": 28011, "s": 27467, "text": "Naive approach is to generate all the permutation from 1 to n and pick the smallest one which satisfy the condition of absolute difference k. Time complexity of this approach is Ω(n!) which will definitely time out for large value of n.The Efficient approach is to observe the pattern at each position of index. For each position of index i, there can only exist two candidate i.e., i + k and i – k. As we need to find lexicographically smallest permutation so we will first look for i – k candidate(if possible) and then for i + k candidate. " }, { "code": null, "e": 28478, "s": 28011, "text": " Illustration:\n n = 8, k = 2\n P : 1 2 3 4 5 6 7 8\n\n For any ith position we will check which candidate\n is possible i.e., i + k or i - k \n\n 1st pos = 1 + 2 = 3 (1 - 2 not possible)\n 2nd pos = 2 + 2 = 4 (2 - 2 not possible)\n 3rd pos = 3 - 2 = 1 (possible)\n 4th pos = 4 - 2 = 2 (possible)\n 5th pos = 5 + 2 = 7 (5 - 2 already placed, not possible)\n 6th pos = 6 + 2 = 8 (6 - 2 already placed, not possible)\n 7th pos = 7 - 2 = 5 (possible)\n 8th pos = 8 - 2 = 6 (possible)" }, { "code": null, "e": 28761, "s": 28478, "text": "Note: If we observe above illustration then we will find that i + k and i – k are alternating after kth consecutive interval. Another observation is that the whole permutation is only when n is even such that n can be divided into two parts where each part must be divisible by k. " }, { "code": null, "e": 28765, "s": 28761, "text": "C++" }, { "code": null, "e": 28770, "s": 28765, "text": "Java" }, { "code": null, "e": 28778, "s": 28770, "text": "Python3" }, { "code": null, "e": 28781, "s": 28778, "text": "C#" }, { "code": null, "e": 28785, "s": 28781, "text": "PHP" }, { "code": null, "e": 28796, "s": 28785, "text": "Javascript" }, { "code": "// C++ program to find k absolute difference// permutation#include<bits/stdc++.h>using namespace std; void kDifferencePermutation(int n, int k){ // If k is 0 then we just print the // permutation from 1 to n if (!k) { for (int i = 0; i < n; ++i) cout << i + 1 << \" \"; } // Check whether permutation is feasible or not else if (n % (2 * k) != 0) cout <<\"Not Possible\"; else { for (int i = 0; i < n; ++i) { // Put i + k + 1 candidate if position is // feasible, otherwise put the i - k - 1 // candidate if ((i / k) % 2 == 0) cout << i + k + 1 << \" \"; else cout << i - k + 1 << \" \"; } } cout << \"\\n\";} // Driver codeint main(){ int n = 6 , k = 3; kDifferencePermutation(n, k); n = 6 , k = 2; kDifferencePermutation(n, k); n = 8 , k = 2; kDifferencePermutation(n, k); return 0;}", "e": 29761, "s": 28796, "text": null }, { "code": "// Java program to find k absolute// difference permutationimport java.io.*; class GFG { static void kDifferencePermutation(int n, int k) { // If k is 0 then we just print the // permutation from 1 to n if (!(k > 0)) { for (int i = 0; i < n; ++i) System.out.print( i + 1 + \" \"); } // Check whether permutation is // feasible or not else if (n % (2 * k) != 0) System.out.print(\"Not Possible\"); else { for (int i = 0; i < n; ++i) { // Put i + k + 1 candidate // if position is feasible, // otherwise put the // i - k - 1 candidate if ((i / k) % 2 == 0) System.out.print( i + k + 1 + \" \"); else System.out.print( i - k + 1 + \" \"); } } System.out.println() ; } // Driver code static public void main (String[] args) { int n = 6 , k = 3; kDifferencePermutation(n, k); n = 6 ; k = 2; kDifferencePermutation(n, k); n = 8 ; k = 2; kDifferencePermutation(n, k); }} // This code is contributed by anuj_67.", "e": 31131, "s": 29761, "text": null }, { "code": "# Python 3 program to find k# absolute difference permutationdef kDifferencePermutation(n, k): # If k is 0 then we just print the # permutation from 1 to n if (k == 0): for i in range(n): print(i + 1, end = \" \") # Check whether permutation # is feasible or not elif (n % (2 * k) != 0): print(\"Not Possible\", end = \"\") else: for i in range(n): # Put i + k + 1 candidate if position is # feasible, otherwise put the i - k - 1 # candidate if (int(i / k) % 2 == 0): print(i + k + 1, end = \" \") else: print(i - k + 1, end = \" \") print(\"\\n\", end = \"\") # Driver codeif __name__ == '__main__': n = 6 k = 3 kDifferencePermutation(n, k) n = 6 k = 2 kDifferencePermutation(n, k) n = 8 k = 2 kDifferencePermutation(n, k) # This code is contributed by# Surendra_Gangwar", "e": 32083, "s": 31131, "text": null }, { "code": "// C# program to find k absolute// difference permutationusing System; class GFG { static void kDifferencePermutation(int n, int k) { // If k is 0 then we just print the // permutation from 1 to n if (!(k > 0)) { for (int i = 0; i < n; ++i) Console.Write( i + 1 + \" \"); } // Check whether permutation is // feasible or not else if (n % (2 * k) != 0) Console.Write(\"Not Possible\"); else { for (int i = 0; i < n; ++i) { // Put i + k + 1 candidate // if position is feasible, // otherwise put the // i - k - 1 candidate if ((i / k) % 2 == 0) Console.Write( i + k + 1 + \" \"); else Console.Write( i - k + 1 + \" \"); } } Console.WriteLine() ; } // Driver code static public void Main () { int n = 6 , k = 3; kDifferencePermutation(n, k); n = 6 ; k = 2; kDifferencePermutation(n, k); n = 8 ; k = 2; kDifferencePermutation(n, k); }} // This code is contributed by anuj_67.", "e": 33428, "s": 32083, "text": null }, { "code": "<?php// PHP program to find k absolute// difference permutation function kDifferencePermutation( $n, $k){ // If k is 0 then we just print the // permutation from 1 to n if (!$k) { for($i = 0; $i < $n; ++$i) echo $i + 1 ,\" \"; } // Check whether permutation // is feasible or not else if ($n % (2 * $k) != 0) echo\"Not Possible\"; else { for($i = 0; $i < $n; ++$i) { // Put i + k + 1 candidate // if position is feasible, // otherwise put the i - k - 1 // candidate if (($i / $k) % 2 == 0) echo $i + $k + 1 , \" \"; else echo $i - $k + 1 , \" \"; } } echo \"\\n\";} // Driver Code $n = 6 ; $k = 3; kDifferencePermutation($n, $k); $n = 6 ; $k = 2; kDifferencePermutation($n, $k); $n = 8 ;$k = 2; kDifferencePermutation($n, $k); // This code is contributed by anuj_67.?>", "e": 34408, "s": 33428, "text": null }, { "code": "<script> // Javascript program to find k absolute difference permutation function kDifferencePermutation(n, k) { // If k is 0 then we just print the // permutation from 1 to n if (!(k > 0)) { for (let i = 0; i < n; ++i) document.write( i + 1 + \" \"); } // Check whether permutation is // feasible or not else if (n % (2 * k) != 0) document.write(\"Not Possible\"); else { for (let i = 0; i < n; ++i) { // Put i + k + 1 candidate // if position is feasible, // otherwise put the // i - k - 1 candidate if (parseInt(i / k, 10) % 2 == 0) document.write( i + k + 1 + \" \"); else document.write( i - k + 1 + \" \"); } } document.write(\"</br>\") ; } let n = 6 , k = 3; kDifferencePermutation(n, k); n = 6 ; k = 2; kDifferencePermutation(n, k); n = 8 ; k = 2; kDifferencePermutation(n, k); // This code is contributed by rameshtravel07.</script>", "e": 35644, "s": 34408, "text": null }, { "code": null, "e": 35654, "s": 35644, "text": "Output: " }, { "code": null, "e": 35697, "s": 35654, "text": "4 5 6 1 2 3 \nNot Possible\n3 4 1 2 7 8 5 6 " }, { "code": null, "e": 36162, "s": 35697, "text": "Time complexity: O(n) Auxiliary space: O(1)This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 36167, "s": 36162, "text": "vt_m" }, { "code": null, "e": 36184, "s": 36167, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 36199, "s": 36184, "text": "rameshtravel07" }, { "code": null, "e": 36211, "s": 36199, "text": "permutation" }, { "code": null, "e": 36225, "s": 36211, "text": "Combinatorial" }, { "code": null, "e": 36237, "s": 36225, "text": "permutation" }, { "code": null, "e": 36251, "s": 36237, "text": "Combinatorial" }, { "code": null, "e": 36349, "s": 36251, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36421, "s": 36349, "text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed" }, { "code": null, "e": 36484, "s": 36421, "text": "Generate all possible combinations of K numbers that sums to N" }, { "code": null, "e": 36514, "s": 36484, "text": "Combinations with repetitions" }, { "code": null, "e": 36592, "s": 36514, "text": "Generate all possible combinations of at most X characters from a given array" }, { "code": null, "e": 36659, "s": 36592, "text": "Given number of matches played, find number of teams in tournament" }, { "code": null, "e": 36738, "s": 36659, "text": "Print all possible permutations of an array with duplicates using Backtracking" }, { "code": null, "e": 36791, "s": 36738, "text": "Print all permutations with repetition of characters" }, { "code": null, "e": 36846, "s": 36791, "text": "Number of ways to form a heap with n distinct integers" }, { "code": null, "e": 36895, "s": 36846, "text": "Print all Strong numbers less than or equal to N" } ]
Python | CAP - Cumulative Accuracy Profile analysis - GeeksforGeeks
09 Sep, 2021 CAP popularly called the ‘Cumulative Accuracy Profile’ is used in the performance evaluation of the classification model. It helps us to understand and conclude about the robustness of the classification model. In order to visualize this, three distinct curves are plotted in our plot: A random plotA plot obtained by using a SVM classifier or a random forest classifierA perfect plot( an ideal line) A random plot A plot obtained by using a SVM classifier or a random forest classifier A perfect plot( an ideal line) We are working the DATA to understand the concept. Code : Loading dataset. Python3 # importing librariesimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltimport numpy as np # loading datasetdata = pd.read_csv('C:\\Users\\DELL\\Desktop\\Social_Network_Ads.csv') print ("Data Head : \n\n", data.head()) Output : Data Head : User ID Gender Age EstimatedSalary Purchased 0 15624510 Male 19 19000 0 1 15810944 Male 35 20000 0 2 15668575 Female 26 43000 0 3 15603246 Female 27 57000 0 4 15804002 Male 19 76000 0 Code : Data Input Output. Python3 # Input and Outputx = data.iloc[:, 2:4]y = data.iloc[:, 4] print ("Input : \n", x.iloc[0:10, :]) Output : Input : Age EstimatedSalary 0 19 19000 1 35 20000 2 26 43000 3 27 57000 4 19 76000 5 27 58000 6 27 84000 7 32 150000 8 25 33000 9 35 65000 Code : Splitting dataset for training and testing. Python3 # splitting datafrom sklearn.model_selection import train_test_splitx_train, x_test, y_train, y_test = train_test_split( x, y, test_size = 0.3, random_state = 0) Code : Random Forest Classifier Python3 # classifierfrom sklearn.ensemble import RandomForestClassifierclassifier = RandomForestClassifier(n_estimators = 400) # trainingclassifier.fit(x_train, y_train) # predictingpred = classifier.predict(x_test) Code : Finding the classifier accuracy. Python3 # Model Performancefrom sklearn.metrics import accuracy_scoreprint("Accuracy : ", accuracy_score(y_test, pred) * 100) Output : Accuracy : 91.66666666666666 The random plot is made under the assumption that we have plotted the total number of points ranging from 0 to the total number of data points in the dataset. The y-axis has been kept as the total number of points for which the dependent variable from our dataset has the outcome as 1. The random plot can be understood like a linearly increasing relationship. An example is a model that predicts whether a product is bought (positive outcome) by each individual from a group of people (classifying parameter) based on factors such as their gender, age, income etc. If group members would be contacted at random, the cumulative number of products sold would rise linearly toward a maximum value corresponding to the total number of buyers within the group. This distribution is called the “random” CAP. Code : Random Model Python3 # code for the random plotimport matplotlib.pyplot as pltimport numpy as np # length of the test datatotal = len(y_test) # Counting '1' labels in test dataone_count = np.sum(y_test) # counting '0' labels in test datazero_count = total - one_count plt.figure(figsize = (10, 6)) # x-axis ranges from 0 to total people contacted# y-axis ranges from 0 to the total positive outcomes. plt.plot([0, total], [0, one_count], c = 'b', linestyle = '--', label = 'Random Model')plt.legend() Output : Code : Random forest classification algorithm is applied to the dataset for the random classifier line plot. Python3 lm = [y for _, y in sorted(zip(pred, y_test), reverse = True)]x = np.arange(0, total + 1)y = np.append([0], np.cumsum(lm))plt.plot(x, y, c = 'b', label = 'Random classifier', linewidth = 2) Output : Explanation: pred is the prediction made by the random classifier. We zip the prediction and test values and sort it in the reverse order so that higher values come first and then the lower values. We extract only the y_test values in an array and store it in lm. np.cumsum() creates an array of values while cumulatively adding all previous values in the array to the present value. The x-values will be ranging from 0 to the total + 1. We add one to the total cause arange() does not include one to the array and we want the x-axis to range from 0 to the total. We then plot the perfect plot(or the ideal line). A perfect prediction determines exactly which group members will buy the product, such that the maximum number of products sold will be reached with a minimum number of calls. This produces a steep line on the CAP curve that stays flat once the maximum is reached (contacting all other group members will not lead to more products sold), which is the “perfect” CAP. Python3 plt.plot([0, one_count, total], [0, one_count, one_count], c = 'grey', linewidth = 2, label = 'Perfect Model') Output : Explanation: A perfect model finds positive outcomes in the same number of tries as the number of positive outcomes. We have total of 41 positive outcomes in our dataset and so at exactly 41, the maximum is achieved. In any case, our classifier algorithm should not produce a line that lies under the random line. It is considered to be a really bad model in that case. Since the plotted classifier line is close to the ideal line we can say that our model is a really good fit. Take the area under the perfect plot and call it aP. Take the area under the prediction model and call it aR. Then take the ratio as aR/aP. This ratio is called the Accuracy Rate. The closer is the value to 1, the better the model. This is one way to analyze it. Another way to analyze it would be to project a line from about 50% from the axis on the prediction model and project it on the y-axis. Let us say that we obtain the projection value as X%. -> 60% : it is a really bad model -> 60%<X<70% : it is still a bad model but better than the first case obviously -> 70%<X<80% : it is a good model -> 80%<X<90% : it is a very good model -> 90%<X<100% : it is extraordinarily good and might be one of the overfitting cases. So according to this analysis, we can determine how accurate our model is. Reference:- wikipedia.org Akanksha_Rai simranarora5sos Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Reinforcement learning Decision Tree Activation functions in Neural Networks Decision Tree Introduction with example 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": 26081, "s": 26053, "text": "\n09 Sep, 2021" }, { "code": null, "e": 26368, "s": 26081, "text": "CAP popularly called the ‘Cumulative Accuracy Profile’ is used in the performance evaluation of the classification model. It helps us to understand and conclude about the robustness of the classification model. In order to visualize this, three distinct curves are plotted in our plot: " }, { "code": null, "e": 26483, "s": 26368, "text": "A random plotA plot obtained by using a SVM classifier or a random forest classifierA perfect plot( an ideal line)" }, { "code": null, "e": 26497, "s": 26483, "text": "A random plot" }, { "code": null, "e": 26569, "s": 26497, "text": "A plot obtained by using a SVM classifier or a random forest classifier" }, { "code": null, "e": 26600, "s": 26569, "text": "A perfect plot( an ideal line)" }, { "code": null, "e": 26652, "s": 26600, "text": "We are working the DATA to understand the concept. " }, { "code": null, "e": 26677, "s": 26652, "text": "Code : Loading dataset. " }, { "code": null, "e": 26685, "s": 26677, "text": "Python3" }, { "code": "# importing librariesimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltimport numpy as np # loading datasetdata = pd.read_csv('C:\\\\Users\\\\DELL\\\\Desktop\\\\Social_Network_Ads.csv') print (\"Data Head : \\n\\n\", data.head())", "e": 26924, "s": 26685, "text": null }, { "code": null, "e": 26934, "s": 26924, "text": "Output : " }, { "code": null, "e": 27267, "s": 26934, "text": "Data Head : \n\n User ID Gender Age EstimatedSalary Purchased\n0 15624510 Male 19 19000 0\n1 15810944 Male 35 20000 0\n2 15668575 Female 26 43000 0\n3 15603246 Female 27 57000 0\n4 15804002 Male 19 76000 0" }, { "code": null, "e": 27294, "s": 27267, "text": "Code : Data Input Output. " }, { "code": null, "e": 27302, "s": 27294, "text": "Python3" }, { "code": "# Input and Outputx = data.iloc[:, 2:4]y = data.iloc[:, 4] print (\"Input : \\n\", x.iloc[0:10, :])", "e": 27399, "s": 27302, "text": null }, { "code": null, "e": 27409, "s": 27399, "text": "Output : " }, { "code": null, "e": 27683, "s": 27409, "text": "Input : \n Age EstimatedSalary\n0 19 19000\n1 35 20000\n2 26 43000\n3 27 57000\n4 19 76000\n5 27 58000\n6 27 84000\n7 32 150000\n8 25 33000\n9 35 65000" }, { "code": null, "e": 27735, "s": 27683, "text": "Code : Splitting dataset for training and testing. " }, { "code": null, "e": 27743, "s": 27735, "text": "Python3" }, { "code": "# splitting datafrom sklearn.model_selection import train_test_splitx_train, x_test, y_train, y_test = train_test_split( x, y, test_size = 0.3, random_state = 0)", "e": 27912, "s": 27743, "text": null }, { "code": null, "e": 27945, "s": 27912, "text": "Code : Random Forest Classifier " }, { "code": null, "e": 27953, "s": 27945, "text": "Python3" }, { "code": "# classifierfrom sklearn.ensemble import RandomForestClassifierclassifier = RandomForestClassifier(n_estimators = 400) # trainingclassifier.fit(x_train, y_train) # predictingpred = classifier.predict(x_test)", "e": 28161, "s": 27953, "text": null }, { "code": null, "e": 28202, "s": 28161, "text": "Code : Finding the classifier accuracy. " }, { "code": null, "e": 28210, "s": 28202, "text": "Python3" }, { "code": "# Model Performancefrom sklearn.metrics import accuracy_scoreprint(\"Accuracy : \", accuracy_score(y_test, pred) * 100)", "e": 28329, "s": 28210, "text": null }, { "code": null, "e": 28339, "s": 28329, "text": "Output : " }, { "code": null, "e": 28369, "s": 28339, "text": "Accuracy : 91.66666666666666" }, { "code": null, "e": 29173, "s": 28369, "text": "The random plot is made under the assumption that we have plotted the total number of points ranging from 0 to the total number of data points in the dataset. The y-axis has been kept as the total number of points for which the dependent variable from our dataset has the outcome as 1. The random plot can be understood like a linearly increasing relationship. An example is a model that predicts whether a product is bought (positive outcome) by each individual from a group of people (classifying parameter) based on factors such as their gender, age, income etc. If group members would be contacted at random, the cumulative number of products sold would rise linearly toward a maximum value corresponding to the total number of buyers within the group. This distribution is called the “random” CAP. " }, { "code": null, "e": 29195, "s": 29173, "text": "Code : Random Model " }, { "code": null, "e": 29203, "s": 29195, "text": "Python3" }, { "code": "# code for the random plotimport matplotlib.pyplot as pltimport numpy as np # length of the test datatotal = len(y_test) # Counting '1' labels in test dataone_count = np.sum(y_test) # counting '0' labels in test datazero_count = total - one_count plt.figure(figsize = (10, 6)) # x-axis ranges from 0 to total people contacted# y-axis ranges from 0 to the total positive outcomes. plt.plot([0, total], [0, one_count], c = 'b', linestyle = '--', label = 'Random Model')plt.legend()", "e": 29691, "s": 29203, "text": null }, { "code": null, "e": 29701, "s": 29691, "text": "Output : " }, { "code": null, "e": 29812, "s": 29701, "text": "Code : Random forest classification algorithm is applied to the dataset for the random classifier line plot. " }, { "code": null, "e": 29820, "s": 29812, "text": "Python3" }, { "code": "lm = [y for _, y in sorted(zip(pred, y_test), reverse = True)]x = np.arange(0, total + 1)y = np.append([0], np.cumsum(lm))plt.plot(x, y, c = 'b', label = 'Random classifier', linewidth = 2)", "e": 30010, "s": 29820, "text": null }, { "code": null, "e": 30020, "s": 30010, "text": "Output : " }, { "code": null, "e": 30585, "s": 30020, "text": "Explanation: pred is the prediction made by the random classifier. We zip the prediction and test values and sort it in the reverse order so that higher values come first and then the lower values. We extract only the y_test values in an array and store it in lm. np.cumsum() creates an array of values while cumulatively adding all previous values in the array to the present value. The x-values will be ranging from 0 to the total + 1. We add one to the total cause arange() does not include one to the array and we want the x-axis to range from 0 to the total. " }, { "code": null, "e": 31003, "s": 30585, "text": "We then plot the perfect plot(or the ideal line). A perfect prediction determines exactly which group members will buy the product, such that the maximum number of products sold will be reached with a minimum number of calls. This produces a steep line on the CAP curve that stays flat once the maximum is reached (contacting all other group members will not lead to more products sold), which is the “perfect” CAP. " }, { "code": null, "e": 31011, "s": 31003, "text": "Python3" }, { "code": "plt.plot([0, one_count, total], [0, one_count, one_count], c = 'grey', linewidth = 2, label = 'Perfect Model')", "e": 31130, "s": 31011, "text": null }, { "code": null, "e": 31140, "s": 31130, "text": "Output : " }, { "code": null, "e": 31358, "s": 31140, "text": "Explanation: A perfect model finds positive outcomes in the same number of tries as the number of positive outcomes. We have total of 41 positive outcomes in our dataset and so at exactly 41, the maximum is achieved. " }, { "code": null, "e": 31883, "s": 31358, "text": "In any case, our classifier algorithm should not produce a line that lies under the random line. It is considered to be a really bad model in that case. Since the plotted classifier line is close to the ideal line we can say that our model is a really good fit. Take the area under the perfect plot and call it aP. Take the area under the prediction model and call it aR. Then take the ratio as aR/aP. This ratio is called the Accuracy Rate. The closer is the value to 1, the better the model. This is one way to analyze it." }, { "code": null, "e": 32075, "s": 31883, "text": "Another way to analyze it would be to project a line from about 50% from the axis on the prediction model and project it on the y-axis. Let us say that we obtain the projection value as X%. " }, { "code": null, "e": 32358, "s": 32075, "text": "-> 60% : it is a really bad model\n-> 60%<X<70% : it is still a bad model but better than the first case obviously\n-> 70%<X<80% : it is a good model\n-> 80%<X<90% : it is a very good model\n-> 90%<X<100% : it is extraordinarily good and might be one of the overfitting cases." }, { "code": null, "e": 32434, "s": 32358, "text": "So according to this analysis, we can determine how accurate our model is. " }, { "code": null, "e": 32462, "s": 32434, "text": "Reference:- wikipedia.org " }, { "code": null, "e": 32475, "s": 32462, "text": "Akanksha_Rai" }, { "code": null, "e": 32491, "s": 32475, "text": "simranarora5sos" }, { "code": null, "e": 32508, "s": 32491, "text": "Machine Learning" }, { "code": null, "e": 32515, "s": 32508, "text": "Python" }, { "code": null, "e": 32532, "s": 32515, "text": "Machine Learning" }, { "code": null, "e": 32630, "s": 32532, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32653, "s": 32630, "text": "ML | Linear Regression" }, { "code": null, "e": 32676, "s": 32653, "text": "Reinforcement learning" }, { "code": null, "e": 32690, "s": 32676, "text": "Decision Tree" }, { "code": null, "e": 32730, "s": 32690, "text": "Activation functions in Neural Networks" }, { "code": null, "e": 32770, "s": 32730, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 32798, "s": 32770, "text": "Read JSON file using Python" }, { "code": null, "e": 32848, "s": 32798, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 32870, "s": 32848, "text": "Python map() function" } ]
Print the string by ignoring alternate occurrences of any character - GeeksforGeeks
20 May, 2021 Given a string of both uppercase and lowercase alphabets, the task is to print the string with alternate occurrences of any character dropped(including space and consider upper and lowercase as same).Examples: Input : It is a long day Dear. Output : It sa longdy ear. Print first I and then ignore next i. Similarly print first space then ignore next space. Input : Geeks for geeks Output : Geks fore Asked in: Microsoft As we have to print characters in an alternate manner, so start traversing the string and perform following two steps:- Increment the count of occurrence of current character in a hash table. Check if the count becomes odd, then print the current character, else not. C++ Java Python3 C# PHP Javascript // C++ program to print the string in given pattern#include <bits/stdc++.h>using namespace std; // Function to print the stringvoid printStringAlternate(string str){ unordered_map<char, int> occ; // Start traversing the string for (int i = 0; i < str.length(); i++) { // Convert uppercase to lowercase char temp = tolower(str[i]); // Increment occurrence count occ[temp]++; // If count is odd then print the character if (occ[temp] & 1) cout << str[i]; } cout << endl;} // Drivers codeint main(){ string str = "Geeks for geeks"; string str2 = "It is a long day Dear"; printStringAlternate(str); printStringAlternate(str2); return 0;} // Java program to print the string in given patternimport java.io.*; class GFG{ // Function to print the string static void printStringAlternate(String str) { int[] occ = new int[122]; // Convert uppercase to lowercase String s = str.toLowerCase(); // Start traversing the string for (int i = 0; i < str.length(); i++) { char temp = s.charAt(i); // Increment occurrence count occ[temp]++; // If count is odd then print the character if (occ[temp]%2 != 0) System.out.print(str.charAt(i)); } System.out.println(); } // driver program public static void main (String[] args) { String str1 = "Geeks for geeks"; String str2 = "It is a long day Dear"; printStringAlternate(str1); printStringAlternate(str2); }} // Contributed by Pramod Kumar # Python3 program to print the string# in given pattern # Function to print the stringdef printStringAlternate(string): occ = {} # Start traversing the string for i in range(0, len(string)): # Convert uppercase to lowercase temp = string[i].lower() # Increment occurrence count occ[temp] = occ.get(temp, 0) + 1 # If count is odd then print the character if occ[temp] & 1: print(string[i], end = "") print() # Driver codeif __name__ == "__main__": string = "Geeks for geeks" string2 = "It is a long day Dear" printStringAlternate(string) printStringAlternate(string2) # This code is contributed by Rituraj Jain // C# program to print the// string in given patternusing System; public class GFG { // Function to print the string static void printStringAlternate(String str) { int[] occ = new int[122]; // Convert uppercase to lowercase string s = str.ToLower(); // Start traversing the string for (int i = 0; i < str.Length; i++) { char temp = s[i]; // Increment occurrence count occ[temp]++; // If count is odd then print // the character if (occ[temp] % 2 != 0) Console.Write(str[i]); } Console.WriteLine(); } // Driver Code public static void Main () { string str1 = "Geeks for geeks"; string str2 = "It is a long day Dear"; printStringAlternate(str1); printStringAlternate(str2); }} // This code is contributed by Sam007. <?php// PHP program to print the string// in given pattern // Function to print the stringfunction printStringAlternate($str){ $occ = array(); // Convert uppercase to lowercase $s = strtolower($str); // Start traversing the string for ($i = 0; $i < strlen($str); $i++) { $temp = $s[$i]; // Increment occurrence count $occ[($temp)]++; // If count is odd // then print the character if ($occ[$temp] % 2 != 0) echo($str[$i]); } echo "\n";} // Driver Code$str1 = "Geeks for geeks";$str2 = "It is a long day Dear";printStringAlternate($str1);printStringAlternate($str2); // This code is contributed by Code_Mech.?> <script> // JavaScript program to print the // string in given pattern // Function to print the string function printStringAlternate(str) { let occ = new Array(122); occ.fill(0); // Convert uppercase to lowercase let s = str.toLowerCase(); // Start traversing the string for (let i = 0; i < str.length; i++) { let temp = s[i]; // Increment occurrence count occ[temp.charCodeAt()]++; // If count is odd then print // the character if (occ[temp.charCodeAt()] % 2 != 0) document.write(str[i]); } document.write("</br>"); } let str1 = "Geeks for geeks"; let str2 = "It is a long day Dear"; printStringAlternate(str1); printStringAlternate(str2); </script> Output: Geks fore It sa longdy ear This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Sam007 rituraj_jain Code_Mech suresh07 Microsoft Strings Microsoft Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check for Balanced Brackets in an expression (well-formedness) using Stack Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching Different methods to reverse a string in C/C++ Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++ Longest Palindromic Substring | Set 1 Caesar Cipher in Cryptography Check whether two strings are anagram of each other Top 50 String Coding Problems for Interviews
[ { "code": null, "e": 26495, "s": 26467, "text": "\n20 May, 2021" }, { "code": null, "e": 26707, "s": 26495, "text": "Given a string of both uppercase and lowercase alphabets, the task is to print the string with alternate occurrences of any character dropped(including space and consider upper and lowercase as same).Examples: " }, { "code": null, "e": 26901, "s": 26707, "text": "Input : It is a long day Dear.\nOutput : It sa longdy ear.\nPrint first I and then ignore next i.\nSimilarly print first space then \nignore next space.\n\n\nInput : Geeks for geeks\nOutput : Geks fore" }, { "code": null, "e": 26922, "s": 26901, "text": "Asked in: Microsoft " }, { "code": null, "e": 27044, "s": 26922, "text": "As we have to print characters in an alternate manner, so start traversing the string and perform following two steps:- " }, { "code": null, "e": 27116, "s": 27044, "text": "Increment the count of occurrence of current character in a hash table." }, { "code": null, "e": 27194, "s": 27116, "text": "Check if the count becomes odd, then print the current character, else not. " }, { "code": null, "e": 27200, "s": 27196, "text": "C++" }, { "code": null, "e": 27205, "s": 27200, "text": "Java" }, { "code": null, "e": 27213, "s": 27205, "text": "Python3" }, { "code": null, "e": 27216, "s": 27213, "text": "C#" }, { "code": null, "e": 27220, "s": 27216, "text": "PHP" }, { "code": null, "e": 27231, "s": 27220, "text": "Javascript" }, { "code": "// C++ program to print the string in given pattern#include <bits/stdc++.h>using namespace std; // Function to print the stringvoid printStringAlternate(string str){ unordered_map<char, int> occ; // Start traversing the string for (int i = 0; i < str.length(); i++) { // Convert uppercase to lowercase char temp = tolower(str[i]); // Increment occurrence count occ[temp]++; // If count is odd then print the character if (occ[temp] & 1) cout << str[i]; } cout << endl;} // Drivers codeint main(){ string str = \"Geeks for geeks\"; string str2 = \"It is a long day Dear\"; printStringAlternate(str); printStringAlternate(str2); return 0;}", "e": 27955, "s": 27231, "text": null }, { "code": "// Java program to print the string in given patternimport java.io.*; class GFG{ // Function to print the string static void printStringAlternate(String str) { int[] occ = new int[122]; // Convert uppercase to lowercase String s = str.toLowerCase(); // Start traversing the string for (int i = 0; i < str.length(); i++) { char temp = s.charAt(i); // Increment occurrence count occ[temp]++; // If count is odd then print the character if (occ[temp]%2 != 0) System.out.print(str.charAt(i)); } System.out.println(); } // driver program public static void main (String[] args) { String str1 = \"Geeks for geeks\"; String str2 = \"It is a long day Dear\"; printStringAlternate(str1); printStringAlternate(str2); }} // Contributed by Pramod Kumar", "e": 28903, "s": 27955, "text": null }, { "code": "# Python3 program to print the string# in given pattern # Function to print the stringdef printStringAlternate(string): occ = {} # Start traversing the string for i in range(0, len(string)): # Convert uppercase to lowercase temp = string[i].lower() # Increment occurrence count occ[temp] = occ.get(temp, 0) + 1 # If count is odd then print the character if occ[temp] & 1: print(string[i], end = \"\") print() # Driver codeif __name__ == \"__main__\": string = \"Geeks for geeks\" string2 = \"It is a long day Dear\" printStringAlternate(string) printStringAlternate(string2) # This code is contributed by Rituraj Jain", "e": 29598, "s": 28903, "text": null }, { "code": "// C# program to print the// string in given patternusing System; public class GFG { // Function to print the string static void printStringAlternate(String str) { int[] occ = new int[122]; // Convert uppercase to lowercase string s = str.ToLower(); // Start traversing the string for (int i = 0; i < str.Length; i++) { char temp = s[i]; // Increment occurrence count occ[temp]++; // If count is odd then print // the character if (occ[temp] % 2 != 0) Console.Write(str[i]); } Console.WriteLine(); } // Driver Code public static void Main () { string str1 = \"Geeks for geeks\"; string str2 = \"It is a long day Dear\"; printStringAlternate(str1); printStringAlternate(str2); }} // This code is contributed by Sam007.", "e": 30545, "s": 29598, "text": null }, { "code": "<?php// PHP program to print the string// in given pattern // Function to print the stringfunction printStringAlternate($str){ $occ = array(); // Convert uppercase to lowercase $s = strtolower($str); // Start traversing the string for ($i = 0; $i < strlen($str); $i++) { $temp = $s[$i]; // Increment occurrence count $occ[($temp)]++; // If count is odd // then print the character if ($occ[$temp] % 2 != 0) echo($str[$i]); } echo \"\\n\";} // Driver Code$str1 = \"Geeks for geeks\";$str2 = \"It is a long day Dear\";printStringAlternate($str1);printStringAlternate($str2); // This code is contributed by Code_Mech.?>", "e": 31249, "s": 30545, "text": null }, { "code": "<script> // JavaScript program to print the // string in given pattern // Function to print the string function printStringAlternate(str) { let occ = new Array(122); occ.fill(0); // Convert uppercase to lowercase let s = str.toLowerCase(); // Start traversing the string for (let i = 0; i < str.length; i++) { let temp = s[i]; // Increment occurrence count occ[temp.charCodeAt()]++; // If count is odd then print // the character if (occ[temp.charCodeAt()] % 2 != 0) document.write(str[i]); } document.write(\"</br>\"); } let str1 = \"Geeks for geeks\"; let str2 = \"It is a long day Dear\"; printStringAlternate(str1); printStringAlternate(str2); </script>", "e": 32128, "s": 31249, "text": null }, { "code": null, "e": 32138, "s": 32128, "text": "Output: " }, { "code": null, "e": 32165, "s": 32138, "text": "Geks fore\nIt sa longdy ear" }, { "code": null, "e": 32586, "s": 32165, "text": "This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 32593, "s": 32586, "text": "Sam007" }, { "code": null, "e": 32606, "s": 32593, "text": "rituraj_jain" }, { "code": null, "e": 32616, "s": 32606, "text": "Code_Mech" }, { "code": null, "e": 32625, "s": 32616, "text": "suresh07" }, { "code": null, "e": 32635, "s": 32625, "text": "Microsoft" }, { "code": null, "e": 32643, "s": 32635, "text": "Strings" }, { "code": null, "e": 32653, "s": 32643, "text": "Microsoft" }, { "code": null, "e": 32661, "s": 32653, "text": "Strings" }, { "code": null, "e": 32759, "s": 32661, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32834, "s": 32759, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 32891, "s": 32834, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 32927, "s": 32891, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 32974, "s": 32927, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 33027, "s": 32974, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 33063, "s": 33027, "text": "Convert string to char array in C++" }, { "code": null, "e": 33101, "s": 33063, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 33131, "s": 33101, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 33183, "s": 33131, "text": "Check whether two strings are anagram of each other" } ]
Python | Increment 1's in list based on pattern - GeeksforGeeks
30 Jul, 2019 Given a list of binary numbers 0 and 1, Write a Python program to transform the list in such a way that whenever 1 appears after the occurrence of a sequence of 0’s, increment it by n+1, where ‘n’ is the last increment. Examples: Input : [0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1] Output : [0, 1, 0, 0, 2, 2, 0, 0, 0, 3, 3, 3] Input : [1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1] Output : [1, 0, 2, 0, 0, 0, 3, 3, 0, 0, 4, 4, 4, 0, 5, 0, 6] Approach #1 : Naive Approach This is a naive approach to the given problem. It uses two variable ‘previous’ and ‘grp’ to store previously incremented number and to store the number of 1’s in a group. Now, using a for loop, increment 1’s accordingly. # Python3 program to increment 1's in # list based on pattern def transform(lst): previous = 0 grp = 0 for elem in lst: if elem and not previous: grp += 1 previous = elem yield (grp if elem else 0) # Driver codelst = [0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1]x = (transform(lst))res = []for i in range(0, len(lst)): res.append(next(x))print(res) [0, 1, 0, 0, 2, 2, 0, 0, 0, 3, 3, 3] Approach #2 : Using count, chain and groupby from itertools module.This is an efficient and more pythonic approach towards the given problem where we use count, chain and groupby from itertools module. # Python3 program to increment 1's in # list based on pattern from itertools import * def transform(lst): c = count(1) return list(chain(*[list(g) if k != 1 else [next(c)]*len(list(g)) for k, g in groupby(lst)])) # Driver codelst = [0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1]print(transform(lst)) [0, 1, 0, 0, 2, 2, 0, 0, 0, 3, 3, 3] ManasChhabra2 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25657, "s": 25629, "text": "\n30 Jul, 2019" }, { "code": null, "e": 25877, "s": 25657, "text": "Given a list of binary numbers 0 and 1, Write a Python program to transform the list in such a way that whenever 1 appears after the occurrence of a sequence of 0’s, increment it by n+1, where ‘n’ is the last increment." }, { "code": null, "e": 25887, "s": 25877, "text": "Examples:" }, { "code": null, "e": 26101, "s": 25887, "text": "Input : [0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1]\nOutput : [0, 1, 0, 0, 2, 2, 0, 0, 0, 3, 3, 3]\n\nInput : [1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1]\nOutput : [1, 0, 2, 0, 0, 0, 3, 3, 0, 0, 4, 4, 4, 0, 5, 0, 6]\n" }, { "code": null, "e": 26131, "s": 26101, "text": " Approach #1 : Naive Approach" }, { "code": null, "e": 26352, "s": 26131, "text": "This is a naive approach to the given problem. It uses two variable ‘previous’ and ‘grp’ to store previously incremented number and to store the number of 1’s in a group. Now, using a for loop, increment 1’s accordingly." }, { "code": "# Python3 program to increment 1's in # list based on pattern def transform(lst): previous = 0 grp = 0 for elem in lst: if elem and not previous: grp += 1 previous = elem yield (grp if elem else 0) # Driver codelst = [0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1]x = (transform(lst))res = []for i in range(0, len(lst)): res.append(next(x))print(res)", "e": 26750, "s": 26352, "text": null }, { "code": null, "e": 26788, "s": 26750, "text": "[0, 1, 0, 0, 2, 2, 0, 0, 0, 3, 3, 3]\n" }, { "code": null, "e": 26992, "s": 26790, "text": "Approach #2 : Using count, chain and groupby from itertools module.This is an efficient and more pythonic approach towards the given problem where we use count, chain and groupby from itertools module." }, { "code": "# Python3 program to increment 1's in # list based on pattern from itertools import * def transform(lst): c = count(1) return list(chain(*[list(g) if k != 1 else [next(c)]*len(list(g)) for k, g in groupby(lst)])) # Driver codelst = [0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1]print(transform(lst))", "e": 27305, "s": 26992, "text": null }, { "code": null, "e": 27343, "s": 27305, "text": "[0, 1, 0, 0, 2, 2, 0, 0, 0, 3, 3, 3]\n" }, { "code": null, "e": 27357, "s": 27343, "text": "ManasChhabra2" }, { "code": null, "e": 27378, "s": 27357, "text": "Python list-programs" }, { "code": null, "e": 27385, "s": 27378, "text": "Python" }, { "code": null, "e": 27401, "s": 27385, "text": "Python Programs" }, { "code": null, "e": 27499, "s": 27401, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27517, "s": 27499, "text": "Python Dictionary" }, { "code": null, "e": 27552, "s": 27517, "text": "Read a file line by line in Python" }, { "code": null, "e": 27584, "s": 27552, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27606, "s": 27584, "text": "Enumerate() in Python" }, { "code": null, "e": 27648, "s": 27606, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27691, "s": 27648, "text": "Python program to convert a list to string" }, { "code": null, "e": 27713, "s": 27691, "text": "Defaultdict in Python" }, { "code": null, "e": 27752, "s": 27713, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27798, "s": 27752, "text": "Python | Split string into list of characters" } ]
Tailwind CSS List Style Type - GeeksforGeeks
23 Mar, 2022 This class accepts lots of value in tailwind CSS in which all the properties are covered as in class form. It is the alternative to the CSS List Style Type property. This class specifies the appearance of the list item marker (such as a disc, character, or custom counter style) if the ‘list-style-image’ has the value ‘none’. List Style Type classes: list-none: No marker is shown in this mode. list-disc: This is the default value. The marker is a filled circle. list-decimal: A marker is a decimal number, beginning with 1. Syntax: <element class="List Style Type">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center mx-4 space-y-2"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS List Style Type Class</b> <div class="mx-24 bg-green-200 text-justify px-6"> <ul class="list-disc"> <li>Self learning</li> <li>Contribute at Open Source</li> <li>Gain Stack overflow respect</li> </ul> <br> <ol class="list-decimal"> <li>Self learning</li> <li>Contribute at Open Source</li> <li>Gain Stack overflow respect</li> </ol> <br> <ul class="list-none"> <li>Self learning</li> <li>Contribute at Open Source</li> <li>Gain Stack overflow respect</li> </ul> </div></body> </html> Output: List style type Tailwind CSS Tailwind-Typography CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to 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 ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 37385, "s": 37357, "text": "\n23 Mar, 2022" }, { "code": null, "e": 37712, "s": 37385, "text": "This class accepts lots of value in tailwind CSS in which all the properties are covered as in class form. It is the alternative to the CSS List Style Type property. This class specifies the appearance of the list item marker (such as a disc, character, or custom counter style) if the ‘list-style-image’ has the value ‘none’." }, { "code": null, "e": 37737, "s": 37712, "text": "List Style Type classes:" }, { "code": null, "e": 37781, "s": 37737, "text": "list-none: No marker is shown in this mode." }, { "code": null, "e": 37850, "s": 37781, "text": "list-disc: This is the default value. The marker is a filled circle." }, { "code": null, "e": 37912, "s": 37850, "text": "list-decimal: A marker is a decimal number, beginning with 1." }, { "code": null, "e": 37920, "s": 37912, "text": "Syntax:" }, { "code": null, "e": 37967, "s": 37920, "text": "<element class=\"List Style Type\">...</element>" }, { "code": null, "e": 37976, "s": 37967, "text": "Example:" }, { "code": null, "e": 37981, "s": 37976, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center mx-4 space-y-2\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS List Style Type Class</b> <div class=\"mx-24 bg-green-200 text-justify px-6\"> <ul class=\"list-disc\"> <li>Self learning</li> <li>Contribute at Open Source</li> <li>Gain Stack overflow respect</li> </ul> <br> <ol class=\"list-decimal\"> <li>Self learning</li> <li>Contribute at Open Source</li> <li>Gain Stack overflow respect</li> </ol> <br> <ul class=\"list-none\"> <li>Self learning</li> <li>Contribute at Open Source</li> <li>Gain Stack overflow respect</li> </ul> </div></body> </html> ", "e": 38924, "s": 37981, "text": null }, { "code": null, "e": 38932, "s": 38924, "text": "Output:" }, { "code": null, "e": 38956, "s": 38940, "text": "List style type" }, { "code": null, "e": 38969, "s": 38956, "text": "Tailwind CSS" }, { "code": null, "e": 38989, "s": 38969, "text": "Tailwind-Typography" }, { "code": null, "e": 38993, "s": 38989, "text": "CSS" }, { "code": null, "e": 39010, "s": 38993, "text": "Web Technologies" }, { "code": null, "e": 39108, "s": 39010, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39170, "s": 39108, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 39220, "s": 39170, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 39268, "s": 39220, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 39326, "s": 39268, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 39381, "s": 39326, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 39421, "s": 39381, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 39454, "s": 39421, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 39499, "s": 39454, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 39542, "s": 39499, "text": "How to fetch data from an API in ReactJS ?" } ]
Semantic-UI | Transition - GeeksforGeeks
22 Jun, 2021 Semantic UI is an open-source framework that provides transition animation which is usually used to move the page content in or out of the viewport. It uses jQuery and CSS to create nice user interfaces which are very similar to bootstrap. It has many elements for creating interactive webpages. Classes are used for styling different elements in the HTML page structure. Example: The following example shows how elements can be scaled in or out of the view. html <!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /></head> <body> <div style="margin-top: 100px" class="ui container"> <h2>Transitions</h2> <img class="ui image medium" src="https://media.geeksforgeeks.org/wp-content/uploads/20200612171552/image34.png" /> <button class="ui button"> Go out </button> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script> <script> $('button').click(function () { $('.image').transition('scale'); }) </script></body> </html> Output: Example: The following example demonstrates zoom in and zoom out transitions. html <!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /></head> <body> <div style="margin-top: 100px" class="ui container"> <h2>Transitions</h2> <img class="ui image medium" src="https://media.geeksforgeeks.org/wp-content/uploads/20200612171552/image34.png" /> <button class="ui button"> Zoom </button> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script> <script> $('button').click(function () { $('.image').transition('zoom'); }) </script></body> </html> Output: Example: The following example demonstrates fade transition. html <!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /></head> <body> <div style="margin-top: 100px" class="ui container"> <h2>Transitions</h2> <img class="ui image medium" src="https://media.geeksforgeeks.org/wp-content/uploads/20200612171552/image34.png" /> <br> <button class="ui button one">Fade</button> <button class="ui button up">Fade Up</button> <button class="ui button down">Fade Down</button> <button class="ui button left">Fade Left</button> <button class="ui button right">Fade Right</button> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script> <script> $('.one').click(function () { $('.image').transition('fade'); }) $('.up').click(function () { $('.image').transition('fade up'); }) $('.down').click(function () { $('.image').transition('fade down'); }) $('.left').click(function () { $('.image').transition('fade left'); }) $('.right').click(function () { $('.image').transition('fade right'); }) </script></body> </html> Output: Example: The following example demonstrates flip transition. html <!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /></head> <body> <div style="margin-top: 100px" class="ui container"> <h2>Transitions</h2> <img class="ui image medium" src="https://media.geeksforgeeks.org/wp-content/uploads/20200612171552/image34.png" /> <br> <button class="ui button hor"> Horizontal Flip </button> <button class="ui button ver"> Vertical Flip </button> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script> <script> $('.hor').click(function () { $('.image').transition('horizontal flip'); }) $('.ver').click(function () { $('.image').transition('vertical flip'); }) </script></body> </html> Output: Example: The following example demonstrates fly, swing, and slide transitions. html <!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /></head> <body> <div style="margin-top: 100px" class="ui container"> <h2>Transitions</h2> <img class="ui image medium" src="https://media.geeksforgeeks.org/wp-content/uploads/20200612171552/image34.png" /> <br> <button class="ui button fly">Fly Left</button> <button class="ui button swing">Swing Left</button> <button class="ui button slide">Slide Left</button> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script> <script> $('.fly').click(function () { $('.image').transition('fly left'); }) $('.swing').click(function () { $('.image').transition('swing left'); }) $('.slide').click(function () { $('.image').transition('slide left'); }) </script></body> </html> Output: You can use right, down and up also. Example: The following example demonstrates static animation. html <!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /></head> <body> <div style="margin-top: 100px" class="ui container"> <h2>Transitions</h2> <img class="ui image medium" src="https://media.geeksforgeeks.org/wp-content/uploads/20200612171552/image34.png" /> <br> <button class="ui button jiggle">Jiggle</button> <button class="ui button flash">Flash</button> <button class="ui button shake">Shake</button> <button class="ui button pulse">Pulse</button> <button class="ui button tada">Tada</button> <button class="ui button bounce">Bounce</button> <button class="ui button glow">Glow</button> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script> <script> $('.jiggle').click(function () { $('.image').transition('jiggle'); }) $('.flash').click(function () { $('.image').transition('flash'); }) $('.shake').click(function () { $('.image').transition('shake'); }) $('.pulse').click(function () { $('.image').transition('pulse'); }) $('.tada').click(function () { $('.image').transition('tada'); }) $('.bounce').click(function () { $('.image').transition('bounce'); }) $('.glow').click(function () { $('.image').transition('glow'); }) </script></body> </html> Output:se Akanksha_Rai simmytarika5 Semantic-UI 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": 40451, "s": 40423, "text": "\n22 Jun, 2021" }, { "code": null, "e": 40823, "s": 40451, "text": "Semantic UI is an open-source framework that provides transition animation which is usually used to move the page content in or out of the viewport. It uses jQuery and CSS to create nice user interfaces which are very similar to bootstrap. It has many elements for creating interactive webpages. Classes are used for styling different elements in the HTML page structure." }, { "code": null, "e": 40910, "s": 40823, "text": "Example: The following example shows how elements can be scaled in or out of the view." }, { "code": null, "e": 40915, "s": 40910, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /></head> <body> <div style=\"margin-top: 100px\" class=\"ui container\"> <h2>Transitions</h2> <img class=\"ui image medium\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200612171552/image34.png\" /> <button class=\"ui button\"> Go out </button> </div> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script> <script> $('button').click(function () { $('.image').transition('scale'); }) </script></body> </html>", "e": 41839, "s": 40915, "text": null }, { "code": null, "e": 41849, "s": 41839, "text": "Output: " }, { "code": null, "e": 41929, "s": 41851, "text": "Example: The following example demonstrates zoom in and zoom out transitions." }, { "code": null, "e": 41936, "s": 41931, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /></head> <body> <div style=\"margin-top: 100px\" class=\"ui container\"> <h2>Transitions</h2> <img class=\"ui image medium\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200612171552/image34.png\" /> <button class=\"ui button\"> Zoom </button> </div> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script> <script> $('button').click(function () { $('.image').transition('zoom'); }) </script></body> </html>", "e": 42870, "s": 41936, "text": null }, { "code": null, "e": 42880, "s": 42870, "text": "Output: " }, { "code": null, "e": 42943, "s": 42882, "text": "Example: The following example demonstrates fade transition." }, { "code": null, "e": 42950, "s": 42945, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /></head> <body> <div style=\"margin-top: 100px\" class=\"ui container\"> <h2>Transitions</h2> <img class=\"ui image medium\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200612171552/image34.png\" /> <br> <button class=\"ui button one\">Fade</button> <button class=\"ui button up\">Fade Up</button> <button class=\"ui button down\">Fade Down</button> <button class=\"ui button left\">Fade Left</button> <button class=\"ui button right\">Fade Right</button> </div> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script> <script> $('.one').click(function () { $('.image').transition('fade'); }) $('.up').click(function () { $('.image').transition('fade up'); }) $('.down').click(function () { $('.image').transition('fade down'); }) $('.left').click(function () { $('.image').transition('fade left'); }) $('.right').click(function () { $('.image').transition('fade right'); }) </script></body> </html>", "e": 44468, "s": 42950, "text": null }, { "code": null, "e": 44478, "s": 44468, "text": "Output: " }, { "code": null, "e": 44541, "s": 44480, "text": "Example: The following example demonstrates flip transition." }, { "code": null, "e": 44548, "s": 44543, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /></head> <body> <div style=\"margin-top: 100px\" class=\"ui container\"> <h2>Transitions</h2> <img class=\"ui image medium\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200612171552/image34.png\" /> <br> <button class=\"ui button hor\"> Horizontal Flip </button> <button class=\"ui button ver\"> Vertical Flip </button> </div> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script> <script> $('.hor').click(function () { $('.image').transition('horizontal flip'); }) $('.ver').click(function () { $('.image').transition('vertical flip'); }) </script></body> </html>", "e": 45685, "s": 44548, "text": null }, { "code": null, "e": 45695, "s": 45685, "text": "Output: " }, { "code": null, "e": 45776, "s": 45697, "text": "Example: The following example demonstrates fly, swing, and slide transitions." }, { "code": null, "e": 45783, "s": 45778, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /></head> <body> <div style=\"margin-top: 100px\" class=\"ui container\"> <h2>Transitions</h2> <img class=\"ui image medium\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200612171552/image34.png\" /> <br> <button class=\"ui button fly\">Fly Left</button> <button class=\"ui button swing\">Swing Left</button> <button class=\"ui button slide\">Slide Left</button> </div> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script> <script> $('.fly').click(function () { $('.image').transition('fly left'); }) $('.swing').click(function () { $('.image').transition('swing left'); }) $('.slide').click(function () { $('.image').transition('slide left'); }) </script></body> </html>", "e": 47003, "s": 45783, "text": null }, { "code": null, "e": 47013, "s": 47003, "text": "Output: " }, { "code": null, "e": 47052, "s": 47015, "text": "You can use right, down and up also." }, { "code": null, "e": 47116, "s": 47054, "text": "Example: The following example demonstrates static animation." }, { "code": null, "e": 47123, "s": 47118, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /></head> <body> <div style=\"margin-top: 100px\" class=\"ui container\"> <h2>Transitions</h2> <img class=\"ui image medium\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200612171552/image34.png\" /> <br> <button class=\"ui button jiggle\">Jiggle</button> <button class=\"ui button flash\">Flash</button> <button class=\"ui button shake\">Shake</button> <button class=\"ui button pulse\">Pulse</button> <button class=\"ui button tada\">Tada</button> <button class=\"ui button bounce\">Bounce</button> <button class=\"ui button glow\">Glow</button> </div> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script> <script> $('.jiggle').click(function () { $('.image').transition('jiggle'); }) $('.flash').click(function () { $('.image').transition('flash'); }) $('.shake').click(function () { $('.image').transition('shake'); }) $('.pulse').click(function () { $('.image').transition('pulse'); }) $('.tada').click(function () { $('.image').transition('tada'); }) $('.bounce').click(function () { $('.image').transition('bounce'); }) $('.glow').click(function () { $('.image').transition('glow'); }) </script></body> </html>", "e": 48925, "s": 47123, "text": null }, { "code": null, "e": 48937, "s": 48925, "text": "Output:se " }, { "code": null, "e": 48952, "s": 48939, "text": "Akanksha_Rai" }, { "code": null, "e": 48965, "s": 48952, "text": "simmytarika5" }, { "code": null, "e": 48977, "s": 48965, "text": "Semantic-UI" }, { "code": null, "e": 48981, "s": 48977, "text": "CSS" }, { "code": null, "e": 48998, "s": 48981, "text": "Web Technologies" }, { "code": null, "e": 49096, "s": 48998, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 49146, "s": 49096, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 49208, "s": 49146, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 49256, "s": 49208, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 49314, "s": 49256, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 49369, "s": 49314, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 49409, "s": 49369, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 49442, "s": 49409, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 49487, "s": 49442, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 49530, "s": 49487, "text": "How to fetch data from an API in ReactJS ?" } ]
Ways to Re-run Last Executed Commands in Linux - GeeksforGeeks
30 Jun, 2021 It would be quite efficient to re-execute the last command. If the command was quite big to type in again, this would be quite a great trick to improve efficiency. So let us see what the commands are to run the last executed command again in the Linux terminal. The ways to run the last executed command are as follows: Ctrl + PUp Arrow key.bang-bang operator. Nth bang operator.fc command. Ctrl + P Up Arrow key. bang-bang operator. Nth bang operator. fc command. This is the most dependable shortcut in Linux to execute the last run command in the terminal. Just press the Ctrl and P keys together to fill the prompt with the last executed command and you are ready to go. This method works in bash perfectly even after closing the terminal, but it might not work in zsh after closing the session. But still, it is quite more reliable than other methods. Gif to demonstrate the usage of CTRL+ P The above GIF demonstrates the usage of CTRL + P to run the last executed command in Linux. In that example, the cat command was used before and CTRL + P was used to run it again. If the command was quite big, then CTRL + P becomes very useful. Simply works most of the time, using arrow keys is the most popular way to search through previous commands. This is the most known and used a keyboard shortcut to run the previous commands. The usage It’s quite straightforward to use the up arrow key to search through the previously executed command. Demonstrating usage of upArrow to re-run the last executed command. Double bang or !! is also one of the ways where you can run the last command. It is also known as the bang-bang command, which repeats the previously executed command as previously mentioned. !! Using bang bang to re-run the last executed command. The above screencast is a demonstration of using the bang-bang operator to run the last executed command. This doesn’t give a clear command to the user if he/she doesn’t have the idea of the previously executed command. You cannot even edit the command before executing it, so choose this only if you are sure. The single band operator is followed by the number, which tells it which previous command it would run. For running the last command, we use !-1, indicating the last command, if we use !-2, we will run the second-last command and so forth. The bang operator searches for commands from the shell history and executes as the mentioned number accordingly. !-1 Using a bang operator to re-run the last executed command. In this command, you cannot make changes like previous commands like CTRL + P and up arrow key, you cannot even view the command before pressing enter, just like the bang-bang command. Use this only if you are confident about the last executed command. Though we also have a bit of freedom to choose from if we use ! before any command such as !source, it will run the last executed command with the first match only and not in the embedded command. FC is a program built-in certain popular shells to work with the previously executed commands. We can use it for executing the last command very easily by just entering a flag or argument into it. fc -s By adding in -s, we can easily execute the last run command. Using fc -s to re-run the last executed command. Quite similar to the bang commands, it doesn’t show the command we might be executing. So we have to be sure about the command we are looking for. The above screencast shows the usage of fc with -s to re-run the last executed commands. linux-command Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples Docker - COPY Instruction mv command in Linux with examples SED command in Linux | Set 2 chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 25677, "s": 25649, "text": "\n30 Jun, 2021" }, { "code": null, "e": 25997, "s": 25677, "text": "It would be quite efficient to re-execute the last command. If the command was quite big to type in again, this would be quite a great trick to improve efficiency. So let us see what the commands are to run the last executed command again in the Linux terminal. The ways to run the last executed command are as follows:" }, { "code": null, "e": 26068, "s": 25997, "text": "Ctrl + PUp Arrow key.bang-bang operator. Nth bang operator.fc command." }, { "code": null, "e": 26077, "s": 26068, "text": "Ctrl + P" }, { "code": null, "e": 26091, "s": 26077, "text": "Up Arrow key." }, { "code": null, "e": 26111, "s": 26091, "text": "bang-bang operator." }, { "code": null, "e": 26131, "s": 26111, "text": " Nth bang operator." }, { "code": null, "e": 26143, "s": 26131, "text": "fc command." }, { "code": null, "e": 26535, "s": 26143, "text": "This is the most dependable shortcut in Linux to execute the last run command in the terminal. Just press the Ctrl and P keys together to fill the prompt with the last executed command and you are ready to go. This method works in bash perfectly even after closing the terminal, but it might not work in zsh after closing the session. But still, it is quite more reliable than other methods." }, { "code": null, "e": 26575, "s": 26535, "text": "Gif to demonstrate the usage of CTRL+ P" }, { "code": null, "e": 26821, "s": 26575, "text": "The above GIF demonstrates the usage of CTRL + P to run the last executed command in Linux. In that example, the cat command was used before and CTRL + P was used to run it again. If the command was quite big, then CTRL + P becomes very useful." }, { "code": null, "e": 27124, "s": 26821, "text": "Simply works most of the time, using arrow keys is the most popular way to search through previous commands. This is the most known and used a keyboard shortcut to run the previous commands. The usage It’s quite straightforward to use the up arrow key to search through the previously executed command." }, { "code": null, "e": 27192, "s": 27124, "text": "Demonstrating usage of upArrow to re-run the last executed command." }, { "code": null, "e": 27384, "s": 27192, "text": "Double bang or !! is also one of the ways where you can run the last command. It is also known as the bang-bang command, which repeats the previously executed command as previously mentioned." }, { "code": null, "e": 27387, "s": 27384, "text": "!!" }, { "code": null, "e": 27440, "s": 27387, "text": "Using bang bang to re-run the last executed command." }, { "code": null, "e": 27752, "s": 27440, "text": "The above screencast is a demonstration of using the bang-bang operator to run the last executed command. This doesn’t give a clear command to the user if he/she doesn’t have the idea of the previously executed command. You cannot even edit the command before executing it, so choose this only if you are sure." }, { "code": null, "e": 28105, "s": 27752, "text": "The single band operator is followed by the number, which tells it which previous command it would run. For running the last command, we use !-1, indicating the last command, if we use !-2, we will run the second-last command and so forth. The bang operator searches for commands from the shell history and executes as the mentioned number accordingly." }, { "code": null, "e": 28110, "s": 28105, "text": "!-1 " }, { "code": null, "e": 28169, "s": 28110, "text": "Using a bang operator to re-run the last executed command." }, { "code": null, "e": 28422, "s": 28169, "text": "In this command, you cannot make changes like previous commands like CTRL + P and up arrow key, you cannot even view the command before pressing enter, just like the bang-bang command. Use this only if you are confident about the last executed command." }, { "code": null, "e": 28619, "s": 28422, "text": "Though we also have a bit of freedom to choose from if we use ! before any command such as !source, it will run the last executed command with the first match only and not in the embedded command." }, { "code": null, "e": 28816, "s": 28619, "text": "FC is a program built-in certain popular shells to work with the previously executed commands. We can use it for executing the last command very easily by just entering a flag or argument into it." }, { "code": null, "e": 28822, "s": 28816, "text": "fc -s" }, { "code": null, "e": 28884, "s": 28822, "text": "By adding in -s, we can easily execute the last run command. " }, { "code": null, "e": 28933, "s": 28884, "text": "Using fc -s to re-run the last executed command." }, { "code": null, "e": 29170, "s": 28933, "text": "Quite similar to the bang commands, it doesn’t show the command we might be executing. So we have to be sure about the command we are looking for. The above screencast shows the usage of fc with -s to re-run the last executed commands. " }, { "code": null, "e": 29184, "s": 29170, "text": "linux-command" }, { "code": null, "e": 29191, "s": 29184, "text": "Picked" }, { "code": null, "e": 29202, "s": 29191, "text": "Linux-Unix" }, { "code": null, "e": 29300, "s": 29202, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29335, "s": 29300, "text": "scp command in Linux with Examples" }, { "code": null, "e": 29361, "s": 29335, "text": "Docker - COPY Instruction" }, { "code": null, "e": 29395, "s": 29361, "text": "mv command in Linux with examples" }, { "code": null, "e": 29424, "s": 29395, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 29461, "s": 29424, "text": "chown command in Linux with Examples" }, { "code": null, "e": 29498, "s": 29461, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 29540, "s": 29498, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 29566, "s": 29540, "text": "Thread functions in C/C++" }, { "code": null, "e": 29602, "s": 29566, "text": "uniq Command in LINUX with examples" } ]
Create an Expandable Notification Containing a Picture in Android - GeeksforGeeks
01 Sep, 2020 Notification is a type of message that is generated by any application present inside the mobile phone, suggesting to check the application and this could be anything from an update (Low priority notification) to something that’s not going right in the application (High priority notification). A basic notification consists of a title, a line of text, and one or more actions the user can perform in response. To provide even more information, one can also create large, expandable notifications by applying one of several notification templates as described in this article. Some daily life examples could be the notifications appended by Whatsapp, Gmail, SMS, etc in the notification drawer, where the user can expand it and can find some details about the message received such as sender name, subject and some part of the text in case of Gmail. In this article let’s create a notification inside an application that contains a picture. Step 1: Create a new project To create a new project in android studio please refer to How to Create/Start a New Project in Android Studio. Step 2: Modify activity_main.xml file Inside the XML file just add a button, which on click would build an expandable notification. By expanding the notification from the notification drawer would display a picture. activity_main.xml <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="click" android:layout_centerInParent="true"/> </RelativeLayout> Step 3: Modify the MainActivity file Now, look at the code below which is in Kotlin. To start, build a notification with all the basic content as described in Create a Notification. Then, call setStyle() with a style object and supply information corresponding to each template, as shown below. MainActivity.kt package com.example.expandablenotification import android.app.*import android.content.Contextimport android.content.Intentimport android.graphics.BitmapFactoryimport android.graphics.Colorimport android.os.Buildimport android.os.Bundleimport android.widget.Buttonimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { // Assigning variables to Notification Manager, Channel and Builder lateinit var notifManager: NotificationManager lateinit var notifChannel: NotificationChannel lateinit var notifBuilder: Notification.Builder // Evaluating ChannelID and Description for the Custom Notification private val description = "Some Description" private val channelID = "Some Channel ID" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring the button which onclick generates a notification val btn = findViewById<Button>(R.id.btn) // Notification Service for the Manager notifManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager // Notifications are in the form of Intents val someintent = Intent(this, LauncherActivity::class.java) val pendingIntent = PendingIntent.getActivity( this, 0, someintent, PendingIntent.FLAG_UPDATE_CURRENT ) // Idea is to click the button and the notification appears btn.setOnClickListener { // This is how an Image to be displayed in our Notification // is decoded and stored in a variable. I've added a picture // named "download.jpeg" in the "Drawables". val myBitmap = BitmapFactory.decodeResource(resources, R.drawable.download) // If Min. API level of the phone is 26, then notification could be // made asthetic if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { notifChannel = NotificationChannel( channelID, description, NotificationManager.IMPORTANCE_HIGH ) notifChannel.enableLights(true) notifChannel.lightColor = Color.RED notifChannel.enableVibration(true) notifManager.createNotificationChannel(notifChannel) notifBuilder = Notification.Builder(this, channelID) .setContentTitle("Some Title") .setContentText("Some Content Text") .setSmallIcon(R.mipmap.ic_launcher_round) // Command to Insert Image in the Notification .setStyle( Notification.BigPictureStyle() // <---- Look here .bigPicture(myBitmap) ) // <---- Look here .setContentIntent(pendingIntent) } // Else the Android device would give out default UI attributes else { notifBuilder = Notification.Builder(this) .setContentTitle("Some Title") .setContentText("Some Content Text") .setContentIntent(pendingIntent) } // Everything is done now and the Manager is to be notified about // the Builder which built a Notification for the application notifManager.notify(1234, notifBuilder.build()) } }} Note: If you have previously searched for the code for expandable notifications, then you must have seen this particular line of code: “.setStyle(NotificationCompat.BigPictureStyle().bigPicture(myBitmap)” As “NotificationCompat” is currently deprecated and your code would always crash whenever an attempt is made to build a notification (on button click in our case). Instead, just use “Notification”. android Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Android Project folder Structure Broadcast Receiver in Android With Example Different Ways to Change the Project Name in Android Studio Fix “SDK tools directory is missing” Error in Android Studio How to Retrieve Data from the Firebase Realtime Database in Android? Android UI Layouts Broadcast Receiver in Android With Example Content Providers in Android with Example Kotlin Hashmap How to Change the Color of Status Bar in an Android App?
[ { "code": null, "e": 26803, "s": 26775, "text": "\n01 Sep, 2020" }, { "code": null, "e": 27744, "s": 26803, "text": "Notification is a type of message that is generated by any application present inside the mobile phone, suggesting to check the application and this could be anything from an update (Low priority notification) to something that’s not going right in the application (High priority notification). A basic notification consists of a title, a line of text, and one or more actions the user can perform in response. To provide even more information, one can also create large, expandable notifications by applying one of several notification templates as described in this article. Some daily life examples could be the notifications appended by Whatsapp, Gmail, SMS, etc in the notification drawer, where the user can expand it and can find some details about the message received such as sender name, subject and some part of the text in case of Gmail. In this article let’s create a notification inside an application that contains a picture." }, { "code": null, "e": 27774, "s": 27744, "text": "Step 1: Create a new project " }, { "code": null, "e": 27885, "s": 27774, "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": 27923, "s": 27885, "text": "Step 2: Modify activity_main.xml file" }, { "code": null, "e": 28101, "s": 27923, "text": "Inside the XML file just add a button, which on click would build an expandable notification. By expanding the notification from the notification drawer would display a picture." }, { "code": null, "e": 28119, "s": 28101, "text": "activity_main.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/btn\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"click\" android:layout_centerInParent=\"true\"/> </RelativeLayout>", "e": 28675, "s": 28119, "text": null }, { "code": null, "e": 28712, "s": 28675, "text": "Step 3: Modify the MainActivity file" }, { "code": null, "e": 28970, "s": 28712, "text": "Now, look at the code below which is in Kotlin. To start, build a notification with all the basic content as described in Create a Notification. Then, call setStyle() with a style object and supply information corresponding to each template, as shown below." }, { "code": null, "e": 28986, "s": 28970, "text": "MainActivity.kt" }, { "code": "package com.example.expandablenotification import android.app.*import android.content.Contextimport android.content.Intentimport android.graphics.BitmapFactoryimport android.graphics.Colorimport android.os.Buildimport android.os.Bundleimport android.widget.Buttonimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { // Assigning variables to Notification Manager, Channel and Builder lateinit var notifManager: NotificationManager lateinit var notifChannel: NotificationChannel lateinit var notifBuilder: Notification.Builder // Evaluating ChannelID and Description for the Custom Notification private val description = \"Some Description\" private val channelID = \"Some Channel ID\" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring the button which onclick generates a notification val btn = findViewById<Button>(R.id.btn) // Notification Service for the Manager notifManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager // Notifications are in the form of Intents val someintent = Intent(this, LauncherActivity::class.java) val pendingIntent = PendingIntent.getActivity( this, 0, someintent, PendingIntent.FLAG_UPDATE_CURRENT ) // Idea is to click the button and the notification appears btn.setOnClickListener { // This is how an Image to be displayed in our Notification // is decoded and stored in a variable. I've added a picture // named \"download.jpeg\" in the \"Drawables\". val myBitmap = BitmapFactory.decodeResource(resources, R.drawable.download) // If Min. API level of the phone is 26, then notification could be // made asthetic if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { notifChannel = NotificationChannel( channelID, description, NotificationManager.IMPORTANCE_HIGH ) notifChannel.enableLights(true) notifChannel.lightColor = Color.RED notifChannel.enableVibration(true) notifManager.createNotificationChannel(notifChannel) notifBuilder = Notification.Builder(this, channelID) .setContentTitle(\"Some Title\") .setContentText(\"Some Content Text\") .setSmallIcon(R.mipmap.ic_launcher_round) // Command to Insert Image in the Notification .setStyle( Notification.BigPictureStyle() // <---- Look here .bigPicture(myBitmap) ) // <---- Look here .setContentIntent(pendingIntent) } // Else the Android device would give out default UI attributes else { notifBuilder = Notification.Builder(this) .setContentTitle(\"Some Title\") .setContentText(\"Some Content Text\") .setContentIntent(pendingIntent) } // Everything is done now and the Manager is to be notified about // the Builder which built a Notification for the application notifManager.notify(1234, notifBuilder.build()) } }}", "e": 32524, "s": 28986, "text": null }, { "code": null, "e": 32659, "s": 32524, "text": "Note: If you have previously searched for the code for expandable notifications, then you must have seen this particular line of code:" }, { "code": null, "e": 32730, "s": 32659, "text": " “.setStyle(NotificationCompat.BigPictureStyle().bigPicture(myBitmap)”" }, { "code": null, "e": 32928, "s": 32730, "text": "As “NotificationCompat” is currently deprecated and your code would always crash whenever an attempt is made to build a notification (on button click in our case). Instead, just use “Notification”." }, { "code": null, "e": 32936, "s": 32928, "text": "android" }, { "code": null, "e": 32944, "s": 32936, "text": "Android" }, { "code": null, "e": 32951, "s": 32944, "text": "Kotlin" }, { "code": null, "e": 32959, "s": 32951, "text": "Android" }, { "code": null, "e": 33057, "s": 32959, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33090, "s": 33057, "text": "Android Project folder Structure" }, { "code": null, "e": 33133, "s": 33090, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 33193, "s": 33133, "text": "Different Ways to Change the Project Name in Android Studio" }, { "code": null, "e": 33254, "s": 33193, "text": "Fix “SDK tools directory is missing” Error in Android Studio" }, { "code": null, "e": 33323, "s": 33254, "text": "How to Retrieve Data from the Firebase Realtime Database in Android?" }, { "code": null, "e": 33342, "s": 33323, "text": "Android UI Layouts" }, { "code": null, "e": 33385, "s": 33342, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 33427, "s": 33385, "text": "Content Providers in Android with Example" }, { "code": null, "e": 33442, "s": 33427, "text": "Kotlin Hashmap" } ]
MathF.Pow() Method in C# with Examples - GeeksforGeeks
04 Apr, 2019 In C#, MathF.Pow(Single, Single) is a MathF class method. This method is used to calculate a number raise to the power of some other number. Syntax: public static float Pow (float x, float y); Parameters:x: It is a single-precision floating-point number which is to be raised to a power and type of this parameter is System.Single.y: It is a single-precision floating-point number which specifies a power or exponent and type of this parameter is System.Single. Return Type: The function returns the number base raised to the power. The return type of this method is System.Single Example: // C# program to illustrate the// MathF.Pow(Single, Single) Methodusing System; class GFG { // Main Method static public void Main() { // Find power using MathF.Pow // 8 is base and 4 is power or // index or exponent of a number float pow_ab = MathF.Pow(8f, 4f); // Print the result Console.WriteLine(pow_ab); // 7.5 is base and 2 is power or // index or exponent of a number float pow_tt = MathF.Pow(7.5f, 2f); // Print the result Console.WriteLine(pow_tt); // 1234 is base and 7 is power or // index or exponent of a number float pow_t = MathF.Pow(1234f, 7f); // Print the result Console.WriteLine(pow_t); }} 4096 56.25 4.357186E+21 CSharp-MathF-Class CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | Class and Object C# | Constructors C# | String.IndexOf( ) Method | Set - 1 C# | Replace() Method
[ { "code": null, "e": 25671, "s": 25643, "text": "\n04 Apr, 2019" }, { "code": null, "e": 25812, "s": 25671, "text": "In C#, MathF.Pow(Single, Single) is a MathF class method. This method is used to calculate a number raise to the power of some other number." }, { "code": null, "e": 25864, "s": 25812, "text": "Syntax: public static float Pow (float x, float y);" }, { "code": null, "e": 26133, "s": 25864, "text": "Parameters:x: It is a single-precision floating-point number which is to be raised to a power and type of this parameter is System.Single.y: It is a single-precision floating-point number which specifies a power or exponent and type of this parameter is System.Single." }, { "code": null, "e": 26252, "s": 26133, "text": "Return Type: The function returns the number base raised to the power. The return type of this method is System.Single" }, { "code": null, "e": 26261, "s": 26252, "text": "Example:" }, { "code": "// C# program to illustrate the// MathF.Pow(Single, Single) Methodusing System; class GFG { // Main Method static public void Main() { // Find power using MathF.Pow // 8 is base and 4 is power or // index or exponent of a number float pow_ab = MathF.Pow(8f, 4f); // Print the result Console.WriteLine(pow_ab); // 7.5 is base and 2 is power or // index or exponent of a number float pow_tt = MathF.Pow(7.5f, 2f); // Print the result Console.WriteLine(pow_tt); // 1234 is base and 7 is power or // index or exponent of a number float pow_t = MathF.Pow(1234f, 7f); // Print the result Console.WriteLine(pow_t); }}", "e": 27011, "s": 26261, "text": null }, { "code": null, "e": 27036, "s": 27011, "text": "4096\n56.25\n4.357186E+21\n" }, { "code": null, "e": 27055, "s": 27036, "text": "CSharp-MathF-Class" }, { "code": null, "e": 27069, "s": 27055, "text": "CSharp-method" }, { "code": null, "e": 27072, "s": 27069, "text": "C#" }, { "code": null, "e": 27170, "s": 27072, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27198, "s": 27170, "text": "C# Dictionary with examples" }, { "code": null, "e": 27213, "s": 27198, "text": "C# | Delegates" }, { "code": null, "e": 27236, "s": 27213, "text": "C# | Method Overriding" }, { "code": null, "e": 27258, "s": 27236, "text": "C# | Abstract Classes" }, { "code": null, "e": 27304, "s": 27258, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 27327, "s": 27304, "text": "Extension Method in C#" }, { "code": null, "e": 27349, "s": 27327, "text": "C# | Class and Object" }, { "code": null, "e": 27367, "s": 27349, "text": "C# | Constructors" }, { "code": null, "e": 27407, "s": 27367, "text": "C# | String.IndexOf( ) Method | Set - 1" } ]
Count numbers with same first and last digits in C++
We are given an interval [first, last]. The goal is to find the count of numbers that have the same first and last digit within this interval. For example, 232 has the same first and last digit as 2. We will do this by traversing from i=first to i=last. For each number I compare its first digit with the last digit, if they are the same increment the count. Let’s understand with examples. Input − first=8 last=40 Output − Count of numbers with same first and last digits − 5 Explanation − Numbers between 8 and 40 with same first and last digit − 8, 9, 11, 22, 33 Input − first=100 last=200 Output − Count of numbers with same first and last digits: 5 Explanation − Numbers between 100 and 200 with same first and last digit − 101, 111, 121, 131, 141, 151, 161, 171, 181, 191. We take two integers first and last to define range [first,last]. We take two integers first and last to define range [first,last]. Function getFirstDigit(int num) takes a number and returns its first digit. Function getFirstDigit(int num) takes a number and returns its first digit. While num>=10, divide num by 10. In the end num will have the first digit. Return this value. While num>=10, divide num by 10. In the end num will have the first digit. Return this value. Function getCount(int fst,int lst) takes range variables and returns the count of numbers with the same first and last digits. Function getCount(int fst,int lst) takes range variables and returns the count of numbers with the same first and last digits. Take the initial count as 0. Take the initial count as 0. Using for loop start from i=fst to i=lst, for each i calculate it first digit by calling getFirstDigit(i) and store in fdigit. (fdigit=getFirstDigit(i)). Using for loop start from i=fst to i=lst, for each i calculate it first digit by calling getFirstDigit(i) and store in fdigit. (fdigit=getFirstDigit(i)). Calculate last digit as ldigit=i%10. Calculate last digit as ldigit=i%10. If ldigit==fdigit, means they are the same. Increment count. If ldigit==fdigit, means they are the same. Increment count. Return count as result. Return count as result. Live Demo #include <bits/stdc++.h> using namespace std; //to find starting digit int getFirstDigit(int num){ while (num >= 10) { num = num/ 10; } return num; } int getCount(int fst,int lst){ int count=0; for(int i=fst;i<=lst;i++){ int fdigit=getFirstDigit(i); int ldigit=i%10; //to get last digit if(fdigit==ldigit) //if both are equal increment count { ++count; } } return count; } int main(){ int first = 10, last = 23; cout<<"Numbers with same first and last digits:"<<getCount(first, last); return 0; } If we run the above code it will generate the following output − Numbers with same first and last digits:2
[ { "code": null, "e": 1262, "s": 1062, "text": "We are given an interval [first, last]. The goal is to find the count of numbers that have the same first and last digit within this interval. For example, 232 has the same first and last digit as 2." }, { "code": null, "e": 1421, "s": 1262, "text": "We will do this by traversing from i=first to i=last. For each number I compare its first digit with the last digit, if they are the same increment the count." }, { "code": null, "e": 1453, "s": 1421, "text": "Let’s understand with examples." }, { "code": null, "e": 1477, "s": 1453, "text": "Input − first=8 last=40" }, { "code": null, "e": 1539, "s": 1477, "text": "Output − Count of numbers with same first and last digits − 5" }, { "code": null, "e": 1611, "s": 1539, "text": "Explanation − Numbers between 8 and 40 with same first and last digit −" }, { "code": null, "e": 1628, "s": 1611, "text": "8, 9, 11, 22, 33" }, { "code": null, "e": 1655, "s": 1628, "text": "Input − first=100 last=200" }, { "code": null, "e": 1716, "s": 1655, "text": "Output − Count of numbers with same first and last digits: 5" }, { "code": null, "e": 1791, "s": 1716, "text": "Explanation − Numbers between 100 and 200 with same first and last digit −" }, { "code": null, "e": 1841, "s": 1791, "text": "101, 111, 121, 131, 141, 151, 161, 171, 181, 191." }, { "code": null, "e": 1907, "s": 1841, "text": "We take two integers first and last to define range [first,last]." }, { "code": null, "e": 1973, "s": 1907, "text": "We take two integers first and last to define range [first,last]." }, { "code": null, "e": 2049, "s": 1973, "text": "Function getFirstDigit(int num) takes a number and returns its first digit." }, { "code": null, "e": 2125, "s": 2049, "text": "Function getFirstDigit(int num) takes a number and returns its first digit." }, { "code": null, "e": 2219, "s": 2125, "text": "While num>=10, divide num by 10. In the end num will have the first digit. Return this value." }, { "code": null, "e": 2313, "s": 2219, "text": "While num>=10, divide num by 10. In the end num will have the first digit. Return this value." }, { "code": null, "e": 2440, "s": 2313, "text": "Function getCount(int fst,int lst) takes range variables and returns the count of numbers with the same first and last digits." }, { "code": null, "e": 2567, "s": 2440, "text": "Function getCount(int fst,int lst) takes range variables and returns the count of numbers with the same first and last digits." }, { "code": null, "e": 2596, "s": 2567, "text": "Take the initial count as 0." }, { "code": null, "e": 2625, "s": 2596, "text": "Take the initial count as 0." }, { "code": null, "e": 2779, "s": 2625, "text": "Using for loop start from i=fst to i=lst, for each i calculate it first digit by calling getFirstDigit(i) and store in fdigit. (fdigit=getFirstDigit(i))." }, { "code": null, "e": 2933, "s": 2779, "text": "Using for loop start from i=fst to i=lst, for each i calculate it first digit by calling getFirstDigit(i) and store in fdigit. (fdigit=getFirstDigit(i))." }, { "code": null, "e": 2970, "s": 2933, "text": "Calculate last digit as ldigit=i%10." }, { "code": null, "e": 3007, "s": 2970, "text": "Calculate last digit as ldigit=i%10." }, { "code": null, "e": 3068, "s": 3007, "text": "If ldigit==fdigit, means they are the same. Increment count." }, { "code": null, "e": 3129, "s": 3068, "text": "If ldigit==fdigit, means they are the same. Increment count." }, { "code": null, "e": 3153, "s": 3129, "text": "Return count as result." }, { "code": null, "e": 3177, "s": 3153, "text": "Return count as result." }, { "code": null, "e": 3188, "s": 3177, "text": " Live Demo" }, { "code": null, "e": 3745, "s": 3188, "text": "#include <bits/stdc++.h>\nusing namespace std;\n//to find starting digit\nint getFirstDigit(int num){\n while (num >= 10)\n { num = num/ 10; }\n return num;\n}\nint getCount(int fst,int lst){\n int count=0;\n for(int i=fst;i<=lst;i++){\n int fdigit=getFirstDigit(i);\n int ldigit=i%10; //to get last digit\n if(fdigit==ldigit) //if both are equal increment count\n { ++count; }\n }\n return count;\n}\nint main(){\n int first = 10, last = 23;\n cout<<\"Numbers with same first and last digits:\"<<getCount(first, last);\n return 0;\n}" }, { "code": null, "e": 3810, "s": 3745, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 3852, "s": 3810, "text": "Numbers with same first and last digits:2" } ]
C Language | Set 7 - GeeksforGeeks
27 Mar, 2017 Following questions have been asked in GATE CS 2010 exam. 1. What does the following program print? #include<stdio.h>void f(int *p, int *q){ p = q; *p = 2;}int i = 0, j = 1;int main(){ f(&i, &j); printf("%d %d \n", i, j); getchar(); return 0;} (A) 2 2(B) 2 1(C) 0 1(D) 0 2 Answer (D)See below f() with comments for explanation. /* p points to i and q points to j */void f(int *p, int *q){ p = q; /* p also points to j now */ *p = 2; /* Value of j is changed to 2 now */} 2. What is the value printed by the following C program? #include<stdio.h>int f(int *a, int n){ if(n <= 0) return 0; else if(*a % 2 == 0) return *a + f(a+1, n-1); else return *a - f(a+1, n-1);} int main(){ int a[] = {12, 7, 13, 4, 11, 6}; printf("%d", f(a, 6)); getchar(); return 0;} (A) -9(B) 5(C) 15(D) 19 Answer (C)f() is a recursive function which adds f(a+1, n-1) to *a if *a is even. If *a is odd then f() subtracts f(a+1, n-1) from *a. See below recursion tree for execution of f(a, 6).. f(add(12), 6) /*Since 12 is first element. a contains address of 12 */ | | 12 + f(add(7), 5) /* Since 7 is the next element, a+1 contains address of 7 */ | | 7 - f(add(13), 4) | | 13 - f(add(4), 3) | | 4 + f(add(11), 2) | | 11 - f(add(6), 1) | | 6 + 0 So, the final returned value is 12 + (7 – (13 – (4 + (11 – (6 + 0))))) = 15 Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc. Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above. GATE-CS-2010 GATE-CS-C-Language GATE CS MCQ Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between TCP and UDP Semaphores in Process Synchronization Inter Process Communication (IPC) Introduction of Operating System - Set 1 Data encryption standard (DES) | Set 1 Data Structures and Algorithms | Set 25 Operating Systems | Set 1 Practice questions on Height balanced/AVL Tree Computer Networks | Set 1 Computer Networks | Set 2
[ { "code": null, "e": 25315, "s": 25287, "text": "\n27 Mar, 2017" }, { "code": null, "e": 25373, "s": 25315, "text": "Following questions have been asked in GATE CS 2010 exam." }, { "code": null, "e": 25415, "s": 25373, "text": "1. What does the following program print?" }, { "code": "#include<stdio.h>void f(int *p, int *q){ p = q; *p = 2;}int i = 0, j = 1;int main(){ f(&i, &j); printf(\"%d %d \\n\", i, j); getchar(); return 0;}", "e": 25564, "s": 25415, "text": null }, { "code": null, "e": 25593, "s": 25564, "text": "(A) 2 2(B) 2 1(C) 0 1(D) 0 2" }, { "code": null, "e": 25648, "s": 25593, "text": "Answer (D)See below f() with comments for explanation." }, { "code": "/* p points to i and q points to j */void f(int *p, int *q){ p = q; /* p also points to j now */ *p = 2; /* Value of j is changed to 2 now */}", "e": 25797, "s": 25648, "text": null }, { "code": null, "e": 25854, "s": 25797, "text": "2. What is the value printed by the following C program?" }, { "code": "#include<stdio.h>int f(int *a, int n){ if(n <= 0) return 0; else if(*a % 2 == 0) return *a + f(a+1, n-1); else return *a - f(a+1, n-1);} int main(){ int a[] = {12, 7, 13, 4, 11, 6}; printf(\"%d\", f(a, 6)); getchar(); return 0;}", "e": 26089, "s": 25854, "text": null }, { "code": null, "e": 26113, "s": 26089, "text": "(A) -9(B) 5(C) 15(D) 19" }, { "code": null, "e": 26300, "s": 26113, "text": "Answer (C)f() is a recursive function which adds f(a+1, n-1) to *a if *a is even. If *a is odd then f() subtracts f(a+1, n-1) from *a. See below recursion tree for execution of f(a, 6).." }, { "code": null, "e": 26873, "s": 26300, "text": " f(add(12), 6) /*Since 12 is first element. a contains address of 12 */\n |\n |\n 12 + f(add(7), 5) /* Since 7 is the next element, a+1 contains address of 7 */\n |\n |\n 7 - f(add(13), 4)\n |\n |\n 13 - f(add(4), 3)\n |\n |\n 4 + f(add(11), 2)\n |\n |\n 11 - f(add(6), 1)\n |\n |\n 6 + 0\n" }, { "code": null, "e": 26949, "s": 26873, "text": "So, the final returned value is 12 + (7 – (13 – (4 + (11 – (6 + 0))))) = 15" }, { "code": null, "e": 27063, "s": 26949, "text": "Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc." }, { "code": null, "e": 27212, "s": 27063, "text": "Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above." }, { "code": null, "e": 27225, "s": 27212, "text": "GATE-CS-2010" }, { "code": null, "e": 27244, "s": 27225, "text": "GATE-CS-C-Language" }, { "code": null, "e": 27252, "s": 27244, "text": "GATE CS" }, { "code": null, "e": 27256, "s": 27252, "text": "MCQ" }, { "code": null, "e": 27354, "s": 27256, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27386, "s": 27354, "text": "Differences between TCP and UDP" }, { "code": null, "e": 27424, "s": 27386, "text": "Semaphores in Process Synchronization" }, { "code": null, "e": 27458, "s": 27424, "text": "Inter Process Communication (IPC)" }, { "code": null, "e": 27499, "s": 27458, "text": "Introduction of Operating System - Set 1" }, { "code": null, "e": 27538, "s": 27499, "text": "Data encryption standard (DES) | Set 1" }, { "code": null, "e": 27578, "s": 27538, "text": "Data Structures and Algorithms | Set 25" }, { "code": null, "e": 27604, "s": 27578, "text": "Operating Systems | Set 1" }, { "code": null, "e": 27651, "s": 27604, "text": "Practice questions on Height balanced/AVL Tree" }, { "code": null, "e": 27677, "s": 27651, "text": "Computer Networks | Set 1" } ]