title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Different ways to instantiate an object in C++ with Examples - GeeksforGeeks
27 Dec, 2021 prerequisite: C++ Classes and Objects Different Ways to Instantiate an Object In C++, there are different ways to instantiate an objects and one of the method is using Constructors. These are special class members which are called by the compiler every time an object of that class is instantiated. There are three different ways of instantiating an object through constructors: Through Default constructors.Through Parameterized constructors.Through Copy constructors. Through Default constructors. Through Parameterized constructors. Through Copy constructors. 1. Through Default Constructor: An object can be instantiated through a default constructor in either static way or dynamic way. Syntax: Automatic Storage Duration/ Static initialization classname objectname; Dynamic Storage Duration/ Dynamic Initialization classname *objectname = new classname(); Delete Dynamic Object delete objectname; Below is the C++ program to demonstrate the object instantiation through default constructor- C++14 // C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Defining class exampleclass example { int x; public: void set(int x) { this->x = x; cout << "The value of x is: " << x << "\n"; }}; // Driver codeint main(){ // Creating automatic storage object example obj1; obj1.set(5); // Creating dynamic storage object example* obj2 = new example(); obj2->set(10); // Explicitly deleting the obj2 delete obj2; return 0;} Explanation:In the above code, there are two types of different ways of instantiating an object- example obj1: This line is instantiating an object that has automatic storage duration. This object will be deleted automatically when it will be out of scope.example *obj2 = new example(): This is the way of instantiating an object that has dynamic storage duration. This object will not be deleted automatically. The user will have to use an explicit delete statement for deleting the object. example obj1: This line is instantiating an object that has automatic storage duration. This object will be deleted automatically when it will be out of scope. example *obj2 = new example(): This is the way of instantiating an object that has dynamic storage duration. This object will not be deleted automatically. The user will have to use an explicit delete statement for deleting the object. delete obj2; 2. Through Parameterized Constructor: Object instantiation can be done through parameterized constructor in static and dynamic way. It is possible to pass arguments to parameterized constructors. Typically, these arguments help initialize an object when it is created. Syntax: Static Initialization 1. classname objectname(parameter); 2. classname objectname = classname(parameter); Dynamic Initialization classname *objectname = new classname(parameter); Delete Dynamic Object delete objectname; Below is the C++ program to demonstrate the parameterized constructor- C++ // C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Defining the class exampleclass example { int x; public: // Parameterized constructor example(int y) { x = y; cout << "The value of x is: " << x << "\n"; }}; // Driver codeint main(){ // Creating object with automatic // storage duration using Method 1 example obj1(10); // Creating object with automatic // storage duration using Method 2 example obj2 = example(8); // Creating object with dynamic // storage duration using Method 3 example* obj3 = new example(20); delete obj3; return 0;} Explanation:In the above code, there are three ways of instantiating an object- example obj1(10): This line is instantiating an object using the parameterized constructor that has automatic storage duration. This object will be deleted automatically when it will be out of scope.example obj2 = example(8): This line is instantiating an object using the parameterized constructor that has automatic storage duration. This object will be deleted automatically when it will be out of scope.example *obj3 = new example(20): This is the way of instantiating an object using the parameterized constructor that has dynamic storage duration. This object will not be deleted automatically. The user will have to use an explicit delete statement for deleting the object. example obj1(10): This line is instantiating an object using the parameterized constructor that has automatic storage duration. This object will be deleted automatically when it will be out of scope. example obj2 = example(8): This line is instantiating an object using the parameterized constructor that has automatic storage duration. This object will be deleted automatically when it will be out of scope. example *obj3 = new example(20): This is the way of instantiating an object using the parameterized constructor that has dynamic storage duration. This object will not be deleted automatically. The user will have to use an explicit delete statement for deleting the object. 3. Copy constructor: A copy constructor can be used to instantiate an object statically or dynamically. Static or dynamic initialization of object using a copy constructor has the following general function prototype: Syntax: Copy Constructor ClassName (const ClassName &old_obj); Instantiate an object using copy constructor Static Initialization 1. classname obj1; classname obj2 = obj1; 2. classname obj1; classname obj2(obj1); Dynamic Initialization 1. classname *obj1 = new classname(); classname *obj2 = new classname(*obj1); Below is the C++ program to demonstrate the copy constructor- C++ // C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Defining the classclass example { int x; public: // Parameterized constructor example(int y) { x = y; cout << "The value of x is: " << x << "\n"; } // Copy constructor example(example& obj) { x = obj.x; cout << "The value of x in " << "copy constructor: " << x << "\n"; };}; // Driver codeint main(){ // Instantiating copy constructor // using Method 1 example obj1(4); example obj2 = obj1; // Instantiating copy constructor // using Method 2 example obj3(obj1); // Instantiating copy constructor // using Method 3 example* obj4 = new example(10); example* obj5 = new example(*obj4); delete obj5; delete obj4; return 0;} Explanation:In the above code, there are three ways of instantiating an object using a copy constructor- Method 1:example obj1(4): This line is instantiating an object that has automatic storage duration.example obj2 = obj1: This line is invoking copy constructor and creates a new object obj2 that is a copy of object obj1.Method 2:example obj3(obj1): This line is invoking copy constructor and creates a new object obj3 that is a copy of object obj1.Method 3:example *obj4 = new example(10): This is the way of instantiating an object that has dynamic storage duration. This object will not be deleted automatically. The user will have to use an explicit delete statement for deleting the object.example *obj5 = new example(*obj4): This line is invoking a copy constructor and creates a new object obj5 that is a copy of object obj4. The user will have to use an explicit delete statement for deleting the object. Method 1:example obj1(4): This line is instantiating an object that has automatic storage duration.example obj2 = obj1: This line is invoking copy constructor and creates a new object obj2 that is a copy of object obj1. example obj1(4): This line is instantiating an object that has automatic storage duration. example obj2 = obj1: This line is invoking copy constructor and creates a new object obj2 that is a copy of object obj1. Method 2:example obj3(obj1): This line is invoking copy constructor and creates a new object obj3 that is a copy of object obj1. example obj3(obj1): This line is invoking copy constructor and creates a new object obj3 that is a copy of object obj1. Method 3:example *obj4 = new example(10): This is the way of instantiating an object that has dynamic storage duration. This object will not be deleted automatically. The user will have to use an explicit delete statement for deleting the object.example *obj5 = new example(*obj4): This line is invoking a copy constructor and creates a new object obj5 that is a copy of object obj4. The user will have to use an explicit delete statement for deleting the object. example *obj4 = new example(10): This is the way of instantiating an object that has dynamic storage duration. This object will not be deleted automatically. The user will have to use an explicit delete statement for deleting the object. example *obj5 = new example(*obj4): This line is invoking a copy constructor and creates a new object obj5 that is a copy of object obj4. The user will have to use an explicit delete statement for deleting the object. sweetyty C++-Class and Object C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Iterators in C++ STL Operator Overloading in C++ Friend class and function in C++ Polymorphism in C++ Sorting a vector in C++ Inline Functions in C++ Convert string to char array in C++ List in C++ Standard Template Library (STL) std::string class in C++ Exception Handling in C++
[ { "code": null, "e": 24018, "s": 23990, "text": "\n27 Dec, 2021" }, { "code": null, "e": 24056, "s": 24018, "text": "prerequisite: C++ Classes and Objects" }, { "code": null, "e": 24096, "s": 24056, "text": "Different Ways to Instantiate an Object" }, { "code": null, "e": 24397, "s": 24096, "text": "In C++, there are different ways to instantiate an objects and one of the method is using Constructors. These are special class members which are called by the compiler every time an object of that class is instantiated. There are three different ways of instantiating an object through constructors:" }, { "code": null, "e": 24488, "s": 24397, "text": "Through Default constructors.Through Parameterized constructors.Through Copy constructors." }, { "code": null, "e": 24518, "s": 24488, "text": "Through Default constructors." }, { "code": null, "e": 24554, "s": 24518, "text": "Through Parameterized constructors." }, { "code": null, "e": 24581, "s": 24554, "text": "Through Copy constructors." }, { "code": null, "e": 24711, "s": 24581, "text": "1. Through Default Constructor: An object can be instantiated through a default constructor in either static way or dynamic way. " }, { "code": null, "e": 24719, "s": 24711, "text": "Syntax:" }, { "code": null, "e": 24922, "s": 24719, "text": "Automatic Storage Duration/ Static initialization classname objectname; Dynamic Storage Duration/ Dynamic Initialization classname *objectname = new classname(); Delete Dynamic Object delete objectname;" }, { "code": null, "e": 25016, "s": 24922, "text": "Below is the C++ program to demonstrate the object instantiation through default constructor-" }, { "code": null, "e": 25022, "s": 25016, "text": "C++14" }, { "code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Defining class exampleclass example { int x; public: void set(int x) { this->x = x; cout << \"The value of x is: \" << x << \"\\n\"; }}; // Driver codeint main(){ // Creating automatic storage object example obj1; obj1.set(5); // Creating dynamic storage object example* obj2 = new example(); obj2->set(10); // Explicitly deleting the obj2 delete obj2; return 0;}", "e": 25545, "s": 25022, "text": null }, { "code": null, "e": 25642, "s": 25545, "text": "Explanation:In the above code, there are two types of different ways of instantiating an object-" }, { "code": null, "e": 26037, "s": 25642, "text": "example obj1: This line is instantiating an object that has automatic storage duration. This object will be deleted automatically when it will be out of scope.example *obj2 = new example(): This is the way of instantiating an object that has dynamic storage duration. This object will not be deleted automatically. The user will have to use an explicit delete statement for deleting the object." }, { "code": null, "e": 26197, "s": 26037, "text": "example obj1: This line is instantiating an object that has automatic storage duration. This object will be deleted automatically when it will be out of scope." }, { "code": null, "e": 26433, "s": 26197, "text": "example *obj2 = new example(): This is the way of instantiating an object that has dynamic storage duration. This object will not be deleted automatically. The user will have to use an explicit delete statement for deleting the object." }, { "code": null, "e": 26446, "s": 26433, "text": "delete obj2;" }, { "code": null, "e": 26717, "s": 26446, "text": "2. Through Parameterized Constructor: Object instantiation can be done through parameterized constructor in static and dynamic way. It is possible to pass arguments to parameterized constructors. Typically, these arguments help initialize an object when it is created. " }, { "code": null, "e": 26726, "s": 26717, "text": "Syntax: " }, { "code": null, "e": 26946, "s": 26726, "text": "Static Initialization 1. classname objectname(parameter); 2. classname objectname = classname(parameter); Dynamic Initialization classname *objectname = new classname(parameter); Delete Dynamic Object delete objectname;" }, { "code": null, "e": 27017, "s": 26946, "text": "Below is the C++ program to demonstrate the parameterized constructor-" }, { "code": null, "e": 27021, "s": 27017, "text": "C++" }, { "code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Defining the class exampleclass example { int x; public: // Parameterized constructor example(int y) { x = y; cout << \"The value of x is: \" << x << \"\\n\"; }}; // Driver codeint main(){ // Creating object with automatic // storage duration using Method 1 example obj1(10); // Creating object with automatic // storage duration using Method 2 example obj2 = example(8); // Creating object with dynamic // storage duration using Method 3 example* obj3 = new example(20); delete obj3; return 0;}", "e": 27685, "s": 27021, "text": null }, { "code": null, "e": 27765, "s": 27685, "text": "Explanation:In the above code, there are three ways of instantiating an object-" }, { "code": null, "e": 28446, "s": 27765, "text": "example obj1(10): This line is instantiating an object using the parameterized constructor that has automatic storage duration. This object will be deleted automatically when it will be out of scope.example obj2 = example(8): This line is instantiating an object using the parameterized constructor that has automatic storage duration. This object will be deleted automatically when it will be out of scope.example *obj3 = new example(20): This is the way of instantiating an object using the parameterized constructor that has dynamic storage duration. This object will not be deleted automatically. The user will have to use an explicit delete statement for deleting the object." }, { "code": null, "e": 28646, "s": 28446, "text": "example obj1(10): This line is instantiating an object using the parameterized constructor that has automatic storage duration. This object will be deleted automatically when it will be out of scope." }, { "code": null, "e": 28855, "s": 28646, "text": "example obj2 = example(8): This line is instantiating an object using the parameterized constructor that has automatic storage duration. This object will be deleted automatically when it will be out of scope." }, { "code": null, "e": 29129, "s": 28855, "text": "example *obj3 = new example(20): This is the way of instantiating an object using the parameterized constructor that has dynamic storage duration. This object will not be deleted automatically. The user will have to use an explicit delete statement for deleting the object." }, { "code": null, "e": 29348, "s": 29129, "text": "3. Copy constructor: A copy constructor can be used to instantiate an object statically or dynamically. Static or dynamic initialization of object using a copy constructor has the following general function prototype: " }, { "code": null, "e": 29357, "s": 29348, "text": "Syntax: " }, { "code": null, "e": 29664, "s": 29357, "text": "Copy Constructor ClassName (const ClassName &old_obj); Instantiate an object using copy constructor Static Initialization 1. classname obj1; classname obj2 = obj1; 2. classname obj1; classname obj2(obj1); Dynamic Initialization 1. classname *obj1 = new classname(); classname *obj2 = new classname(*obj1); " }, { "code": null, "e": 29727, "s": 29664, "text": "Below is the C++ program to demonstrate the copy constructor- " }, { "code": null, "e": 29731, "s": 29727, "text": "C++" }, { "code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Defining the classclass example { int x; public: // Parameterized constructor example(int y) { x = y; cout << \"The value of x is: \" << x << \"\\n\"; } // Copy constructor example(example& obj) { x = obj.x; cout << \"The value of x in \" << \"copy constructor: \" << x << \"\\n\"; };}; // Driver codeint main(){ // Instantiating copy constructor // using Method 1 example obj1(4); example obj2 = obj1; // Instantiating copy constructor // using Method 2 example obj3(obj1); // Instantiating copy constructor // using Method 3 example* obj4 = new example(10); example* obj5 = new example(*obj4); delete obj5; delete obj4; return 0;}", "e": 30585, "s": 29731, "text": null }, { "code": null, "e": 30691, "s": 30585, "text": " Explanation:In the above code, there are three ways of instantiating an object using a copy constructor-" }, { "code": null, "e": 31502, "s": 30691, "text": "Method 1:example obj1(4): This line is instantiating an object that has automatic storage duration.example obj2 = obj1: This line is invoking copy constructor and creates a new object obj2 that is a copy of object obj1.Method 2:example obj3(obj1): This line is invoking copy constructor and creates a new object obj3 that is a copy of object obj1.Method 3:example *obj4 = new example(10): This is the way of instantiating an object that has dynamic storage duration. This object will not be deleted automatically. The user will have to use an explicit delete statement for deleting the object.example *obj5 = new example(*obj4): This line is invoking a copy constructor and creates a new object obj5 that is a copy of object obj4. The user will have to use an explicit delete statement for deleting the object." }, { "code": null, "e": 31722, "s": 31502, "text": "Method 1:example obj1(4): This line is instantiating an object that has automatic storage duration.example obj2 = obj1: This line is invoking copy constructor and creates a new object obj2 that is a copy of object obj1." }, { "code": null, "e": 31813, "s": 31722, "text": "example obj1(4): This line is instantiating an object that has automatic storage duration." }, { "code": null, "e": 31934, "s": 31813, "text": "example obj2 = obj1: This line is invoking copy constructor and creates a new object obj2 that is a copy of object obj1." }, { "code": null, "e": 32063, "s": 31934, "text": "Method 2:example obj3(obj1): This line is invoking copy constructor and creates a new object obj3 that is a copy of object obj1." }, { "code": null, "e": 32183, "s": 32063, "text": "example obj3(obj1): This line is invoking copy constructor and creates a new object obj3 that is a copy of object obj1." }, { "code": null, "e": 32647, "s": 32183, "text": "Method 3:example *obj4 = new example(10): This is the way of instantiating an object that has dynamic storage duration. This object will not be deleted automatically. The user will have to use an explicit delete statement for deleting the object.example *obj5 = new example(*obj4): This line is invoking a copy constructor and creates a new object obj5 that is a copy of object obj4. The user will have to use an explicit delete statement for deleting the object." }, { "code": null, "e": 32885, "s": 32647, "text": "example *obj4 = new example(10): This is the way of instantiating an object that has dynamic storage duration. This object will not be deleted automatically. The user will have to use an explicit delete statement for deleting the object." }, { "code": null, "e": 33103, "s": 32885, "text": "example *obj5 = new example(*obj4): This line is invoking a copy constructor and creates a new object obj5 that is a copy of object obj4. The user will have to use an explicit delete statement for deleting the object." }, { "code": null, "e": 33114, "s": 33105, "text": "sweetyty" }, { "code": null, "e": 33135, "s": 33114, "text": "C++-Class and Object" }, { "code": null, "e": 33139, "s": 33135, "text": "C++" }, { "code": null, "e": 33143, "s": 33139, "text": "CPP" }, { "code": null, "e": 33241, "s": 33143, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33250, "s": 33241, "text": "Comments" }, { "code": null, "e": 33263, "s": 33250, "text": "Old Comments" }, { "code": null, "e": 33284, "s": 33263, "text": "Iterators in C++ STL" }, { "code": null, "e": 33312, "s": 33284, "text": "Operator Overloading in C++" }, { "code": null, "e": 33345, "s": 33312, "text": "Friend class and function in C++" }, { "code": null, "e": 33365, "s": 33345, "text": "Polymorphism in C++" }, { "code": null, "e": 33389, "s": 33365, "text": "Sorting a vector in C++" }, { "code": null, "e": 33413, "s": 33389, "text": "Inline Functions in C++" }, { "code": null, "e": 33449, "s": 33413, "text": "Convert string to char array in C++" }, { "code": null, "e": 33493, "s": 33449, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 33518, "s": 33493, "text": "std::string class in C++" } ]
Neo4j CQL - AGGREGATION
Like SQL, Neo4j CQL has provided some aggregation functions to use in RETURN clause. It is similar to GROUP BY clause in SQL We can use this RETURN + Aggregation Functions in MATCH command to work on a group of nodes and return some aggregated value. Now we will discuss each Neo4j CQL AGGREGATION Functions in detail with examples It takes results from MATCH clause and counts the number of rows presents in that results and return that count value. All CQL Functions should use "( )" brackets. COUNT(<value>) NOTE - <value> may be *, a node or relationship label name or a property name. Example - This example demonstrates how to use COUNT(*) function to return number of Employee nodes available in the Database. Step 1 - Type the below command at dollar prompt in Data Browser. MATCH (e:Employee) RETURN e.id,e.name,e.sal,e.deptno Step 2 - Click on Execute button and observe the results. We can observe that this query returns 4 rows. Step 3 - Type the below command and click on Execute button. MATCH (e:Employee) RETURN COUNT(*) This query returns value 4 because Database contains 4 Employee nodes. It takes set of rows and a <property-name> of a Node or Relationship as input and find the minimum value from the give <property-name> column of given rows. MAX(<property-name> ) It takes set of rows and a <property-name> of a Node or Relationship as input and find the minimum value from the give <property-name> column of given rows. MIN(<property-name> ) NOTE - < property-name > should be name of a node or relationship. Let us examine the MAX and MIN functions with an example. Example - This example demonstrates how to find the highest and lowest salary value from all Employee Nodes Step 1 - Type the below command at dollar prompt in Data Browser. MATCH (e:Employee) RETURN e.id,e.name,e.sal,e.deptno Step 2 - Click on Execute button and observe the results. We can observe that this query returns 4 rows. Step 3 - Type the below command and click on Execute button. MATCH (e:Employee) RETURN MAX(e.sal),MIN(e.sal) This command finds max and min salary value from all Employee nodes available in the Database. It takes set of rows and a <property-name> of a Node or Relationship as input and find the average value from the give <property-name> column of given rows. AVG(<property-name> ) It takes set of rows and a <property-name> of a Node or Relationship as input and find the summation value from the give <property-name> column of given rows. SUM(<property-name> ) Let us examine the SUM and AVG functions with an example. Example1 - This example demonstrates how to find the total and average salary value of all Employee Nodes Step 1 - Type the below command at dollar prompt in Data Browser. MATCH (e:Employee) RETURN e.id,e.name,e.sal,e.deptno Step 2 - Click on Execute button and observe the results. We can observe that this query returns 4 rows. Step 3 - Type the below command and click on Execute button. MATCH (e:Employee) RETURN SUM(e.sal),AVG(e.sal) This command finds total and average salary value from all Employee nodes available in the Database. Print Add Notes Bookmark this page
[ { "code": null, "e": 2464, "s": 2339, "text": "Like SQL, Neo4j CQL has provided some aggregation functions to use in RETURN clause. It is similar to GROUP BY clause in SQL" }, { "code": null, "e": 2590, "s": 2464, "text": "We can use this RETURN + Aggregation Functions in MATCH command to work on a group of nodes and return some aggregated value." }, { "code": null, "e": 2671, "s": 2590, "text": "Now we will discuss each Neo4j CQL AGGREGATION Functions in detail with examples" }, { "code": null, "e": 2835, "s": 2671, "text": "It takes results from MATCH clause and counts the number of rows presents in that results and return that count value. All CQL Functions should use \"( )\" brackets." }, { "code": null, "e": 2850, "s": 2835, "text": "COUNT(<value>)" }, { "code": null, "e": 2857, "s": 2850, "text": "NOTE -" }, { "code": null, "e": 2929, "s": 2857, "text": "<value> may be *, a node or relationship label name or a property name." }, { "code": null, "e": 2939, "s": 2929, "text": "Example -" }, { "code": null, "e": 3056, "s": 2939, "text": "This example demonstrates how to use COUNT(*) function to return number of Employee nodes available in the Database." }, { "code": null, "e": 3122, "s": 3056, "text": "Step 1 - Type the below command at dollar prompt in Data Browser." }, { "code": null, "e": 3176, "s": 3122, "text": "MATCH (e:Employee) \nRETURN e.id,e.name,e.sal,e.deptno" }, { "code": null, "e": 3234, "s": 3176, "text": "Step 2 - Click on Execute button and observe the results." }, { "code": null, "e": 3281, "s": 3234, "text": "We can observe that this query returns 4 rows." }, { "code": null, "e": 3342, "s": 3281, "text": "Step 3 - Type the below command and click on Execute button." }, { "code": null, "e": 3377, "s": 3342, "text": "MATCH (e:Employee) RETURN COUNT(*)" }, { "code": null, "e": 3448, "s": 3377, "text": "This query returns value 4 because Database contains 4 Employee nodes." }, { "code": null, "e": 3605, "s": 3448, "text": "It takes set of rows and a <property-name> of a Node or Relationship as input and find the minimum value from the give <property-name> column of given rows." }, { "code": null, "e": 3627, "s": 3605, "text": "MAX(<property-name> )" }, { "code": null, "e": 3784, "s": 3627, "text": "It takes set of rows and a <property-name> of a Node or Relationship as input and find the minimum value from the give <property-name> column of given rows." }, { "code": null, "e": 3806, "s": 3784, "text": "MIN(<property-name> )" }, { "code": null, "e": 3813, "s": 3806, "text": "NOTE -" }, { "code": null, "e": 3873, "s": 3813, "text": "< property-name > should be name of a node or relationship." }, { "code": null, "e": 3931, "s": 3873, "text": "Let us examine the MAX and MIN functions with an example." }, { "code": null, "e": 3941, "s": 3931, "text": "Example -" }, { "code": null, "e": 4039, "s": 3941, "text": "This example demonstrates how to find the highest and lowest salary value from all Employee Nodes" }, { "code": null, "e": 4105, "s": 4039, "text": "Step 1 - Type the below command at dollar prompt in Data Browser." }, { "code": null, "e": 4159, "s": 4105, "text": "MATCH (e:Employee) \nRETURN e.id,e.name,e.sal,e.deptno" }, { "code": null, "e": 4217, "s": 4159, "text": "Step 2 - Click on Execute button and observe the results." }, { "code": null, "e": 4264, "s": 4217, "text": "We can observe that this query returns 4 rows." }, { "code": null, "e": 4325, "s": 4264, "text": "Step 3 - Type the below command and click on Execute button." }, { "code": null, "e": 4374, "s": 4325, "text": "MATCH (e:Employee) \nRETURN MAX(e.sal),MIN(e.sal)" }, { "code": null, "e": 4469, "s": 4374, "text": "This command finds max and min salary value from all Employee nodes available in the Database." }, { "code": null, "e": 4626, "s": 4469, "text": "It takes set of rows and a <property-name> of a Node or Relationship as input and find the average value from the give <property-name> column of given rows." }, { "code": null, "e": 4648, "s": 4626, "text": "AVG(<property-name> )" }, { "code": null, "e": 4807, "s": 4648, "text": "It takes set of rows and a <property-name> of a Node or Relationship as input and find the summation value from the give <property-name> column of given rows." }, { "code": null, "e": 4829, "s": 4807, "text": "SUM(<property-name> )" }, { "code": null, "e": 4887, "s": 4829, "text": "Let us examine the SUM and AVG functions with an example." }, { "code": null, "e": 4898, "s": 4887, "text": "Example1 -" }, { "code": null, "e": 4993, "s": 4898, "text": "This example demonstrates how to find the total and average salary value of all Employee Nodes" }, { "code": null, "e": 5059, "s": 4993, "text": "Step 1 - Type the below command at dollar prompt in Data Browser." }, { "code": null, "e": 5113, "s": 5059, "text": "MATCH (e:Employee) \nRETURN e.id,e.name,e.sal,e.deptno" }, { "code": null, "e": 5171, "s": 5113, "text": "Step 2 - Click on Execute button and observe the results." }, { "code": null, "e": 5218, "s": 5171, "text": "We can observe that this query returns 4 rows." }, { "code": null, "e": 5279, "s": 5218, "text": "Step 3 - Type the below command and click on Execute button." }, { "code": null, "e": 5328, "s": 5279, "text": "MATCH (e:Employee) \nRETURN SUM(e.sal),AVG(e.sal)" }, { "code": null, "e": 5429, "s": 5328, "text": "This command finds total and average salary value from all Employee nodes available in the Database." }, { "code": null, "e": 5436, "s": 5429, "text": " Print" }, { "code": null, "e": 5447, "s": 5436, "text": " Add Notes" } ]
Merge two sorted arrays in Java
Two sorted arrays can be merged so that a single resultant sorted array is obtained. An example of this is given as follows. Array 1 = 1 3 7 9 10 Array 2 = 2 5 8 Merged array = 1 2 3 5 7 8 9 10 A program that demonstrates this is given as follows. Live Demo public class Example { public static void main (String[] args) { int[] arr1 = {11, 34, 66, 75}; int n1 = arr1.length; int[] arr2 = {1, 5, 19, 50, 89, 100}; int n2 = arr2.length; int[] merge = new int[n1 + n2]; int i = 0, j = 0, k = 0, x; System.out.print("Array 1: "); for (x = 0; x < n1; x++) System.out.print(arr1[x] + " "); System.out.print("\nArray 2: "); for (x = 0; x < n2; x++) System.out.print(arr2[x] + " "); while (i < n1 && j < n2) { if (arr1[i] < arr2[j]) merge[k++] = arr1[i++]; else merge[k++] = arr2[j++]; } while (i < n1) merge[k++] = arr1[i++]; while (j < n2) merge[k++] = arr2[j++]; System.out.print("\nArray after merging: "); for (x = 0; x < n1 + n2; x++) System.out.print(merge[x] + " "); } } Array 1: 11 34 66 75 Array 2: 1 5 19 50 89 100 Array after merging: 1 5 11 19 34 50 66 75 89 100 Now let us understand the above program. First the 2 sorted arrays arr1 and arr2 are displayed. The code snippet that demonstrates this is given as follows. System.out.print("Array 1: "); for (x = 0; x < n1; x++) System.out.print(arr1[x] + " "); System.out.print("\nArray 2: "); for (x = 0; x < n2; x++) System.out.print(arr2[x] + " "); The sorted arrays are merged into a single array using a while loop. After the while loop, if any elements are left in arr1 or arr2, then they are added to the merged array. The code snippet that demonstrates this is given as follows. while (i < n1 && j < n2) { if (arr1[i] < arr2[j]) merge[k++] = arr1[i++]; else merge[k++] = arr2[j++]; } while (i < n1) merge[k++] = arr1[i++]; while (j < n2) merge[k++] = arr2[j++]; Finally the merged array is displayed. The code snippet that demonstrates this is given as follows. System.out.print("\nArray after merging: "); for (x = 0; x < n1 + n2; x++) System.out.print(merge[x] + " ");
[ { "code": null, "e": 1187, "s": 1062, "text": "Two sorted arrays can be merged so that a single resultant sorted array is obtained. An example of this is given as follows." }, { "code": null, "e": 1256, "s": 1187, "text": "Array 1 = 1 3 7 9 10\nArray 2 = 2 5 8\nMerged array = 1 2 3 5 7 8 9 10" }, { "code": null, "e": 1310, "s": 1256, "text": "A program that demonstrates this is given as follows." }, { "code": null, "e": 1321, "s": 1310, "text": " Live Demo" }, { "code": null, "e": 2209, "s": 1321, "text": "public class Example {\n public static void main (String[] args) {\n int[] arr1 = {11, 34, 66, 75};\n int n1 = arr1.length;\n int[] arr2 = {1, 5, 19, 50, 89, 100};\n int n2 = arr2.length;\n int[] merge = new int[n1 + n2];\n int i = 0, j = 0, k = 0, x;\n System.out.print(\"Array 1: \");\n for (x = 0; x < n1; x++)\n System.out.print(arr1[x] + \" \");\n System.out.print(\"\\nArray 2: \");\n for (x = 0; x < n2; x++)\n System.out.print(arr2[x] + \" \");\n while (i < n1 && j < n2) {\n if (arr1[i] < arr2[j])\n merge[k++] = arr1[i++];\n else\n merge[k++] = arr2[j++];\n }\n while (i < n1)\n merge[k++] = arr1[i++];\n while (j < n2)\n merge[k++] = arr2[j++];\n System.out.print(\"\\nArray after merging: \");\n for (x = 0; x < n1 + n2; x++)\n System.out.print(merge[x] + \" \");\n }\n}" }, { "code": null, "e": 2306, "s": 2209, "text": "Array 1: 11 34 66 75\nArray 2: 1 5 19 50 89 100\nArray after merging: 1 5 11 19 34 50 66 75 89 100" }, { "code": null, "e": 2347, "s": 2306, "text": "Now let us understand the above program." }, { "code": null, "e": 2463, "s": 2347, "text": "First the 2 sorted arrays arr1 and arr2 are displayed. The code snippet that demonstrates this is given as follows." }, { "code": null, "e": 2643, "s": 2463, "text": "System.out.print(\"Array 1: \");\nfor (x = 0; x < n1; x++)\nSystem.out.print(arr1[x] + \" \");\nSystem.out.print(\"\\nArray 2: \");\nfor (x = 0; x < n2; x++)\nSystem.out.print(arr2[x] + \" \");" }, { "code": null, "e": 2878, "s": 2643, "text": "The sorted arrays are merged into a single array using a while loop. After the while loop, if any elements are left in arr1 or arr2, then they are added to the merged array. The code snippet that demonstrates this is given as follows." }, { "code": null, "e": 3079, "s": 2878, "text": "while (i < n1 && j < n2) {\n if (arr1[i] < arr2[j])\n merge[k++] = arr1[i++];\n else\n merge[k++] = arr2[j++];\n}\nwhile (i < n1)\nmerge[k++] = arr1[i++];\nwhile (j < n2)\nmerge[k++] = arr2[j++];" }, { "code": null, "e": 3179, "s": 3079, "text": "Finally the merged array is displayed. The code snippet that demonstrates this is given as follows." }, { "code": null, "e": 3288, "s": 3179, "text": "System.out.print(\"\\nArray after merging: \");\nfor (x = 0; x < n1 + n2; x++)\nSystem.out.print(merge[x] + \" \");" } ]
Java Program For Swapping Nodes In A Linked List Without Swapping Data - GeeksforGeeks
30 Mar, 2022 Given a linked list and two keys in it, swap nodes for two given keys. Nodes should be swapped by changing links. Swapping data of nodes may be expensive in many situations when data contains many fields. It may be assumed that all keys in the linked list are distinct. Examples: Input : 10->15->12->13->20->14, x = 12, y = 20 Output: 10->15->20->13->12->14 Input : 10->15->12->13->20->14, x = 10, y = 20 Output: 20->15->12->13->10->14 Input : 10->15->12->13->20->14, x = 12, y = 13 Output: 10->15->13->12->20->14 This may look a simple problem, but is an interesting question as it has the following cases to be handled. x and y may or may not be adjacent.Either x or y may be a head node.Either x or y may be the last node.x and/or y may not be present in the linked list. x and y may or may not be adjacent. Either x or y may be a head node. Either x or y may be the last node. x and/or y may not be present in the linked list. How to write a clean working code that handles all the above possibilities. The idea is to first search x and y in the given linked list. If any of them is not present, then return. While searching for x and y, keep track of current and previous pointers. First change next of previous pointers, then change next of current pointers. Below is the implementation of the above approach. Java // Java program to swap two given nodes// of a linked listclass Node{ int data; Node next; Node(int d) { data = d; next = null; }} class LinkedList{ // head of list Node head; /* Function to swap Nodes x and y in linked list by changing links */ public void swapNodes(int x, int y) { // Nothing to do if x and y // are same if (x == y) return; // Search for x (keep track of // prevX and CurrX) Node prevX = null, currX = head; while (currX != null && currX.data != x) { prevX = currX; currX = currX.next; } // Search for y (keep track of // prevY and currY) Node prevY = null, currY = head; while (currY != null && currY.data != y) { prevY = currY; currY = currY.next; } // If either x or y is not present, // nothing to do if (currX == null || currY == null) return; // If x is not head of linked list if (prevX != null) prevX.next = currY; else // make y the new head head = currY; // If y is not head of linked list if (prevY != null) prevY.next = currX; else // make x the new head head = currX; // Swap next pointers Node temp = currX.next; currX.next = currY.next; currY.next = temp; } // Function to add Node at // beginning of list. public void push(int new_data) { // 1. alloc the Node and put the data Node new_Node = new Node(new_data); // 2. Make next of new Node as head new_Node.next = head; // 3. Move the head to point to new Node head = new_Node; } /* This function prints contents of linked list starting from the given Node */ public void printList() { Node tNode = head; while (tNode != null) { System.out.print(tNode.data + " "); tNode = tNode.next; } } // Driver code public static void main(String[] args) { LinkedList llist = new LinkedList(); /* The constructed linked list is: 1->2->3->4->5->6->7 */ llist.push(7); llist.push(6); llist.push(5); llist.push(4); llist.push(3); llist.push(2); llist.push(1); System.out.print( "Linked list before calling swapNodes() "); llist.printList(); llist.swapNodes(4, 3); System.out.print( "Linked list after calling swapNodes() "); llist.printList(); }}// This code is contributed by Rajat Mishra Output: Linked list before calling swapNodes() 1 2 3 4 5 6 7 Linked list after calling swapNodes() 1 2 4 3 5 6 7 Time Complexity: O(n) Auxiliary Space: O(1) Optimizations: The above code can be optimized to search x and y in single traversal. Two loops are used to keep program simple. Simpler approach: Java // Java program to swap two given nodes// of a linked listpublic class Solution{ // Represent a node of the // singly linked list class Node { int data; Node next; public Node(int data) { this.data = data; this.next = null; } } // Represent the head and tail // of the singly linked list public Node head = null; public Node tail = null; // addNode() will add a new node // to the list public void addNode(int data) { // Create a new node Node newNode = new Node(data); // Checks if the list is empty if (head == null) { // If list is empty, both head and // tail will point to new node head = newNode; tail = newNode; } else { // newNode will be added after tail // such that tail's next will point // to newNode tail.next = newNode; // newNode will become new tail of // the list tail = newNode; } } // swap() will swap the given two nodes public void swap(int n1, int n2) { Node prevNode1 = null, prevNode2 = null, node1 = head, node2 = head; // Checks if list is empty if (head == null) { return; } // If n1 and n2 are equal, then // list will remain the same if (n1 == n2) return; // Search for node1 while (node1 != null && node1.data != n1) { prevNode1 = node1; node1 = node1.next; } // Search for node2 while (node2 != null && node2.data != n2) { prevNode2 = node2; node2 = node2.next; } if (node1 != null && node2 != null) { // If previous node to node1 is not // null then, it will point to node2 if (prevNode1 != null) prevNode1.next = node2; else head = node2; // If previous node to node2 is not // null then, it will point to node1 if (prevNode2 != null) prevNode2.next = node1; else head = node1; // Swaps the next nodes of node1 // and node2 Node temp = node1.next; node1.next = node2.next; node2.next = temp; } else { System.out.println("Swapping is not possible"); } } // display() will display all the // nodes present in the list public void display() { // Node current will point to head Node current = head; if (head == null) { System.out.println("List is empty"); return; } while (current != null) { // Prints each node by incrementing // pointer System.out.print(current.data + " "); current = current.next; } System.out.println(); } public static void main(String[] args) { Solution sList = new Solution(); // Add nodes to the list sList.addNode(1); sList.addNode(2); sList.addNode(3); sList.addNode(4); sList.addNode(5); sList.addNode(6); sList.addNode(7); System.out.println("Original list: "); sList.display(); // Swaps the node 2 with node 5 sList.swap(6, 1); System.out.println( "List after swapping nodes: "); sList.display(); }} Output: Linked list before calling swapNodes() 1 2 3 4 5 6 7 Linked list after calling swapNodes() 6 2 3 4 5 1 7 Time Complexity: O(n) Auxiliary Space: O(1) Please refer complete article on Swap nodes in a linked list without swapping data for more details! rohan07 Linked Lists Java Java Programs Linked List Linked List Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Constructors in Java Stream In Java Exceptions in Java Different ways of Reading a text file in Java Functional Interfaces in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java?
[ { "code": null, "e": 23946, "s": 23918, "text": "\n30 Mar, 2022" }, { "code": null, "e": 24152, "s": 23946, "text": "Given a linked list and two keys in it, swap nodes for two given keys. Nodes should be swapped by changing links. Swapping data of nodes may be expensive in many situations when data contains many fields. " }, { "code": null, "e": 24217, "s": 24152, "text": "It may be assumed that all keys in the linked list are distinct." }, { "code": null, "e": 24228, "s": 24217, "text": "Examples: " }, { "code": null, "e": 24467, "s": 24228, "text": "Input : 10->15->12->13->20->14, x = 12, y = 20\nOutput: 10->15->20->13->12->14\n\nInput : 10->15->12->13->20->14, x = 10, y = 20\nOutput: 20->15->12->13->10->14\n\nInput : 10->15->12->13->20->14, x = 12, y = 13\nOutput: 10->15->13->12->20->14" }, { "code": null, "e": 24576, "s": 24467, "text": "This may look a simple problem, but is an interesting question as it has the following cases to be handled. " }, { "code": null, "e": 24729, "s": 24576, "text": "x and y may or may not be adjacent.Either x or y may be a head node.Either x or y may be the last node.x and/or y may not be present in the linked list." }, { "code": null, "e": 24765, "s": 24729, "text": "x and y may or may not be adjacent." }, { "code": null, "e": 24799, "s": 24765, "text": "Either x or y may be a head node." }, { "code": null, "e": 24835, "s": 24799, "text": "Either x or y may be the last node." }, { "code": null, "e": 24885, "s": 24835, "text": "x and/or y may not be present in the linked list." }, { "code": null, "e": 24961, "s": 24885, "text": "How to write a clean working code that handles all the above possibilities." }, { "code": null, "e": 25220, "s": 24961, "text": "The idea is to first search x and y in the given linked list. If any of them is not present, then return. While searching for x and y, keep track of current and previous pointers. First change next of previous pointers, then change next of current pointers. " }, { "code": null, "e": 25272, "s": 25220, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 25277, "s": 25272, "text": "Java" }, { "code": "// Java program to swap two given nodes// of a linked listclass Node{ int data; Node next; Node(int d) { data = d; next = null; }} class LinkedList{ // head of list Node head; /* Function to swap Nodes x and y in linked list by changing links */ public void swapNodes(int x, int y) { // Nothing to do if x and y // are same if (x == y) return; // Search for x (keep track of // prevX and CurrX) Node prevX = null, currX = head; while (currX != null && currX.data != x) { prevX = currX; currX = currX.next; } // Search for y (keep track of // prevY and currY) Node prevY = null, currY = head; while (currY != null && currY.data != y) { prevY = currY; currY = currY.next; } // If either x or y is not present, // nothing to do if (currX == null || currY == null) return; // If x is not head of linked list if (prevX != null) prevX.next = currY; else // make y the new head head = currY; // If y is not head of linked list if (prevY != null) prevY.next = currX; else // make x the new head head = currX; // Swap next pointers Node temp = currX.next; currX.next = currY.next; currY.next = temp; } // Function to add Node at // beginning of list. public void push(int new_data) { // 1. alloc the Node and put the data Node new_Node = new Node(new_data); // 2. Make next of new Node as head new_Node.next = head; // 3. Move the head to point to new Node head = new_Node; } /* This function prints contents of linked list starting from the given Node */ public void printList() { Node tNode = head; while (tNode != null) { System.out.print(tNode.data + \" \"); tNode = tNode.next; } } // Driver code public static void main(String[] args) { LinkedList llist = new LinkedList(); /* The constructed linked list is: 1->2->3->4->5->6->7 */ llist.push(7); llist.push(6); llist.push(5); llist.push(4); llist.push(3); llist.push(2); llist.push(1); System.out.print( \"Linked list before calling swapNodes() \"); llist.printList(); llist.swapNodes(4, 3); System.out.print( \"Linked list after calling swapNodes() \"); llist.printList(); }}// This code is contributed by Rajat Mishra", "e": 28013, "s": 25277, "text": null }, { "code": null, "e": 28021, "s": 28013, "text": "Output:" }, { "code": null, "e": 28128, "s": 28021, "text": "Linked list before calling swapNodes() 1 2 3 4 5 6 7 \nLinked list after calling swapNodes() 1 2 4 3 5 6 7 " }, { "code": null, "e": 28150, "s": 28128, "text": "Time Complexity: O(n)" }, { "code": null, "e": 28172, "s": 28150, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 28301, "s": 28172, "text": "Optimizations: The above code can be optimized to search x and y in single traversal. Two loops are used to keep program simple." }, { "code": null, "e": 28319, "s": 28301, "text": "Simpler approach:" }, { "code": null, "e": 28324, "s": 28319, "text": "Java" }, { "code": "// Java program to swap two given nodes// of a linked listpublic class Solution{ // Represent a node of the // singly linked list class Node { int data; Node next; public Node(int data) { this.data = data; this.next = null; } } // Represent the head and tail // of the singly linked list public Node head = null; public Node tail = null; // addNode() will add a new node // to the list public void addNode(int data) { // Create a new node Node newNode = new Node(data); // Checks if the list is empty if (head == null) { // If list is empty, both head and // tail will point to new node head = newNode; tail = newNode; } else { // newNode will be added after tail // such that tail's next will point // to newNode tail.next = newNode; // newNode will become new tail of // the list tail = newNode; } } // swap() will swap the given two nodes public void swap(int n1, int n2) { Node prevNode1 = null, prevNode2 = null, node1 = head, node2 = head; // Checks if list is empty if (head == null) { return; } // If n1 and n2 are equal, then // list will remain the same if (n1 == n2) return; // Search for node1 while (node1 != null && node1.data != n1) { prevNode1 = node1; node1 = node1.next; } // Search for node2 while (node2 != null && node2.data != n2) { prevNode2 = node2; node2 = node2.next; } if (node1 != null && node2 != null) { // If previous node to node1 is not // null then, it will point to node2 if (prevNode1 != null) prevNode1.next = node2; else head = node2; // If previous node to node2 is not // null then, it will point to node1 if (prevNode2 != null) prevNode2.next = node1; else head = node1; // Swaps the next nodes of node1 // and node2 Node temp = node1.next; node1.next = node2.next; node2.next = temp; } else { System.out.println(\"Swapping is not possible\"); } } // display() will display all the // nodes present in the list public void display() { // Node current will point to head Node current = head; if (head == null) { System.out.println(\"List is empty\"); return; } while (current != null) { // Prints each node by incrementing // pointer System.out.print(current.data + \" \"); current = current.next; } System.out.println(); } public static void main(String[] args) { Solution sList = new Solution(); // Add nodes to the list sList.addNode(1); sList.addNode(2); sList.addNode(3); sList.addNode(4); sList.addNode(5); sList.addNode(6); sList.addNode(7); System.out.println(\"Original list: \"); sList.display(); // Swaps the node 2 with node 5 sList.swap(6, 1); System.out.println( \"List after swapping nodes: \"); sList.display(); }}", "e": 31956, "s": 28324, "text": null }, { "code": null, "e": 31964, "s": 31956, "text": "Output:" }, { "code": null, "e": 32071, "s": 31964, "text": "Linked list before calling swapNodes() 1 2 3 4 5 6 7 \nLinked list after calling swapNodes() 6 2 3 4 5 1 7 " }, { "code": null, "e": 32093, "s": 32071, "text": "Time Complexity: O(n)" }, { "code": null, "e": 32115, "s": 32093, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 32216, "s": 32115, "text": "Please refer complete article on Swap nodes in a linked list without swapping data for more details!" }, { "code": null, "e": 32224, "s": 32216, "text": "rohan07" }, { "code": null, "e": 32237, "s": 32224, "text": "Linked Lists" }, { "code": null, "e": 32242, "s": 32237, "text": "Java" }, { "code": null, "e": 32256, "s": 32242, "text": "Java Programs" }, { "code": null, "e": 32268, "s": 32256, "text": "Linked List" }, { "code": null, "e": 32280, "s": 32268, "text": "Linked List" }, { "code": null, "e": 32285, "s": 32280, "text": "Java" }, { "code": null, "e": 32383, "s": 32285, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32392, "s": 32383, "text": "Comments" }, { "code": null, "e": 32405, "s": 32392, "text": "Old Comments" }, { "code": null, "e": 32426, "s": 32405, "text": "Constructors in Java" }, { "code": null, "e": 32441, "s": 32426, "text": "Stream In Java" }, { "code": null, "e": 32460, "s": 32441, "text": "Exceptions in Java" }, { "code": null, "e": 32506, "s": 32460, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 32536, "s": 32506, "text": "Functional Interfaces in Java" }, { "code": null, "e": 32580, "s": 32536, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 32606, "s": 32580, "text": "Java Programming Examples" }, { "code": null, "e": 32640, "s": 32606, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 32687, "s": 32640, "text": "Implementing a Linked List in Java using Class" } ]
crypto.createDecipheriv() Method in Node.js
The crypto.createCipheriv() is a programming interface from the 'crypto' module. It will create and return the Decipher object as per the given algorithm, key, iv and options passed in the function. crypto.createDecipheriv(algorithm, key, iv, [options]) The above parameters are described as below βˆ’ algorithm – It takes the input for the algorithm that would be used to create the cipher. Some possible values are: aes192, aes256, etc. algorithm – It takes the input for the algorithm that would be used to create the cipher. Some possible values are: aes192, aes256, etc. key – It takes input for the raw key that is used by the algorithm and iv. Possible values can be of type: string, buffer, TypedArray or DataView. It can optionally be a type object of secret type. key – It takes input for the raw key that is used by the algorithm and iv. Possible values can be of type: string, buffer, TypedArray or DataView. It can optionally be a type object of secret type. iv – Also known as the initialization vector. This parameter takes input for iv that will make the cipher uncertain and unique. It does not need to be a secret. Its possible value types are: string, buffer, TypedArray, DataView. This can be null if not needed by the cipher. iv – Also known as the initialization vector. This parameter takes input for iv that will make the cipher uncertain and unique. It does not need to be a secret. Its possible value types are: string, buffer, TypedArray, DataView. This can be null if not needed by the cipher. options – This is an optional parameter for controlling the stream behaviour. This is not optional when cipher is used in CCM or OCB mode (Like 'aes-256-ccm') options – This is an optional parameter for controlling the stream behaviour. This is not optional when cipher is used in CCM or OCB mode (Like 'aes-256-ccm') Create a file with name – createDecipheriv.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below βˆ’ node createDecipheriv.js createDecipheriv.js // A node demo program for creating the ECDH // Importing the crypto module const crypto = require('crypto'); // Initializing the algorithm const algorithm = 'aes-192-cbc'; // Defining and initializing the password const password = '123456789' // Initializing the key const key = crypto.scryptSync(password, 'TutorialsPoint', 24); // Initializing the iv vector const iv = Buffer.alloc(16, 0); // Creating the Decipher with the above defined parameters const decipher = crypto.createDecipheriv(algorithm, key, iv); let decrypted = ''; // Reading and encrypting the data decipher.on('readable', () => { let chunk; while (null !== (chunk = decipher.read())) { decrypted += chunk.toString('utf8'); } }); //Handling the closing/end event decipher.on('end', () => { console.log(decrypted); }); // Encrypted data which is going to be decrypted const encrypted = 'uqeQEkXy5dpJjQv+JDvMHw=='; // Printing the decrypted text decipher.write(encrypted, 'base64'); decipher.end(); console.log("Completed... !"); C:\home\node>> node createDecipheriv.js Completed... ! TutorialsPoint Let's take a look at one more example. Live Demo // A node demo program for creating the ECDH // Importing the crypto module const crypto = require('crypto'); // Initializing the algorithm const algorithm = 'aes-256-cbc'; // Defining and initializing the password const password = '123456789' // Initializing the key const key = crypto.randomBytes(32); // Initializing the iv vector const iv = crypto.randomBytes(16); // Encrypt function to encrypt the data function encrypt(text) { // Creating the cipher with the above defined parameters let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv); // Updating the encrypted text... let encrypted = cipher.update(text); // Using concatenation encrypted = Buffer.concat([encrypted, cipher.final()]); // Returning the iv vector along with the encrypted data return { iv: iv.toString('hex'), encryptedData: encrypted.toString('hex') }; } //Decrypt function for decrypting the data function decrypt(text) { let iv = Buffer.from(text.iv, 'hex'); let encryptedText = Buffer.from(text.encryptedData, 'hex'); // Creating the decipher from algo, key and iv let decipher = crypto.createDecipheriv( 'aes-256-cbc', Buffer.from(key), iv); // Updating decrypted text let decrypted = decipher.update(encryptedText); decrypted = Buffer.concat([decrypted, decipher.final()]); // returning response data after decryption return decrypted.toString(); } // Encrypting the below data and printing output var output = encrypt("Welcome to TutorialsPoint !"); console.log("Encrypted data -- ", output); //Printing decrypted data console.log("Decrypted data -- ", decrypt(output)); C:\home\node>> node createDecipheriv.js Encrypted data -- { iv: '3fb2c84290e04d9bfb099bc65a7ac941', encryptedData: '4490777e90c5a78037cb92a99d561ae250562e2636af459b911cfa01c0191e3f' } Decrypted data -- Welcome to TutorialsPoint !
[ { "code": null, "e": 1261, "s": 1062, "text": "The crypto.createCipheriv() is a programming interface from the 'crypto' module. It will create and return the Decipher object as per the given algorithm, key, iv and options passed in the function." }, { "code": null, "e": 1316, "s": 1261, "text": "crypto.createDecipheriv(algorithm, key, iv, [options])" }, { "code": null, "e": 1362, "s": 1316, "text": "The above parameters are described as below βˆ’" }, { "code": null, "e": 1499, "s": 1362, "text": "algorithm – It takes the input for the algorithm that would be used to create the cipher. Some possible values are: aes192, aes256, etc." }, { "code": null, "e": 1636, "s": 1499, "text": "algorithm – It takes the input for the algorithm that would be used to create the cipher. Some possible values are: aes192, aes256, etc." }, { "code": null, "e": 1834, "s": 1636, "text": "key – It takes input for the raw key that is used by the algorithm and iv. Possible values can be of type: string, buffer, TypedArray or DataView. It can optionally be a type object of secret type." }, { "code": null, "e": 2032, "s": 1834, "text": "key – It takes input for the raw key that is used by the algorithm and iv. Possible values can be of type: string, buffer, TypedArray or DataView. It can optionally be a type object of secret type." }, { "code": null, "e": 2307, "s": 2032, "text": "iv – Also known as the initialization vector. This parameter takes input for iv that will make the cipher uncertain and unique. It does not need to be a secret. Its possible value types are: string, buffer, TypedArray, DataView. This can be null if not needed by the cipher." }, { "code": null, "e": 2582, "s": 2307, "text": "iv – Also known as the initialization vector. This parameter takes input for iv that will make the cipher uncertain and unique. It does not need to be a secret. Its possible value types are: string, buffer, TypedArray, DataView. This can be null if not needed by the cipher." }, { "code": null, "e": 2741, "s": 2582, "text": "options – This is an optional parameter for controlling the stream behaviour. This is not optional when cipher is used in CCM or OCB mode (Like 'aes-256-ccm')" }, { "code": null, "e": 2900, "s": 2741, "text": "options – This is an optional parameter for controlling the stream behaviour. This is not optional when cipher is used in CCM or OCB mode (Like 'aes-256-ccm')" }, { "code": null, "e": 3075, "s": 2900, "text": "Create a file with name – createDecipheriv.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below βˆ’" }, { "code": null, "e": 3100, "s": 3075, "text": "node createDecipheriv.js" }, { "code": null, "e": 3120, "s": 3100, "text": "createDecipheriv.js" }, { "code": null, "e": 4146, "s": 3120, "text": "// A node demo program for creating the ECDH\n\n// Importing the crypto module\nconst crypto = require('crypto');\n\n// Initializing the algorithm\nconst algorithm = 'aes-192-cbc';\n\n// Defining and initializing the password\nconst password = '123456789'\n\n// Initializing the key\nconst key = crypto.scryptSync(password, 'TutorialsPoint', 24);\n\n// Initializing the iv vector\nconst iv = Buffer.alloc(16, 0);\n\n// Creating the Decipher with the above defined parameters\nconst decipher = crypto.createDecipheriv(algorithm, key, iv);\n\nlet decrypted = '';\n\n// Reading and encrypting the data\ndecipher.on('readable', () => {\n let chunk;\n while (null !== (chunk = decipher.read())) {\n decrypted += chunk.toString('utf8');\n }\n});\n\n//Handling the closing/end event\ndecipher.on('end', () => {\n console.log(decrypted);\n});\n\n// Encrypted data which is going to be decrypted\nconst encrypted = 'uqeQEkXy5dpJjQv+JDvMHw==';\n// Printing the decrypted text\ndecipher.write(encrypted, 'base64');\ndecipher.end();\nconsole.log(\"Completed... !\");" }, { "code": null, "e": 4216, "s": 4146, "text": "C:\\home\\node>> node createDecipheriv.js\nCompleted... !\nTutorialsPoint" }, { "code": null, "e": 4255, "s": 4216, "text": "Let's take a look at one more example." }, { "code": null, "e": 4266, "s": 4255, "text": " Live Demo" }, { "code": null, "e": 5866, "s": 4266, "text": "// A node demo program for creating the ECDH\n\n// Importing the crypto module\nconst crypto = require('crypto');\n\n// Initializing the algorithm\nconst algorithm = 'aes-256-cbc';\n\n// Defining and initializing the password\nconst password = '123456789'\n\n// Initializing the key\nconst key = crypto.randomBytes(32);\n\n// Initializing the iv vector\nconst iv = crypto.randomBytes(16);\n\n// Encrypt function to encrypt the data\nfunction encrypt(text) {\n\n// Creating the cipher with the above defined parameters\nlet cipher =\n crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);\n\n// Updating the encrypted text...\nlet encrypted = cipher.update(text);\n\n// Using concatenation\nencrypted = Buffer.concat([encrypted, cipher.final()]);\n\n// Returning the iv vector along with the encrypted data\nreturn { iv: iv.toString('hex'),\n encryptedData: encrypted.toString('hex') };\n}\n\n//Decrypt function for decrypting the data\nfunction decrypt(text) {\n\nlet iv = Buffer.from(text.iv, 'hex');\nlet encryptedText =\n Buffer.from(text.encryptedData, 'hex');\n\n// Creating the decipher from algo, key and iv\nlet decipher = crypto.createDecipheriv(\n 'aes-256-cbc', Buffer.from(key), iv);\n\n// Updating decrypted text\nlet decrypted = decipher.update(encryptedText);\ndecrypted = Buffer.concat([decrypted, decipher.final()]);\n\n// returning response data after decryption\nreturn decrypted.toString();\n}\n// Encrypting the below data and printing output\nvar output = encrypt(\"Welcome to TutorialsPoint !\");\nconsole.log(\"Encrypted data -- \", output);\n\n//Printing decrypted data\nconsole.log(\"Decrypted data -- \", decrypt(output));" }, { "code": null, "e": 6096, "s": 5866, "text": "C:\\home\\node>> node createDecipheriv.js\nEncrypted data -- { iv: '3fb2c84290e04d9bfb099bc65a7ac941',\nencryptedData:\n'4490777e90c5a78037cb92a99d561ae250562e2636af459b911cfa01c0191e3f' }\nDecrypted data -- Welcome to TutorialsPoint !" } ]
POSIX shared-memory API
22 Mar, 2022 Several IPC mechanisms are available for POSIX systems, including shared memory and message passing. Here, we explore the POSIX API for shared memory. POSIX shared memory is organized using memory-mapped files, which associate the region of shared memory with a file. A process must first create a shared-memory object using the shm_open() system call, as follows: shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666); Parameters: name: The first parameter specifies the name of the shared-memory object. Processes that wish to access this shared memory must refer to the object by this name. O_CREAT | O_RDWR : The subsequent parameters specify that the shared-memory object is to be created if it does not yet exist (O_CREAT) and that the object is open for reading and writing (O_RDWR). The last parameter establishes the directory permissions of the shared-memory object. A successful call to shm_open() returns an integer file descriptor for the shared-memory object. Once the object is established, the ftruncate() function is used to configure the size of the object in bytes. The call ftruncate(shm_fd, 4096); sets the size of the object to 4, 096 bytes. Finally, the mmap() function establishes a memory-mapped file containing the shared-memory object. It also returns a pointer to the memory-mapped file that is used for accessing the shared-memory object. Programs showing POSIX shared memory API for producer and consumer C //C program for Producer process illustrating POSIX shared-memory API. #include <stdio.h>#include <stdlib.h>#include <string.h>#include <fcntl.h>#include <sys/shm.h>#include <sys/stat.h>#include <sys/mman.h> int main(){ /* the size (in bytes) of shared memory object */ const int SIZE = 4096; /* name of the shared memory object */ const char* name = "OS"; /* strings written to shared memory */ const char* message_0 = "Hello"; const char* message_1 = "World!"; /* shared memory file descriptor */ int shm_fd; /* pointer to shared memory object */ void* ptr; /* create the shared memory object */ shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666); /* configure the size of the shared memory object */ ftruncate(shm_fd, SIZE); /* memory map the shared memory object */ ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0); /* write to the shared memory object */ sprintf(ptr, "%s", message_0); ptr += strlen(message_0); sprintf(ptr, "%s", message_1); ptr += strlen(message_1); return 0;} C // C program for Consumer process illustrating// POSIX shared-memory API.#include <stdio.h>#include <stdlib.h>#include <fcntl.h>#include <sys/shm.h>#include <sys/stat.h>#include <sys/mman.h> int main(){ /* the size (in bytes) of shared memory object */ const int SIZE = 4096; /* name of the shared memory object */ const char* name = "OS"; /* shared memory file descriptor */ int shm_fd; /* pointer to shared memory object */ void* ptr; /* open the shared memory object */ shm_fd = shm_open(name, O_RDONLY, 0666); /* memory map the shared memory object */ ptr = mmap(0, SIZE, PROT_READ, MAP_SHARED, shm_fd, 0); /* read from the shared memory object */ printf("%s", (char*)ptr); /* remove the shared memory object */ shm_unlink(name); return 0;} The above programs can be compiled by typing the following commands in terminal opened in working directory – gcc producer.c -pthread -lrt -o producer gcc consumer.c -pthread -lrt -o consumer ./consumer & ./producer & This should output the following – HelloWorld! The above programs use the producer–consumer model in implementing shared memory. The producer establishes a shared memory object and writes to shared memory, and the consumer reads from shared memory. The producer, creates a shared-memory object named OS and writes the famous string β€œHello World!” to shared memory. The program memory-maps a shared-memory object of the specified size and allows writing to the object. (Obviously, only writing is necessary for the producer.) The flag MAP SHARED specifies that changes to the shared memory object will be visible to all processes sharing the object. Notice that we write to the shared-memory object by calling the sprintf() function and writing the formatted string to the pointer ptr. After each write, we must increment the pointer by the number of bytes written. The consumer process, reads and outputs the contents of the shared memory. The consumer also invokes the shm_unlink() function, which removes the shared-memory segment after the consumer has accessed it. References Silberschatz’s Operating System concepts http://www.cse.cuhk.edu.hk/~ericlo/teaching/os/lab/7-IPC2/sync-pro.html This article is contributed by Mayank Rana. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. HamidRamazani anikakapoor siddharthakapoor Articles Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction Time complexities of different data structures SQL | DROP, TRUNCATE Difference Between Object And Class Implementation of LinkedList in Javascript 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": 54, "s": 26, "text": "\n22 Mar, 2022" }, { "code": null, "e": 205, "s": 54, "text": "Several IPC mechanisms are available for POSIX systems, including shared memory and message passing. Here, we explore the POSIX API for shared memory." }, { "code": null, "e": 419, "s": 205, "text": "POSIX shared memory is organized using memory-mapped files, which associate the region of shared memory with a file. A process must first create a shared-memory object using the shm_open() system call, as follows:" }, { "code": null, "e": 931, "s": 419, "text": "shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);\nParameters:\nname: The first parameter specifies the name of the shared-memory object. \nProcesses that wish to access this shared memory must refer to the \nobject by this name.\nO_CREAT | O_RDWR : The subsequent parameters specify that the shared-memory \nobject is to be created if it does not yet exist (O_CREAT) and that the object is \nopen for reading and writing (O_RDWR).\n\nThe last parameter establishes the directory permissions of the \nshared-memory object." }, { "code": null, "e": 1148, "s": 931, "text": "A successful call to shm_open() returns an integer file descriptor for the shared-memory object. Once the object is established, the ftruncate() function is used to configure the size of the object in bytes. The call" }, { "code": null, "e": 1174, "s": 1148, "text": " ftruncate(shm_fd, 4096);" }, { "code": null, "e": 1424, "s": 1174, "text": "sets the size of the object to 4, 096 bytes. Finally, the mmap() function establishes a memory-mapped file containing the shared-memory object. It also returns a pointer to the memory-mapped file that is used for accessing the shared-memory object. " }, { "code": null, "e": 1492, "s": 1424, "text": "Programs showing POSIX shared memory API for producer and consumer " }, { "code": null, "e": 1494, "s": 1492, "text": "C" }, { "code": "//C program for Producer process illustrating POSIX shared-memory API. #include <stdio.h>#include <stdlib.h>#include <string.h>#include <fcntl.h>#include <sys/shm.h>#include <sys/stat.h>#include <sys/mman.h> int main(){ /* the size (in bytes) of shared memory object */ const int SIZE = 4096; /* name of the shared memory object */ const char* name = \"OS\"; /* strings written to shared memory */ const char* message_0 = \"Hello\"; const char* message_1 = \"World!\"; /* shared memory file descriptor */ int shm_fd; /* pointer to shared memory object */ void* ptr; /* create the shared memory object */ shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666); /* configure the size of the shared memory object */ ftruncate(shm_fd, SIZE); /* memory map the shared memory object */ ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0); /* write to the shared memory object */ sprintf(ptr, \"%s\", message_0); ptr += strlen(message_0); sprintf(ptr, \"%s\", message_1); ptr += strlen(message_1); return 0;}", "e": 2560, "s": 1494, "text": null }, { "code": null, "e": 2562, "s": 2560, "text": "C" }, { "code": "// C program for Consumer process illustrating// POSIX shared-memory API.#include <stdio.h>#include <stdlib.h>#include <fcntl.h>#include <sys/shm.h>#include <sys/stat.h>#include <sys/mman.h> int main(){ /* the size (in bytes) of shared memory object */ const int SIZE = 4096; /* name of the shared memory object */ const char* name = \"OS\"; /* shared memory file descriptor */ int shm_fd; /* pointer to shared memory object */ void* ptr; /* open the shared memory object */ shm_fd = shm_open(name, O_RDONLY, 0666); /* memory map the shared memory object */ ptr = mmap(0, SIZE, PROT_READ, MAP_SHARED, shm_fd, 0); /* read from the shared memory object */ printf(\"%s\", (char*)ptr); /* remove the shared memory object */ shm_unlink(name); return 0;}", "e": 3365, "s": 2562, "text": null }, { "code": null, "e": 3475, "s": 3365, "text": "The above programs can be compiled by typing the following commands in terminal opened in working directory –" }, { "code": null, "e": 3584, "s": 3475, "text": "gcc producer.c -pthread -lrt -o producer\ngcc consumer.c -pthread -lrt -o consumer\n./consumer & ./producer & " }, { "code": null, "e": 3619, "s": 3584, "text": "This should output the following –" }, { "code": null, "e": 3631, "s": 3619, "text": "HelloWorld!" }, { "code": null, "e": 3714, "s": 3631, "text": "The above programs use the producer–consumer model in implementing shared memory. " }, { "code": null, "e": 3834, "s": 3714, "text": "The producer establishes a shared memory object and writes to shared memory, and the consumer reads from shared memory." }, { "code": null, "e": 3950, "s": 3834, "text": "The producer, creates a shared-memory object named OS and writes the famous string β€œHello World!” to shared memory." }, { "code": null, "e": 4110, "s": 3950, "text": "The program memory-maps a shared-memory object of the specified size and allows writing to the object. (Obviously, only writing is necessary for the producer.)" }, { "code": null, "e": 4370, "s": 4110, "text": "The flag MAP SHARED specifies that changes to the shared memory object will be visible to all processes sharing the object. Notice that we write to the shared-memory object by calling the sprintf() function and writing the formatted string to the pointer ptr." }, { "code": null, "e": 4525, "s": 4370, "text": "After each write, we must increment the pointer by the number of bytes written. The consumer process, reads and outputs the contents of the shared memory." }, { "code": null, "e": 4654, "s": 4525, "text": "The consumer also invokes the shm_unlink() function, which removes the shared-memory segment after the consumer has accessed it." }, { "code": null, "e": 4707, "s": 4654, "text": "References Silberschatz’s Operating System concepts " }, { "code": null, "e": 4779, "s": 4707, "text": "http://www.cse.cuhk.edu.hk/~ericlo/teaching/os/lab/7-IPC2/sync-pro.html" }, { "code": null, "e": 5199, "s": 4779, "text": "This article is contributed by Mayank Rana. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 5213, "s": 5199, "text": "HamidRamazani" }, { "code": null, "e": 5225, "s": 5213, "text": "anikakapoor" }, { "code": null, "e": 5242, "s": 5225, "text": "siddharthakapoor" }, { "code": null, "e": 5251, "s": 5242, "text": "Articles" }, { "code": null, "e": 5262, "s": 5251, "text": "Linux-Unix" }, { "code": null, "e": 5360, "s": 5262, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5386, "s": 5360, "text": "Docker - COPY Instruction" }, { "code": null, "e": 5433, "s": 5386, "text": "Time complexities of different data structures" }, { "code": null, "e": 5454, "s": 5433, "text": "SQL | DROP, TRUNCATE" }, { "code": null, "e": 5490, "s": 5454, "text": "Difference Between Object And Class" }, { "code": null, "e": 5533, "s": 5490, "text": "Implementation of LinkedList in Javascript" }, { "code": null, "e": 5573, "s": 5533, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 5613, "s": 5573, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 5640, "s": 5613, "text": "grep command in Unix/Linux" }, { "code": null, "e": 5675, "s": 5640, "text": "cut command in Linux with examples" } ]
Smallest prime divisor of a number
13 Jun, 2022 Given a number N, find the smallest prime divisor of N. Examples: Input: 25 Output: 5 Input: 31 Output: 31 Approach: Check if the number is divisible by 2 or not. Iterate from i = 3 to sqrt(N) and making a jump of 2. If any of the numbers divide N then it is the smallest prime divisor. If none of them divide, then N is the answer. Below is the implementation of the above algorithm: C++ Java Python3 C# PHP Javascript // C++ program to count the number of// subarrays that having 1#include <bits/stdc++.h>using namespace std; // Function to find the smallest divisorint smallestDivisor(int n){ // if divisible by 2 if (n % 2 == 0) return 2; // iterate from 3 to sqrt(n) for (int i = 3; i * i <= n; i += 2) { if (n % i == 0) return i; } return n;} // Driver Codeint main(){ int n = 31; cout << smallestDivisor(n); return 0;} // Java program to count the number of// subarrays that having 1 import java.io.*; class GFG {// Function to find the smallest divisorstatic int smallestDivisor(int n){ // if divisible by 2 if (n % 2 == 0) return 2; // iterate from 3 to sqrt(n) for (int i = 3; i * i <= n; i += 2) { if (n % i == 0) return i; } return n;} // Driver Code public static void main (String[] args) { int n = 31; System.out.println (smallestDivisor(n)); }} # Python3 program to count the number# of subarrays that having 1 # Function to find the smallest divisordef smallestDivisor(n): # if divisible by 2 if (n % 2 == 0): return 2; # iterate from 3 to sqrt(n) i = 3; while(i * i <= n): if (n % i == 0): return i; i += 2; return n; # Driver Coden = 31;print(smallestDivisor(n)); # This code is contributed by mits // C# program to count the number// of subarrays that having 1using System; class GFG{ // Function to find the// smallest divisorstatic int smallestDivisor(int n){ // if divisible by 2 if (n % 2 == 0) return 2; // iterate from 3 to sqrt(n) for (int i = 3; i * i <= n; i += 2) { if (n % i == 0) return i; } return n;} // Driver Codestatic public void Main (){ int n = 31; Console.WriteLine(smallestDivisor(n));}} // This code is contributed// by Sach_Code <?php// PHP program to count the number// of subarrays that having 1 // Function to find the smallest divisorfunction smallestDivisor($n){ // if divisible by 2 if ($n % 2 == 0) return 2; // iterate from 3 to sqrt(n) for ($i = 3; $i * $i <= $n; $i += 2) { if ($n % $i == 0) return $i; } return $n;} // Driver Code$n = 31;echo smallestDivisor($n); // This code is contributed by Sachin?> <script>// javascript program to count the number of// subarrays that having 1 // Function to find the smallest divisor function smallestDivisor(n) { // if divisible by 2 if (n % 2 == 0) return 2; // iterate from 3 to sqrt(n) for (var i = 3; i * i <= n; i += 2) { if (n % i == 0) return i; } return n; } // Driver Code var n = 31; document.write(smallestDivisor(n)); // This code is contributed by todaysgaurav</script> 31 How to efficiently find prime factors of all numbers till n? Please refer Least prime factor of numbers till n Time Complexity: O(sqrt(N)), as we are using a loop to traverse sqrt (N) times. As the condition is i*i<=N, on application of sqrt function on both the sides we get sqrt (i*i) <= sqrt(N), which is i<= sqrt(N), therefore the loop will traverse for sqrt(N) times. Auxiliary Space: O(1), as we are not using any extra space. Sach_Code Mithun Kumar todaysgaurav rohitkumarsinghcna prime-factor Competitive Programming Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Competitive Programming and How to Prepare for It? Count of strings whose prefix match with the given string to a given length k Bitwise Hacks for Competitive Programming Algorithm Library | C++ Magicians STL Algorithm Ordered Set and GNU C++ PBDS Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Jun, 2022" }, { "code": null, "e": 111, "s": 54, "text": "Given a number N, find the smallest prime divisor of N. " }, { "code": null, "e": 122, "s": 111, "text": "Examples: " }, { "code": null, "e": 142, "s": 122, "text": "Input: 25 Output: 5" }, { "code": null, "e": 165, "s": 142, "text": "Input: 31 Output: 31 " }, { "code": null, "e": 176, "s": 165, "text": "Approach: " }, { "code": null, "e": 222, "s": 176, "text": "Check if the number is divisible by 2 or not." }, { "code": null, "e": 276, "s": 222, "text": "Iterate from i = 3 to sqrt(N) and making a jump of 2." }, { "code": null, "e": 346, "s": 276, "text": "If any of the numbers divide N then it is the smallest prime divisor." }, { "code": null, "e": 392, "s": 346, "text": "If none of them divide, then N is the answer." }, { "code": null, "e": 445, "s": 392, "text": "Below is the implementation of the above algorithm: " }, { "code": null, "e": 449, "s": 445, "text": "C++" }, { "code": null, "e": 454, "s": 449, "text": "Java" }, { "code": null, "e": 462, "s": 454, "text": "Python3" }, { "code": null, "e": 465, "s": 462, "text": "C#" }, { "code": null, "e": 469, "s": 465, "text": "PHP" }, { "code": null, "e": 480, "s": 469, "text": "Javascript" }, { "code": "// C++ program to count the number of// subarrays that having 1#include <bits/stdc++.h>using namespace std; // Function to find the smallest divisorint smallestDivisor(int n){ // if divisible by 2 if (n % 2 == 0) return 2; // iterate from 3 to sqrt(n) for (int i = 3; i * i <= n; i += 2) { if (n % i == 0) return i; } return n;} // Driver Codeint main(){ int n = 31; cout << smallestDivisor(n); return 0;}", "e": 941, "s": 480, "text": null }, { "code": "// Java program to count the number of// subarrays that having 1 import java.io.*; class GFG {// Function to find the smallest divisorstatic int smallestDivisor(int n){ // if divisible by 2 if (n % 2 == 0) return 2; // iterate from 3 to sqrt(n) for (int i = 3; i * i <= n; i += 2) { if (n % i == 0) return i; } return n;} // Driver Code public static void main (String[] args) { int n = 31; System.out.println (smallestDivisor(n)); }}", "e": 1461, "s": 941, "text": null }, { "code": "# Python3 program to count the number# of subarrays that having 1 # Function to find the smallest divisordef smallestDivisor(n): # if divisible by 2 if (n % 2 == 0): return 2; # iterate from 3 to sqrt(n) i = 3; while(i * i <= n): if (n % i == 0): return i; i += 2; return n; # Driver Coden = 31;print(smallestDivisor(n)); # This code is contributed by mits", "e": 1872, "s": 1461, "text": null }, { "code": "// C# program to count the number// of subarrays that having 1using System; class GFG{ // Function to find the// smallest divisorstatic int smallestDivisor(int n){ // if divisible by 2 if (n % 2 == 0) return 2; // iterate from 3 to sqrt(n) for (int i = 3; i * i <= n; i += 2) { if (n % i == 0) return i; } return n;} // Driver Codestatic public void Main (){ int n = 31; Console.WriteLine(smallestDivisor(n));}} // This code is contributed// by Sach_Code", "e": 2397, "s": 1872, "text": null }, { "code": "<?php// PHP program to count the number// of subarrays that having 1 // Function to find the smallest divisorfunction smallestDivisor($n){ // if divisible by 2 if ($n % 2 == 0) return 2; // iterate from 3 to sqrt(n) for ($i = 3; $i * $i <= $n; $i += 2) { if ($n % $i == 0) return $i; } return $n;} // Driver Code$n = 31;echo smallestDivisor($n); // This code is contributed by Sachin?>", "e": 2831, "s": 2397, "text": null }, { "code": "<script>// javascript program to count the number of// subarrays that having 1 // Function to find the smallest divisor function smallestDivisor(n) { // if divisible by 2 if (n % 2 == 0) return 2; // iterate from 3 to sqrt(n) for (var i = 3; i * i <= n; i += 2) { if (n % i == 0) return i; } return n; } // Driver Code var n = 31; document.write(smallestDivisor(n)); // This code is contributed by todaysgaurav</script>", "e": 3368, "s": 2831, "text": null }, { "code": null, "e": 3371, "s": 3368, "text": "31" }, { "code": null, "e": 3483, "s": 3371, "text": "How to efficiently find prime factors of all numbers till n? Please refer Least prime factor of numbers till n " }, { "code": null, "e": 3745, "s": 3483, "text": "Time Complexity: O(sqrt(N)), as we are using a loop to traverse sqrt (N) times. As the condition is i*i<=N, on application of sqrt function on both the sides we get sqrt (i*i) <= sqrt(N), which is i<= sqrt(N), therefore the loop will traverse for sqrt(N) times." }, { "code": null, "e": 3805, "s": 3745, "text": "Auxiliary Space: O(1), as we are not using any extra space." }, { "code": null, "e": 3815, "s": 3805, "text": "Sach_Code" }, { "code": null, "e": 3828, "s": 3815, "text": "Mithun Kumar" }, { "code": null, "e": 3841, "s": 3828, "text": "todaysgaurav" }, { "code": null, "e": 3860, "s": 3841, "text": "rohitkumarsinghcna" }, { "code": null, "e": 3873, "s": 3860, "text": "prime-factor" }, { "code": null, "e": 3897, "s": 3873, "text": "Competitive Programming" }, { "code": null, "e": 3910, "s": 3897, "text": "Mathematical" }, { "code": null, "e": 3923, "s": 3910, "text": "Mathematical" }, { "code": null, "e": 4021, "s": 3923, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4080, "s": 4021, "text": "What is Competitive Programming and How to Prepare for It?" }, { "code": null, "e": 4158, "s": 4080, "text": "Count of strings whose prefix match with the given string to a given length k" }, { "code": null, "e": 4200, "s": 4158, "text": "Bitwise Hacks for Competitive Programming" }, { "code": null, "e": 4248, "s": 4200, "text": "Algorithm Library | C++ Magicians STL Algorithm" }, { "code": null, "e": 4277, "s": 4248, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 4307, "s": 4277, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 4350, "s": 4307, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 4410, "s": 4350, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 4425, "s": 4410, "text": "C++ Data Types" } ]
How to get column and row names in DataFrame?
22 Feb, 2022 While analyzing the real datasets which are often very huge in size, we might need to get the rows or index names and columns names in order to perform certain operations. Note: For downloading the nba dataset used in the below examples Click Here First, let’s create a simple dataframe with nba.csv Python3 # Import pandas packageimport pandas as pd # making data framedata = pd.read_csv("nba.csv") # calling head() method # storing in new variabledata_top = data.head(10) # displaydata_top Output: Now let’s try to get the row name from the above dataset. Method #1: Simply iterate over indices Python3 # Import pandas packageimport pandas as pd # making data framedata = pd.read_csv("nba.csv") # calling head() method # storing in new variabledata_top = data.head() # iterating the columnsfor row in data_top.index: print(row, end = " ") Output: 0 1 2 3 4 5 6 7 8 9 Method #2: Using rows with dataframe object Python3 # Import pandas packageimport pandas as pd # making data framedata = pd.read_csv("nba.csv") # calling head() method # storing in new variabledata_top = data.head() # list(data_top) orlist(data_top.index) Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Method #3: index.values method returns an array of indexes. Python3 # Import pandas packageimport pandas as pd # making data framedata = pd.read_csv("nba.csv") # calling head() method # storing in new variabledata_top = data.head() list(data_top.index.values) Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Method #4: Using the tolist() method with values given the list of indexes. Python3 # Import pandas packageimport pandas as pd # making data framedata = pd.read_csv("nba.csv") # calling head() method # storing in new variabledata_top = data.head() list(data_top.index.values.tolist()) Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Method #5: Count the number of rows in dataframeSince we have loaded only 10 top rows of the dataframe using the head() method, let’s verify the total number of rows first. Python3 # iterate the indices and print each onefor row in data.index: print(row, end = " ") Output: Now, let’s print the total count of the index. Python3 # Import pandas packageimport pandas as pd # making data framedata = pd.read_csv("nba.csv") row_count = 0 # iterating over indicesfor col in data.index: row_count += 1 # print the row countprint(row_count) Output: 458 Now let’s try to get the columns name from the nba.csv dataset.Method #1: Simply iterating over columns Python3 # Import pandas packageimport pandas as pd # making data framedata = pd.read_csv("nba.csv") # iterating the columnsfor col in data.columns: print(col) Output: Method #2: Using columns with dataframe object Python3 # Import pandas packageimport pandas as pd # making data framedata = pd.read_csv("nba.csv") # list(data) orlist(data.columns) Output: Method #3: column.values method returns an array of indexes. Python3 # Import pandas packageimport pandas as pd # making data framedata = pd.read_csv("nba.csv") list(data.columns.values) Output: Method #4: Using tolist() method with values with given the list of columns. Python3 # Import pandas packageimport pandas as pd # making data framedata = pd.read_csv("nba.csv") list(data.columns.values.tolist()) Output: Method #5: Using sorted() methodSorted() method will return the list of columns sorted in alphabetical order. Python3 # Import pandas packageimport pandas as pd # making data framedata = pd.read_csv("nba.csv") # using sorted() methodsorted(data) Output: simmytarika5 surinderdawra388 kumaripunam984122 Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Feb, 2022" }, { "code": null, "e": 225, "s": 52, "text": "While analyzing the real datasets which are often very huge in size, we might need to get the rows or index names and columns names in order to perform certain operations. " }, { "code": null, "e": 302, "s": 225, "text": "Note: For downloading the nba dataset used in the below examples Click Here " }, { "code": null, "e": 355, "s": 302, "text": "First, let’s create a simple dataframe with nba.csv " }, { "code": null, "e": 363, "s": 355, "text": "Python3" }, { "code": "# Import pandas packageimport pandas as pd # making data framedata = pd.read_csv(\"nba.csv\") # calling head() method # storing in new variabledata_top = data.head(10) # displaydata_top", "e": 553, "s": 363, "text": null }, { "code": null, "e": 562, "s": 553, "text": "Output: " }, { "code": null, "e": 620, "s": 562, "text": "Now let’s try to get the row name from the above dataset." }, { "code": null, "e": 660, "s": 620, "text": "Method #1: Simply iterate over indices " }, { "code": null, "e": 668, "s": 660, "text": "Python3" }, { "code": "# Import pandas packageimport pandas as pd # making data framedata = pd.read_csv(\"nba.csv\") # calling head() method # storing in new variabledata_top = data.head() # iterating the columnsfor row in data_top.index: print(row, end = \" \")", "e": 911, "s": 668, "text": null }, { "code": null, "e": 920, "s": 911, "text": "Output: " }, { "code": null, "e": 941, "s": 920, "text": "0 1 2 3 4 5 6 7 8 9 " }, { "code": null, "e": 988, "s": 941, "text": " Method #2: Using rows with dataframe object " }, { "code": null, "e": 996, "s": 988, "text": "Python3" }, { "code": "# Import pandas packageimport pandas as pd # making data framedata = pd.read_csv(\"nba.csv\") # calling head() method # storing in new variabledata_top = data.head() # list(data_top) orlist(data_top.index)", "e": 1204, "s": 996, "text": null }, { "code": null, "e": 1213, "s": 1204, "text": "Output: " }, { "code": null, "e": 1244, "s": 1213, "text": "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" }, { "code": null, "e": 1307, "s": 1244, "text": " Method #3: index.values method returns an array of indexes. " }, { "code": null, "e": 1315, "s": 1307, "text": "Python3" }, { "code": "# Import pandas packageimport pandas as pd # making data framedata = pd.read_csv(\"nba.csv\") # calling head() method # storing in new variabledata_top = data.head() list(data_top.index.values)", "e": 1511, "s": 1315, "text": null }, { "code": null, "e": 1520, "s": 1511, "text": "Output: " }, { "code": null, "e": 1551, "s": 1520, "text": "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" }, { "code": null, "e": 1630, "s": 1551, "text": " Method #4: Using the tolist() method with values given the list of indexes. " }, { "code": null, "e": 1638, "s": 1630, "text": "Python3" }, { "code": "# Import pandas packageimport pandas as pd # making data framedata = pd.read_csv(\"nba.csv\") # calling head() method # storing in new variabledata_top = data.head() list(data_top.index.values.tolist())", "e": 1843, "s": 1638, "text": null }, { "code": null, "e": 1852, "s": 1843, "text": "Output: " }, { "code": null, "e": 1883, "s": 1852, "text": "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" }, { "code": null, "e": 2056, "s": 1883, "text": "Method #5: Count the number of rows in dataframeSince we have loaded only 10 top rows of the dataframe using the head() method, let’s verify the total number of rows first." }, { "code": null, "e": 2064, "s": 2056, "text": "Python3" }, { "code": "# iterate the indices and print each onefor row in data.index: print(row, end = \" \")", "e": 2152, "s": 2064, "text": null }, { "code": null, "e": 2161, "s": 2152, "text": "Output: " }, { "code": null, "e": 2209, "s": 2161, "text": "Now, let’s print the total count of the index. " }, { "code": null, "e": 2217, "s": 2209, "text": "Python3" }, { "code": "# Import pandas packageimport pandas as pd # making data framedata = pd.read_csv(\"nba.csv\") row_count = 0 # iterating over indicesfor col in data.index: row_count += 1 # print the row countprint(row_count)", "e": 2428, "s": 2217, "text": null }, { "code": null, "e": 2437, "s": 2428, "text": "Output: " }, { "code": null, "e": 2441, "s": 2437, "text": "458" }, { "code": null, "e": 2546, "s": 2441, "text": "Now let’s try to get the columns name from the nba.csv dataset.Method #1: Simply iterating over columns " }, { "code": null, "e": 2554, "s": 2546, "text": "Python3" }, { "code": "# Import pandas packageimport pandas as pd # making data framedata = pd.read_csv(\"nba.csv\") # iterating the columnsfor col in data.columns: print(col)", "e": 2710, "s": 2554, "text": null }, { "code": null, "e": 2719, "s": 2710, "text": "Output: " }, { "code": null, "e": 2769, "s": 2719, "text": " Method #2: Using columns with dataframe object " }, { "code": null, "e": 2777, "s": 2769, "text": "Python3" }, { "code": "# Import pandas packageimport pandas as pd # making data framedata = pd.read_csv(\"nba.csv\") # list(data) orlist(data.columns)", "e": 2907, "s": 2777, "text": null }, { "code": null, "e": 2917, "s": 2907, "text": "Output: " }, { "code": null, "e": 2981, "s": 2917, "text": " Method #3: column.values method returns an array of indexes. " }, { "code": null, "e": 2989, "s": 2981, "text": "Python3" }, { "code": "# Import pandas packageimport pandas as pd # making data framedata = pd.read_csv(\"nba.csv\") list(data.columns.values)", "e": 3111, "s": 2989, "text": null }, { "code": null, "e": 3121, "s": 3111, "text": "Output: " }, { "code": null, "e": 3201, "s": 3121, "text": " Method #4: Using tolist() method with values with given the list of columns. " }, { "code": null, "e": 3209, "s": 3201, "text": "Python3" }, { "code": "# Import pandas packageimport pandas as pd # making data framedata = pd.read_csv(\"nba.csv\") list(data.columns.values.tolist())", "e": 3340, "s": 3209, "text": null }, { "code": null, "e": 3350, "s": 3340, "text": "Output: " }, { "code": null, "e": 3463, "s": 3350, "text": " Method #5: Using sorted() methodSorted() method will return the list of columns sorted in alphabetical order. " }, { "code": null, "e": 3471, "s": 3463, "text": "Python3" }, { "code": "# Import pandas packageimport pandas as pd # making data framedata = pd.read_csv(\"nba.csv\") # using sorted() methodsorted(data)", "e": 3603, "s": 3471, "text": null }, { "code": null, "e": 3613, "s": 3603, "text": "Output: " }, { "code": null, "e": 3628, "s": 3615, "text": "simmytarika5" }, { "code": null, "e": 3645, "s": 3628, "text": "surinderdawra388" }, { "code": null, "e": 3663, "s": 3645, "text": "kumaripunam984122" }, { "code": null, "e": 3687, "s": 3663, "text": "Python pandas-dataFrame" }, { "code": null, "e": 3701, "s": 3687, "text": "Python-pandas" }, { "code": null, "e": 3708, "s": 3701, "text": "Python" } ]
Python – Tensorflow math.add() method
07 Jan, 2022 Tensorflow math.add() method returns the a + b of the passes inputs. The operation is done on the representation of a and b. This method belongs to math module. Syntax: tf.math.add(a, b, name=None) Arguments a: This parameter should be a Tensor and also from the one of the following types: bfloat16, half, float32, float64, uint8, int8, int16, int32, int64, complex64, complex128, string b: This should also be a Tensor and must have the same type as a. name: This is optional parameter and this is the name of the operation. Return: It returns a Tensor having the same shape as of input a. Python3 # Importing the Tensorflow library import tensorflow as tf # A constant a and ba = tf.constant(3)b = tf.constant(6) # Applying the math.add() function # storing the result in 'c' c = tf.math.add(a, b) # Initiating a Tensorflow session with tf.Session() as sess: print("Input 1", a) print(sess.run(a)) print("Input 2", b) print(sess.run(b)) print("Output: ", c) print(sess.run(c)) Input 1 Tensor("Const_79:0", shape=(), dtype=int32) 3 Input 2 Tensor("Const_80:0", shape=(), dtype=int32) 6 Output: Tensor("Add_1:0", shape=(), dtype=int32) 9 Example 2: Python3 # Importing the Tensorflow library import tensorflow as tf # A constant a and ba = tf.constant(u"This is ")b = tf.constant(u"GeeksForGeeks") # Applying the math.add() function # storing the result in 'c' c = tf.math.add(a, b) # Initiating a Tensorflow session with tf.Session() as sess: print("Input 1", a) print(sess.run(a)) print("Input 2", b) print(sess.run(b)) print("Output: ", c) print(sess.run(c)) Input 1 Tensor("Const_87:0", shape=(), dtype=string) b'This is ' Input 2 Tensor("Const_88:0", shape=(), dtype=string) b'GeeksForGeeks' Output: Tensor("Add_5:0", shape=(), dtype=string) b'This is GeeksForGeeks' sumitgumber28 Python Tensorflow-math-functions Python-Tensorflow Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jan, 2022" }, { "code": null, "e": 189, "s": 28, "text": "Tensorflow math.add() method returns the a + b of the passes inputs. The operation is done on the representation of a and b. This method belongs to math module." }, { "code": null, "e": 226, "s": 189, "text": "Syntax: tf.math.add(a, b, name=None)" }, { "code": null, "e": 236, "s": 226, "text": "Arguments" }, { "code": null, "e": 417, "s": 236, "text": "a: This parameter should be a Tensor and also from the one of the following types: bfloat16, half, float32, float64, uint8, int8, int16, int32, int64, complex64, complex128, string" }, { "code": null, "e": 483, "s": 417, "text": "b: This should also be a Tensor and must have the same type as a." }, { "code": null, "e": 555, "s": 483, "text": "name: This is optional parameter and this is the name of the operation." }, { "code": null, "e": 620, "s": 555, "text": "Return: It returns a Tensor having the same shape as of input a." }, { "code": null, "e": 628, "s": 620, "text": "Python3" }, { "code": "# Importing the Tensorflow library import tensorflow as tf # A constant a and ba = tf.constant(3)b = tf.constant(6) # Applying the math.add() function # storing the result in 'c' c = tf.math.add(a, b) # Initiating a Tensorflow session with tf.Session() as sess: print(\"Input 1\", a) print(sess.run(a)) print(\"Input 2\", b) print(sess.run(b)) print(\"Output: \", c) print(sess.run(c))", "e": 1032, "s": 628, "text": null }, { "code": null, "e": 1193, "s": 1032, "text": "Input 1 Tensor(\"Const_79:0\", shape=(), dtype=int32)\n3\nInput 2 Tensor(\"Const_80:0\", shape=(), dtype=int32)\n6\nOutput: Tensor(\"Add_1:0\", shape=(), dtype=int32)\n9\n" }, { "code": null, "e": 1204, "s": 1193, "text": "Example 2:" }, { "code": null, "e": 1212, "s": 1204, "text": "Python3" }, { "code": "# Importing the Tensorflow library import tensorflow as tf # A constant a and ba = tf.constant(u\"This is \")b = tf.constant(u\"GeeksForGeeks\") # Applying the math.add() function # storing the result in 'c' c = tf.math.add(a, b) # Initiating a Tensorflow session with tf.Session() as sess: print(\"Input 1\", a) print(sess.run(a)) print(\"Input 2\", b) print(sess.run(b)) print(\"Output: \", c) print(sess.run(c))", "e": 1641, "s": 1212, "text": null }, { "code": null, "e": 1853, "s": 1641, "text": "Input 1 Tensor(\"Const_87:0\", shape=(), dtype=string)\nb'This is '\nInput 2 Tensor(\"Const_88:0\", shape=(), dtype=string)\nb'GeeksForGeeks'\nOutput: Tensor(\"Add_5:0\", shape=(), dtype=string)\nb'This is GeeksForGeeks'\n" }, { "code": null, "e": 1867, "s": 1853, "text": "sumitgumber28" }, { "code": null, "e": 1900, "s": 1867, "text": "Python Tensorflow-math-functions" }, { "code": null, "e": 1918, "s": 1900, "text": "Python-Tensorflow" }, { "code": null, "e": 1925, "s": 1918, "text": "Python" }, { "code": null, "e": 2023, "s": 1925, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2055, "s": 2023, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2082, "s": 2055, "text": "Python Classes and Objects" }, { "code": null, "e": 2103, "s": 2082, "text": "Python OOPs Concepts" }, { "code": null, "e": 2126, "s": 2103, "text": "Introduction To PYTHON" }, { "code": null, "e": 2182, "s": 2126, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2213, "s": 2182, "text": "Python | os.path.join() method" }, { "code": null, "e": 2255, "s": 2213, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2297, "s": 2255, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2336, "s": 2297, "text": "Python | Get unique values from a list" } ]
Python Program for Pigeonhole Sort
30 Dec, 2020 Pigeonhole sorting is a sorting algorithm that is suitable for sorting lists of elements where the number of elements and the number of possible key values are approximately the same.It requires O(n + Range) time where n is number of elements in input array and \’Range\’ is number of possible values in array. Working of Algorithm : Find minimum and maximum values in array. Let the minimum and maximum values be \’min\’ and \’max\’ respectively. Also find range as \’max-min-1\’.Set up an array of initially empty β€œpigeonholes” the same size as of the range.Visit each element of the array and then put each element in its pigeonhole. An element arr[i] is put in hole at index arr[i] – min.Start the loop all over the pigeonhole array in order and put the elements from non- empty holes back into the original array. Find minimum and maximum values in array. Let the minimum and maximum values be \’min\’ and \’max\’ respectively. Also find range as \’max-min-1\’. Set up an array of initially empty β€œpigeonholes” the same size as of the range. Visit each element of the array and then put each element in its pigeonhole. An element arr[i] is put in hole at index arr[i] – min. Start the loop all over the pigeonhole array in order and put the elements from non- empty holes back into the original array. # Python program to implement Pigeonhole Sort */ # source code : "https://en.wikibooks.org/wiki/# Algorithm_Implementation/Sorting/Pigeonhole_sort"def pigeonhole_sort(a): # size of range of values in the list # (ie, number of pigeonholes we need) my_min = min(a) my_max = max(a) size = my_max - my_min + 1 # our list of pigeonholes holes = [0] * size # Populate the pigeonholes. for x in a: assert type(x) is int, "integers only please" holes[x - my_min] += 1 # Put the elements back into the array in order. i = 0 for count in range(size): while holes[count] > 0: holes[count] -= 1 a[i] = count + my_min i += 1 a = [8, 3, 2, 7, 4, 6, 8]print("Sorted order is : ", end =" ") pigeonhole_sort(a) for i in range(0, len(a)): print(a[i], end =" ") Output: Sorted order is : 2 3 4 6 7 8 8 Please refer complete article on Pigeonhole Sort for more details! python sorting-exercises Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers Python program to check whether a number is Prime or not Python program to add two numbers Python Program for Binary Search (Recursive and Iterative) Python Program for factorial of a number Python program to find second largest number in a list Iterate over characters of a string in Python Python program to interchange first and last elements in a list
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Dec, 2020" }, { "code": null, "e": 339, "s": 28, "text": "Pigeonhole sorting is a sorting algorithm that is suitable for sorting lists of elements where the number of elements and the number of possible key values are approximately the same.It requires O(n + Range) time where n is number of elements in input array and \\’Range\\’ is number of possible values in array." }, { "code": null, "e": 362, "s": 339, "text": "Working of Algorithm :" }, { "code": null, "e": 847, "s": 362, "text": "Find minimum and maximum values in array. Let the minimum and maximum values be \\’min\\’ and \\’max\\’ respectively. Also find range as \\’max-min-1\\’.Set up an array of initially empty β€œpigeonholes” the same size as of the range.Visit each element of the array and then put each element in its pigeonhole. An element arr[i] is put in hole at index arr[i] – min.Start the loop all over the pigeonhole array in order and put the elements from non- empty holes back into the original array." }, { "code": null, "e": 995, "s": 847, "text": "Find minimum and maximum values in array. Let the minimum and maximum values be \\’min\\’ and \\’max\\’ respectively. Also find range as \\’max-min-1\\’." }, { "code": null, "e": 1075, "s": 995, "text": "Set up an array of initially empty β€œpigeonholes” the same size as of the range." }, { "code": null, "e": 1208, "s": 1075, "text": "Visit each element of the array and then put each element in its pigeonhole. An element arr[i] is put in hole at index arr[i] – min." }, { "code": null, "e": 1335, "s": 1208, "text": "Start the loop all over the pigeonhole array in order and put the elements from non- empty holes back into the original array." }, { "code": "# Python program to implement Pigeonhole Sort */ # source code : \"https://en.wikibooks.org/wiki/# Algorithm_Implementation/Sorting/Pigeonhole_sort\"def pigeonhole_sort(a): # size of range of values in the list # (ie, number of pigeonholes we need) my_min = min(a) my_max = max(a) size = my_max - my_min + 1 # our list of pigeonholes holes = [0] * size # Populate the pigeonholes. for x in a: assert type(x) is int, \"integers only please\" holes[x - my_min] += 1 # Put the elements back into the array in order. i = 0 for count in range(size): while holes[count] > 0: holes[count] -= 1 a[i] = count + my_min i += 1 a = [8, 3, 2, 7, 4, 6, 8]print(\"Sorted order is : \", end =\" \") pigeonhole_sort(a) for i in range(0, len(a)): print(a[i], end =\" \") ", "e": 2211, "s": 1335, "text": null }, { "code": null, "e": 2219, "s": 2211, "text": "Output:" }, { "code": null, "e": 2252, "s": 2219, "text": "Sorted order is : 2 3 4 6 7 8 8 " }, { "code": null, "e": 2319, "s": 2252, "text": "Please refer complete article on Pigeonhole Sort for more details!" }, { "code": null, "e": 2344, "s": 2319, "text": "python sorting-exercises" }, { "code": null, "e": 2360, "s": 2344, "text": "Python Programs" }, { "code": null, "e": 2458, "s": 2360, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2496, "s": 2458, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2545, "s": 2496, "text": "Python | Convert string dictionary to dictionary" }, { "code": null, "e": 2582, "s": 2545, "text": "Python Program for Fibonacci numbers" }, { "code": null, "e": 2639, "s": 2582, "text": "Python program to check whether a number is Prime or not" }, { "code": null, "e": 2673, "s": 2639, "text": "Python program to add two numbers" }, { "code": null, "e": 2732, "s": 2673, "text": "Python Program for Binary Search (Recursive and Iterative)" }, { "code": null, "e": 2773, "s": 2732, "text": "Python Program for factorial of a number" }, { "code": null, "e": 2828, "s": 2773, "text": "Python program to find second largest number in a list" }, { "code": null, "e": 2874, "s": 2828, "text": "Iterate over characters of a string in Python" } ]
Flutter – Setup for Web Development
16 Oct, 2020 As we know, the Flutter is growing day by day and become more powerful in just a small-time span. Initially, the flutter SDK released for Mobile App Development. But, now it is not limited to Mobile Apps, It also is available for Web and Desktop Application. Today, We learn how to make your first Web App using Flutter. Switching Flutter to the web does not require any hard configuration. By using some commands we can easily move to the web. Let’s get to one of the most exciting features on the Horizon for Flutter which is Web Development. 1. Let’s start by switching to the Master Channel. Run the following command in your terminal. flutter channel master 2. Then upgrade your channel to the latest version flutter upgrade 3. Then you have to enable the web flag to get Web Support for your project. You may restart your project after this step. flutter config --enable-web 4. Now, we can check that is every this is fine working by running the doctor command in the terminal. flutter doctor You can check that your channel is which to Master Successfully We can also check the devices which are available for launching your Web App. Because web app needs a browser to be run. Run the following command and you will see the list of the browser available on your system. flutter devices Output 1. Let’s start to create a Flutter Project by running the simple and most powerful command in the Flutter. If everything is going to be fine. We see the index.html file in the terminal flutter create <your _projectName> # In this case we named the project is web_flutter See index.html file is added to our project 2. Now, Your Project is ready to run on the Web. Just run the last Command which is. flutter run -d chrome You can use any of the available devices. After running this just wait for some time, it may take some time for the first time. If you get the error regarding firewalls. You can run the following commands. flutter clean And then flutter run -d chrome If you have to move again to Mobile development, then you have to switch to the stable channel. Now, all flutter web setup is done. Hope this is helpful and if there is any correction. android Web technologies Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Search Bar Flutter - Pop Up Menu Flutter - BorderRadius Widget Flutter - Card Widget Flutter - Positioned Widget Flutter - Padding Widget Flutter - Modal Bottom Sheet Flutter - Managing the MediaQuery Object Flutter - dispose() Method with Example Format Dates in Flutter
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Oct, 2020" }, { "code": null, "e": 287, "s": 28, "text": "As we know, the Flutter is growing day by day and become more powerful in just a small-time span. Initially, the flutter SDK released for Mobile App Development. But, now it is not limited to Mobile Apps, It also is available for Web and Desktop Application." }, { "code": null, "e": 574, "s": 287, "text": "Today, We learn how to make your first Web App using Flutter. Switching Flutter to the web does not require any hard configuration. By using some commands we can easily move to the web. Let’s get to one of the most exciting features on the Horizon for Flutter which is Web Development." }, { "code": null, "e": 672, "s": 574, "text": " 1. Let’s start by switching to the Master Channel. Run the following command in your terminal." }, { "code": null, "e": 695, "s": 672, "text": "flutter channel master" }, { "code": null, "e": 749, "s": 695, "text": " 2. Then upgrade your channel to the latest version" }, { "code": null, "e": 765, "s": 749, "text": "flutter upgrade" }, { "code": null, "e": 890, "s": 765, "text": " 3. Then you have to enable the web flag to get Web Support for your project. You may restart your project after this step." }, { "code": null, "e": 919, "s": 890, "text": "flutter config --enable-web " }, { "code": null, "e": 1024, "s": 919, "text": " 4. Now, we can check that is every this is fine working by running the doctor command in the terminal." }, { "code": null, "e": 1039, "s": 1024, "text": "flutter doctor" }, { "code": null, "e": 1103, "s": 1039, "text": "You can check that your channel is which to Master Successfully" }, { "code": null, "e": 1317, "s": 1103, "text": "We can also check the devices which are available for launching your Web App. Because web app needs a browser to be run. Run the following command and you will see the list of the browser available on your system." }, { "code": null, "e": 1333, "s": 1317, "text": "flutter devices" }, { "code": null, "e": 1340, "s": 1333, "text": "Output" }, { "code": null, "e": 1528, "s": 1340, "text": " 1. Let’s start to create a Flutter Project by running the simple and most powerful command in the Flutter. If everything is going to be fine. We see the index.html file in the terminal" }, { "code": null, "e": 1563, "s": 1528, "text": "flutter create <your _projectName>" }, { "code": null, "e": 1614, "s": 1563, "text": "# In this case we named the project is web_flutter" }, { "code": null, "e": 1658, "s": 1614, "text": "See index.html file is added to our project" }, { "code": null, "e": 1745, "s": 1658, "text": " 2. Now, Your Project is ready to run on the Web. Just run the last Command which is." }, { "code": null, "e": 1767, "s": 1745, "text": "flutter run -d chrome" }, { "code": null, "e": 1897, "s": 1767, "text": " You can use any of the available devices. After running this just wait for some time, it may take some time for the first time. " }, { "code": null, "e": 1975, "s": 1897, "text": "If you get the error regarding firewalls. You can run the following commands." }, { "code": null, "e": 1989, "s": 1975, "text": "flutter clean" }, { "code": null, "e": 1998, "s": 1989, "text": "And then" }, { "code": null, "e": 2020, "s": 1998, "text": "flutter run -d chrome" }, { "code": null, "e": 2117, "s": 2020, "text": " If you have to move again to Mobile development, then you have to switch to the stable channel." }, { "code": null, "e": 2207, "s": 2117, "text": "Now, all flutter web setup is done. Hope this is helpful and if there is any correction. " }, { "code": null, "e": 2215, "s": 2207, "text": "android" }, { "code": null, "e": 2232, "s": 2215, "text": "Web technologies" }, { "code": null, "e": 2240, "s": 2232, "text": "Flutter" }, { "code": null, "e": 2338, "s": 2240, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2359, "s": 2338, "text": "Flutter - Search Bar" }, { "code": null, "e": 2381, "s": 2359, "text": "Flutter - Pop Up Menu" }, { "code": null, "e": 2411, "s": 2381, "text": "Flutter - BorderRadius Widget" }, { "code": null, "e": 2433, "s": 2411, "text": "Flutter - Card Widget" }, { "code": null, "e": 2461, "s": 2433, "text": "Flutter - Positioned Widget" }, { "code": null, "e": 2486, "s": 2461, "text": "Flutter - Padding Widget" }, { "code": null, "e": 2515, "s": 2486, "text": "Flutter - Modal Bottom Sheet" }, { "code": null, "e": 2556, "s": 2515, "text": "Flutter - Managing the MediaQuery Object" }, { "code": null, "e": 2596, "s": 2556, "text": "Flutter - dispose() Method with Example" } ]
Python - Matplotlib
Matplotlib is a python library used to create 2D graphs and plots by using python scripts. It has a module named pyplot which makes things easy for plotting by providing feature to control line styles, font properties, formatting axes etc. It supports a very wide variety of graphs and plots namely - histogram, bar charts, power spectra, error charts etc. It is used along with NumPy to provide an environment that is an effective open source alternative for MatLab. It can also be used with graphics toolkits like PyQt and wxPython. Conventionally, the package is imported into the Python script by adding the following statement βˆ’ from matplotlib import pyplot as plt The following script produces the sine wave plot using matplotlib. import numpy as np import matplotlib.pyplot as plt # Compute the x and y coordinates for points on a sine curve x = np.arange(0, 3 * np.pi, 0.1) y = np.sin(x) plt.title("sine wave form") # Plot the points using matplotlib plt.plot(x, y) plt.show() Its output is as follows βˆ’ We will see lots of examples on using Matplotlib library of python in Data science work in the next chapters.
[ { "code": null, "e": 3198, "s": 2663, "text": "Matplotlib is a python library used to create 2D graphs and plots by using python scripts. It has a module named pyplot which makes things easy for plotting by providing feature to control line styles, font properties, formatting axes etc. It supports a very wide variety of graphs and plots namely - histogram, bar charts, power spectra, error charts etc. It is used along with NumPy to provide an environment that is an effective open source alternative for MatLab. It can also be used with graphics toolkits like PyQt and wxPython." }, { "code": null, "e": 3297, "s": 3198, "text": "Conventionally, the package is imported into the Python script by adding the following statement βˆ’" }, { "code": null, "e": 3335, "s": 3297, "text": "from matplotlib import pyplot as plt\n" }, { "code": null, "e": 3402, "s": 3335, "text": "The following script produces the sine wave plot using matplotlib." }, { "code": null, "e": 3662, "s": 3402, "text": "import numpy as np \nimport matplotlib.pyplot as plt \n\n# Compute the x and y coordinates for points on a sine curve \nx = np.arange(0, 3 * np.pi, 0.1) \ny = np.sin(x) \nplt.title(\"sine wave form\") \n\n# Plot the points using matplotlib \nplt.plot(x, y) \nplt.show() " }, { "code": null, "e": 3689, "s": 3662, "text": "Its output is as follows βˆ’" } ]
For Loop in Java | Important points
17 Dec, 2021 Looping in programming languages is a feature that facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. In Java, just unlikely any programming language provides four ways for executing the loops namely while loop, for loop, for-each loop, do-while loop or we can call it basically three types of loops in some books as for-each loop is treated as enhanced for loop. Let us discuss for loop in details. Generally, we tend to use while loops as we do get a better understanding if we are into learning loops but after a saturation, we as programmers tend to tilt towards for loop as it is cleaner and foundations are carried out in a straight go for which we have to carefully grasp syntax as follows: Syntax: It consists of three parts namely as listed: Initialization of variables Specific condition as per requirement over which these defined variables are needed to be iterated A terminating part where we generally play with variables to reach to terminating condition state. for(initialization; boolean expression; update statement) { // Body of for loop } This is generally the basic pilgrimage structure of for loop. Let’s look at some basic examples of using for loop and the common pitfalls in using for loop which enables us to know even better as internal working will be depicted as we will be playing with codes. Usecase 1: Providing expression in for loop is a must For loop must consist of a valid expression in the loop statement failing which can lead to an infinite loop. The statement for ( ; ; ) is similar to while(true) Note: This above said is crux of advanced programming as it is origin of logic building in programming. Example Java // Java program to illustrate Infinite For loop // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // For loop for (;;) { // Print statement everytime condition holds // true making body to execute System.out.println("This is an infinite loop"); } }} Output: Prints the statement β€œThis is an infinite loop” repeatedly. This is an infinite loop This is an infinite loop This is an infinite loop This is an infinite loop ... ... This is an infinite loop Usecase 2: Initializing Multiple Variables In Java, multiple variables can be initialized in the initialization block of for loop regardless of whether you use it in the loop or not. Example: Java // Java Program to Illustrate Initializing Multiple// Variables in Initialization Block // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring an integer variable int x = 2; // For loop to iterate for (long y = 0, z = 4; x < 10 && y < 10; x++, y++) { // Printing value/s stored in variable named y // defined inside body of for loop System.out.println(y + " "); } // Printing value/s stored in variable named x // defined outside body of for loop System.out.println(x); }} 0 1 2 3 4 5 6 7 10 In the above code, there is simple variation in the for loop. Two variables are declared and initialized in the initialization block. The variable β€˜z’ is not being used. Also, the other two components contain extra variables. So, it can be seen that the blocks may include extra variables which may not be referenced by each other. Usecase 3: Redeclaration of a Variable in the Initialization Block Suppose, an initialization variable is already declared as an integer. Here we can not re-declare it in for loop with another data type as follows: Example 1: Java // Java Program to Illustrate Redeclaring a Variable// in Initialization Block // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring an integer variable int x = 0; // Redeclaring above variable // as long will not work for (long y = 0, x = 1; x < 5; x++) { // Printing the value inside the variable System.out.print(x + " "); } }} Output: Example3.java:12: error: variable x is already defined in method main(String[]) for(long y = 0, x = 1; x < 5; x++) Here, x was already initialized to zero as an integer and is being re-declared in the loop with data type long. But this problem can be fixed by slightly modifying the code. Here, the variables x and y are declared in a different way. Example 2: Java // Java Program to Illustrate Redeclaring a Variable// in Initialization Block // Main classpublic class GFG { // main driver method public static void main(String[] args) { // Declaring and initializing variables int x = 0; long y = 10; // For loop to iterate over till // custom specified check for (y = 0, x = 1; x < 5; x++) { // Printing value contained in memory block // of the variable System.out.print(x + " "); } }} Output: 1 2 3 4 Usecase 4: Variables declared in the initialization block must be of the same type It is just common sense that when we declare a variable as shown below: int x, y; Here both variables are of the same type. It is just the same in for loop initialization block too. Example: Java // Java program to Illustrate Declaring a Variable// in Initialization Block // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring integer variable // int x; // Note: This will cause error; // Redeclaring x as long will not work for (long y = 0, x = 1; x < 5; x++) { // Printing the value stored System.out.print(x + " "); } }} 1 2 3 4 Usecase 5: Variables in the loop are accessible only within The variables that are declared in the initialization block can be accessed only within the loop as we have as per the concept of the scope of variables. Example: Java // Java Program to Illustrate Scope of Initializing// Variables Within the oop // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // x and y scope is declared only // within for loop for (int x = 0, y = 0; x < 3 && y < 3; x++, y++) { // Printing value stored in variable named y System.out.println(y + " "); } // Printing value stored in variable named x // after inner loop is over System.out.println(x); }} Error: Example5.java:13: error: cannot find symbol System.out.println(x); In the above example, variable x is not accessible outside the loop. The statement which is commented gives a compiler error. This article is contributed by Preeti Pardeshi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Akanksha_Rai solankimayank anikakapoor sweetyty simranarora5sos Java-Control-Flow Java Java-Control-Flow Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Stream In Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Dec, 2021" }, { "code": null, "e": 513, "s": 52, "text": "Looping in programming languages is a feature that facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. In Java, just unlikely any programming language provides four ways for executing the loops namely while loop, for loop, for-each loop, do-while loop or we can call it basically three types of loops in some books as for-each loop is treated as enhanced for loop. Let us discuss for loop in details." }, { "code": null, "e": 811, "s": 513, "text": "Generally, we tend to use while loops as we do get a better understanding if we are into learning loops but after a saturation, we as programmers tend to tilt towards for loop as it is cleaner and foundations are carried out in a straight go for which we have to carefully grasp syntax as follows:" }, { "code": null, "e": 864, "s": 811, "text": "Syntax: It consists of three parts namely as listed:" }, { "code": null, "e": 892, "s": 864, "text": "Initialization of variables" }, { "code": null, "e": 991, "s": 892, "text": "Specific condition as per requirement over which these defined variables are needed to be iterated" }, { "code": null, "e": 1090, "s": 991, "text": "A terminating part where we generally play with variables to reach to terminating condition state." }, { "code": null, "e": 1175, "s": 1090, "text": "for(initialization; boolean expression; update statement) { \n// Body of for loop \n} " }, { "code": null, "e": 1237, "s": 1175, "text": "This is generally the basic pilgrimage structure of for loop." }, { "code": null, "e": 1440, "s": 1237, "text": "Let’s look at some basic examples of using for loop and the common pitfalls in using for loop which enables us to know even better as internal working will be depicted as we will be playing with codes. " }, { "code": null, "e": 1494, "s": 1440, "text": "Usecase 1: Providing expression in for loop is a must" }, { "code": null, "e": 1619, "s": 1494, "text": "For loop must consist of a valid expression in the loop statement failing which can lead to an infinite loop. The statement " }, { "code": null, "e": 1658, "s": 1619, "text": "for ( ; ; ) \nis similar to\nwhile(true)" }, { "code": null, "e": 1762, "s": 1658, "text": "Note: This above said is crux of advanced programming as it is origin of logic building in programming." }, { "code": null, "e": 1770, "s": 1762, "text": "Example" }, { "code": null, "e": 1775, "s": 1770, "text": "Java" }, { "code": "// Java program to illustrate Infinite For loop // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // For loop for (;;) { // Print statement everytime condition holds // true making body to execute System.out.println(\"This is an infinite loop\"); } }}", "e": 2138, "s": 1775, "text": null }, { "code": null, "e": 2206, "s": 2138, "text": "Output: Prints the statement β€œThis is an infinite loop” repeatedly." }, { "code": null, "e": 2339, "s": 2206, "text": "This is an infinite loop\nThis is an infinite loop\nThis is an infinite loop\nThis is an infinite loop\n...\n...\nThis is an infinite loop" }, { "code": null, "e": 2382, "s": 2339, "text": "Usecase 2: Initializing Multiple Variables" }, { "code": null, "e": 2522, "s": 2382, "text": "In Java, multiple variables can be initialized in the initialization block of for loop regardless of whether you use it in the loop or not." }, { "code": null, "e": 2531, "s": 2522, "text": "Example:" }, { "code": null, "e": 2536, "s": 2531, "text": "Java" }, { "code": "// Java Program to Illustrate Initializing Multiple// Variables in Initialization Block // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring an integer variable int x = 2; // For loop to iterate for (long y = 0, z = 4; x < 10 && y < 10; x++, y++) { // Printing value/s stored in variable named y // defined inside body of for loop System.out.println(y + \" \"); } // Printing value/s stored in variable named x // defined outside body of for loop System.out.println(x); }}", "e": 3178, "s": 2536, "text": null }, { "code": null, "e": 3205, "s": 3178, "text": "0 \n1 \n2 \n3 \n4 \n5 \n6 \n7 \n10" }, { "code": null, "e": 3538, "s": 3205, "text": "In the above code, there is simple variation in the for loop. Two variables are declared and initialized in the initialization block. The variable β€˜z’ is not being used. Also, the other two components contain extra variables. So, it can be seen that the blocks may include extra variables which may not be referenced by each other. " }, { "code": null, "e": 3605, "s": 3538, "text": "Usecase 3: Redeclaration of a Variable in the Initialization Block" }, { "code": null, "e": 3753, "s": 3605, "text": "Suppose, an initialization variable is already declared as an integer. Here we can not re-declare it in for loop with another data type as follows:" }, { "code": null, "e": 3764, "s": 3753, "text": "Example 1:" }, { "code": null, "e": 3769, "s": 3764, "text": "Java" }, { "code": "// Java Program to Illustrate Redeclaring a Variable// in Initialization Block // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring an integer variable int x = 0; // Redeclaring above variable // as long will not work for (long y = 0, x = 1; x < 5; x++) { // Printing the value inside the variable System.out.print(x + \" \"); } }}", "e": 4233, "s": 3769, "text": null }, { "code": null, "e": 4241, "s": 4233, "text": "Output:" }, { "code": null, "e": 4364, "s": 4241, "text": "Example3.java:12: error: variable x is already defined in method main(String[])\n for(long y = 0, x = 1; x < 5; x++)" }, { "code": null, "e": 4600, "s": 4364, "text": "Here, x was already initialized to zero as an integer and is being re-declared in the loop with data type long. But this problem can be fixed by slightly modifying the code. Here, the variables x and y are declared in a different way. " }, { "code": null, "e": 4611, "s": 4600, "text": "Example 2:" }, { "code": null, "e": 4616, "s": 4611, "text": "Java" }, { "code": "// Java Program to Illustrate Redeclaring a Variable// in Initialization Block // Main classpublic class GFG { // main driver method public static void main(String[] args) { // Declaring and initializing variables int x = 0; long y = 10; // For loop to iterate over till // custom specified check for (y = 0, x = 1; x < 5; x++) { // Printing value contained in memory block // of the variable System.out.print(x + \" \"); } }}", "e": 5148, "s": 4616, "text": null }, { "code": null, "e": 5157, "s": 5148, "text": "Output: " }, { "code": null, "e": 5165, "s": 5157, "text": "1 2 3 4" }, { "code": null, "e": 5248, "s": 5165, "text": "Usecase 4: Variables declared in the initialization block must be of the same type" }, { "code": null, "e": 5320, "s": 5248, "text": "It is just common sense that when we declare a variable as shown below:" }, { "code": null, "e": 5331, "s": 5320, "text": " int x, y;" }, { "code": null, "e": 5432, "s": 5331, "text": "Here both variables are of the same type. It is just the same in for loop initialization block too. " }, { "code": null, "e": 5441, "s": 5432, "text": "Example:" }, { "code": null, "e": 5446, "s": 5441, "text": "Java" }, { "code": "// Java program to Illustrate Declaring a Variable// in Initialization Block // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring integer variable // int x; // Note: This will cause error; // Redeclaring x as long will not work for (long y = 0, x = 1; x < 5; x++) { // Printing the value stored System.out.print(x + \" \"); } }}", "e": 5919, "s": 5446, "text": null }, { "code": null, "e": 5928, "s": 5919, "text": "1 2 3 4 " }, { "code": null, "e": 5988, "s": 5928, "text": "Usecase 5: Variables in the loop are accessible only within" }, { "code": null, "e": 6143, "s": 5988, "text": "The variables that are declared in the initialization block can be accessed only within the loop as we have as per the concept of the scope of variables. " }, { "code": null, "e": 6152, "s": 6143, "text": "Example:" }, { "code": null, "e": 6157, "s": 6152, "text": "Java" }, { "code": "// Java Program to Illustrate Scope of Initializing// Variables Within the oop // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // x and y scope is declared only // within for loop for (int x = 0, y = 0; x < 3 && y < 3; x++, y++) { // Printing value stored in variable named y System.out.println(y + \" \"); } // Printing value stored in variable named x // after inner loop is over System.out.println(x); }}", "e": 6695, "s": 6157, "text": null }, { "code": null, "e": 6702, "s": 6695, "text": "Error:" }, { "code": null, "e": 6777, "s": 6702, "text": "Example5.java:13: error: cannot find symbol\n System.out.println(x);" }, { "code": null, "e": 6904, "s": 6777, "text": "In the above example, variable x is not accessible outside the loop. The statement which is commented gives a compiler error. " }, { "code": null, "e": 7328, "s": 6904, "text": "This article is contributed by Preeti Pardeshi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 7341, "s": 7328, "text": "Akanksha_Rai" }, { "code": null, "e": 7355, "s": 7341, "text": "solankimayank" }, { "code": null, "e": 7367, "s": 7355, "text": "anikakapoor" }, { "code": null, "e": 7376, "s": 7367, "text": "sweetyty" }, { "code": null, "e": 7392, "s": 7376, "text": "simranarora5sos" }, { "code": null, "e": 7410, "s": 7392, "text": "Java-Control-Flow" }, { "code": null, "e": 7415, "s": 7410, "text": "Java" }, { "code": null, "e": 7433, "s": 7415, "text": "Java-Control-Flow" }, { "code": null, "e": 7438, "s": 7433, "text": "Java" }, { "code": null, "e": 7536, "s": 7438, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7587, "s": 7536, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 7618, "s": 7587, "text": "How to iterate any Map in Java" }, { "code": null, "e": 7637, "s": 7618, "text": "Interfaces in Java" }, { "code": null, "e": 7667, "s": 7637, "text": "HashMap in Java with Examples" }, { "code": null, "e": 7685, "s": 7667, "text": "ArrayList in Java" }, { "code": null, "e": 7700, "s": 7685, "text": "Stream In Java" }, { "code": null, "e": 7720, "s": 7700, "text": "Collections in Java" }, { "code": null, "e": 7744, "s": 7720, "text": "Singleton Class in Java" }, { "code": null, "e": 7776, "s": 7744, "text": "Multidimensional Arrays in Java" } ]
PHP | intval() Function
12 Sep, 2019 The intval() function is an inbuilt function in PHP which returns the integer value of a variable. Syntax: int intval ( $var, $base ) Parameters: This function accepts two parameters out of which one is mandatory while the other one is optional. Parameters are described below: $var: It is a mandatory parameter serves as the variable which needs to be converted to its integer value. $base: It ia a optional parameter specifies the base for conversion of $var to its corresponding integer. If $base is not specified.If $var contains 0x (or 0X) as prefix, the base is taken as 16.If $var starts with 0, the base is taken as 8Otherwise, the base is taken as 10. If $var contains 0x (or 0X) as prefix, the base is taken as 16. If $var starts with 0, the base is taken as 8 Otherwise, the base is taken as 10. Return Value: It returns the corresponding integer value of $var. Examples: Input : $var = '120', $base = 8 Output : 80 Input : $var = 0x34 Output : 52 Input : $var = 034 Output : 28 Below programs illustrate the use of intval() function in PHP: Program 1: <?php$var = '7.423';$int_value = intval($var);echo $int_value;?> 7 Program 2: <?php$var = 0x423;$int_value = intval($var);echo $int_value;?> 1059 Program 3: <?php$var = "64";echo intval($var)."\n".intval($var, 8); ?> 64 52 Reference: http://php.net/manual/en/function.intval.php bansalpiyush177 PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from localserver database and display on HTML table using PHP ? Difference between HTTP GET and POST Methods Different ways for passing data to view in Laravel PHP | file_exists( ) Function PHP | Ternary Operator Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Sep, 2019" }, { "code": null, "e": 127, "s": 28, "text": "The intval() function is an inbuilt function in PHP which returns the integer value of a variable." }, { "code": null, "e": 135, "s": 127, "text": "Syntax:" }, { "code": null, "e": 163, "s": 135, "text": "int intval ( $var, $base )\n" }, { "code": null, "e": 307, "s": 163, "text": "Parameters: This function accepts two parameters out of which one is mandatory while the other one is optional. Parameters are described below:" }, { "code": null, "e": 414, "s": 307, "text": "$var: It is a mandatory parameter serves as the variable which needs to be converted to its integer value." }, { "code": null, "e": 690, "s": 414, "text": "$base: It ia a optional parameter specifies the base for conversion of $var to its corresponding integer. If $base is not specified.If $var contains 0x (or 0X) as prefix, the base is taken as 16.If $var starts with 0, the base is taken as 8Otherwise, the base is taken as 10." }, { "code": null, "e": 754, "s": 690, "text": "If $var contains 0x (or 0X) as prefix, the base is taken as 16." }, { "code": null, "e": 800, "s": 754, "text": "If $var starts with 0, the base is taken as 8" }, { "code": null, "e": 836, "s": 800, "text": "Otherwise, the base is taken as 10." }, { "code": null, "e": 902, "s": 836, "text": "Return Value: It returns the corresponding integer value of $var." }, { "code": null, "e": 912, "s": 902, "text": "Examples:" }, { "code": null, "e": 1022, "s": 912, "text": "Input : $var = '120', $base = 8\nOutput : 80\n\nInput : $var = 0x34\nOutput : 52\n\nInput : $var = 034\nOutput : 28\n" }, { "code": null, "e": 1085, "s": 1022, "text": "Below programs illustrate the use of intval() function in PHP:" }, { "code": null, "e": 1096, "s": 1085, "text": "Program 1:" }, { "code": "<?php$var = '7.423';$int_value = intval($var);echo $int_value;?>", "e": 1161, "s": 1096, "text": null }, { "code": null, "e": 1164, "s": 1161, "text": "7\n" }, { "code": null, "e": 1175, "s": 1164, "text": "Program 2:" }, { "code": "<?php$var = 0x423;$int_value = intval($var);echo $int_value;?>", "e": 1238, "s": 1175, "text": null }, { "code": null, "e": 1244, "s": 1238, "text": "1059\n" }, { "code": null, "e": 1255, "s": 1244, "text": "Program 3:" }, { "code": "<?php$var = \"64\";echo intval($var).\"\\n\".intval($var, 8); ?>", "e": 1316, "s": 1255, "text": null }, { "code": null, "e": 1323, "s": 1316, "text": "64\n52\n" }, { "code": null, "e": 1379, "s": 1323, "text": "Reference: http://php.net/manual/en/function.intval.php" }, { "code": null, "e": 1395, "s": 1379, "text": "bansalpiyush177" }, { "code": null, "e": 1408, "s": 1395, "text": "PHP-function" }, { "code": null, "e": 1412, "s": 1408, "text": "PHP" }, { "code": null, "e": 1429, "s": 1412, "text": "Web Technologies" }, { "code": null, "e": 1433, "s": 1429, "text": "PHP" }, { "code": null, "e": 1531, "s": 1433, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1613, "s": 1531, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 1658, "s": 1613, "text": "Difference between HTTP GET and POST Methods" }, { "code": null, "e": 1709, "s": 1658, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 1739, "s": 1709, "text": "PHP | file_exists( ) Function" }, { "code": null, "e": 1762, "s": 1739, "text": "PHP | Ternary Operator" }, { "code": null, "e": 1795, "s": 1762, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1857, "s": 1795, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1918, "s": 1857, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1968, "s": 1918, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Print with your own font using Python !!
11 Aug, 2021 Given user input, this Python3 program will print the input in designed font. In this article, we will do some cool Python trick. For the user input, given code will print the input in your own designed font. Example : Input : ROOT Output : ..######.. ..#....#.. ..#.##... ..#...#... ..#....#.. ..######.. ..#....#.. ..#....#.. ..#....#.. ..######.. ..######.. ..#....#.. ..#....#.. ..#....#.. ..######.. ..######.. ....##.... ....##.... ....##.... ....##.... Below is Python3 code implementation : Python3 # Python3 code to print input in your own font name = "GEEK" # To take input from User# name = input("Enter your name: \n\n") length = len(name)l = "" for x in range(0, length): c = name[x] c = c.upper() if (c == "A"): print("..######..\n..#....#..\n..######..", end = " ") print("\n..#....#..\n..#....#..\n\n") elif (c == "B"): print("..######..\n..#....#..\n..#####...", end = " ") print("\n..#....#..\n..######..\n\n") elif (c == "C"): print("..######..\n..#.......\n..#.......", end = " ") print("\n..#.......\n..######..\n\n") elif (c == "D"): print("..#####...\n..#....#..\n..#....#..", end = " ") print("\n..#....#..\n..#####...\n\n") elif (c == "E"): print("..######..\n..#.......\n..#####...", end = " ") print("\n..#.......\n..######..\n\n") elif (c == "F"): print("..######..\n..#.......\n..#####...", end = " ") print("\n..#.......\n..#.......\n\n") elif (c == "G"): print("..######..\n..#.......\n..#.####..", end = " ") print("\n..#....#..\n..#####...\n\n") elif (c == "H"): print("..#....#..\n..#....#..\n..######..", end = " ") print("\n..#....#..\n..#....#..\n\n") elif (c == "I"): print("..######..\n....##....\n....##....", end = " ") print("\n....##....\n..######..\n\n") elif (c == "J"): print("..######..\n....##....\n....##....", end = " ") print("\n..#.##....\n..####....\n\n") elif (c == "K"): print("..#...#...\n..#..#....\n..##......", end = " ") print("\n..#..#....\n..#...#...\n\n") elif (c == "L"): print("..#.......\n..#.......\n..#.......", end = " ") print("\n..#.......\n..######..\n\n") elif (c == "M"): print("..#....#..\n..##..##..\n..#.##.#..", end = " ") print("\n..#....#..\n..#....#..\n\n") elif (c == "N"): print("..#....#..\n..##...#..\n..#.#..#..", end = " ") print("\n..#..#.#..\n..#...##..\n\n") elif (c == "O"): print("..######..\n..#....#..\n..#....#..", end = " ") print("\n..#....#..\n..######..\n\n") elif (c == "P"): print("..######..\n..#....#..\n..######..", end = " ") print("\n..#.......\n..#.......\n\n") elif (c == "Q"): print("..######..\n..#....#..\n..#.#..#..", end = " ") print("\n..#..#.#..\n..######..\n\n") elif (c == "R"): print("..######..\n..#....#..\n..#.##...", end = " ") print("\n..#...#...\n..#....#..\n\n") elif (c == "S"): print("..######..\n..#.......\n..######..", end = " ") print("\n.......#..\n..######..\n\n") elif (c == "T"): print("..######..\n....##....\n....##....", end = " ") print("\n....##....\n....##....\n\n") elif (c == "U"): print("..#....#..\n..#....#..\n..#....#..", end = " ") print("\n..#....#..\n..######..\n\n") elif (c == "V"): print("..#....#..\n..#....#..\n..#....#..", end = " ") print("\n...#..#...\n....##....\n\n") elif (c == "W"): print("..#....#..\n..#....#..\n..#.##.#..", end = " ") print("\n..##..##..\n..#....#..\n\n") elif (c == "X"): print("..#....#..\n...#..#...\n....##....", end = " ") print("\n...#..#...\n..#....#..\n\n") elif (c == "Y"): print("..#....#..\n...#..#...\n....##....", end = " ") print("\n....##....\n....##....\n\n") elif (c == "Z"): print("..######..\n......#...\n.....#....", end = " ") print("\n....#.....\n..######..\n\n") elif (c == " "): print("..........\n..........\n..........", end = " ") print("\n..........\n\n") elif (c == "."): print("----..----\n\n") Output: ..######.. ..#....... ..#.####.. ..#....#.. ..#####... ..######.. ..#....... ..#####... ..#....... ..######.. ..######.. ..#....... ..#####... ..#....... ..######.. ..#...#... ..#..#.... ..##...... ..#..#.... ..#...#... gulshankumarar231 pattern-printing Python Pattern-printing Python Python Programs School Programming pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 53, "s": 25, "text": "\n11 Aug, 2021" }, { "code": null, "e": 131, "s": 53, "text": "Given user input, this Python3 program will print the input in designed font." }, { "code": null, "e": 274, "s": 131, "text": "In this article, we will do some cool Python trick. For the user input, given code will print the input in your own designed font. Example : " }, { "code": null, "e": 603, "s": 274, "text": "Input : ROOT\n\nOutput :\n\n..######..\n..#....#..\n..#.##... \n..#...#...\n..#....#..\n\n\n..######..\n..#....#..\n..#....#.. \n..#....#..\n..######..\n\n\n..######..\n..#....#..\n..#....#.. \n..#....#..\n..######..\n\n\n..######..\n....##....\n....##.... \n....##....\n....##...." }, { "code": null, "e": 644, "s": 603, "text": " Below is Python3 code implementation :" }, { "code": null, "e": 652, "s": 644, "text": "Python3" }, { "code": "# Python3 code to print input in your own font name = \"GEEK\" # To take input from User# name = input(\"Enter your name: \\n\\n\") length = len(name)l = \"\" for x in range(0, length): c = name[x] c = c.upper() if (c == \"A\"): print(\"..######..\\n..#....#..\\n..######..\", end = \" \") print(\"\\n..#....#..\\n..#....#..\\n\\n\") elif (c == \"B\"): print(\"..######..\\n..#....#..\\n..#####...\", end = \" \") print(\"\\n..#....#..\\n..######..\\n\\n\") elif (c == \"C\"): print(\"..######..\\n..#.......\\n..#.......\", end = \" \") print(\"\\n..#.......\\n..######..\\n\\n\") elif (c == \"D\"): print(\"..#####...\\n..#....#..\\n..#....#..\", end = \" \") print(\"\\n..#....#..\\n..#####...\\n\\n\") elif (c == \"E\"): print(\"..######..\\n..#.......\\n..#####...\", end = \" \") print(\"\\n..#.......\\n..######..\\n\\n\") elif (c == \"F\"): print(\"..######..\\n..#.......\\n..#####...\", end = \" \") print(\"\\n..#.......\\n..#.......\\n\\n\") elif (c == \"G\"): print(\"..######..\\n..#.......\\n..#.####..\", end = \" \") print(\"\\n..#....#..\\n..#####...\\n\\n\") elif (c == \"H\"): print(\"..#....#..\\n..#....#..\\n..######..\", end = \" \") print(\"\\n..#....#..\\n..#....#..\\n\\n\") elif (c == \"I\"): print(\"..######..\\n....##....\\n....##....\", end = \" \") print(\"\\n....##....\\n..######..\\n\\n\") elif (c == \"J\"): print(\"..######..\\n....##....\\n....##....\", end = \" \") print(\"\\n..#.##....\\n..####....\\n\\n\") elif (c == \"K\"): print(\"..#...#...\\n..#..#....\\n..##......\", end = \" \") print(\"\\n..#..#....\\n..#...#...\\n\\n\") elif (c == \"L\"): print(\"..#.......\\n..#.......\\n..#.......\", end = \" \") print(\"\\n..#.......\\n..######..\\n\\n\") elif (c == \"M\"): print(\"..#....#..\\n..##..##..\\n..#.##.#..\", end = \" \") print(\"\\n..#....#..\\n..#....#..\\n\\n\") elif (c == \"N\"): print(\"..#....#..\\n..##...#..\\n..#.#..#..\", end = \" \") print(\"\\n..#..#.#..\\n..#...##..\\n\\n\") elif (c == \"O\"): print(\"..######..\\n..#....#..\\n..#....#..\", end = \" \") print(\"\\n..#....#..\\n..######..\\n\\n\") elif (c == \"P\"): print(\"..######..\\n..#....#..\\n..######..\", end = \" \") print(\"\\n..#.......\\n..#.......\\n\\n\") elif (c == \"Q\"): print(\"..######..\\n..#....#..\\n..#.#..#..\", end = \" \") print(\"\\n..#..#.#..\\n..######..\\n\\n\") elif (c == \"R\"): print(\"..######..\\n..#....#..\\n..#.##...\", end = \" \") print(\"\\n..#...#...\\n..#....#..\\n\\n\") elif (c == \"S\"): print(\"..######..\\n..#.......\\n..######..\", end = \" \") print(\"\\n.......#..\\n..######..\\n\\n\") elif (c == \"T\"): print(\"..######..\\n....##....\\n....##....\", end = \" \") print(\"\\n....##....\\n....##....\\n\\n\") elif (c == \"U\"): print(\"..#....#..\\n..#....#..\\n..#....#..\", end = \" \") print(\"\\n..#....#..\\n..######..\\n\\n\") elif (c == \"V\"): print(\"..#....#..\\n..#....#..\\n..#....#..\", end = \" \") print(\"\\n...#..#...\\n....##....\\n\\n\") elif (c == \"W\"): print(\"..#....#..\\n..#....#..\\n..#.##.#..\", end = \" \") print(\"\\n..##..##..\\n..#....#..\\n\\n\") elif (c == \"X\"): print(\"..#....#..\\n...#..#...\\n....##....\", end = \" \") print(\"\\n...#..#...\\n..#....#..\\n\\n\") elif (c == \"Y\"): print(\"..#....#..\\n...#..#...\\n....##....\", end = \" \") print(\"\\n....##....\\n....##....\\n\\n\") elif (c == \"Z\"): print(\"..######..\\n......#...\\n.....#....\", end = \" \") print(\"\\n....#.....\\n..######..\\n\\n\") elif (c == \" \"): print(\"..........\\n..........\\n..........\", end = \" \") print(\"\\n..........\\n\\n\") elif (c == \".\"): print(\"----..----\\n\\n\")", "e": 4575, "s": 652, "text": null }, { "code": null, "e": 4584, "s": 4575, "text": "Output: " }, { "code": null, "e": 4810, "s": 4584, "text": "..######..\n..#.......\n..#.####..\n..#....#..\n..#####...\n\n\n..######..\n..#.......\n..#####...\n..#.......\n..######..\n\n\n..######..\n..#.......\n..#####...\n..#.......\n..######..\n\n\n..#...#...\n..#..#....\n..##......\n..#..#....\n..#...#..." }, { "code": null, "e": 4830, "s": 4812, "text": "gulshankumarar231" }, { "code": null, "e": 4847, "s": 4830, "text": "pattern-printing" }, { "code": null, "e": 4871, "s": 4847, "text": "Python Pattern-printing" }, { "code": null, "e": 4878, "s": 4871, "text": "Python" }, { "code": null, "e": 4894, "s": 4878, "text": "Python Programs" }, { "code": null, "e": 4913, "s": 4894, "text": "School Programming" }, { "code": null, "e": 4930, "s": 4913, "text": "pattern-printing" }, { "code": null, "e": 5028, "s": 4930, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5046, "s": 5028, "text": "Python Dictionary" }, { "code": null, "e": 5088, "s": 5046, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 5110, "s": 5088, "text": "Enumerate() in Python" }, { "code": null, "e": 5145, "s": 5110, "text": "Read a file line by line in Python" }, { "code": null, "e": 5171, "s": 5145, "text": "Python String | replace()" }, { "code": null, "e": 5214, "s": 5171, "text": "Python program to convert a list to string" }, { "code": null, "e": 5236, "s": 5214, "text": "Defaultdict in Python" }, { "code": null, "e": 5275, "s": 5236, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 5313, "s": 5275, "text": "Python | Convert a list to dictionary" } ]
Find duplicates under given constraints
07 Jul, 2022 A sorted array contains 6 different numbers, only 1 number is repeated five times. So there are total 10 numbers in array. Find the duplicate numbers using two comparisons only. Examples : Input: arr[] = {1, 1, 1, 1, 1, 5, 7, 10, 20, 30} Output: 1 Input: arr[] = {1, 2, 3, 3, 3, 3, 3, 5, 9, 10} Output: 3 Asked in Yahoo An important observation is, arr[4] or arr[5] is an occurrence of repeated element for sure. Below is the implementation based on this observation. Implementation: CPP JAVA Python3 C# PHP Javascript // C++ program to find duplicate element under// given constraints.#include<bits/stdc++.h>using namespace std; // This function assumes array is sorted, has// 10 elements, there are total 6 different// elements and one element repeats 5 times.int findDuplicate(int a[]){ if (a[3] == a[4]) return a[3]; else if (a[4] == a[5]) return a[4]; else return a[5];} // Driver codeint main(){ int a[] = {1, 1, 1, 1, 1, 5, 7, 10, 20, 30}; cout << findDuplicate(a); return 0;} // Java program to find duplicate element under// given constraints.class Num{ // This function assumes array is sorted, has// 10 elements, there are total 6 different// elements and one element repeats 5 times.static int findDuplicate(int a[]){ if (a[3] == a[4]) return a[3]; else if (a[4] == a[5]) return a[4]; else return a[5];} // Driver codepublic static void main(String[] args){ int a[] = {1, 1, 1, 1, 1, 5, 7, 10, 20, 30}; System.out.println(findDuplicate(a));}}//This code is contributed by//Smitha Dinesh Semwal # Python 3 program to find duplicate# element under given constraints. # This function assumes array is# sorted, has 10 elements, there are# total 6 different elements and one# element repeats 5 times.def findDuplicate(a): if (a[3] == a[4]): return a[3] else if (a[4] == a[5]): return a[4] else: return a[5] # Driver codea = [1, 1, 1, 1, 1, 5, 7, 10, 20, 30] print(findDuplicate(a)) # This code is contributed by Smitha Dinesh Semwal // C# program to find duplicate // element under given constraints.using System; class GFG { // This function assumes array is// sorted, has 10 elements, there// are total 6 different elements// and one element repeats 5 times.static int findDuplicate(int []a){ if (a[3] == a[4]) return a[3]; else if (a[4] == a[5]) return a[4]; else return a[5];} // Driver codepublic static void Main(){ int []a = {1, 1, 1, 1, 1, 5, 7, 10, 20, 30}; Console.Write(findDuplicate(a));}} // This code is contributed by nitin mittal <?php// PHP program to find duplicate// element under given constraints. // This function assumes array is// sorted, has 10 elements, there// are total 6 different elements// and one element repeats 5 times.function findDuplicate($a){ if ($a[3] == $a[4]) return $a[3]; else if ($a[4] == $a[5]) return $a[4]; else return $a[5];} // Driver code$a = array(1, 1, 1, 1, 1, 5, 7, 10, 20, 30);echo findDuplicate($a); // This code is contributed by nitin mittal.?> <script> // JavaScript program to find duplicate element under// given constraints. // This function assumes array is sorted, has// 10 elements, there are total 6 different// elements and one element repeats 5 times.function findDuplicate(a){ if (a[3] == a[4]) return a[3]; else if (a[4] == a[5]) return a[4]; else return a[5];} // Driver code let a = [1, 1, 1, 1, 1, 5, 7, 10, 20, 30]; document.write(findDuplicate(a)); </script> 1 Exercise: Extend the above problem for an array with n different elements, size of array is 2*(n-1) and one element repeats (n-1) times. This article is contributed by Rakesh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. nitin mittal _saurabh_jaiswal as5853535 surinderdawra388 hardikkoriintern Yahoo Arrays Yahoo Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Search, insert and delete in an unsorted array Window Sliding Technique Chocolate Distribution Problem Find duplicates in O(n) time and O(1) extra space | Set 1 Next Greater Element Move all negative numbers to beginning and positive to end with constant extra space What is Data Structure: Types, Classifications and Applications Count pairs with given sum Find subarray with given sum | Set 1 (Nonnegative Numbers)
[ { "code": null, "e": 53, "s": 25, "text": "\n07 Jul, 2022" }, { "code": null, "e": 232, "s": 53, "text": "A sorted array contains 6 different numbers, only 1 number is repeated five times. So there are total 10 numbers in array. Find the duplicate numbers using two comparisons only. " }, { "code": null, "e": 244, "s": 232, "text": "Examples : " }, { "code": null, "e": 361, "s": 244, "text": "Input: arr[] = {1, 1, 1, 1, 1, 5, 7, 10, 20, 30}\nOutput: 1\n\nInput: arr[] = {1, 2, 3, 3, 3, 3, 3, 5, 9, 10}\nOutput: 3" }, { "code": null, "e": 376, "s": 361, "text": "Asked in Yahoo" }, { "code": null, "e": 525, "s": 376, "text": "An important observation is, arr[4] or arr[5] is an occurrence of repeated element for sure. Below is the implementation based on this observation. " }, { "code": null, "e": 541, "s": 525, "text": "Implementation:" }, { "code": null, "e": 545, "s": 541, "text": "CPP" }, { "code": null, "e": 550, "s": 545, "text": "JAVA" }, { "code": null, "e": 558, "s": 550, "text": "Python3" }, { "code": null, "e": 561, "s": 558, "text": "C#" }, { "code": null, "e": 565, "s": 561, "text": "PHP" }, { "code": null, "e": 576, "s": 565, "text": "Javascript" }, { "code": "// C++ program to find duplicate element under// given constraints.#include<bits/stdc++.h>using namespace std; // This function assumes array is sorted, has// 10 elements, there are total 6 different// elements and one element repeats 5 times.int findDuplicate(int a[]){ if (a[3] == a[4]) return a[3]; else if (a[4] == a[5]) return a[4]; else return a[5];} // Driver codeint main(){ int a[] = {1, 1, 1, 1, 1, 5, 7, 10, 20, 30}; cout << findDuplicate(a); return 0;}", "e": 1082, "s": 576, "text": null }, { "code": "// Java program to find duplicate element under// given constraints.class Num{ // This function assumes array is sorted, has// 10 elements, there are total 6 different// elements and one element repeats 5 times.static int findDuplicate(int a[]){ if (a[3] == a[4]) return a[3]; else if (a[4] == a[5]) return a[4]; else return a[5];} // Driver codepublic static void main(String[] args){ int a[] = {1, 1, 1, 1, 1, 5, 7, 10, 20, 30}; System.out.println(findDuplicate(a));}}//This code is contributed by//Smitha Dinesh Semwal", "e": 1640, "s": 1082, "text": null }, { "code": "# Python 3 program to find duplicate# element under given constraints. # This function assumes array is# sorted, has 10 elements, there are# total 6 different elements and one# element repeats 5 times.def findDuplicate(a): if (a[3] == a[4]): return a[3] else if (a[4] == a[5]): return a[4] else: return a[5] # Driver codea = [1, 1, 1, 1, 1, 5, 7, 10, 20, 30] print(findDuplicate(a)) # This code is contributed by Smitha Dinesh Semwal", "e": 2118, "s": 1640, "text": null }, { "code": "// C# program to find duplicate // element under given constraints.using System; class GFG { // This function assumes array is// sorted, has 10 elements, there// are total 6 different elements// and one element repeats 5 times.static int findDuplicate(int []a){ if (a[3] == a[4]) return a[3]; else if (a[4] == a[5]) return a[4]; else return a[5];} // Driver codepublic static void Main(){ int []a = {1, 1, 1, 1, 1, 5, 7, 10, 20, 30}; Console.Write(findDuplicate(a));}} // This code is contributed by nitin mittal", "e": 2681, "s": 2118, "text": null }, { "code": "<?php// PHP program to find duplicate// element under given constraints. // This function assumes array is// sorted, has 10 elements, there// are total 6 different elements// and one element repeats 5 times.function findDuplicate($a){ if ($a[3] == $a[4]) return $a[3]; else if ($a[4] == $a[5]) return $a[4]; else return $a[5];} // Driver code$a = array(1, 1, 1, 1, 1, 5, 7, 10, 20, 30);echo findDuplicate($a); // This code is contributed by nitin mittal.?>", "e": 3178, "s": 2681, "text": null }, { "code": "<script> // JavaScript program to find duplicate element under// given constraints. // This function assumes array is sorted, has// 10 elements, there are total 6 different// elements and one element repeats 5 times.function findDuplicate(a){ if (a[3] == a[4]) return a[3]; else if (a[4] == a[5]) return a[4]; else return a[5];} // Driver code let a = [1, 1, 1, 1, 1, 5, 7, 10, 20, 30]; document.write(findDuplicate(a)); </script>", "e": 3650, "s": 3178, "text": null }, { "code": null, "e": 3652, "s": 3650, "text": "1" }, { "code": null, "e": 3789, "s": 3652, "text": "Exercise: Extend the above problem for an array with n different elements, size of array is 2*(n-1) and one element repeats (n-1) times." }, { "code": null, "e": 4086, "s": 3789, "text": "This article is contributed by Rakesh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 4099, "s": 4086, "text": "nitin mittal" }, { "code": null, "e": 4116, "s": 4099, "text": "_saurabh_jaiswal" }, { "code": null, "e": 4126, "s": 4116, "text": "as5853535" }, { "code": null, "e": 4143, "s": 4126, "text": "surinderdawra388" }, { "code": null, "e": 4160, "s": 4143, "text": "hardikkoriintern" }, { "code": null, "e": 4166, "s": 4160, "text": "Yahoo" }, { "code": null, "e": 4173, "s": 4166, "text": "Arrays" }, { "code": null, "e": 4179, "s": 4173, "text": "Yahoo" }, { "code": null, "e": 4186, "s": 4179, "text": "Arrays" }, { "code": null, "e": 4284, "s": 4186, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4316, "s": 4284, "text": "Introduction to Data Structures" }, { "code": null, "e": 4363, "s": 4316, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 4388, "s": 4363, "text": "Window Sliding Technique" }, { "code": null, "e": 4419, "s": 4388, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 4477, "s": 4419, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 4498, "s": 4477, "text": "Next Greater Element" }, { "code": null, "e": 4583, "s": 4498, "text": "Move all negative numbers to beginning and positive to end with constant extra space" }, { "code": null, "e": 4647, "s": 4583, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 4674, "s": 4647, "text": "Count pairs with given sum" } ]
Find k most frequent in linear time
03 Feb, 2022 Given an array of integers, we need to print k most frequent elements. If there is a tie, we need to prefer the elements whose first appearance is first. Examples: Input : arr[] = {10, 5, 20, 5, 10, 10, 30}, k = 2 Output : 10 5 Input : arr[] = {7, 7, 6, 6, 6, 7, 5, 4, 4, 10, 5}, k = 3 Output : 7 6 5 Explanation : In this example, 7 and 6 have the same frequencies. We print 7 first because the first appearance of 7 is first. Similarly, 5 and 4 have the same frequencies. We prefer 5 because 5’s first appearance is first. We have discussed two methods in the post below. Find k numbers with most occurrences in the given arrayLet us first talk about a simple solution that prints in any order in the case of a tie. Then we will discuss the solution that takes of the order. The idea is to use hashing with frequency indexing. We first store counts in a hash. Then we traverse through the hash and use frequencies as the index to store elements with given frequencies. The important factor here is, the maximum frequency can be n. So an array of size n+1 would be good. C++ Java Python3 C# Javascript // C++ implementation to find k numbers with most// occurrences in the given array#include <bits/stdc++.h>using namespace std; // function to print the k numbers with most occurrencesvoid print_N_mostFrequentNumber(int arr[], int n, int k){ // unordered_map 'um' implemented as frequency // hash table unordered_map<int, int> um; for (int i = 0; i < n; i++) um[arr[i]]++; // Use frequencies as indexes and put // elements with given frequency in a // vector (related to a frequency) vector<int> freq[n + 1]; for (auto x : um) freq[x.second].push_back(x.first); // Initialize count of items printed int count = 0; // Traverse the frequency array from // right side as we need the most // frequent items. for (int i = n; i >= 0; i--) { // Print items of current frequency for (int x : freq[i]) { cout << x << " "; count++; if (count == k) return; } }} // Driver program to test aboveint main(){ int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; print_N_mostFrequentNumber(arr, n, k); return 0;} // Java implementation to find k elements with max occurrence.import java.util.*;public class KFrequentNumbers { static void print_N_mostFrequentNumber(int[] arr, int n, int k) { Map<Integer, Integer> mp = new HashMap<Integer, Integer>(); // Put count of all the distinct elements in Map // with element as the key & count as the value. for (int i = 0; i < n; i++) { // Get the count for the element if already // present in the Map or get the default value // which is 0. mp.put(arr[i], mp.getOrDefault(arr[i], 0) + 1); } // Initialize an array list of array lists List<List<Integer> > freq = new ArrayList<List<Integer> >(); for (int i = 0; i <= n; i++) freq.add(new ArrayList<Integer>()); // Use frequencies as indexes and add corresponding // values to the list for (Map.Entry<Integer, Integer> x : mp.entrySet()) freq.get(x.getValue()).add(x.getKey()); // Traverse freq[] from right side. int count = 0; for (int i = n; i >= 0; i--) { for (int x : freq.get(i)) { System.out.println(x); count++; if (count == k) return; } } } // Driver Code to test the code. public static void main(String[] args) { int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 }; int n = arr.length; int k = 2; print_N_mostFrequentNumber(arr, n, k); }} # Python3 implementation to find k numbers# with most occurrences in the given array # Function to print k numbers with most occurrencesdef print_N_mostFrequentNumber(arr, n, k): # unordered_map 'um' implemented as # frequency hash table um = {} for i in range(n): um[arr[i]] = um.get(arr[i], 0) + 1 # Use frequencies as indexes and put # elements with given frequency in a # vector (related to a frequency) freq = [[] for i in range(n + 1)] for x in um: freq[um[x]].append(x) # Initialize count of items printed count = 0 # Traverse the frequency array from # right side as we need the most # frequent items. for i in range(n, -1, -1): # Print items of current frequency for x in sorted(freq[i])[::-1]: print(x, end = " ") count += 1 if (count == k): return # Driver codeif __name__ == '__main__': arr = [ 3, 1, 4, 4, 5, 2, 6, 1 ] n = len(arr) k = 2 print_N_mostFrequentNumber(arr, n, k) # This code is contributed by mohit kumar 29 // C# implementation to find// k elements with max occurrence.using System;using System.Collections.Generic;class KFrequentNumbers{ static void print_N_mostFrequentNumber(int[] arr, int n, int k){ Dictionary<int, int> mp = new Dictionary<int, int>(); // Put count of all the // distinct elements in Map // with element as the key // & count as the value. for (int i = 0; i < n; i++) { // Get the count for the // element if already // present in the Map // or get the default value // which is 0. if(mp.ContainsKey(arr[i])) { mp[arr[i]] = mp[arr[i]] + 1; } else { mp.Add(arr[i], 1); } } // Initialize an array // list of array lists List<List<int> > freq = new List<List<int> >(); for (int i = 0; i <= n; i++) freq.Add(new List<int>()); // Use frequencies as indexes // and add corresponding // values to the list foreach (KeyValuePair<int, int> x in mp) freq[x.Value].Add(x.Key); // Traverse []freq from // right side. int count = 0; for (int i = n; i >= 0; i--) { foreach (int x in freq[i]) { Console.WriteLine(x); count++; if (count == k) return; } }} // Driver Code to test the code.public static void Main(String[] args){ int []arr = {3, 1, 4, 4, 5, 2, 6, 1}; int n = arr.Length; int k = 2; print_N_mostFrequentNumber(arr, n, k);}} // This code is contributed by Princi Singh <script>// Javascript implementation to find k elements with max occurrence. function print_N_mostFrequentNumber(arr, n, k){ let mp = new Map(); // Put count of all the distinct elements in Map // with element as the key & count as the value. for (let i = 0; i < n; i++) { // Get the count for the element if already // present in the Map or get the default value // which is 0. mp.set(arr[i], mp.get(arr[i])==null?1:mp.get(arr[i]) + 1); } // Initialize an array list of array lists let freq = []; for (let i = 0; i <= n; i++) freq.push([]); // Use frequencies as indexes and add corresponding // values to the list for (let [key, value] of mp.entries()) freq[value].push(key); // Traverse freq[] from right side. let count = 0; for (let i = n; i >= 0; i--) { for (let x=0;x< freq[i].length;x++) { document.write(freq[i][x]+" "); count++; if (count == k) return; } }} // Driver Code to test the code.let arr = [ 3, 1, 4, 4, 5, 2, 6, 1 ];let n = arr.length;let k = 2;print_N_mostFrequentNumber(arr, n, k); // This code is contributed by patel2127</script> 4 1 Time Complexity: O(n) Auxiliary Space: O(n) Printing according to the first appearance. To keep the required order, we traverse the original array instead of the map. To avoid duplicates, we need to mark processed entries as -1 on the map. C++ Java Python3 C# Javascript // C++ implementation to find k numbers with most// occurrences in the given array#include <bits/stdc++.h>using namespace std; // function to print the k numbers with most occurrencesvoid print_N_mostFrequentNumber(int arr[], int n, int k){ // unordered_map 'um' implemented as frequency // hash table unordered_map<int, int> um; for (int i = 0; i < n; i++) um[arr[i]]++; // Use frequencies as indexes and put // elements with given frequency in a // vector (related to a frequency) vector<int> freq[n + 1]; for (int i = 0; i < n; i++) { int f = um[arr[i]]; if (f != -1) { freq[f].push_back(arr[i]); um[arr[i]] = -1; } } // Initialize count of items printed int count = 0; // Traverse the frequency array from // right side as we need the most // frequent items. for (int i = n; i >= 0; i--) { // Print items of current frequency for (int x : freq[i]) { cout << x << " "; count++; if (count == k) return; } }} // Driver program to test aboveint main(){ int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; print_N_mostFrequentNumber(arr, n, k); return 0;} // Java implementation to find k elements with max occurrence.import java.util.*;public class KFrequentNumbers { static void print_N_mostFrequentNumber(int[] arr, int n, int k) { Map<Integer, Integer> mp = new HashMap<Integer, Integer>(); // Put count of all the distinct elements in Map // with element as the key & count as the value. for (int i = 0; i < n; i++) { // Get the count for the element if already // present in the Map or get the default value // which is 0. mp.put(arr[i], mp.getOrDefault(arr[i], 0) + 1); } // Initialize an array list of array lists List<List<Integer> > freq = new ArrayList<List<Integer> >(); for (int i = 0; i <= n; i++) freq.add(new ArrayList<Integer>()); // Use frequencies as indexes and add corresponding // values to the list for (int i = 0; i < n; i++) { int f = mp.get(arr[i]); if (f != -1) { freq.get(f).add(arr[i]); mp.put(arr[i], -1); } } // Traverse freq[] from right side. int count = 0; for (int i = n; i >= 0; i--) { for (int x : freq.get(i)) { System.out.println(x); count++; if (count == k) return; } } } // Driver Code to test the code. public static void main(String[] args) { int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 }; int n = arr.length; int k = 3; print_N_mostFrequentNumber(arr, n, k); }} # Python implementation to find k elements# with max occurrence.def print_N_mostFrequentNumber(arr, n, k): mp = {} # Put count of all the distinct # elements in Map with element # as the key & count as the value. for i in range(n): # Get the count for the element # if already present in the Map # or get the default value which is 0. if arr[i] in mp: mp[arr[i]] += 1 else: mp[arr[i]] = 0 # Initialize an array list of array lists freq = [[] for i in range(n+1)] # Use frequencies as indexes and # add corresponding values to # the list for i in range(n): f = mp[arr[i]] if (f != -1): freq[f].append(arr[i]) mp[arr[i]] = -1 # Traverse []freq from right side. count = 0 for i in range(n, -1, -1): for x in freq[i]: print(x ,end = " ") count+=1 if (count == k): return # Driver Codearr = [3, 1, 4, 4, 5, 2, 6, 1]n = len(arr)k = 3 print_N_mostFrequentNumber(arr, n, k) # This code is contributed by Shubham Singh // C# implementation to find k elements// with max occurrence.using System;using System.Collections.Generic; class GFG{ static void print_N_mostFrequentNumber(int[] arr, int n, int k){ Dictionary<int, int> mp = new Dictionary<int, int>(); // Put count of all the distinct // elements in Map with element // as the key & count as the value. for(int i = 0; i < n; i++) { // Get the count for the element // if already present in the Map // or get the default value which is 0. if (mp.ContainsKey(arr[i])) mp[arr[i]]++; else mp.Add(arr[i], 0); } // Initialize an array list of array lists List<List<int>> freq = new List<List<int>>(); for(int i = 0; i <= n; i++) freq.Add(new List<int>()); // Use frequencies as indexes and // add corresponding values to // the list for(int i = 0; i < n; i++) { int f = mp[arr[i]]; if (f != -1) { freq[f].Add(arr[i]); if (mp.ContainsKey(arr[i])) mp[arr[i]] = -1; else mp.Add(arr[i], 0); } } // Traverse []freq from right side. int count = 0; for(int i = n; i >= 0; i--) { foreach(int x in freq[i]) { Console.Write(x); Console.Write(" "); count++; if (count == k) return; } }} // Driver Codepublic static void Main(String[] args){ int []arr = { 3, 1, 4, 4, 5, 2, 6, 1 }; int n = arr.Length; int k = 3; print_N_mostFrequentNumber(arr, n, k);}} // This code is contributed by Amit Katiyar <script> // JavaScript implementation to find k elements // with max occurrence. function print_N_mostFrequentNumber(arr, n, k) { var mp = {}; // Put count of all the distinct // elements in Map with element // as the key & count as the value. for (var i = 0; i < n; i++) { // Get the count for the element // if already present in the Map // or get the default value which is 0. if (mp.hasOwnProperty(arr[i])) mp[arr[i]]++; else mp[arr[i]] = 0; } // Initialize an array list of array lists var freq = Array.from(Array(n + 1), () => Array()); // Use frequencies as indexes and // add corresponding values to // the list for (var i = 0; i < n; i++) { var f = mp[arr[i]]; if (f !== -1) { freq[f].push(arr[i]); if (mp.hasOwnProperty(arr[i])) mp[arr[i]] = -1; else mp[arr[i]] = 0; } } // Traverse []freq from right side. var count = 0; for (var i = n; i >= 0; i--) { for (const x of freq[i]) { document.write(x + " "); count++; if (count === k) return; } } } // Driver Code var arr = [3, 1, 4, 4, 5, 2, 6, 1]; var n = arr.length; var k = 3; print_N_mostFrequentNumber(arr, n, k);</script> 1 4 3 Time Complexity: O(n) Auxiliary Space: O(n) princi singh amit143katiyar mohit kumar 29 rdtank patel2127 akshaysingh98088 khushboogoyal499 anikakapoor simmytarika5 SHUBHAMSINGH10 frequency-counting Arrays Hash Arrays Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array What is Data Structure: Types, Classifications and Applications Chocolate Distribution Problem What is Hashing | A Complete Tutorial Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Count pairs with given sum Sort string of characters
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Feb, 2022" }, { "code": null, "e": 208, "s": 54, "text": "Given an array of integers, we need to print k most frequent elements. If there is a tie, we need to prefer the elements whose first appearance is first." }, { "code": null, "e": 219, "s": 208, "text": "Examples: " }, { "code": null, "e": 283, "s": 219, "text": "Input : arr[] = {10, 5, 20, 5, 10, 10, 30}, k = 2 Output : 10 5" }, { "code": null, "e": 580, "s": 283, "text": "Input : arr[] = {7, 7, 6, 6, 6, 7, 5, 4, 4, 10, 5}, k = 3 Output : 7 6 5 Explanation : In this example, 7 and 6 have the same frequencies. We print 7 first because the first appearance of 7 is first. Similarly, 5 and 4 have the same frequencies. We prefer 5 because 5’s first appearance is first." }, { "code": null, "e": 840, "s": 580, "text": "We have discussed two methods in the post below. Find k numbers with most occurrences in the given arrayLet us first talk about a simple solution that prints in any order in the case of a tie. Then we will discuss the solution that takes of the order." }, { "code": null, "e": 1135, "s": 840, "text": "The idea is to use hashing with frequency indexing. We first store counts in a hash. Then we traverse through the hash and use frequencies as the index to store elements with given frequencies. The important factor here is, the maximum frequency can be n. So an array of size n+1 would be good." }, { "code": null, "e": 1139, "s": 1135, "text": "C++" }, { "code": null, "e": 1144, "s": 1139, "text": "Java" }, { "code": null, "e": 1152, "s": 1144, "text": "Python3" }, { "code": null, "e": 1155, "s": 1152, "text": "C#" }, { "code": null, "e": 1166, "s": 1155, "text": "Javascript" }, { "code": "// C++ implementation to find k numbers with most// occurrences in the given array#include <bits/stdc++.h>using namespace std; // function to print the k numbers with most occurrencesvoid print_N_mostFrequentNumber(int arr[], int n, int k){ // unordered_map 'um' implemented as frequency // hash table unordered_map<int, int> um; for (int i = 0; i < n; i++) um[arr[i]]++; // Use frequencies as indexes and put // elements with given frequency in a // vector (related to a frequency) vector<int> freq[n + 1]; for (auto x : um) freq[x.second].push_back(x.first); // Initialize count of items printed int count = 0; // Traverse the frequency array from // right side as we need the most // frequent items. for (int i = n; i >= 0; i--) { // Print items of current frequency for (int x : freq[i]) { cout << x << \" \"; count++; if (count == k) return; } }} // Driver program to test aboveint main(){ int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; print_N_mostFrequentNumber(arr, n, k); return 0;}", "e": 2348, "s": 1166, "text": null }, { "code": "// Java implementation to find k elements with max occurrence.import java.util.*;public class KFrequentNumbers { static void print_N_mostFrequentNumber(int[] arr, int n, int k) { Map<Integer, Integer> mp = new HashMap<Integer, Integer>(); // Put count of all the distinct elements in Map // with element as the key & count as the value. for (int i = 0; i < n; i++) { // Get the count for the element if already // present in the Map or get the default value // which is 0. mp.put(arr[i], mp.getOrDefault(arr[i], 0) + 1); } // Initialize an array list of array lists List<List<Integer> > freq = new ArrayList<List<Integer> >(); for (int i = 0; i <= n; i++) freq.add(new ArrayList<Integer>()); // Use frequencies as indexes and add corresponding // values to the list for (Map.Entry<Integer, Integer> x : mp.entrySet()) freq.get(x.getValue()).add(x.getKey()); // Traverse freq[] from right side. int count = 0; for (int i = n; i >= 0; i--) { for (int x : freq.get(i)) { System.out.println(x); count++; if (count == k) return; } } } // Driver Code to test the code. public static void main(String[] args) { int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 }; int n = arr.length; int k = 2; print_N_mostFrequentNumber(arr, n, k); }}", "e": 3877, "s": 2348, "text": null }, { "code": "# Python3 implementation to find k numbers# with most occurrences in the given array # Function to print k numbers with most occurrencesdef print_N_mostFrequentNumber(arr, n, k): # unordered_map 'um' implemented as # frequency hash table um = {} for i in range(n): um[arr[i]] = um.get(arr[i], 0) + 1 # Use frequencies as indexes and put # elements with given frequency in a # vector (related to a frequency) freq = [[] for i in range(n + 1)] for x in um: freq[um[x]].append(x) # Initialize count of items printed count = 0 # Traverse the frequency array from # right side as we need the most # frequent items. for i in range(n, -1, -1): # Print items of current frequency for x in sorted(freq[i])[::-1]: print(x, end = \" \") count += 1 if (count == k): return # Driver codeif __name__ == '__main__': arr = [ 3, 1, 4, 4, 5, 2, 6, 1 ] n = len(arr) k = 2 print_N_mostFrequentNumber(arr, n, k) # This code is contributed by mohit kumar 29", "e": 4985, "s": 3877, "text": null }, { "code": "// C# implementation to find// k elements with max occurrence.using System;using System.Collections.Generic;class KFrequentNumbers{ static void print_N_mostFrequentNumber(int[] arr, int n, int k){ Dictionary<int, int> mp = new Dictionary<int, int>(); // Put count of all the // distinct elements in Map // with element as the key // & count as the value. for (int i = 0; i < n; i++) { // Get the count for the // element if already // present in the Map // or get the default value // which is 0. if(mp.ContainsKey(arr[i])) { mp[arr[i]] = mp[arr[i]] + 1; } else { mp.Add(arr[i], 1); } } // Initialize an array // list of array lists List<List<int> > freq = new List<List<int> >(); for (int i = 0; i <= n; i++) freq.Add(new List<int>()); // Use frequencies as indexes // and add corresponding // values to the list foreach (KeyValuePair<int, int> x in mp) freq[x.Value].Add(x.Key); // Traverse []freq from // right side. int count = 0; for (int i = n; i >= 0; i--) { foreach (int x in freq[i]) { Console.WriteLine(x); count++; if (count == k) return; } }} // Driver Code to test the code.public static void Main(String[] args){ int []arr = {3, 1, 4, 4, 5, 2, 6, 1}; int n = arr.Length; int k = 2; print_N_mostFrequentNumber(arr, n, k);}} // This code is contributed by Princi Singh", "e": 6514, "s": 4985, "text": null }, { "code": "<script>// Javascript implementation to find k elements with max occurrence. function print_N_mostFrequentNumber(arr, n, k){ let mp = new Map(); // Put count of all the distinct elements in Map // with element as the key & count as the value. for (let i = 0; i < n; i++) { // Get the count for the element if already // present in the Map or get the default value // which is 0. mp.set(arr[i], mp.get(arr[i])==null?1:mp.get(arr[i]) + 1); } // Initialize an array list of array lists let freq = []; for (let i = 0; i <= n; i++) freq.push([]); // Use frequencies as indexes and add corresponding // values to the list for (let [key, value] of mp.entries()) freq[value].push(key); // Traverse freq[] from right side. let count = 0; for (let i = n; i >= 0; i--) { for (let x=0;x< freq[i].length;x++) { document.write(freq[i][x]+\" \"); count++; if (count == k) return; } }} // Driver Code to test the code.let arr = [ 3, 1, 4, 4, 5, 2, 6, 1 ];let n = arr.length;let k = 2;print_N_mostFrequentNumber(arr, n, k); // This code is contributed by patel2127</script>", "e": 7827, "s": 6514, "text": null }, { "code": null, "e": 7831, "s": 7827, "text": "4 1" }, { "code": null, "e": 8074, "s": 7833, "text": "Time Complexity: O(n) Auxiliary Space: O(n) Printing according to the first appearance. To keep the required order, we traverse the original array instead of the map. To avoid duplicates, we need to mark processed entries as -1 on the map." }, { "code": null, "e": 8078, "s": 8074, "text": "C++" }, { "code": null, "e": 8083, "s": 8078, "text": "Java" }, { "code": null, "e": 8091, "s": 8083, "text": "Python3" }, { "code": null, "e": 8094, "s": 8091, "text": "C#" }, { "code": null, "e": 8105, "s": 8094, "text": "Javascript" }, { "code": "// C++ implementation to find k numbers with most// occurrences in the given array#include <bits/stdc++.h>using namespace std; // function to print the k numbers with most occurrencesvoid print_N_mostFrequentNumber(int arr[], int n, int k){ // unordered_map 'um' implemented as frequency // hash table unordered_map<int, int> um; for (int i = 0; i < n; i++) um[arr[i]]++; // Use frequencies as indexes and put // elements with given frequency in a // vector (related to a frequency) vector<int> freq[n + 1]; for (int i = 0; i < n; i++) { int f = um[arr[i]]; if (f != -1) { freq[f].push_back(arr[i]); um[arr[i]] = -1; } } // Initialize count of items printed int count = 0; // Traverse the frequency array from // right side as we need the most // frequent items. for (int i = n; i >= 0; i--) { // Print items of current frequency for (int x : freq[i]) { cout << x << \" \"; count++; if (count == k) return; } }} // Driver program to test aboveint main(){ int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; print_N_mostFrequentNumber(arr, n, k); return 0;}", "e": 9386, "s": 8105, "text": null }, { "code": "// Java implementation to find k elements with max occurrence.import java.util.*;public class KFrequentNumbers { static void print_N_mostFrequentNumber(int[] arr, int n, int k) { Map<Integer, Integer> mp = new HashMap<Integer, Integer>(); // Put count of all the distinct elements in Map // with element as the key & count as the value. for (int i = 0; i < n; i++) { // Get the count for the element if already // present in the Map or get the default value // which is 0. mp.put(arr[i], mp.getOrDefault(arr[i], 0) + 1); } // Initialize an array list of array lists List<List<Integer> > freq = new ArrayList<List<Integer> >(); for (int i = 0; i <= n; i++) freq.add(new ArrayList<Integer>()); // Use frequencies as indexes and add corresponding // values to the list for (int i = 0; i < n; i++) { int f = mp.get(arr[i]); if (f != -1) { freq.get(f).add(arr[i]); mp.put(arr[i], -1); } } // Traverse freq[] from right side. int count = 0; for (int i = n; i >= 0; i--) { for (int x : freq.get(i)) { System.out.println(x); count++; if (count == k) return; } } } // Driver Code to test the code. public static void main(String[] args) { int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 }; int n = arr.length; int k = 3; print_N_mostFrequentNumber(arr, n, k); }}", "e": 11000, "s": 9386, "text": null }, { "code": "# Python implementation to find k elements# with max occurrence.def print_N_mostFrequentNumber(arr, n, k): mp = {} # Put count of all the distinct # elements in Map with element # as the key & count as the value. for i in range(n): # Get the count for the element # if already present in the Map # or get the default value which is 0. if arr[i] in mp: mp[arr[i]] += 1 else: mp[arr[i]] = 0 # Initialize an array list of array lists freq = [[] for i in range(n+1)] # Use frequencies as indexes and # add corresponding values to # the list for i in range(n): f = mp[arr[i]] if (f != -1): freq[f].append(arr[i]) mp[arr[i]] = -1 # Traverse []freq from right side. count = 0 for i in range(n, -1, -1): for x in freq[i]: print(x ,end = \" \") count+=1 if (count == k): return # Driver Codearr = [3, 1, 4, 4, 5, 2, 6, 1]n = len(arr)k = 3 print_N_mostFrequentNumber(arr, n, k) # This code is contributed by Shubham Singh", "e": 12162, "s": 11000, "text": null }, { "code": "// C# implementation to find k elements// with max occurrence.using System;using System.Collections.Generic; class GFG{ static void print_N_mostFrequentNumber(int[] arr, int n, int k){ Dictionary<int, int> mp = new Dictionary<int, int>(); // Put count of all the distinct // elements in Map with element // as the key & count as the value. for(int i = 0; i < n; i++) { // Get the count for the element // if already present in the Map // or get the default value which is 0. if (mp.ContainsKey(arr[i])) mp[arr[i]]++; else mp.Add(arr[i], 0); } // Initialize an array list of array lists List<List<int>> freq = new List<List<int>>(); for(int i = 0; i <= n; i++) freq.Add(new List<int>()); // Use frequencies as indexes and // add corresponding values to // the list for(int i = 0; i < n; i++) { int f = mp[arr[i]]; if (f != -1) { freq[f].Add(arr[i]); if (mp.ContainsKey(arr[i])) mp[arr[i]] = -1; else mp.Add(arr[i], 0); } } // Traverse []freq from right side. int count = 0; for(int i = n; i >= 0; i--) { foreach(int x in freq[i]) { Console.Write(x); Console.Write(\" \"); count++; if (count == k) return; } }} // Driver Codepublic static void Main(String[] args){ int []arr = { 3, 1, 4, 4, 5, 2, 6, 1 }; int n = arr.Length; int k = 3; print_N_mostFrequentNumber(arr, n, k);}} // This code is contributed by Amit Katiyar", "e": 13916, "s": 12162, "text": null }, { "code": "<script> // JavaScript implementation to find k elements // with max occurrence. function print_N_mostFrequentNumber(arr, n, k) { var mp = {}; // Put count of all the distinct // elements in Map with element // as the key & count as the value. for (var i = 0; i < n; i++) { // Get the count for the element // if already present in the Map // or get the default value which is 0. if (mp.hasOwnProperty(arr[i])) mp[arr[i]]++; else mp[arr[i]] = 0; } // Initialize an array list of array lists var freq = Array.from(Array(n + 1), () => Array()); // Use frequencies as indexes and // add corresponding values to // the list for (var i = 0; i < n; i++) { var f = mp[arr[i]]; if (f !== -1) { freq[f].push(arr[i]); if (mp.hasOwnProperty(arr[i])) mp[arr[i]] = -1; else mp[arr[i]] = 0; } } // Traverse []freq from right side. var count = 0; for (var i = n; i >= 0; i--) { for (const x of freq[i]) { document.write(x + \" \"); count++; if (count === k) return; } } } // Driver Code var arr = [3, 1, 4, 4, 5, 2, 6, 1]; var n = arr.length; var k = 3; print_N_mostFrequentNumber(arr, n, k);</script>", "e": 15400, "s": 13916, "text": null }, { "code": null, "e": 15406, "s": 15400, "text": "1 4 3" }, { "code": null, "e": 15452, "s": 15408, "text": "Time Complexity: O(n) Auxiliary Space: O(n)" }, { "code": null, "e": 15465, "s": 15452, "text": "princi singh" }, { "code": null, "e": 15480, "s": 15465, "text": "amit143katiyar" }, { "code": null, "e": 15495, "s": 15480, "text": "mohit kumar 29" }, { "code": null, "e": 15502, "s": 15495, "text": "rdtank" }, { "code": null, "e": 15512, "s": 15502, "text": "patel2127" }, { "code": null, "e": 15529, "s": 15512, "text": "akshaysingh98088" }, { "code": null, "e": 15546, "s": 15529, "text": "khushboogoyal499" }, { "code": null, "e": 15558, "s": 15546, "text": "anikakapoor" }, { "code": null, "e": 15571, "s": 15558, "text": "simmytarika5" }, { "code": null, "e": 15586, "s": 15571, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 15605, "s": 15586, "text": "frequency-counting" }, { "code": null, "e": 15612, "s": 15605, "text": "Arrays" }, { "code": null, "e": 15617, "s": 15612, "text": "Hash" }, { "code": null, "e": 15624, "s": 15617, "text": "Arrays" }, { "code": null, "e": 15629, "s": 15624, "text": "Hash" }, { "code": null, "e": 15727, "s": 15629, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15759, "s": 15727, "text": "Introduction to Data Structures" }, { "code": null, "e": 15784, "s": 15759, "text": "Window Sliding Technique" }, { "code": null, "e": 15831, "s": 15784, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 15895, "s": 15831, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 15926, "s": 15895, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 15964, "s": 15926, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 16000, "s": 15964, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 16031, "s": 16000, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 16058, "s": 16031, "text": "Count pairs with given sum" } ]
Java NIO - Quick Guide
Java.nio package was introduced in java 1.4. In contrast of java I/O in java NIO the buffer and channel oriented data flow for I/O operations is introduced which in result provide faster execution and better performance. Also NIO API offer selectors which introduces the functionality of listen to multiple channels for IO events in asynchronous or non blocking way.In NIO the most time-consuming I/O activities including filling and draining of buffers to the operating system which increases in speed. The central abstractions of the NIO APIs are following βˆ’ Buffers,which are containers for data,charsets and their associated decoders and encoders,which translate between bytes and Unicode characters. Buffers,which are containers for data,charsets and their associated decoders and encoders,which translate between bytes and Unicode characters. Channels of various types,which represent connections to entities capable of performing I/O operations Channels of various types,which represent connections to entities capable of performing I/O operations Selectors and selection keys, which together with selectable channels define a multiplexed, non-blocking I/O facility. Selectors and selection keys, which together with selectable channels define a multiplexed, non-blocking I/O facility. This section guides you on how to download and set up Java on your machine. Please follow the following steps to set up the environment. Java SE is freely available from the link Download Java. So you download a version based on your operating system. Follow the instructions to download java and run the .exe to install Java on your machine. Once you installed Java on your machine, you would need to set environment variables to point to correct installation directories βˆ’ Assuming you have installed Java in c:\Program Files\java\jdk directory βˆ’ Right-click on 'My Computer' and select 'Properties'. Right-click on 'My Computer' and select 'Properties'. Click on the 'Environment variables' button under the 'Advanced' tab. Click on the 'Environment variables' button under the 'Advanced' tab. Now alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'. Now alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'. Assuming you have installed Java in c:\Program Files\java\jdk directory βˆ’ Edit the 'C:\autoexec.bat' file and add the following line at the end: 'SET PATH = %PATH%;C:\Program Files\java\jdk\bin' Edit the 'C:\autoexec.bat' file and add the following line at the end: 'SET PATH = %PATH%;C:\Program Files\java\jdk\bin' Environment variable PATH should be set to point to where the java binaries have been installed. Refer to your shell documentation if you have trouble doing this. Example, if you use bash as your shell, then you would add the following line to the end of your '.bashrc: export PATH = /path/to/java:$PATH' To write your java programs you will need a text editor. There are even more sophisticated IDE available in the market. But for now, you can consider one of the following βˆ’ Notepad βˆ’ On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad. Notepad βˆ’ On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad. Netbeans βˆ’ is a Java IDE that is open source and free which can be downloaded from http://www.netbeans.org/index.html. Netbeans βˆ’ is a Java IDE that is open source and free which can be downloaded from http://www.netbeans.org/index.html. Eclipse βˆ’ is also a java IDE developed by the eclipse open source community and can be downloaded from https://www.eclipse.org/. Eclipse βˆ’ is also a java IDE developed by the eclipse open source community and can be downloaded from https://www.eclipse.org/. As we know that java NIO is introduced for advancement of conventional java IO API.The main enhancements which make NIO more efficient than IO are channel data flow model used in NIO and use of operating system for conventional IO tasks. The difference between Java NIO and Java IO can be explained as following βˆ’ As mentioned in previous post in NIO buffer and channel oriented data flow for I/O operations which provide faster execution and better performance as compare to IO.Also NIO uses operating system for conventional I/O tasks which again makes it more efficient. As mentioned in previous post in NIO buffer and channel oriented data flow for I/O operations which provide faster execution and better performance as compare to IO.Also NIO uses operating system for conventional I/O tasks which again makes it more efficient. Other aspect of difference between NIO and IO is this IO uses stream line data flow i.e one more byte at a time and relies on converting data objects into bytes and vice-e-versa while NIO deals with the data blocks which are chunks of bytes. Other aspect of difference between NIO and IO is this IO uses stream line data flow i.e one more byte at a time and relies on converting data objects into bytes and vice-e-versa while NIO deals with the data blocks which are chunks of bytes. In java IO stream objects are unidirectional while in NIO channels are bidirectional meaning a channel can be used for both reading and writing data. In java IO stream objects are unidirectional while in NIO channels are bidirectional meaning a channel can be used for both reading and writing data. The streamline data flow in IO does not allow move forth and back in the data.If case need to move forth and back in the data read from a stream need to cache it in a buffer first.While in case of NIO we uses buffer oriented which allows to access data back and forth without need of caching. The streamline data flow in IO does not allow move forth and back in the data.If case need to move forth and back in the data read from a stream need to cache it in a buffer first.While in case of NIO we uses buffer oriented which allows to access data back and forth without need of caching. NIO API also supports multi threading so that data can be read and written asynchronously in such as a way that while performing IO operations current thread is not blocked.This again make it more efficient than conventional java IO API. NIO API also supports multi threading so that data can be read and written asynchronously in such as a way that while performing IO operations current thread is not blocked.This again make it more efficient than conventional java IO API. Concept of multi threading is introduced with the introduction of Selectors in java NIO which allow to listen to multiple channels for IO events in asynchronous or non blocking way. Concept of multi threading is introduced with the introduction of Selectors in java NIO which allow to listen to multiple channels for IO events in asynchronous or non blocking way. Multi threading in NIO make it Non blocking which means that thread is requested to read or write only when data is available otherwise thread can be used in other task for mean time.But this is not possible in case of conventional java IO as no multi threading is supported in it which make it as Blocking. Multi threading in NIO make it Non blocking which means that thread is requested to read or write only when data is available otherwise thread can be used in other task for mean time.But this is not possible in case of conventional java IO as no multi threading is supported in it which make it as Blocking. NIO allows to manage multiple channels using only a single thread,but the cost is that parsing the data might be somewhat more complicated than when reading data from a blocking stream in case of java IO.So in case fewer connections with very high bandwidth are required with sending a lot of data at a time,than in this case java IO API might be the best fit. NIO allows to manage multiple channels using only a single thread,but the cost is that parsing the data might be somewhat more complicated than when reading data from a blocking stream in case of java IO.So in case fewer connections with very high bandwidth are required with sending a lot of data at a time,than in this case java IO API might be the best fit. As name suggests channel is used as mean of data flow from one end to other.Here in java NIO channel act same between buffer and an entity at other end in other words channel are use to read data to buffer and also write data from buffer. Unlike from streams which are used in conventional Java IO channels are two way i.e can read as well as write.Java NIO channel supports asynchronous flow of data both in blocking and non blocking mode. Java NIO channel is implemented primarily in following classes βˆ’ FileChannel βˆ’ In order to read data from file we uses file channel. Object of file channel can be created only by calling the getChannel() method on file object as we can't create file object directly. FileChannel βˆ’ In order to read data from file we uses file channel. Object of file channel can be created only by calling the getChannel() method on file object as we can't create file object directly. DatagramChannel βˆ’ The datagram channel can read and write the data over the network via UDP (User Datagram Protocol).Object of DataGramchannel can be created using factory methods. DatagramChannel βˆ’ The datagram channel can read and write the data over the network via UDP (User Datagram Protocol).Object of DataGramchannel can be created using factory methods. SocketChannel βˆ’ The SocketChannel channel can read and write the data over the network via TCP (Transmission Control Protocol). It also uses the factory methods for creating the new object. SocketChannel βˆ’ The SocketChannel channel can read and write the data over the network via TCP (Transmission Control Protocol). It also uses the factory methods for creating the new object. ServerSocketChannel βˆ’ The ServerSocketChannel read and write the data over TCP connections, same as a web server. For every incoming connection a SocketChannel is created. ServerSocketChannel βˆ’ The ServerSocketChannel read and write the data over TCP connections, same as a web server. For every incoming connection a SocketChannel is created. Following example reads from a text file from C:/Test/temp.txt and prints the content to the console. Hello World! import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class ChannelDemo { public static void main(String args[]) throws IOException { RandomAccessFile file = new RandomAccessFile("C:/Test/temp.txt", "r"); FileChannel fileChannel = file.getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate(512); while (fileChannel.read(byteBuffer) > 0) { // flip the buffer to prepare for get operation byteBuffer.flip(); while (byteBuffer.hasRemaining()) { System.out.print((char) byteBuffer.get()); } } file.close(); } } Hello World! As already mentioned FileChannel implementation of Java NIO channel is introduced to access meta data properties of the file including creation, modification, size etc.Along with this File Channels are multi threaded which again makes Java NIO more efficient than Java IO. In general we can say that FileChannel is a channel that is connected to a file by which you can read data from a file, and write data to a file.Other important characteristic of FileChannel is this that it cannot be set into non-blocking mode and always runs in blocking mode. We can't get file channel object directly, Object of file channel is obtained either by βˆ’ getChannel() βˆ’ method on any either FileInputStream, FileOutputStream or RandomAccessFile. getChannel() βˆ’ method on any either FileInputStream, FileOutputStream or RandomAccessFile. open() βˆ’ method of File channel which by default open the channel. open() βˆ’ method of File channel which by default open the channel. The object type of File channel depends on type of class called from object creation i.e if object is created by calling getchannel method of FileInputStream then File channel is opened for reading and will throw NonWritableChannelException in case attempt to write to it. The following example shows the how to read and write data from Java NIO FileChannel. Following example reads from a text file from C:/Test/temp.txt and prints the content to the console. Hello World! import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.HashSet; import java.util.Set; public class FileChannelDemo { public static void main(String args[]) throws IOException { //append the content to existing file writeFileChannel(ByteBuffer.wrap("Welcome to TutorialsPoint".getBytes())); //read the file readFileChannel(); } public static void readFileChannel() throws IOException { RandomAccessFile randomAccessFile = new RandomAccessFile("C:/Test/temp.txt", "rw"); FileChannel fileChannel = randomAccessFile.getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate(512); Charset charset = Charset.forName("US-ASCII"); while (fileChannel.read(byteBuffer) > 0) { byteBuffer.rewind(); System.out.print(charset.decode(byteBuffer)); byteBuffer.flip(); } fileChannel.close(); randomAccessFile.close(); } public static void writeFileChannel(ByteBuffer byteBuffer)throws IOException { Set<StandardOpenOption> options = new HashSet<>(); options.add(StandardOpenOption.CREATE); options.add(StandardOpenOption.APPEND); Path path = Paths.get("C:/Test/temp.txt"); FileChannel fileChannel = FileChannel.open(path, options); fileChannel.write(byteBuffer); fileChannel.close(); } } Hello World! Welcome to TutorialsPoint Java NIO Datagram is used as channel which can send and receive UDP packets over a connection less protocol.By default datagram channel is blocking while it can be use in non blocking mode.In order to make it non-blocking we can use the configureBlocking(false) method.DataGram channel can be open by calling its one of the static method named as open() which can also take IP address as parameter so that it can be used for multi casting. Datagram channel alike of FileChannel do not connected by default in order to make it connected we have to explicitly call its connect() method.However datagram channel need not be connected in order for the send and receive methods to be used while it must be connected in order to use the read and write methods, since those methods do not accept or return socket addresses. We can check the connection status of datagram channel by calling its isConnected() method.Once connected, a datagram channel remains connected until it is disconnected or closed.Datagram channels are thread safe and supports multi-threading and concurrency simultaneously. bind(SocketAddress local) βˆ’ This method is used to bind the datagram channel's socket to the local address which is provided as the parameter to this method. bind(SocketAddress local) βˆ’ This method is used to bind the datagram channel's socket to the local address which is provided as the parameter to this method. connect(SocketAddress remote) βˆ’ This method is used to connect the socket to the remote address. connect(SocketAddress remote) βˆ’ This method is used to connect the socket to the remote address. disconnect() βˆ’ This method is used to disconnect the socket to the remote address. disconnect() βˆ’ This method is used to disconnect the socket to the remote address. getRemoteAddress() βˆ’ This method return the address of remote location to which the channel's socket is connected. getRemoteAddress() βˆ’ This method return the address of remote location to which the channel's socket is connected. isConnected() βˆ’ As already mentioned this method returns the status of connection of datagram channel i.e whether it is connected or not. isConnected() βˆ’ As already mentioned this method returns the status of connection of datagram channel i.e whether it is connected or not. open() and open(ProtocolFamily family) βˆ’ Open method is used open a datagram channel for single address while parametrized open method open channel for multiple addresses represented as protocol family. open() and open(ProtocolFamily family) βˆ’ Open method is used open a datagram channel for single address while parametrized open method open channel for multiple addresses represented as protocol family. read(ByteBuffer dst) βˆ’ This method is used to read data from the given buffer through datagram channel. read(ByteBuffer dst) βˆ’ This method is used to read data from the given buffer through datagram channel. receive(ByteBuffer dst) βˆ’ This method is used to receive datagram via this channel. receive(ByteBuffer dst) βˆ’ This method is used to receive datagram via this channel. send(ByteBuffer src, SocketAddress target) βˆ’ This method is used to send datagram via this channel. send(ByteBuffer src, SocketAddress target) βˆ’ This method is used to send datagram via this channel. The following example shows the how to send data from Java NIO DataGramChannel. import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; public class DatagramChannelServer { public static void main(String[] args) throws IOException { DatagramChannel server = DatagramChannel.open(); InetSocketAddress iAdd = new InetSocketAddress("localhost", 8989); server.bind(iAdd); System.out.println("Server Started: " + iAdd); ByteBuffer buffer = ByteBuffer.allocate(1024); //receive buffer from client. SocketAddress remoteAdd = server.receive(buffer); //change mode of buffer buffer.flip(); int limits = buffer.limit(); byte bytes[] = new byte[limits]; buffer.get(bytes, 0, limits); String msg = new String(bytes); System.out.println("Client at " + remoteAdd + " sent: " + msg); server.send(buffer,remoteAdd); server.close(); } } Server Started: localhost/127.0.0.1:8989 import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; public class DatagramChannelClient { public static void main(String[] args) throws IOException { DatagramChannel client = null; client = DatagramChannel.open(); client.bind(null); String msg = "Hello World!"; ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes()); InetSocketAddress serverAddress = new InetSocketAddress("localhost", 8989); client.send(buffer, serverAddress); buffer.clear(); client.receive(buffer); buffer.flip(); client.close(); } } Running the client will print the following output on server. Server Started: localhost/127.0.0.1:8989 Client at /127.0.0.1:64857 sent: Hello World! Java NIO socket channel is a selectable type channel which means it can be multiplexed using selector, used for stream oriented data flow connecting sockets.Socket channel can be created by invoking its static open() method,providing any pre-existing socket is not already present.Socket channel is created by invoking open method but not yet connected.In order to connect socket channel connect() method is to be called.One point to be mentioned here is if channel is not connected and any I/O operation is tried to be attempted then NotYetConnectedException is thrown by this channel.So one must be ensure that channel is connected before performing any IO operation.Once channel is get connected,it remains connected until it is closed.The state of socket channel may be determined by invoking its isConnected method. The connection of socket channel could be finished by invoking its finishConnect() method.Whether or not a connection operation is in progress may be determined by invoking the isConnectionPending method.By default socket channel supports non-blocking connection.Also it support asynchronous shutdown, which is similar to the asynchronous close operation specified in the Channel class. Socket channels are safe for use by multiple concurrent threads. They support concurrent reading and writing, though at most one thread may be reading and at most one thread may be writing at any given time. The connect and finishConnect methods are mutually synchronized against each other, and an attempt to initiate a read or write operation while an invocation of one of these methods is in progress will block until that invocation is complete. bind(SocketAddress local) βˆ’ This method is used to bind the socket channel to the local address which is provided as the parameter to this method. bind(SocketAddress local) βˆ’ This method is used to bind the socket channel to the local address which is provided as the parameter to this method. connect(SocketAddress remote) βˆ’ This method is used to connect the socket to the remote address. connect(SocketAddress remote) βˆ’ This method is used to connect the socket to the remote address. finishConnect() βˆ’ This method is used to finishes the process of connecting a socket channel. finishConnect() βˆ’ This method is used to finishes the process of connecting a socket channel. getRemoteAddress() βˆ’ This method return the address of remote location to which the channel's socket is connected. getRemoteAddress() βˆ’ This method return the address of remote location to which the channel's socket is connected. isConnected() βˆ’ As already mentioned this method returns the status of connection of socket channel i.e whether it is connected or not. isConnected() βˆ’ As already mentioned this method returns the status of connection of socket channel i.e whether it is connected or not. open() and open((SocketAddress remote) βˆ’ Open method is used open a socket channel for no specified address while parameterized open method open channel for specified remote address and also connects to it.This convenience method works as if by invoking the open() method, invoking the connect method upon the resulting socket channel, passing it remote, and then returning that channel. open() and open((SocketAddress remote) βˆ’ Open method is used open a socket channel for no specified address while parameterized open method open channel for specified remote address and also connects to it.This convenience method works as if by invoking the open() method, invoking the connect method upon the resulting socket channel, passing it remote, and then returning that channel. read(ByteBuffer dst) βˆ’ This method is used to read data from the given buffer through socket channel. read(ByteBuffer dst) βˆ’ This method is used to read data from the given buffer through socket channel. isConnectionPending() βˆ’ This method tells whether or not a connection operation is in progress on this channel. isConnectionPending() βˆ’ This method tells whether or not a connection operation is in progress on this channel. The following example shows the how to send data from Java NIO SocketChannel. Hello World! import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.EnumSet; public class SocketChannelClient { public static void main(String[] args) throws IOException { ServerSocketChannel serverSocket = null; SocketChannel client = null; serverSocket = ServerSocketChannel.open(); serverSocket.socket().bind(new InetSocketAddress(9000)); client = serverSocket.accept(); System.out.println("Connection Set: " + client.getRemoteAddress()); Path path = Paths.get("C:/Test/temp1.txt"); FileChannel fileChannel = FileChannel.open(path, EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE) ); ByteBuffer buffer = ByteBuffer.allocate(1024); while(client.read(buffer) > 0) { buffer.flip(); fileChannel.write(buffer); buffer.clear(); } fileChannel.close(); System.out.println("File Received"); client.close(); } } Running the client will not print anything until server starts. import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.SocketChannel; import java.nio.file.Path; import java.nio.file.Paths; public class SocketChannelServer { public static void main(String[] args) throws IOException { SocketChannel server = SocketChannel.open(); SocketAddress socketAddr = new InetSocketAddress("localhost", 9000); server.connect(socketAddr); Path path = Paths.get("C:/Test/temp.txt"); FileChannel fileChannel = FileChannel.open(path); ByteBuffer buffer = ByteBuffer.allocate(1024); while(fileChannel.read(buffer) > 0) { buffer.flip(); server.write(buffer); buffer.clear(); } fileChannel.close(); System.out.println("File Sent"); server.close(); } } Running the server will print the following. Connection Set: /127.0.0.1:49558 File Received Java NIO server socket channel is again a selectable type channel used for stream oriented data flow connecting sockets.Server Socket channel can be created by invoking its static open() method,providing any pre-existing socket is not already present.Server Socket channel is created by invoking open method but not yet bound.In order to bound socket channel bind() method is to be called. One point to be mentioned here is if channel is not bound and any I/O operation is tried to be attempted then NotYetBoundException is thrown by this channel.So one must be ensure that channel is bounded before performing any IO operation. Incoming connections for the server socket channel are listen by calling the ServerSocketChannel.accept() method. When the accept() method returns, it returns a SocketChannel with an incoming connection. Thus, the accept() method blocks until an incoming connection arrives.If the channel is in non-blocking mode then accept method will immediately return null if there are no pending connections. Otherwise it will block indefinitely until a new connection is available or an I/O error occurs. The new channel's socket is initially unbound; it must be bound to a specific address via one of its socket's bind methods before connections can be accepted.Also the new channel is created by invoking the openServerSocketChannel method of the system-wide default SelectorProvider object. Like socket channel server socket channel could read data using read() method.Firstly the buffer is allocated. The data read from a ServerSocketChannel is stored into the buffer.Secondly we call the ServerSocketChannel.read() method and it reads the data from a ServerSocketChannel into a buffer. The integer value of the read() method returns how many bytes were written into the buffer Similarly data could be written to server socket channel using write() method using buffer as a parameter.Commonly uses write method in a while loop as need to repeat the write() method until the Buffer has no further bytes available to write. bind(SocketAddress local) βˆ’ This method is used to bind the socket channel to the local address which is provided as the parameter to this method. bind(SocketAddress local) βˆ’ This method is used to bind the socket channel to the local address which is provided as the parameter to this method. accept() βˆ’ This method is used to accepts a connection made to this channel's socket. accept() βˆ’ This method is used to accepts a connection made to this channel's socket. connect(SocketAddress remote) βˆ’ This method is used to connect the socket to the remote address. connect(SocketAddress remote) βˆ’ This method is used to connect the socket to the remote address. finishConnect() βˆ’ This method is used to finishes the process of connecting a socket channel. finishConnect() βˆ’ This method is used to finishes the process of connecting a socket channel. getRemoteAddress() βˆ’ This method return the address of remote location to which the channel's socket is connected. getRemoteAddress() βˆ’ This method return the address of remote location to which the channel's socket is connected. isConnected() βˆ’ As already mentioned this method returns the status of connection of socket channel i.e whether it is connected or not. isConnected() βˆ’ As already mentioned this method returns the status of connection of socket channel i.e whether it is connected or not. open() βˆ’ Open method is used open a socket channel for no specified address.This convenience method works as if by invoking the open() method, invoking the connect method upon the resulting server socket channel, passing it remote, and then returning that channel. open() βˆ’ Open method is used open a socket channel for no specified address.This convenience method works as if by invoking the open() method, invoking the connect method upon the resulting server socket channel, passing it remote, and then returning that channel. read(ByteBuffer dst) βˆ’ This method is used to read data from the given buffer through socket channel. read(ByteBuffer dst) βˆ’ This method is used to read data from the given buffer through socket channel. setOption(SocketOption<T> name, T value) βˆ’ This method sets the value of a socket option. setOption(SocketOption<T> name, T value) βˆ’ This method sets the value of a socket option. socket() βˆ’ This method retrieves a server socket associated with this channel. socket() βˆ’ This method retrieves a server socket associated with this channel. validOps() βˆ’ This method returns an operation set identifying this channel's supported operations.Server-socket channels only support the accepting of new connections, so this method returns SelectionKey.OP_ACCEPT. validOps() βˆ’ This method returns an operation set identifying this channel's supported operations.Server-socket channels only support the accepting of new connections, so this method returns SelectionKey.OP_ACCEPT. The following example shows the how to send data from Java NIO ServerSocketChannel. Hello World! import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.EnumSet; public class SocketChannelClient { public static void main(String[] args) throws IOException { ServerSocketChannel serverSocket = null; SocketChannel client = null; serverSocket = ServerSocketChannel.open(); serverSocket.socket().bind(new InetSocketAddress(9000)); client = serverSocket.accept(); System.out.println("Connection Set: " + client.getRemoteAddress()); Path path = Paths.get("C:/Test/temp1.txt"); FileChannel fileChannel = FileChannel.open(path, EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE) ); ByteBuffer buffer = ByteBuffer.allocate(1024); while(client.read(buffer) > 0) { buffer.flip(); fileChannel.write(buffer); buffer.clear(); } fileChannel.close(); System.out.println("File Received"); client.close(); } } Running the client will not print anything until server starts. import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.SocketChannel; import java.nio.file.Path; import java.nio.file.Paths; public class SocketChannelServer { public static void main(String[] args) throws IOException { SocketChannel server = SocketChannel.open(); SocketAddress socketAddr = new InetSocketAddress("localhost", 9000); server.connect(socketAddr); Path path = Paths.get("C:/Test/temp.txt"); FileChannel fileChannel = FileChannel.open(path); ByteBuffer buffer = ByteBuffer.allocate(1024); while(fileChannel.read(buffer) > 0) { buffer.flip(); server.write(buffer); buffer.clear(); } fileChannel.close(); System.out.println("File Sent"); server.close(); } } Running the server will print the following. Connection Set: /127.0.0.1:49558 File Received As we know that Java NIO is a more optimized API for data IO operations as compared to the conventional IO API of Java.One more additional support which Java NIO provides is to read/write data from/to multiple buffers to channel.This multiple read and write support is termed as Scatter and Gather in which data is scattered to multiple buffers from single channel in case of read data while data is gathered from multiple buffers to single channel in case of write data. In order to achieve this multiple read and write from channel there is ScatteringByteChannel and GatheringByteChannel API which Java NIO provides for read and write the data as illustrate in below example. Read from multiple channels βˆ’ In this we made to reads data from a single channel into multiple buffers.For this multiple buffers are allocated and are added to a buffer type array.Then this array is passed as parameter to the ScatteringByteChannel read() method which then writes data from the channel in the sequence the buffers occur in the array.Once a buffer is full, the channel moves on to fill the next buffer. The following example shows how scattering of data is performed in Java NIO Hello World! import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ScatteringByteChannel; public class ScatterExample { private static String FILENAME = "C:/Test/temp.txt"; public static void main(String[] args) { ByteBuffer bLen1 = ByteBuffer.allocate(1024); ByteBuffer bLen2 = ByteBuffer.allocate(1024); FileInputStream in; try { in = new FileInputStream(FILENAME); ScatteringByteChannel scatter = in.getChannel(); scatter.read(new ByteBuffer[] {bLen1, bLen2}); bLen1.position(0); bLen2.position(0); int len1 = bLen1.asIntBuffer().get(); int len2 = bLen2.asIntBuffer().get(); System.out.println("Scattering : Len1 = " + len1); System.out.println("Scattering : Len2 = " + len2); } catch (FileNotFoundException exObj) { exObj.printStackTrace(); } catch (IOException ioObj) { ioObj.printStackTrace(); } } } Scattering : Len1 = 1214606444 Scattering : Len2 = 0 In last it can be concluded that scatter/gather approach in Java NIO is introduced as an optimized and multitasked when used properly.It allows you to delegate to the operating system the grunt work of separating out the data you read into multiple buckets, or assembling disparate chunks of data into a whole.No doubt this saves time and uses operating system more efficiently by avoiding buffer copies, and reduces the amount of code need to write and debug. As we know that Java NIO is a more optimized API for data IO operations as compared to the conventional IO API of Java.One more additional support which Java NIO provides is to read/write data from/to multiple buffers to channel.This multiple read and write support is termed as Scatter and Gather in which data is scattered to multiple buffers from single channel in case of read data while data is gathered from multiple buffers to single channel in case of write data. In order to achieve this multiple read and write from channel there is ScatteringByteChannel and GatheringByteChannel API which Java NIO provides for read and write the data as illustrate in below example. write to multiple channels βˆ’ In this we made to write data from multiple buffers into a single channel.For this again multiple buffers are allocated and are added to a buffer type array.Then this array is passed as parameter to the GatheringByteChannel write() method which then writes data from the multiple buffers in the sequence the buffers occur in the array.One point to remember here is only the data between the position and the limit of the buffers are written. The following example shows how data gathering is performed in Java NIO import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.GatheringByteChannel; public class GatherExample { private static String FILENAME = "C:/Test/temp.txt"; public static void main(String[] args) { String stream1 = "Gather data stream first"; String stream2 = "Gather data stream second"; ByteBuffer bLen1 = ByteBuffer.allocate(1024); ByteBuffer bLen2 = ByteBuffer.allocate(1024); // Next two buffer hold the data we want to write ByteBuffer bstream1 = ByteBuffer.wrap(stream1.getBytes()); ByteBuffer bstream2 = ByteBuffer.wrap(stream2.getBytes()); int len1 = stream1.length(); int len2 = stream2.length(); // Writing length(data) to the Buffer bLen1.asIntBuffer().put(len1); bLen2.asIntBuffer().put(len2); System.out.println("Gathering : Len1 = " + len1); System.out.println("Gathering : Len2 = " + len2); // Write data to the file try { FileOutputStream out = new FileOutputStream(FILENAME); GatheringByteChannel gather = out.getChannel(); gather.write(new ByteBuffer[] {bLen1, bLen2, bstream1, bstream2}); out.close(); gather.close(); } catch (FileNotFoundException exObj) { exObj.printStackTrace(); } catch(IOException ioObj) { ioObj.printStackTrace(); } } } Gathering : Len1 = 24 Gathering : Len2 = 25 In last it can be concluded that scatter/gather approach in Java NIO is introduced as an optimized and multitasked when used properly.It allows you to delegate to the operating system the grunt work of separating out the data you read into multiple buckets, or assembling disparate chunks of data into a whole.No doubt this saves time and uses operating system more efficiently by avoiding buffer copies, and reduces the amount of code need to write and debug. Buffers in Java NIO can be treated as a simple object which act as a fixed sized container of data chunks that can be used to write data to channel or read data from channel so that buffers act as endpoints to the channels. It provide set of methods that make more convenient to deal with memory block in order to read and write data to and from channels. Buffers makes NIO package more efficient and faster as compared to classic IO as in case of IO data is deal in the form of streams which do not support asynchronous and concurrent flow of data.Also IO does not allow data execution in chunk or group of bytes. Primary parameters that defines Java NIO buffer could be defined as βˆ’ Capacity βˆ’ Maximum Amount of data/byte that can be stored in the Buffer.Capacity of a buffer can not be altered.Once the buffer is full it should be cleared before writing to it. Capacity βˆ’ Maximum Amount of data/byte that can be stored in the Buffer.Capacity of a buffer can not be altered.Once the buffer is full it should be cleared before writing to it. Limit βˆ’ Limit has meaning as per the mode of Buffer i.e. in write mode of Buffer Limit is equal to the capacity which means that maximum data that could be write in buffer.While in read mode of buffer Limit means the limit of how much data can be read from the Buffer. Limit βˆ’ Limit has meaning as per the mode of Buffer i.e. in write mode of Buffer Limit is equal to the capacity which means that maximum data that could be write in buffer.While in read mode of buffer Limit means the limit of how much data can be read from the Buffer. Position βˆ’ Points to the current location of cursor in buffer.Initially setted as 0 at the time of creation of buffer or in other words it is the index of the next element to be read or written which get updated automatically by get() and put() methods. Position βˆ’ Points to the current location of cursor in buffer.Initially setted as 0 at the time of creation of buffer or in other words it is the index of the next element to be read or written which get updated automatically by get() and put() methods. Mark βˆ’ Mark a bookmark of the position in a buffer.When mark() method is called the current position is recorded and when reset() is called the marked position is restored. Mark βˆ’ Mark a bookmark of the position in a buffer.When mark() method is called the current position is recorded and when reset() is called the marked position is restored. Java NIO buffers can be classified in following variants on the basis of data types the buffer deals with βˆ’ ByteBuffer MappedByteBuffer CharBuffer DoubleBuffer FloatBuffer IntBuffer LongBuffer ShortBuffer As mentioned already that Buffer act as memory object which provide set of methods that make more convenient to deal with memory block.Following are the important methods of Buffer βˆ’ allocate(int capacity) βˆ’ This method is use to allocate a new buffer with capacity as parameter.Allocate method throws IllegalArgumentException in case the passed capacity is a negative integer. allocate(int capacity) βˆ’ This method is use to allocate a new buffer with capacity as parameter.Allocate method throws IllegalArgumentException in case the passed capacity is a negative integer. read() and put() βˆ’ read method of channel is used to write data from channel to buffer while put is a method of buffer which is used to write data in buffer. read() and put() βˆ’ read method of channel is used to write data from channel to buffer while put is a method of buffer which is used to write data in buffer. flip() βˆ’ The flip method switches the mode of Buffer from writing to reading mode.It also sets the position back to 0, and sets the limit to where position was at time of writing. flip() βˆ’ The flip method switches the mode of Buffer from writing to reading mode.It also sets the position back to 0, and sets the limit to where position was at time of writing. write() and get() βˆ’ write method of channel is used to write data from buffer to channel while get is a method of buffer which is used to read data from buffer. write() and get() βˆ’ write method of channel is used to write data from buffer to channel while get is a method of buffer which is used to read data from buffer. rewind() βˆ’ rewind method is used when reread is required as it sets the position back to zero and do not alter the value of limit. rewind() βˆ’ rewind method is used when reread is required as it sets the position back to zero and do not alter the value of limit. clear() and compact() βˆ’ clear and compact both methods are used to make buffer from read to write mode.clear() method makes the position to zero and limit equals to capacity,in this method the data in the buffer is not cleared only the markers get re initialized. On other hand compact() method is use when there remained some un-read data and still we use write mode of buffer in this case compact method copies all unread data to the beginning of the buffer and sets position to right after the last unread element.The limit property is still set to capacity. clear() and compact() βˆ’ clear and compact both methods are used to make buffer from read to write mode.clear() method makes the position to zero and limit equals to capacity,in this method the data in the buffer is not cleared only the markers get re initialized. On other hand compact() method is use when there remained some un-read data and still we use write mode of buffer in this case compact method copies all unread data to the beginning of the buffer and sets position to right after the last unread element.The limit property is still set to capacity. mark() and reset() βˆ’ As name suggest mark method is used to mark any particular position in a buffer while reset make position back to marked position. mark() and reset() βˆ’ As name suggest mark method is used to mark any particular position in a buffer while reset make position back to marked position. The following example shows the implementation of above defined methods. import java.nio.ByteBuffer; import java.nio.CharBuffer; public class BufferDemo { public static void main (String [] args) { //allocate a character type buffer. CharBuffer buffer = CharBuffer.allocate(10); String text = "bufferDemo"; System.out.println("Input text: " + text); for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); //put character in buffer. buffer.put(c); } int buffPos = buffer.position(); System.out.println("Position after data is written into buffer: " + buffPos); buffer.flip(); System.out.println("Reading buffer contents:"); while (buffer.hasRemaining()) { System.out.println(buffer.get()); } //set the position of buffer to 5. buffer.position(5); //sets this buffer's mark at its position buffer.mark(); //try to change the position buffer.position(6); //calling reset method to restore to the position we marked. //reset() raise InvalidMarkException if either the new position is less //than the position marked or merk has not been setted. buffer.reset(); System.out.println("Restored buffer position : " + buffer.position()); } } Input text: bufferDemo Position after data is written into buffer: 10 Reading buffer contents: b u f f e r D e m o Restored buffer position : 5 As we know that Java NIO supports multiple transaction from and to channels and buffer.So in order to examine one or more NIO Channel's, and determine which channels are ready for data transaction i.e reading or writing Java NIO provide Selector. With Selector we can make a thread to know that which channel is ready for data writing and reading and could deal that particular channel. We can get selector instance by calling its static method open().After open selector we have to register a non blocking mode channel with it which returns a instance of SelectionKey. SelectionKey is basically a collection of operations that can be performed with channel or we can say that we could know the state of channel with the help of selection key. The major operations or state of channel represented by selection key are βˆ’ SelectionKey.OP_CONNECT βˆ’ Channel which is ready to connect to server. SelectionKey.OP_CONNECT βˆ’ Channel which is ready to connect to server. SelectionKey.OP_ACCEPT βˆ’ Channel which is ready to accept incoming connections. SelectionKey.OP_ACCEPT βˆ’ Channel which is ready to accept incoming connections. SelectionKey.OP_READ βˆ’ Channel which is ready to data read. SelectionKey.OP_READ βˆ’ Channel which is ready to data read. SelectionKey.OP_WRITE βˆ’ Channel which is ready to data write. SelectionKey.OP_WRITE βˆ’ Channel which is ready to data write. Selection key obtained after registration has some important methods as mentioned below βˆ’ attach() βˆ’ This method is used to attach an object with the key.The main purpose of attaching an object to a channel is to recognizing the same channel. attach() βˆ’ This method is used to attach an object with the key.The main purpose of attaching an object to a channel is to recognizing the same channel. attachment() βˆ’ This method is used to retain the attached object from the channel. attachment() βˆ’ This method is used to retain the attached object from the channel. channel() βˆ’ This method is used to get the channel for which the particular key is created. channel() βˆ’ This method is used to get the channel for which the particular key is created. selector() βˆ’ This method is used to get the selector for which the particular key is created. selector() βˆ’ This method is used to get the selector for which the particular key is created. isValid() βˆ’ This method returns weather the key is valid or not. isValid() βˆ’ This method returns weather the key is valid or not. isReadable() βˆ’ This method states that weather key's channel is ready for read or not. isReadable() βˆ’ This method states that weather key's channel is ready for read or not. isWritable() βˆ’ This method states that weather key's channel is ready for write or not. isWritable() βˆ’ This method states that weather key's channel is ready for write or not. isAcceptable() βˆ’ This method states that weather key's channel is ready for accepting incoming connection or not. isAcceptable() βˆ’ This method states that weather key's channel is ready for accepting incoming connection or not. isConnectable() βˆ’ This method tests whether this key's channel has either finished, or failed to finish, its socket-connection operation. isConnectable() βˆ’ This method tests whether this key's channel has either finished, or failed to finish, its socket-connection operation. isAcceptable() βˆ’ This method tests whether this key's channel is ready to accept a new socket connection. isAcceptable() βˆ’ This method tests whether this key's channel is ready to accept a new socket connection. interestOps() βˆ’ This method retrieves this key's interest set. interestOps() βˆ’ This method retrieves this key's interest set. readyOps() βˆ’ This method retrieves the ready set which is the set of operations the channel is ready for. readyOps() βˆ’ This method retrieves the ready set which is the set of operations the channel is ready for. We can select a channel from selector by calling its static method select().Select method of selector is overloaded as βˆ’ select() βˆ’ This method blocks the current thread until at least one channel is ready for the events it is registered for. select() βˆ’ This method blocks the current thread until at least one channel is ready for the events it is registered for. select(long timeout) βˆ’ This method does the same as select() except it blocks the thread for a maximum of timeout milliseconds (the parameter). select(long timeout) βˆ’ This method does the same as select() except it blocks the thread for a maximum of timeout milliseconds (the parameter). selectNow() βˆ’ This method doesn't block at all.It returns immediately with whatever channels are ready. selectNow() βˆ’ This method doesn't block at all.It returns immediately with whatever channels are ready. Also in order to leave a blocked thread which call out select method,wakeup() method can be called from selector instance after which the thread waiting inside select() will then return immediately. In last we can close the selector by calling close() method which also invalidates all SelectionKey instances registered with this Selector along with closing the selector. import java.io.FileInputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Set; public class SelectorDemo { public static void main(String[] args) throws IOException { String demo_text = "This is a demo String"; Selector selector = Selector.open(); ServerSocketChannel serverSocket = ServerSocketChannel.open(); serverSocket.bind(new InetSocketAddress("localhost", 5454)); serverSocket.configureBlocking(false); serverSocket.register(selector, SelectionKey.OP_ACCEPT); ByteBuffer buffer = ByteBuffer.allocate(256); while (true) { selector.select(); Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> iter = selectedKeys.iterator(); while (iter.hasNext()) { SelectionKey key = iter.next(); int interestOps = key.interestOps(); System.out.println(interestOps); if (key.isAcceptable()) { SocketChannel client = serverSocket.accept(); client.configureBlocking(false); client.register(selector, SelectionKey.OP_READ); } if (key.isReadable()) { SocketChannel client = (SocketChannel) key.channel(); client.read(buffer); if (new String(buffer.array()).trim().equals(demo_text)) { client.close(); System.out.println("Not accepting client messages anymore"); } buffer.flip(); client.write(buffer); buffer.clear(); } iter.remove(); } } } } In Java NIO pipe is a component which is used to write and read data between two threads.Pipe mainly consist of two channels which are responsible for data propagation. Among two constituent channels one is called as Sink channel which is mainly for writing data and other is Source channel whose main purpose is to read data from Sink channel. Data synchronization is kept in order during data writing and reading as it must be ensured that data must be read in a same order in which it is written to the Pipe. It must kept in notice that it is a unidirectional flow of data in Pipe i.e data is written in Sink channel only and could only be read from Source channel. In Java NIO pipe is defined as a abstract class with mainly three methods out of which two are abstract. open() βˆ’ This method is used get an instance of Pipe or we can say pipe is created by calling out this method. open() βˆ’ This method is used get an instance of Pipe or we can say pipe is created by calling out this method. sink() βˆ’ This method returns the Pipe's sink channel which is used to write data by calling its write method. sink() βˆ’ This method returns the Pipe's sink channel which is used to write data by calling its write method. source() βˆ’ This method returns the Pipe's source channel which is used to read data by calling its read method. source() βˆ’ This method returns the Pipe's source channel which is used to read data by calling its read method. The following example shows the implementation of Java NIO pipe. import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.Pipe; public class PipeDemo { public static void main(String[] args) throws IOException { //An instance of Pipe is created Pipe pipe = Pipe.open(); // gets the pipe's sink channel Pipe.SinkChannel skChannel = pipe.sink(); String testData = "Test Data to Check java NIO Channels Pipe."; ByteBuffer buffer = ByteBuffer.allocate(512); buffer.clear(); buffer.put(testData.getBytes()); buffer.flip(); //write data into sink channel. while(buffer.hasRemaining()) { skChannel.write(buffer); } //gets pipe's source channel Pipe.SourceChannel sourceChannel = pipe.source(); buffer = ByteBuffer.allocate(512); //write data into console while(sourceChannel.read(buffer) > 0){ //limit is set to current position and position is set to zero buffer.flip(); while(buffer.hasRemaining()){ char ch = (char) buffer.get(); System.out.print(ch); } //position is set to zero and limit is set to capacity to clear the buffer. buffer.clear(); } } } Test Data to Check java NIO Channels Pipe. Assuming we have a text file c:/test.txt, which has the following content. This file will be used as an input for our example program. As name suggests Path is the particular location of an entity such as file or a directory in a file system so that one can search and access it at that particular location. Technically in terms of Java, Path is an interface which is introduced in Java NIO file package during Java version 7,and is the representation of location in particular file system.As path interface is in Java NIO package so it get its qualified name as java.nio.file.Path. In general path of an entity could be of two types one is absolute path and other is relative path.As name of both paths suggests that absolute path is the location address from the root to the entity where it locates while relative path is the location address which is relative to some other path.Path uses delimiters in its definition as "\" for Windows and "/" for unix operating systems. In order to get the instance of Path we can use static method of java.nio.file.Paths class get().This method converts a path string, or a sequence of strings that when joined form a path string, to a Path instance.This method also throws runtime InvalidPathException if the arguments passed contains illegal characters. As mentioned above absolute path is retrieved by passing root element and the complete directory list required to locate the file.While relative path could be retrieved by combining the base path with the relative path.Retrieval of both paths would be illustrated in following example package com.java.nio; import java.io.IOException; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.file.FileSystem; import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.Paths; public class PathDemo { public static void main(String[] args) throws IOException { Path relative = Paths.get("file2.txt"); System.out.println("Relative path: " + relative); Path absolute = relative.toAbsolutePath(); System.out.println("Absolute path: " + absolute); } } So far we know that what is path interface why do we need that and how could we access it.Now we would know what are the important methods which Path interface provide us. getFileName() βˆ’ Returns the file system that created this object. getFileName() βˆ’ Returns the file system that created this object. getName() βˆ’ Returns a name element of this path as a Path object. getName() βˆ’ Returns a name element of this path as a Path object. getNameCount() βˆ’ Returns the number of name elements in the path. getNameCount() βˆ’ Returns the number of name elements in the path. subpath() βˆ’ Returns a relative Path that is a subsequence of the name elements of this path. subpath() βˆ’ Returns a relative Path that is a subsequence of the name elements of this path. getParent() βˆ’ Returns the parent path, or null if this path does not have a parent. getParent() βˆ’ Returns the parent path, or null if this path does not have a parent. getRoot() βˆ’ Returns the root component of this path as a Path object, or null if this path does not have a root component. getRoot() βˆ’ Returns the root component of this path as a Path object, or null if this path does not have a root component. toAbsolutePath() βˆ’ Returns a Path object representing the absolute path of this path. toAbsolutePath() βˆ’ Returns a Path object representing the absolute path of this path. toRealPath() βˆ’ Returns the real path of an existing file. toRealPath() βˆ’ Returns the real path of an existing file. toFile() βˆ’ Returns a File object representing this path. toFile() βˆ’ Returns a File object representing this path. normalize() βˆ’ Returns a path that is this path with redundant name elements eliminated. normalize() βˆ’ Returns a path that is this path with redundant name elements eliminated. compareTo(Path other) βˆ’ Compares two abstract paths lexicographically.This method returns zero if the argument is equal to this path, a value less than zero if this path is lexicographically less than the argument, or a value greater than zero if this path is lexicographically greater than the argument. compareTo(Path other) βˆ’ Compares two abstract paths lexicographically.This method returns zero if the argument is equal to this path, a value less than zero if this path is lexicographically less than the argument, or a value greater than zero if this path is lexicographically greater than the argument. endsWith(Path other) βˆ’ Tests if this path ends with the given path.If the given path has N elements, and no root component, and this path has N or more elements, then this path ends with the given path if the last N elements of each path, starting at the element farthest from the root, are equal. endsWith(Path other) βˆ’ Tests if this path ends with the given path.If the given path has N elements, and no root component, and this path has N or more elements, then this path ends with the given path if the last N elements of each path, starting at the element farthest from the root, are equal. endsWith(String other) βˆ’ Tests if this path ends with a Path, constructed by converting the given path string, in exactly the manner specified by the endsWith(Path) method. endsWith(String other) βˆ’ Tests if this path ends with a Path, constructed by converting the given path string, in exactly the manner specified by the endsWith(Path) method. Following example illustartes the different methods of Path interface which are mentioned above βˆ’ package com.java.nio; import java.io.IOException; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.file.FileSystem; import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.Paths; public class PathDemo { public static void main(String[] args) throws IOException { Path path = Paths.get("D:/workspace/ContentW/Saurav_CV.docx"); FileSystem fs = path.getFileSystem(); System.out.println(fs.toString()); System.out.println(path.isAbsolute()); System.out.println(path.getFileName()); System.out.println(path.toAbsolutePath().toString()); System.out.println(path.getRoot()); System.out.println(path.getParent()); System.out.println(path.getNameCount()); System.out.println(path.getName(0)); System.out.println(path.subpath(0, 2)); System.out.println(path.toString()); System.out.println(path.getNameCount()); Path realPath = path.toRealPath(LinkOption.NOFOLLOW_LINKS); System.out.println(realPath.toString()); String originalPath = "d:\\data\\projects\\a-project\\..\\another-project"; Path path1 = Paths.get(originalPath); Path path2 = path1.normalize(); System.out.println("path2 = " + path2); } } Java NIO package provide one more utility API named as Files which is basically used for manipulating files and directories using its static methods which mostly works on Path object. As mentioned in Path tutorial that Path interface is introduced in Java NIO package during Java 7 version in file package.So this tutorial is for same File package. This class consists exclusively of static methods that operate on files, directories, or other types of files.In most cases, the methods defined here will delegate to the associated file system provider to perform the file operations. There are many methods defined in the Files class which could also be read from Java docs.In this tutorial we tried to cover some of the important methods among all of the methods of Java NIO Files class. Following are the important methods defined in Java NIO Files class. createFile(Path filePath, FileAttribute attrs) βˆ’ Files class provides this method to create file using specified Path. createFile(Path filePath, FileAttribute attrs) βˆ’ Files class provides this method to create file using specified Path. package com.java.nio; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CreateFile { public static void main(String[] args) { //initialize Path object Path path = Paths.get("D:file.txt"); //create file try { Path createdFilePath = Files.createFile(path); System.out.println("Created a file at : "+createdFilePath); } catch (IOException e) { e.printStackTrace(); } } } Created a file at : D:\data\file.txt copy(InputStream in, Path target, CopyOption... options) βˆ’ This method is used to copies all bytes from specified input stream to specified target file and returns number of bytes read or written as long value.LinkOption for this parameter with the following values βˆ’ copy(InputStream in, Path target, CopyOption... options) βˆ’ This method is used to copies all bytes from specified input stream to specified target file and returns number of bytes read or written as long value.LinkOption for this parameter with the following values βˆ’ COPY_ATTRIBUTES βˆ’ copy attributes to the new file, e.g. last-modified-time attribute. COPY_ATTRIBUTES βˆ’ copy attributes to the new file, e.g. last-modified-time attribute. REPLACE_EXISTING βˆ’ replace an existing file if it exists. REPLACE_EXISTING βˆ’ replace an existing file if it exists. NOFOLLOW_LINKS βˆ’ If a file is a symbolic link, then the link itself, not the target of the link, is copied. NOFOLLOW_LINKS βˆ’ If a file is a symbolic link, then the link itself, not the target of the link, is copied. package com.java.nio; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.List; public class WriteFile { public static void main(String[] args) { Path sourceFile = Paths.get("D:file.txt"); Path targetFile = Paths.get("D:fileCopy.txt"); try { Files.copy(sourceFile, targetFile, StandardCopyOption.REPLACE_EXISTING); } catch (IOException ex) { System.err.format("I/O Error when copying file"); } Path wiki_path = Paths.get("D:fileCopy.txt"); Charset charset = Charset.forName("ISO-8859-1"); try { List<String> lines = Files.readAllLines(wiki_path, charset); for (String line : lines) { System.out.println(line); } } catch (IOException e) { System.out.println(e); } } } To be or not to be? createDirectories(Path dir, FileAttribute<?>...attrs) βˆ’ This method is used to create directories using given path by creating all nonexistent parent directories. createDirectories(Path dir, FileAttribute<?>...attrs) βˆ’ This method is used to create directories using given path by creating all nonexistent parent directories. delete(Path path) βˆ’ This method is used to deletes the file from specified path.It throws NoSuchFileException if the file is not exists at specified path or if the file is directory and it may not empty and cannot be deleted. delete(Path path) βˆ’ This method is used to deletes the file from specified path.It throws NoSuchFileException if the file is not exists at specified path or if the file is directory and it may not empty and cannot be deleted. exists(Path path) βˆ’ This method is used to check if file exists at specified path and if the file exists it will return true or else it returns false. exists(Path path) βˆ’ This method is used to check if file exists at specified path and if the file exists it will return true or else it returns false. readAllBytes(Path path) βˆ’ This method is used to reads all the bytes from the file at given path and returns the byte array containing the bytes read from the file. readAllBytes(Path path) βˆ’ This method is used to reads all the bytes from the file at given path and returns the byte array containing the bytes read from the file. package com.java.nio; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; public class ReadFile { public static void main(String[] args) { Path wiki_path = Paths.get("D:file.txt"); Charset charset = Charset.forName("ISO-8859-1"); try { List<String> lines = Files.readAllLines(wiki_path, charset); for (String line : lines) { System.out.println(line); } } catch (IOException e) { System.out.println(e); } } } Welcome to file. size(Path path) βˆ’ This method is used to get the size of the file at specified path in bytes. size(Path path) βˆ’ This method is used to get the size of the file at specified path in bytes. write(Path path, byte[] bytes, OpenOption... options) βˆ’ This method is used to writes bytes to a file at specified path. write(Path path, byte[] bytes, OpenOption... options) βˆ’ This method is used to writes bytes to a file at specified path. package com.java.nio; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; public class WriteFile { public static void main(String[] args) { Path path = Paths.get("D:file.txt"); String question = "To be or not to be?"; Charset charset = Charset.forName("ISO-8859-1"); try { Files.write(path, question.getBytes()); List<String> lines = Files.readAllLines(path, charset); for (String line : lines) { System.out.println(line); } } catch (IOException e) { System.out.println(e); } } } To be or not to be? As we know that Java NIO supports concurrency and multi-threading which allows us to deal with different channels concurrently at same time.So the API which is responsible for this in Java NIO package is AsynchronousFileChannel which is defined under NIO channels package.Hence qualified name for AsynchronousFileChannel is java.nio.channels.AsynchronousFileChannel. AsynchronousFileChannel is similar to that of the NIO's FileChannel,except that this channel enables file operations to execute asynchronously unlike of synchronous I/O operation in which a thread enters into an action and waits until the request is completed.Thus asynchronous channels are safe for use by multiple concurrent threads. In asynchronous the request is passed by thread to the operating system's kernel to get it done while thread continues to process another job.Once the job of kernel is done it signals the thread then the thread acknowledged the signal and interrupts the current job and processes the I/O job as needed. For achieving concurrency this channel provides two approaches which includes one as returning a java.util.concurrent.Future object and other is Passing to the operation an object of type java.nio.channels.CompletionHandler. We will understand both the approaches with help of examples one by one. Future Object βˆ’ In this an instance of Future Interface is returned from channel.In Future interface there is get() method which returns the status of operation that is handled asynchronously on the basis of which further execution of other task could get decided.We can also check whether task is completed or not by calling its isDone method. Future Object βˆ’ In this an instance of Future Interface is returned from channel.In Future interface there is get() method which returns the status of operation that is handled asynchronously on the basis of which further execution of other task could get decided.We can also check whether task is completed or not by calling its isDone method. The following example shows the how to use Future object and to task asynchronously. package com.java.nio; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousFileChannel; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; public class FutureObject { public static void main(String[] args) throws Exception { readFile(); } private static void readFile() throws IOException, InterruptedException, ExecutionException { String filePath = "D:fileCopy.txt"; printFileContents(filePath); Path path = Paths.get(filePath); AsynchronousFileChannel channel =AsynchronousFileChannel.open(path, StandardOpenOption.READ); ByteBuffer buffer = ByteBuffer.allocate(400); Future<Integer> result = channel.read(buffer, 0); // position = 0 while (! result.isDone()) { System.out.println("Task of reading file is in progress asynchronously."); } System.out.println("Reading done: " + result.isDone()); System.out.println("Bytes read from file: " + result.get()); buffer.flip(); System.out.print("Buffer contents: "); while (buffer.hasRemaining()) { System.out.print((char) buffer.get()); } System.out.println(" "); buffer.clear(); channel.close(); } private static void printFileContents(String path) throws IOException { FileReader fr = new FileReader(path); BufferedReader br = new BufferedReader(fr); String textRead = br.readLine(); System.out.println("File contents: "); while (textRead != null) { System.out.println(" " + textRead); textRead = br.readLine(); } fr.close(); br.close(); } } File contents: To be or not to be? Task of reading file is in progress asynchronously. Task of reading file is in progress asynchronously. Reading done: true Bytes read from file: 19 Buffer contents: To be or not to be? Completion Handler βˆ’ This approach is pretty simple as in this we uses CompletionHandler interface and overrides its two methods one is completed() method which is invoked when the I/O operation completes successfully and other is failed() method which is invoked if the I/O operations fails.In this a handler is created for consuming the result of an asynchronous I/O operation as once a task is completed then only the handler has functions that are executed. Completion Handler βˆ’ This approach is pretty simple as in this we uses CompletionHandler interface and overrides its two methods one is completed() method which is invoked when the I/O operation completes successfully and other is failed() method which is invoked if the I/O operations fails.In this a handler is created for consuming the result of an asynchronous I/O operation as once a task is completed then only the handler has functions that are executed. The following example shows the how to use CompletionHandler to task asynchronously. package com.java.nio; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousFileChannel; import java.nio.channels.CompletionHandler; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class CompletionHandlerDemo { public static void main (String [] args) throws Exception { writeFile(); } private static void writeFile() throws IOException { String input = "Content to be written to the file."; System.out.println("Input string: " + input); byte [] byteArray = input.getBytes(); ByteBuffer buffer = ByteBuffer.wrap(byteArray); Path path = Paths.get("D:fileCopy.txt"); AsynchronousFileChannel channel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE); CompletionHandler handler = new CompletionHandler() { @Override public void completed(Object result, Object attachment) { System.out.println(attachment + " completed and " + result + " bytes are written."); } @Override public void failed(Throwable exc, Object attachment) { System.out.println(attachment + " failed with exception:"); exc.printStackTrace(); } }; channel.write(buffer, 0, "Async Task", handler); channel.close(); printFileContents(path.toString()); } private static void printFileContents(String path) throws IOException { FileReader fr = new FileReader(path); BufferedReader br = new BufferedReader(fr); String textRead = br.readLine(); System.out.println("File contents: "); while (textRead != null) { System.out.println(" " + textRead); textRead = br.readLine(); } fr.close(); br.close(); } } Input string: Content to be written to the file. Async Task completed and 34 bytes are written. File contents: Content to be written to the file. In Java for every character there is a well defined unicode code units which is internally handled by JVM.So Java NIO package defines an abstract class named as Charset which is mainly used for encoding and decoding of charset and UNICODE. The supported Charset in java are given below. US-ASCII βˆ’ Seven bit ASCII characters. US-ASCII βˆ’ Seven bit ASCII characters. ISO-8859-1 βˆ’ ISO Latin alphabet. ISO-8859-1 βˆ’ ISO Latin alphabet. UTF-8 βˆ’ This is 8 bit UCS transformation format. UTF-8 βˆ’ This is 8 bit UCS transformation format. UTF-16BE βˆ’ This is 16 bit UCS transformation format with big endian byte order. UTF-16BE βˆ’ This is 16 bit UCS transformation format with big endian byte order. UTF-16LE βˆ’ This is 16 bit UCS transformation with little endian byte order. UTF-16LE βˆ’ This is 16 bit UCS transformation with little endian byte order. UTF-16 βˆ’ 16 bit UCS transformation format. UTF-16 βˆ’ 16 bit UCS transformation format. forName() βˆ’ This method creates a charset object for the given charset name.The name can be canonical or an alias. forName() βˆ’ This method creates a charset object for the given charset name.The name can be canonical or an alias. displayName() βˆ’ This method returns the canonical name of given charset. displayName() βˆ’ This method returns the canonical name of given charset. canEncode() βˆ’ This method checks whether the given charset supports encoding or not. canEncode() βˆ’ This method checks whether the given charset supports encoding or not. decode() βˆ’ This method decodes the string of a given charset into charbuffer of Unicode charset. decode() βˆ’ This method decodes the string of a given charset into charbuffer of Unicode charset. encode() βˆ’ This method encodes charbuffer of unicode charset into the byte buffer of given charset. encode() βˆ’ This method encodes charbuffer of unicode charset into the byte buffer of given charset. Following example illustrate important methods of Charset class. package com.java.nio; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; public class CharsetExample { public static void main(String[] args) { Charset charset = Charset.forName("US-ASCII"); System.out.println(charset.displayName()); System.out.println(charset.canEncode()); String str = "Demo text for conversion."; //convert byte buffer in given charset to char buffer in unicode ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes()); CharBuffer charBuffer = charset.decode(byteBuffer); //convert char buffer in unicode to byte buffer in given charset ByteBuffer newByteBuffer = charset.encode(charBuffer); while(newbb.hasRemaining()){ char ch = (char) newByteBuffer.get(); System.out.print(ch); } newByteBuffer.clear(); } } US-ASCII Demo text for conversion. As we know that Java NIO supports concurrency and multi threading which enables it to deal with the multiple threads operating on multiple files at same time.But in some cases we require that our file would not get share by any of thread and get non accessible. For such requirement NIO again provides an API known as FileLock which is used to provide lock over whole file or on a part of file,so that file or its part doesn't get shared or accessible. in order to provide or apply such lock we have to use FileChannel or AsynchronousFileChannel,which provides two methods lock() and tryLock()for this purpose.The lock provided may be of two types βˆ’ Exclusive Lock βˆ’ An exclusive lock prevents other programs from acquiring an overlapping lock of either type. Exclusive Lock βˆ’ An exclusive lock prevents other programs from acquiring an overlapping lock of either type. Shared Lock βˆ’ A shared lock prevents other concurrently-running programs from acquiring an overlapping exclusive lock, but does allow them to acquire overlapping shared locks. Shared Lock βˆ’ A shared lock prevents other concurrently-running programs from acquiring an overlapping exclusive lock, but does allow them to acquire overlapping shared locks. Methods used for obtaining lock over file βˆ’ lock() βˆ’ This method of FileChannel or AsynchronousFileChannel acquires an exclusive lock over a file associated with the given channel.Return type of this method is FileLock which is further used for monitoring the obtained lock. lock() βˆ’ This method of FileChannel or AsynchronousFileChannel acquires an exclusive lock over a file associated with the given channel.Return type of this method is FileLock which is further used for monitoring the obtained lock. lock(long position, long size, boolean shared) βˆ’ This method again is the overloaded method of lock method and is used to lock a particular part of a file. lock(long position, long size, boolean shared) βˆ’ This method again is the overloaded method of lock method and is used to lock a particular part of a file. tryLock() βˆ’ This method return a FileLock or a null if the lock could not be acquired and it attempts to acquire an explicitly exclusive lock on this channel's file. tryLock() βˆ’ This method return a FileLock or a null if the lock could not be acquired and it attempts to acquire an explicitly exclusive lock on this channel's file. tryLock(long position, long size, boolean shared) βˆ’ This method attempts to acquires a lock on the given region of this channel's file which may be an exclusive or of shared type. tryLock(long position, long size, boolean shared) βˆ’ This method attempts to acquires a lock on the given region of this channel's file which may be an exclusive or of shared type. acquiredBy() βˆ’ This method returns the channel on whose file lock was acquired. acquiredBy() βˆ’ This method returns the channel on whose file lock was acquired. position() βˆ’ This method returns the position within the file of the first byte of the locked region.A locked region need not be contained within, or even overlap, the actual underlying file, so the value returned by this method may exceed the file's current size. position() βˆ’ This method returns the position within the file of the first byte of the locked region.A locked region need not be contained within, or even overlap, the actual underlying file, so the value returned by this method may exceed the file's current size. size() βˆ’ This method returns the size of the locked region in bytes.A locked region need not be contained within, or even overlap, the actual underlying file, so the value returned by this method may exceed the file's current size. size() βˆ’ This method returns the size of the locked region in bytes.A locked region need not be contained within, or even overlap, the actual underlying file, so the value returned by this method may exceed the file's current size. isShared() βˆ’ This method is used to determine that whether lock is shared or not. isShared() βˆ’ This method is used to determine that whether lock is shared or not. overlaps(long position,long size) βˆ’ This method tells whether or not this lock overlaps the given lock range. overlaps(long position,long size) βˆ’ This method tells whether or not this lock overlaps the given lock range. isValid() βˆ’ This method tells whether or not the obtained lock is valid.A lock object remains valid until it is released or the associated file channel is closed, whichever comes first. isValid() βˆ’ This method tells whether or not the obtained lock is valid.A lock object remains valid until it is released or the associated file channel is closed, whichever comes first. release() βˆ’ Releases the obtained lock.If the lock object is valid then invoking this method releases the lock and renders the object invalid. If this lock object is invalid then invoking this method has no effect. release() βˆ’ Releases the obtained lock.If the lock object is valid then invoking this method releases the lock and renders the object invalid. If this lock object is invalid then invoking this method has no effect. close() βˆ’ This method invokes the release() method. It was added to the class so that it could be used in conjunction with the automatic resource management block construct. close() βˆ’ This method invokes the release() method. It was added to the class so that it could be used in conjunction with the automatic resource management block construct. Following example create lock over a file and write content to it package com.java.nio; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class FileLockExample { public static void main(String[] args) throws IOException { String input = "Demo text to be written in locked mode."; System.out.println("Input string to the test file is: " + input); ByteBuffer buf = ByteBuffer.wrap(input.getBytes()); String fp = "D:file.txt"; Path pt = Paths.get(fp); FileChannel channel = FileChannel.open(pt, StandardOpenOption.WRITE,StandardOpenOption.APPEND); channel.position(channel.size() - 1); // position of a cursor at the end of file FileLock lock = channel.lock(); System.out.println("The Lock is shared: " + lock.isShared()); channel.write(buf); channel.close(); // Releases the Lock System.out.println("Content Writing is complete. Therefore close the channel and release the lock."); PrintFileCreated.print(fp); } } package com.java.nio; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class PrintFileCreated { public static void print(String path) throws IOException { FileReader filereader = new FileReader(path); BufferedReader bufferedreader = new BufferedReader(filereader); String tr = bufferedreader.readLine(); System.out.println("The Content of testout.txt file is: "); while (tr != null) { System.out.println(" " + tr); tr = bufferedreader.readLine(); } filereader.close(); bufferedreader.close(); } } Input string to the test file is: Demo text to be written in locked mode. The Lock is shared: false Content Writing is complete. Therefore close the channel and release the lock. The Content of testout.txt file is: To be or not to be?Demo text to be written in locked mode.
[ { "code": null, "e": 2339, "s": 2118, "text": "Java.nio package was introduced in java 1.4. In contrast of java I/O in java NIO the buffer and channel oriented data flow for I/O operations is introduced which in result provide faster execution and better performance." }, { "code": null, "e": 2622, "s": 2339, "text": "Also NIO API offer selectors which introduces the functionality of listen to multiple channels for IO events in asynchronous or non blocking way.In NIO the most time-consuming I/O activities including filling and draining of buffers to the operating system which increases in speed." }, { "code": null, "e": 2679, "s": 2622, "text": "The central abstractions of the NIO APIs are following βˆ’" }, { "code": null, "e": 2823, "s": 2679, "text": "Buffers,which are containers for data,charsets and their associated decoders and encoders,which translate between bytes and Unicode characters." }, { "code": null, "e": 2967, "s": 2823, "text": "Buffers,which are containers for data,charsets and their associated decoders and encoders,which translate between bytes and Unicode characters." }, { "code": null, "e": 3070, "s": 2967, "text": "Channels of various types,which represent connections to entities capable of performing I/O operations" }, { "code": null, "e": 3173, "s": 3070, "text": "Channels of various types,which represent connections to entities capable of performing I/O operations" }, { "code": null, "e": 3292, "s": 3173, "text": "Selectors and selection keys, which together with selectable channels define a multiplexed, non-blocking I/O facility." }, { "code": null, "e": 3411, "s": 3292, "text": "Selectors and selection keys, which together with selectable channels define a multiplexed, non-blocking I/O facility." }, { "code": null, "e": 3548, "s": 3411, "text": "This section guides you on how to download and set up Java on your machine. Please follow the following steps to set up the environment." }, { "code": null, "e": 3663, "s": 3548, "text": "Java SE is freely available from the link Download Java. So you download a version based on your operating system." }, { "code": null, "e": 3886, "s": 3663, "text": "Follow the instructions to download java and run the .exe to install Java on your machine. Once you installed Java on your machine, you would need to set environment variables to point to correct installation directories βˆ’" }, { "code": null, "e": 3960, "s": 3886, "text": "Assuming you have installed Java in c:\\Program Files\\java\\jdk directory βˆ’" }, { "code": null, "e": 4014, "s": 3960, "text": "Right-click on 'My Computer' and select 'Properties'." }, { "code": null, "e": 4068, "s": 4014, "text": "Right-click on 'My Computer' and select 'Properties'." }, { "code": null, "e": 4138, "s": 4068, "text": "Click on the 'Environment variables' button under the 'Advanced' tab." }, { "code": null, "e": 4208, "s": 4138, "text": "Click on the 'Environment variables' button under the 'Advanced' tab." }, { "code": null, "e": 4443, "s": 4208, "text": "Now alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\\WINDOWS\\SYSTEM32', then change your path to read 'C:\\WINDOWS\\SYSTEM32;c:\\Program Files\\java\\jdk\\bin'." }, { "code": null, "e": 4678, "s": 4443, "text": "Now alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\\WINDOWS\\SYSTEM32', then change your path to read 'C:\\WINDOWS\\SYSTEM32;c:\\Program Files\\java\\jdk\\bin'." }, { "code": null, "e": 4752, "s": 4678, "text": "Assuming you have installed Java in c:\\Program Files\\java\\jdk directory βˆ’" }, { "code": null, "e": 4873, "s": 4752, "text": "Edit the 'C:\\autoexec.bat' file and add the following line at the end: 'SET PATH = %PATH%;C:\\Program Files\\java\\jdk\\bin'" }, { "code": null, "e": 4994, "s": 4873, "text": "Edit the 'C:\\autoexec.bat' file and add the following line at the end: 'SET PATH = %PATH%;C:\\Program Files\\java\\jdk\\bin'" }, { "code": null, "e": 5157, "s": 4994, "text": "Environment variable PATH should be set to point to where the java binaries have been installed. Refer to your shell documentation if you have trouble doing this." }, { "code": null, "e": 5299, "s": 5157, "text": "Example, if you use bash as your shell, then you would add the following line to the end of your '.bashrc: export PATH = /path/to/java:$PATH'" }, { "code": null, "e": 5472, "s": 5299, "text": "To write your java programs you will need a text editor. There are even more sophisticated IDE available in the market. But for now, you can consider one of the following βˆ’" }, { "code": null, "e": 5591, "s": 5472, "text": "Notepad βˆ’ On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad." }, { "code": null, "e": 5710, "s": 5591, "text": "Notepad βˆ’ On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad." }, { "code": null, "e": 5829, "s": 5710, "text": "Netbeans βˆ’ is a Java IDE that is open source and free which can be downloaded from http://www.netbeans.org/index.html." }, { "code": null, "e": 5948, "s": 5829, "text": "Netbeans βˆ’ is a Java IDE that is open source and free which can be downloaded from http://www.netbeans.org/index.html." }, { "code": null, "e": 6078, "s": 5948, "text": "Eclipse βˆ’ is also a java IDE developed by the eclipse open source community and can be downloaded from https://www.eclipse.org/." }, { "code": null, "e": 6208, "s": 6078, "text": "Eclipse βˆ’ is also a java IDE developed by the eclipse open source community and can be downloaded from https://www.eclipse.org/." }, { "code": null, "e": 6446, "s": 6208, "text": "As we know that java NIO is introduced for advancement of conventional java IO API.The main enhancements which make NIO more efficient than IO are channel data flow model used in NIO and use of operating system for conventional IO tasks." }, { "code": null, "e": 6522, "s": 6446, "text": "The difference between Java NIO and Java IO can be explained as following βˆ’" }, { "code": null, "e": 6782, "s": 6522, "text": "As mentioned in previous post in NIO buffer and channel oriented data flow for I/O operations which provide faster execution and better performance as compare to IO.Also NIO uses operating system for conventional I/O tasks which again makes it more efficient." }, { "code": null, "e": 7042, "s": 6782, "text": "As mentioned in previous post in NIO buffer and channel oriented data flow for I/O operations which provide faster execution and better performance as compare to IO.Also NIO uses operating system for conventional I/O tasks which again makes it more efficient." }, { "code": null, "e": 7284, "s": 7042, "text": "Other aspect of difference between NIO and IO is this IO uses stream line data flow i.e one more byte at a time and relies on converting data objects into bytes and vice-e-versa while NIO deals with the data blocks which are chunks of bytes." }, { "code": null, "e": 7526, "s": 7284, "text": "Other aspect of difference between NIO and IO is this IO uses stream line data flow i.e one more byte at a time and relies on converting data objects into bytes and vice-e-versa while NIO deals with the data blocks which are chunks of bytes." }, { "code": null, "e": 7676, "s": 7526, "text": "In java IO stream objects are unidirectional while in NIO channels are bidirectional meaning a channel can be used for both reading and writing data." }, { "code": null, "e": 7826, "s": 7676, "text": "In java IO stream objects are unidirectional while in NIO channels are bidirectional meaning a channel can be used for both reading and writing data." }, { "code": null, "e": 8119, "s": 7826, "text": "The streamline data flow in IO does not allow move forth and back in the data.If case need to move forth and back in the data read from a stream need to cache it in a buffer first.While in case of NIO we uses buffer oriented which allows to access data back and forth without need of caching." }, { "code": null, "e": 8412, "s": 8119, "text": "The streamline data flow in IO does not allow move forth and back in the data.If case need to move forth and back in the data read from a stream need to cache it in a buffer first.While in case of NIO we uses buffer oriented which allows to access data back and forth without need of caching." }, { "code": null, "e": 8650, "s": 8412, "text": "NIO API also supports multi threading so that data can be read and written asynchronously in such as a way that while performing IO operations current thread is not blocked.This again make it more efficient than conventional java IO API." }, { "code": null, "e": 8888, "s": 8650, "text": "NIO API also supports multi threading so that data can be read and written asynchronously in such as a way that while performing IO operations current thread is not blocked.This again make it more efficient than conventional java IO API." }, { "code": null, "e": 9070, "s": 8888, "text": "Concept of multi threading is introduced with the introduction of Selectors in java NIO which allow to listen to multiple channels for IO events in asynchronous or non blocking way." }, { "code": null, "e": 9252, "s": 9070, "text": "Concept of multi threading is introduced with the introduction of Selectors in java NIO which allow to listen to multiple channels for IO events in asynchronous or non blocking way." }, { "code": null, "e": 9560, "s": 9252, "text": "Multi threading in NIO make it Non blocking which means that thread is requested to read or write only when data is available otherwise thread can be used in other task for mean time.But this is not possible in case of conventional java IO as no multi threading is supported in it which make it as Blocking." }, { "code": null, "e": 9868, "s": 9560, "text": "Multi threading in NIO make it Non blocking which means that thread is requested to read or write only when data is available otherwise thread can be used in other task for mean time.But this is not possible in case of conventional java IO as no multi threading is supported in it which make it as Blocking." }, { "code": null, "e": 10229, "s": 9868, "text": "NIO allows to manage multiple channels using only a single thread,but the cost is that parsing the data might be somewhat more complicated than when reading data from a blocking stream in case of java IO.So in case fewer connections with very high bandwidth are required with sending a lot of data at a time,than in this case java IO API might be the best fit." }, { "code": null, "e": 10590, "s": 10229, "text": "NIO allows to manage multiple channels using only a single thread,but the cost is that parsing the data might be somewhat more complicated than when reading data from a blocking stream in case of java IO.So in case fewer connections with very high bandwidth are required with sending a lot of data at a time,than in this case java IO API might be the best fit." }, { "code": null, "e": 10829, "s": 10590, "text": "As name suggests channel is used as mean of data flow from one end to other.Here in java NIO channel act same between buffer and an entity at other end in other words channel are use to read data to buffer and also write data from buffer." }, { "code": null, "e": 11031, "s": 10829, "text": "Unlike from streams which are used in conventional Java IO channels are two way i.e can read as well as write.Java NIO channel supports asynchronous flow of data both in blocking and non blocking mode." }, { "code": null, "e": 11096, "s": 11031, "text": "Java NIO channel is implemented primarily in following classes βˆ’" }, { "code": null, "e": 11298, "s": 11096, "text": "FileChannel βˆ’ In order to read data from file we uses file channel. Object of file channel can be created only by calling the getChannel() method on file object as we can't create file object directly." }, { "code": null, "e": 11500, "s": 11298, "text": "FileChannel βˆ’ In order to read data from file we uses file channel. Object of file channel can be created only by calling the getChannel() method on file object as we can't create file object directly." }, { "code": null, "e": 11681, "s": 11500, "text": "DatagramChannel βˆ’ The datagram channel can read and write the data over the network via UDP (User Datagram Protocol).Object of DataGramchannel can be created using factory methods." }, { "code": null, "e": 11862, "s": 11681, "text": "DatagramChannel βˆ’ The datagram channel can read and write the data over the network via UDP (User Datagram Protocol).Object of DataGramchannel can be created using factory methods." }, { "code": null, "e": 12052, "s": 11862, "text": "SocketChannel βˆ’ The SocketChannel channel can read and write the data over the network via TCP (Transmission Control Protocol). It also uses the factory methods for creating the new object." }, { "code": null, "e": 12242, "s": 12052, "text": "SocketChannel βˆ’ The SocketChannel channel can read and write the data over the network via TCP (Transmission Control Protocol). It also uses the factory methods for creating the new object." }, { "code": null, "e": 12414, "s": 12242, "text": "ServerSocketChannel βˆ’ The ServerSocketChannel read and write the data over TCP connections, same as a web server. For every incoming connection a SocketChannel is created." }, { "code": null, "e": 12586, "s": 12414, "text": "ServerSocketChannel βˆ’ The ServerSocketChannel read and write the data over TCP connections, same as a web server. For every incoming connection a SocketChannel is created." }, { "code": null, "e": 12688, "s": 12586, "text": "Following example reads from a text file from C:/Test/temp.txt and prints the content to the console." }, { "code": null, "e": 12702, "s": 12688, "text": "Hello World!\n" }, { "code": null, "e": 13384, "s": 12702, "text": "import java.io.IOException;\nimport java.io.RandomAccessFile;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.FileChannel;\n\npublic class ChannelDemo {\n public static void main(String args[]) throws IOException {\n RandomAccessFile file = new RandomAccessFile(\"C:/Test/temp.txt\", \"r\");\n FileChannel fileChannel = file.getChannel();\n ByteBuffer byteBuffer = ByteBuffer.allocate(512);\n while (fileChannel.read(byteBuffer) > 0) {\n // flip the buffer to prepare for get operation\n byteBuffer.flip();\n while (byteBuffer.hasRemaining()) {\n System.out.print((char) byteBuffer.get());\n }\n }\n file.close();\n }\n}" }, { "code": null, "e": 13398, "s": 13384, "text": "Hello World!\n" }, { "code": null, "e": 13672, "s": 13398, "text": "As already mentioned FileChannel implementation of Java NIO channel is introduced to access meta data properties of the file including creation, modification, size etc.Along with this File Channels are multi threaded which again makes Java NIO more efficient than Java IO." }, { "code": null, "e": 13950, "s": 13672, "text": "In general we can say that FileChannel is a channel that is connected to a file by which you can read data from a file, and write data to a file.Other important characteristic of FileChannel is this that it cannot be set into non-blocking mode and always runs in blocking mode." }, { "code": null, "e": 14040, "s": 13950, "text": "We can't get file channel object directly, Object of file channel is obtained either by βˆ’" }, { "code": null, "e": 14131, "s": 14040, "text": "getChannel() βˆ’ method on any either FileInputStream, FileOutputStream or RandomAccessFile." }, { "code": null, "e": 14222, "s": 14131, "text": "getChannel() βˆ’ method on any either FileInputStream, FileOutputStream or RandomAccessFile." }, { "code": null, "e": 14289, "s": 14222, "text": "open() βˆ’ method of File channel which by default open the channel." }, { "code": null, "e": 14356, "s": 14289, "text": "open() βˆ’ method of File channel which by default open the channel." }, { "code": null, "e": 14629, "s": 14356, "text": "The object type of File channel depends on type of class called from object creation i.e if object is created by calling getchannel method of FileInputStream then File channel is opened for reading and will throw NonWritableChannelException in case attempt to write to it." }, { "code": null, "e": 14715, "s": 14629, "text": "The following example shows the how to read and write data from Java NIO FileChannel." }, { "code": null, "e": 14817, "s": 14715, "text": "Following example reads from a text file from C:/Test/temp.txt and prints the content to the console." }, { "code": null, "e": 14831, "s": 14817, "text": "Hello World!\n" }, { "code": null, "e": 16387, "s": 14831, "text": "import java.io.IOException;\nimport java.io.RandomAccessFile;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.FileChannel;\nimport java.nio.charset.Charset;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.nio.file.StandardOpenOption;\nimport java.util.HashSet;\nimport java.util.Set;\n\npublic class FileChannelDemo {\n public static void main(String args[]) throws IOException {\n //append the content to existing file \n writeFileChannel(ByteBuffer.wrap(\"Welcome to TutorialsPoint\".getBytes()));\n //read the file\n readFileChannel();\n }\n public static void readFileChannel() throws IOException {\n RandomAccessFile randomAccessFile = new RandomAccessFile(\"C:/Test/temp.txt\",\n \"rw\");\n FileChannel fileChannel = randomAccessFile.getChannel();\n ByteBuffer byteBuffer = ByteBuffer.allocate(512);\n Charset charset = Charset.forName(\"US-ASCII\");\n while (fileChannel.read(byteBuffer) > 0) {\n byteBuffer.rewind();\n System.out.print(charset.decode(byteBuffer));\n byteBuffer.flip();\n }\n fileChannel.close();\n randomAccessFile.close();\n }\n public static void writeFileChannel(ByteBuffer byteBuffer)throws IOException {\n Set<StandardOpenOption> options = new HashSet<>();\n options.add(StandardOpenOption.CREATE);\n options.add(StandardOpenOption.APPEND);\n Path path = Paths.get(\"C:/Test/temp.txt\");\n FileChannel fileChannel = FileChannel.open(path, options);\n fileChannel.write(byteBuffer);\n fileChannel.close();\n }\n}" }, { "code": null, "e": 16427, "s": 16387, "text": "Hello World! Welcome to TutorialsPoint\n" }, { "code": null, "e": 16867, "s": 16427, "text": "Java NIO Datagram is used as channel which can send and receive UDP packets over a connection less protocol.By default datagram channel is blocking while it can be use in non blocking mode.In order to make it non-blocking we can use the configureBlocking(false) method.DataGram channel can be open by calling its one of the static method named as open() which can also take IP address as parameter so that it can be used for multi casting." }, { "code": null, "e": 17244, "s": 16867, "text": "Datagram channel alike of FileChannel do not connected by default in order to make it connected we have to explicitly call its connect() method.However datagram channel need not be connected in order for the send and receive methods to be used while it must be connected in order to use the read and write methods, since those methods do not accept or return socket addresses." }, { "code": null, "e": 17518, "s": 17244, "text": "We can check the connection status of datagram channel by calling its isConnected() method.Once connected, a datagram channel remains connected until it is disconnected or closed.Datagram channels are thread safe and supports multi-threading and concurrency simultaneously." }, { "code": null, "e": 17676, "s": 17518, "text": "bind(SocketAddress local) βˆ’ This method is used to bind the datagram channel's socket to the local address which is provided as the parameter to this method." }, { "code": null, "e": 17834, "s": 17676, "text": "bind(SocketAddress local) βˆ’ This method is used to bind the datagram channel's socket to the local address which is provided as the parameter to this method." }, { "code": null, "e": 17931, "s": 17834, "text": "connect(SocketAddress remote) βˆ’ This method is used to connect the socket to the remote address." }, { "code": null, "e": 18028, "s": 17931, "text": "connect(SocketAddress remote) βˆ’ This method is used to connect the socket to the remote address." }, { "code": null, "e": 18111, "s": 18028, "text": "disconnect() βˆ’ This method is used to disconnect the socket to the remote address." }, { "code": null, "e": 18194, "s": 18111, "text": "disconnect() βˆ’ This method is used to disconnect the socket to the remote address." }, { "code": null, "e": 18309, "s": 18194, "text": "getRemoteAddress() βˆ’ This method return the address of remote location to which the channel's socket is connected." }, { "code": null, "e": 18424, "s": 18309, "text": "getRemoteAddress() βˆ’ This method return the address of remote location to which the channel's socket is connected." }, { "code": null, "e": 18562, "s": 18424, "text": "isConnected() βˆ’ As already mentioned this method returns the status of connection of datagram channel i.e whether it is connected or not." }, { "code": null, "e": 18700, "s": 18562, "text": "isConnected() βˆ’ As already mentioned this method returns the status of connection of datagram channel i.e whether it is connected or not." }, { "code": null, "e": 18903, "s": 18700, "text": "open() and open(ProtocolFamily family) βˆ’ Open method is used open a datagram channel for single address while parametrized open method open channel for multiple addresses represented as protocol family." }, { "code": null, "e": 19106, "s": 18903, "text": "open() and open(ProtocolFamily family) βˆ’ Open method is used open a datagram channel for single address while parametrized open method open channel for multiple addresses represented as protocol family." }, { "code": null, "e": 19210, "s": 19106, "text": "read(ByteBuffer dst) βˆ’ This method is used to read data from the given buffer through datagram channel." }, { "code": null, "e": 19314, "s": 19210, "text": "read(ByteBuffer dst) βˆ’ This method is used to read data from the given buffer through datagram channel." }, { "code": null, "e": 19398, "s": 19314, "text": "receive(ByteBuffer dst) βˆ’ This method is used to receive datagram via this channel." }, { "code": null, "e": 19482, "s": 19398, "text": "receive(ByteBuffer dst) βˆ’ This method is used to receive datagram via this channel." }, { "code": null, "e": 19582, "s": 19482, "text": "send(ByteBuffer src, SocketAddress target) βˆ’ This method is used to send datagram via this channel." }, { "code": null, "e": 19682, "s": 19582, "text": "send(ByteBuffer src, SocketAddress target) βˆ’ This method is used to send datagram via this channel." }, { "code": null, "e": 19762, "s": 19682, "text": "The following example shows the how to send data from Java NIO DataGramChannel." }, { "code": null, "e": 20714, "s": 19762, "text": "import java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.SocketAddress;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.DatagramChannel;\n\npublic class DatagramChannelServer {\n public static void main(String[] args) throws IOException {\n DatagramChannel server = DatagramChannel.open();\n InetSocketAddress iAdd = new InetSocketAddress(\"localhost\", 8989);\n server.bind(iAdd);\n System.out.println(\"Server Started: \" + iAdd);\n ByteBuffer buffer = ByteBuffer.allocate(1024);\n //receive buffer from client.\n SocketAddress remoteAdd = server.receive(buffer);\n //change mode of buffer\n buffer.flip();\n int limits = buffer.limit();\n byte bytes[] = new byte[limits];\n buffer.get(bytes, 0, limits);\n String msg = new String(bytes);\n System.out.println(\"Client at \" + remoteAdd + \" sent: \" + msg);\n server.send(buffer,remoteAdd);\n server.close();\n }\n}" }, { "code": null, "e": 20756, "s": 20714, "text": "Server Started: localhost/127.0.0.1:8989\n" }, { "code": null, "e": 21458, "s": 20756, "text": "import java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.SocketAddress;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.DatagramChannel;\n\npublic class DatagramChannelClient {\n public static void main(String[] args) throws IOException {\n DatagramChannel client = null;\n client = DatagramChannel.open();\n\n client.bind(null);\n\n String msg = \"Hello World!\";\n ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());\n InetSocketAddress serverAddress = new InetSocketAddress(\"localhost\",\n 8989);\n\n client.send(buffer, serverAddress);\n buffer.clear();\n client.receive(buffer);\n buffer.flip();\n \n client.close();\n }\n}" }, { "code": null, "e": 21520, "s": 21458, "text": "Running the client will print the following output on server." }, { "code": null, "e": 21609, "s": 21520, "text": "Server Started: localhost/127.0.0.1:8989\nClient at /127.0.0.1:64857 sent: Hello World!\n" }, { "code": null, "e": 22430, "s": 21609, "text": "Java NIO socket channel is a selectable type channel which means it can be multiplexed using selector, used for stream oriented data flow connecting sockets.Socket channel can be created by invoking its static open() method,providing any pre-existing socket is not already present.Socket channel is created by invoking open method but not yet connected.In order to connect socket channel connect() method is to be called.One point to be mentioned here is if channel is not connected and any I/O operation is tried to be attempted then NotYetConnectedException is thrown by this channel.So one must be ensure that channel is connected before performing any IO operation.Once channel is get connected,it remains connected until it is closed.The state of socket channel may be determined by invoking its isConnected method." }, { "code": null, "e": 22817, "s": 22430, "text": "The connection of socket channel could be finished by invoking its finishConnect() method.Whether or not a connection operation is in progress may be determined by invoking the isConnectionPending method.By default socket channel supports non-blocking connection.Also it support asynchronous shutdown, which is similar to the asynchronous close operation specified in the Channel class." }, { "code": null, "e": 23267, "s": 22817, "text": "Socket channels are safe for use by multiple concurrent threads. They support concurrent reading and writing, though at most one thread may be reading and at most one thread may be writing at any given time. The connect and finishConnect methods are mutually synchronized against each other, and an attempt to initiate a read or write operation while an invocation of one of these methods is in progress will block until that invocation is complete." }, { "code": null, "e": 23414, "s": 23267, "text": "bind(SocketAddress local) βˆ’ This method is used to bind the socket channel to the local address which is provided as the parameter to this method." }, { "code": null, "e": 23561, "s": 23414, "text": "bind(SocketAddress local) βˆ’ This method is used to bind the socket channel to the local address which is provided as the parameter to this method." }, { "code": null, "e": 23658, "s": 23561, "text": "connect(SocketAddress remote) βˆ’ This method is used to connect the socket to the remote address." }, { "code": null, "e": 23755, "s": 23658, "text": "connect(SocketAddress remote) βˆ’ This method is used to connect the socket to the remote address." }, { "code": null, "e": 23849, "s": 23755, "text": "finishConnect() βˆ’ This method is used to finishes the process of connecting a socket channel." }, { "code": null, "e": 23943, "s": 23849, "text": "finishConnect() βˆ’ This method is used to finishes the process of connecting a socket channel." }, { "code": null, "e": 24058, "s": 23943, "text": "getRemoteAddress() βˆ’ This method return the address of remote location to which the channel's socket is connected." }, { "code": null, "e": 24173, "s": 24058, "text": "getRemoteAddress() βˆ’ This method return the address of remote location to which the channel's socket is connected." }, { "code": null, "e": 24309, "s": 24173, "text": "isConnected() βˆ’ As already mentioned this method returns the status of connection of socket channel i.e whether it is connected or not." }, { "code": null, "e": 24445, "s": 24309, "text": "isConnected() βˆ’ As already mentioned this method returns the status of connection of socket channel i.e whether it is connected or not." }, { "code": null, "e": 24833, "s": 24445, "text": "open() and open((SocketAddress remote) βˆ’ Open method is used open a socket channel for no specified address while parameterized open method open channel for specified remote address and also connects to it.This convenience method works as if by invoking the open() method, invoking the connect method upon the resulting socket channel, passing it remote, and then returning that channel." }, { "code": null, "e": 25221, "s": 24833, "text": "open() and open((SocketAddress remote) βˆ’ Open method is used open a socket channel for no specified address while parameterized open method open channel for specified remote address and also connects to it.This convenience method works as if by invoking the open() method, invoking the connect method upon the resulting socket channel, passing it remote, and then returning that channel." }, { "code": null, "e": 25323, "s": 25221, "text": "read(ByteBuffer dst) βˆ’ This method is used to read data from the given buffer through socket channel." }, { "code": null, "e": 25425, "s": 25323, "text": "read(ByteBuffer dst) βˆ’ This method is used to read data from the given buffer through socket channel." }, { "code": null, "e": 25537, "s": 25425, "text": "isConnectionPending() βˆ’ This method tells whether or not a connection operation is in progress on this channel." }, { "code": null, "e": 25649, "s": 25537, "text": "isConnectionPending() βˆ’ This method tells whether or not a connection operation is in progress on this channel." }, { "code": null, "e": 25727, "s": 25649, "text": "The following example shows the how to send data from Java NIO SocketChannel." }, { "code": null, "e": 25741, "s": 25727, "text": "Hello World!\n" }, { "code": null, "e": 27028, "s": 25741, "text": "import java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.FileChannel;\nimport java.nio.channels.ServerSocketChannel;\nimport java.nio.channels.SocketChannel;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.nio.file.StandardOpenOption;\nimport java.util.EnumSet;\n\npublic class SocketChannelClient {\n public static void main(String[] args) throws IOException {\n ServerSocketChannel serverSocket = null;\n SocketChannel client = null;\n serverSocket = ServerSocketChannel.open();\n serverSocket.socket().bind(new InetSocketAddress(9000));\n client = serverSocket.accept();\n System.out.println(\"Connection Set: \" + client.getRemoteAddress());\n Path path = Paths.get(\"C:/Test/temp1.txt\");\n FileChannel fileChannel = FileChannel.open(path, \n EnumSet.of(StandardOpenOption.CREATE, \n StandardOpenOption.TRUNCATE_EXISTING,\n StandardOpenOption.WRITE)\n ); \n ByteBuffer buffer = ByteBuffer.allocate(1024);\n while(client.read(buffer) > 0) {\n buffer.flip();\n fileChannel.write(buffer);\n buffer.clear();\n }\n fileChannel.close();\n System.out.println(\"File Received\");\n client.close();\n }\n}" }, { "code": null, "e": 27092, "s": 27028, "text": "Running the client will not print anything until server starts." }, { "code": null, "e": 27994, "s": 27094, "text": "import java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.SocketAddress;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.FileChannel;\nimport java.nio.channels.SocketChannel;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\n\npublic class SocketChannelServer {\n public static void main(String[] args) throws IOException {\n SocketChannel server = SocketChannel.open();\n SocketAddress socketAddr = new InetSocketAddress(\"localhost\", 9000);\n server.connect(socketAddr);\n\n Path path = Paths.get(\"C:/Test/temp.txt\");\n FileChannel fileChannel = FileChannel.open(path);\n ByteBuffer buffer = ByteBuffer.allocate(1024);\n while(fileChannel.read(buffer) > 0) {\n buffer.flip();\n server.write(buffer);\n buffer.clear();\n }\n fileChannel.close();\n System.out.println(\"File Sent\");\n server.close();\n }\n}" }, { "code": null, "e": 28039, "s": 27994, "text": "Running the server will print the following." }, { "code": null, "e": 28088, "s": 28039, "text": "Connection Set: /127.0.0.1:49558\nFile Received\n" }, { "code": null, "e": 28478, "s": 28088, "text": "Java NIO server socket channel is again a selectable type channel used for stream oriented data flow connecting sockets.Server Socket channel can be created by invoking its static open() method,providing any pre-existing socket is not already present.Server Socket channel is created by invoking open method but not yet bound.In order to bound socket channel bind() method is to be called." }, { "code": null, "e": 28717, "s": 28478, "text": "One point to be mentioned here is if channel is not bound and any I/O operation is tried to be attempted then NotYetBoundException is thrown by this channel.So one must be ensure that channel is bounded before performing any IO operation." }, { "code": null, "e": 29212, "s": 28717, "text": "Incoming connections for the server socket channel are listen by calling the ServerSocketChannel.accept() method. When the accept() method returns, it returns a SocketChannel with an incoming connection. Thus, the accept() method blocks until an incoming connection arrives.If the channel is in non-blocking mode then accept method will immediately return null if there are no pending connections. Otherwise it will block indefinitely until a new connection is available or an I/O error occurs." }, { "code": null, "e": 29501, "s": 29212, "text": "The new channel's socket is initially unbound; it must be bound to a specific address via one of its socket's bind methods before connections can be accepted.Also the new channel is created by invoking the openServerSocketChannel method of the system-wide default SelectorProvider object." }, { "code": null, "e": 29889, "s": 29501, "text": "Like socket channel server socket channel could read data using read() method.Firstly the buffer is allocated. The data read from a ServerSocketChannel is stored into the buffer.Secondly we call the ServerSocketChannel.read() method and it reads the data from a ServerSocketChannel into a buffer. The integer value of the read() method returns how many bytes were written into the buffer" }, { "code": null, "e": 30133, "s": 29889, "text": "Similarly data could be written to server socket channel using write() method using buffer as a parameter.Commonly uses write method in a while loop as need to repeat the write() method until the Buffer has no further bytes available to write." }, { "code": null, "e": 30280, "s": 30133, "text": "bind(SocketAddress local) βˆ’ This method is used to bind the socket channel to the local address which is provided as the parameter to this method." }, { "code": null, "e": 30427, "s": 30280, "text": "bind(SocketAddress local) βˆ’ This method is used to bind the socket channel to the local address which is provided as the parameter to this method." }, { "code": null, "e": 30513, "s": 30427, "text": "accept() βˆ’ This method is used to accepts a connection made to this channel's socket." }, { "code": null, "e": 30599, "s": 30513, "text": "accept() βˆ’ This method is used to accepts a connection made to this channel's socket." }, { "code": null, "e": 30696, "s": 30599, "text": "connect(SocketAddress remote) βˆ’ This method is used to connect the socket to the remote address." }, { "code": null, "e": 30793, "s": 30696, "text": "connect(SocketAddress remote) βˆ’ This method is used to connect the socket to the remote address." }, { "code": null, "e": 30887, "s": 30793, "text": "finishConnect() βˆ’ This method is used to finishes the process of connecting a socket channel." }, { "code": null, "e": 30981, "s": 30887, "text": "finishConnect() βˆ’ This method is used to finishes the process of connecting a socket channel." }, { "code": null, "e": 31096, "s": 30981, "text": "getRemoteAddress() βˆ’ This method return the address of remote location to which the channel's socket is connected." }, { "code": null, "e": 31211, "s": 31096, "text": "getRemoteAddress() βˆ’ This method return the address of remote location to which the channel's socket is connected." }, { "code": null, "e": 31348, "s": 31211, "text": "\tisConnected() βˆ’ As already mentioned this method returns the status of connection of socket channel i.e whether it is connected or not." }, { "code": null, "e": 31485, "s": 31348, "text": "\tisConnected() βˆ’ As already mentioned this method returns the status of connection of socket channel i.e whether it is connected or not." }, { "code": null, "e": 31750, "s": 31485, "text": "open() βˆ’ Open method is used open a socket channel for no specified address.This convenience method works as if by invoking the open() method, invoking the connect method upon the resulting server socket channel, passing it remote, and then returning that channel." }, { "code": null, "e": 32015, "s": 31750, "text": "open() βˆ’ Open method is used open a socket channel for no specified address.This convenience method works as if by invoking the open() method, invoking the connect method upon the resulting server socket channel, passing it remote, and then returning that channel." }, { "code": null, "e": 32117, "s": 32015, "text": "read(ByteBuffer dst) βˆ’ This method is used to read data from the given buffer through socket channel." }, { "code": null, "e": 32219, "s": 32117, "text": "read(ByteBuffer dst) βˆ’ This method is used to read data from the given buffer through socket channel." }, { "code": null, "e": 32309, "s": 32219, "text": "setOption(SocketOption<T> name, T value) βˆ’ This method sets the value of a socket option." }, { "code": null, "e": 32399, "s": 32309, "text": "setOption(SocketOption<T> name, T value) βˆ’ This method sets the value of a socket option." }, { "code": null, "e": 32478, "s": 32399, "text": "socket() βˆ’ This method retrieves a server socket associated with this channel." }, { "code": null, "e": 32557, "s": 32478, "text": "socket() βˆ’ This method retrieves a server socket associated with this channel." }, { "code": null, "e": 32772, "s": 32557, "text": "validOps() βˆ’ This method returns an operation set identifying this channel's supported operations.Server-socket channels only support the accepting of new connections, so this method returns SelectionKey.OP_ACCEPT." }, { "code": null, "e": 32987, "s": 32772, "text": "validOps() βˆ’ This method returns an operation set identifying this channel's supported operations.Server-socket channels only support the accepting of new connections, so this method returns SelectionKey.OP_ACCEPT." }, { "code": null, "e": 33071, "s": 32987, "text": "The following example shows the how to send data from Java NIO ServerSocketChannel." }, { "code": null, "e": 33085, "s": 33071, "text": "Hello World!\n" }, { "code": null, "e": 34372, "s": 33085, "text": "import java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.FileChannel;\nimport java.nio.channels.ServerSocketChannel;\nimport java.nio.channels.SocketChannel;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.nio.file.StandardOpenOption;\nimport java.util.EnumSet;\n\npublic class SocketChannelClient {\n public static void main(String[] args) throws IOException {\n ServerSocketChannel serverSocket = null;\n SocketChannel client = null;\n serverSocket = ServerSocketChannel.open();\n serverSocket.socket().bind(new InetSocketAddress(9000));\n client = serverSocket.accept();\n System.out.println(\"Connection Set: \" + client.getRemoteAddress());\n Path path = Paths.get(\"C:/Test/temp1.txt\");\n FileChannel fileChannel = FileChannel.open(path, \n EnumSet.of(StandardOpenOption.CREATE, \n StandardOpenOption.TRUNCATE_EXISTING,\n StandardOpenOption.WRITE)\n ); \n ByteBuffer buffer = ByteBuffer.allocate(1024);\n while(client.read(buffer) > 0) {\n buffer.flip();\n fileChannel.write(buffer);\n buffer.clear();\n }\n fileChannel.close();\n System.out.println(\"File Received\");\n client.close();\n }\n}" }, { "code": null, "e": 34436, "s": 34372, "text": "Running the client will not print anything until server starts." }, { "code": null, "e": 35337, "s": 34438, "text": "import java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.SocketAddress;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.FileChannel;\nimport java.nio.channels.SocketChannel;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\n\npublic class SocketChannelServer {\n public static void main(String[] args) throws IOException {\n SocketChannel server = SocketChannel.open();\n SocketAddress socketAddr = new InetSocketAddress(\"localhost\", 9000);\n server.connect(socketAddr);\n Path path = Paths.get(\"C:/Test/temp.txt\");\n FileChannel fileChannel = FileChannel.open(path);\n ByteBuffer buffer = ByteBuffer.allocate(1024);\n while(fileChannel.read(buffer) > 0) {\n buffer.flip();\n server.write(buffer);\n buffer.clear();\n }\n fileChannel.close();\n System.out.println(\"File Sent\");\n server.close();\n }\n}" }, { "code": null, "e": 35382, "s": 35337, "text": "Running the server will print the following." }, { "code": null, "e": 35431, "s": 35382, "text": "Connection Set: /127.0.0.1:49558\nFile Received\n" }, { "code": null, "e": 35903, "s": 35431, "text": "As we know that Java NIO is a more optimized API for data IO operations as compared to the conventional IO API of Java.One more additional support which Java NIO provides is to read/write data from/to multiple buffers to channel.This multiple read and write support is termed as Scatter and Gather in which data is scattered to multiple buffers from single channel in case of read data while data is gathered from multiple buffers to single channel in case of write data." }, { "code": null, "e": 36109, "s": 35903, "text": "In order to achieve this multiple read and write from channel there is ScatteringByteChannel and GatheringByteChannel API which Java NIO provides for read and write the data as illustrate in below example." }, { "code": null, "e": 36528, "s": 36109, "text": "Read from multiple channels βˆ’ In this we made to reads data from a single channel into multiple buffers.For this multiple buffers are allocated and are added to a buffer type array.Then this array is passed as parameter to the ScatteringByteChannel read() method which then writes data from the channel in the sequence the buffers occur in the array.Once a buffer is full, the channel moves on to fill the next buffer." }, { "code": null, "e": 36604, "s": 36528, "text": "The following example shows how scattering of data is performed in Java NIO" }, { "code": null, "e": 36618, "s": 36604, "text": "Hello World!\n" }, { "code": null, "e": 37673, "s": 36618, "text": "import java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.ScatteringByteChannel;\n\npublic class ScatterExample {\t\n private static String FILENAME = \"C:/Test/temp.txt\";\n public static void main(String[] args) {\n ByteBuffer bLen1 = ByteBuffer.allocate(1024);\n ByteBuffer bLen2 = ByteBuffer.allocate(1024);\n FileInputStream in;\n try {\n in = new FileInputStream(FILENAME);\n ScatteringByteChannel scatter = in.getChannel();\n scatter.read(new ByteBuffer[] {bLen1, bLen2});\n bLen1.position(0);\n bLen2.position(0);\n int len1 = bLen1.asIntBuffer().get();\n int len2 = bLen2.asIntBuffer().get();\n System.out.println(\"Scattering : Len1 = \" + len1);\n System.out.println(\"Scattering : Len2 = \" + len2);\n } \n catch (FileNotFoundException exObj) {\n exObj.printStackTrace();\n }\n catch (IOException ioObj) {\n ioObj.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 37727, "s": 37673, "text": "Scattering : Len1 = 1214606444\nScattering : Len2 = 0\n" }, { "code": null, "e": 38188, "s": 37727, "text": "In last it can be concluded that scatter/gather approach in Java NIO is introduced as an optimized and multitasked when used properly.It allows you to delegate to the operating system the grunt work of separating out the data you read into multiple buckets, or assembling disparate chunks of data into a whole.No doubt this saves time and uses operating system more efficiently by avoiding buffer copies, and reduces the amount of code need to write and debug." }, { "code": null, "e": 38660, "s": 38188, "text": "As we know that Java NIO is a more optimized API for data IO operations as compared to the conventional IO API of Java.One more additional support which Java NIO provides is to read/write data from/to multiple buffers to channel.This multiple read and write support is termed as Scatter and Gather in which data is scattered to multiple buffers from single channel in case of read data while data is gathered from multiple buffers to single channel in case of write data." }, { "code": null, "e": 38866, "s": 38660, "text": "In order to achieve this multiple read and write from channel there is ScatteringByteChannel and GatheringByteChannel API which Java NIO provides for read and write the data as illustrate in below example." }, { "code": null, "e": 39337, "s": 38866, "text": "write to multiple channels βˆ’ In this we made to write data from multiple buffers into a single channel.For this again multiple buffers are allocated and are added to a buffer type array.Then this array is passed as parameter to the GatheringByteChannel write() method which then writes data from the multiple buffers in the sequence the buffers occur in the array.One point to remember here is only the data between the position and the limit of the buffers are written." }, { "code": null, "e": 39409, "s": 39337, "text": "The following example shows how data gathering is performed in Java NIO" }, { "code": null, "e": 40877, "s": 39409, "text": "import java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.GatheringByteChannel;\n\npublic class GatherExample {\n private static String FILENAME = \"C:/Test/temp.txt\";\n public static void main(String[] args) {\n String stream1 = \"Gather data stream first\";\n String stream2 = \"Gather data stream second\";\n ByteBuffer bLen1 = ByteBuffer.allocate(1024);\n ByteBuffer bLen2 = ByteBuffer.allocate(1024);\n // Next two buffer hold the data we want to write\n ByteBuffer bstream1 = ByteBuffer.wrap(stream1.getBytes());\n ByteBuffer bstream2 = ByteBuffer.wrap(stream2.getBytes());\n int len1 = stream1.length();\n int len2 = stream2.length();\n // Writing length(data) to the Buffer\n bLen1.asIntBuffer().put(len1);\n bLen2.asIntBuffer().put(len2);\n System.out.println(\"Gathering : Len1 = \" + len1);\n System.out.println(\"Gathering : Len2 = \" + len2);\n // Write data to the file\n try { \n FileOutputStream out = new FileOutputStream(FILENAME);\n GatheringByteChannel gather = out.getChannel();\t\t\t\t\t\t\n gather.write(new ByteBuffer[] {bLen1, bLen2, bstream1, bstream2});\n out.close();\n gather.close();\n }\n catch (FileNotFoundException exObj) {\n exObj.printStackTrace();\n }\n catch(IOException ioObj) {\n ioObj.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 40922, "s": 40877, "text": "Gathering : Len1 = 24\nGathering : Len2 = 25\n" }, { "code": null, "e": 41383, "s": 40922, "text": "In last it can be concluded that scatter/gather approach in Java NIO is introduced as an optimized and multitasked when used properly.It allows you to delegate to the operating system the grunt work of separating out the data you read into multiple buckets, or assembling disparate chunks of data into a whole.No doubt this saves time and uses operating system more efficiently by avoiding buffer copies, and reduces the amount of code need to write and debug." }, { "code": null, "e": 41607, "s": 41383, "text": "Buffers in Java NIO can be treated as a simple object which act as a fixed sized container of data chunks that can be used to write data to channel or read data from channel so that buffers act as endpoints to the channels." }, { "code": null, "e": 41739, "s": 41607, "text": "It provide set of methods that make more convenient to deal with memory block in order to read and write data to and from channels." }, { "code": null, "e": 41998, "s": 41739, "text": "Buffers makes NIO package more efficient and faster as compared to classic IO as in case of IO data is deal in the form of streams which do not support asynchronous and concurrent flow of data.Also IO does not allow data execution in chunk or group of bytes." }, { "code": null, "e": 42069, "s": 41998, "text": "Primary parameters that defines Java NIO buffer could be defined as βˆ’" }, { "code": null, "e": 42248, "s": 42069, "text": "Capacity βˆ’ Maximum Amount of data/byte that can be stored in the Buffer.Capacity of a buffer can not be altered.Once the buffer is full it should be cleared before writing to it." }, { "code": null, "e": 42427, "s": 42248, "text": "Capacity βˆ’ Maximum Amount of data/byte that can be stored in the Buffer.Capacity of a buffer can not be altered.Once the buffer is full it should be cleared before writing to it." }, { "code": null, "e": 42696, "s": 42427, "text": "Limit βˆ’ Limit has meaning as per the mode of Buffer i.e. in write mode of Buffer Limit is equal to the capacity which means that maximum data that could be write in buffer.While in read mode of buffer Limit means the limit of how much data can be read from the Buffer." }, { "code": null, "e": 42965, "s": 42696, "text": "Limit βˆ’ Limit has meaning as per the mode of Buffer i.e. in write mode of Buffer Limit is equal to the capacity which means that maximum data that could be write in buffer.While in read mode of buffer Limit means the limit of how much data can be read from the Buffer." }, { "code": null, "e": 43219, "s": 42965, "text": "Position βˆ’ Points to the current location of cursor in buffer.Initially setted as 0 at the time of creation of buffer or in other words it is the index of the next element to be read or written which get updated automatically by get() and put() methods." }, { "code": null, "e": 43473, "s": 43219, "text": "Position βˆ’ Points to the current location of cursor in buffer.Initially setted as 0 at the time of creation of buffer or in other words it is the index of the next element to be read or written which get updated automatically by get() and put() methods." }, { "code": null, "e": 43646, "s": 43473, "text": "Mark βˆ’ Mark a bookmark of the position in a buffer.When mark() method is called the current position is recorded and when reset() is called the marked position is restored." }, { "code": null, "e": 43819, "s": 43646, "text": "Mark βˆ’ Mark a bookmark of the position in a buffer.When mark() method is called the current position is recorded and when reset() is called the marked position is restored." }, { "code": null, "e": 43927, "s": 43819, "text": "Java NIO buffers can be classified in following variants on the basis of data types the buffer deals with βˆ’" }, { "code": null, "e": 43938, "s": 43927, "text": "ByteBuffer" }, { "code": null, "e": 43955, "s": 43938, "text": "MappedByteBuffer" }, { "code": null, "e": 43966, "s": 43955, "text": "CharBuffer" }, { "code": null, "e": 43979, "s": 43966, "text": "DoubleBuffer" }, { "code": null, "e": 43991, "s": 43979, "text": "FloatBuffer" }, { "code": null, "e": 44001, "s": 43991, "text": "IntBuffer" }, { "code": null, "e": 44012, "s": 44001, "text": "LongBuffer" }, { "code": null, "e": 44024, "s": 44012, "text": "ShortBuffer" }, { "code": null, "e": 44207, "s": 44024, "text": "As mentioned already that Buffer act as memory object which provide set of methods that make more convenient to deal with memory block.Following are the important methods of Buffer βˆ’" }, { "code": null, "e": 44402, "s": 44207, "text": "allocate(int capacity) βˆ’ This method is use to allocate a new buffer with capacity as parameter.Allocate method throws IllegalArgumentException in case the passed capacity is a negative integer." }, { "code": null, "e": 44597, "s": 44402, "text": "allocate(int capacity) βˆ’ This method is use to allocate a new buffer with capacity as parameter.Allocate method throws IllegalArgumentException in case the passed capacity is a negative integer." }, { "code": null, "e": 44755, "s": 44597, "text": "read() and put() βˆ’ read method of channel is used to write data from channel to buffer while put is a method of buffer which is used to write data in buffer." }, { "code": null, "e": 44913, "s": 44755, "text": "read() and put() βˆ’ read method of channel is used to write data from channel to buffer while put is a method of buffer which is used to write data in buffer." }, { "code": null, "e": 45093, "s": 44913, "text": "flip() βˆ’ The flip method switches the mode of Buffer from writing to reading mode.It also sets the position back to 0, and sets the limit to where position was at time of writing." }, { "code": null, "e": 45273, "s": 45093, "text": "flip() βˆ’ The flip method switches the mode of Buffer from writing to reading mode.It also sets the position back to 0, and sets the limit to where position was at time of writing." }, { "code": null, "e": 45434, "s": 45273, "text": "write() and get() βˆ’ write method of channel is used to write data from buffer to channel while get is a method of buffer which is used to read data from buffer." }, { "code": null, "e": 45595, "s": 45434, "text": "write() and get() βˆ’ write method of channel is used to write data from buffer to channel while get is a method of buffer which is used to read data from buffer." }, { "code": null, "e": 45726, "s": 45595, "text": "rewind() βˆ’ rewind method is used when reread is required as it sets the position back to zero and do not alter the value of limit." }, { "code": null, "e": 45857, "s": 45726, "text": "rewind() βˆ’ rewind method is used when reread is required as it sets the position back to zero and do not alter the value of limit." }, { "code": null, "e": 46419, "s": 45857, "text": "clear() and compact() βˆ’ clear and compact both methods are used to make buffer from read to write mode.clear() method makes the position to zero and limit equals to capacity,in this method the data in the buffer is not cleared only the markers get re initialized.\nOn other hand compact() method is use when there remained some un-read data and still we use write mode of buffer in this case compact method copies all unread data to the beginning of the buffer and sets position to right after the last unread element.The limit property is still set to capacity." }, { "code": null, "e": 46683, "s": 46419, "text": "clear() and compact() βˆ’ clear and compact both methods are used to make buffer from read to write mode.clear() method makes the position to zero and limit equals to capacity,in this method the data in the buffer is not cleared only the markers get re initialized." }, { "code": null, "e": 46981, "s": 46683, "text": "On other hand compact() method is use when there remained some un-read data and still we use write mode of buffer in this case compact method copies all unread data to the beginning of the buffer and sets position to right after the last unread element.The limit property is still set to capacity." }, { "code": null, "e": 47133, "s": 46981, "text": "mark() and reset() βˆ’ As name suggest mark method is used to mark any particular position in a buffer while reset make position back to marked position." }, { "code": null, "e": 47285, "s": 47133, "text": "mark() and reset() βˆ’ As name suggest mark method is used to mark any particular position in a buffer while reset make position back to marked position." }, { "code": null, "e": 47358, "s": 47285, "text": "The following example shows the implementation of above defined methods." }, { "code": null, "e": 48623, "s": 47358, "text": "import java.nio.ByteBuffer;\nimport java.nio.CharBuffer;\n\npublic class BufferDemo {\n public static void main (String [] args) {\n //allocate a character type buffer.\n CharBuffer buffer = CharBuffer.allocate(10);\n String text = \"bufferDemo\";\n System.out.println(\"Input text: \" + text);\n for (int i = 0; i < text.length(); i++) {\n char c = text.charAt(i);\n //put character in buffer.\n\t\t buffer.put(c);\n }\n int buffPos = buffer.position();\n System.out.println(\"Position after data is written into buffer: \" + buffPos);\n buffer.flip();\n System.out.println(\"Reading buffer contents:\");\n while (buffer.hasRemaining()) {\n System.out.println(buffer.get()); \n }\n //set the position of buffer to 5.\n buffer.position(5);\n //sets this buffer's mark at its position\n buffer.mark();\n //try to change the position\n buffer.position(6);\n //calling reset method to restore to the position we marked.\n //reset() raise InvalidMarkException if either the new position is less\n //than the position marked or merk has not been setted.\n buffer.reset();\n System.out.println(\"Restored buffer position : \" + buffer.position());\n }\n}" }, { "code": null, "e": 48768, "s": 48623, "text": "Input text: bufferDemo\nPosition after data is written into buffer: 10\nReading buffer contents:\nb\nu\nf\nf\ne\nr\nD\ne\nm\no\nRestored buffer position : 5\n" }, { "code": null, "e": 49015, "s": 48768, "text": "As we know that Java NIO supports multiple transaction from and to channels and buffer.So in order to examine one or more NIO Channel's, and determine which channels are ready for data transaction i.e reading or writing Java NIO provide Selector." }, { "code": null, "e": 49155, "s": 49015, "text": "With Selector we can make a thread to know that which channel is ready for data writing and reading and could deal that particular channel." }, { "code": null, "e": 49338, "s": 49155, "text": "We can get selector instance by calling its static method open().After open selector we have to register a non blocking mode channel with it which returns a instance of SelectionKey." }, { "code": null, "e": 49512, "s": 49338, "text": "SelectionKey is basically a collection of operations that can be performed with channel or we can say that we could know the state of channel with the help of selection key." }, { "code": null, "e": 49588, "s": 49512, "text": "The major operations or state of channel represented by selection key are βˆ’" }, { "code": null, "e": 49659, "s": 49588, "text": "SelectionKey.OP_CONNECT βˆ’ Channel which is ready to connect to server." }, { "code": null, "e": 49730, "s": 49659, "text": "SelectionKey.OP_CONNECT βˆ’ Channel which is ready to connect to server." }, { "code": null, "e": 49810, "s": 49730, "text": "SelectionKey.OP_ACCEPT βˆ’ Channel which is ready to accept incoming connections." }, { "code": null, "e": 49890, "s": 49810, "text": "SelectionKey.OP_ACCEPT βˆ’ Channel which is ready to accept incoming connections." }, { "code": null, "e": 49950, "s": 49890, "text": "SelectionKey.OP_READ βˆ’ Channel which is ready to data read." }, { "code": null, "e": 50010, "s": 49950, "text": "SelectionKey.OP_READ βˆ’ Channel which is ready to data read." }, { "code": null, "e": 50072, "s": 50010, "text": "SelectionKey.OP_WRITE βˆ’ Channel which is ready to data write." }, { "code": null, "e": 50134, "s": 50072, "text": "SelectionKey.OP_WRITE βˆ’ Channel which is ready to data write." }, { "code": null, "e": 50224, "s": 50134, "text": "Selection key obtained after registration has some important methods as mentioned below βˆ’" }, { "code": null, "e": 50377, "s": 50224, "text": "attach() βˆ’ This method is used to attach an object with the key.The main purpose of attaching an object to a channel is to recognizing the same channel." }, { "code": null, "e": 50530, "s": 50377, "text": "attach() βˆ’ This method is used to attach an object with the key.The main purpose of attaching an object to a channel is to recognizing the same channel." }, { "code": null, "e": 50613, "s": 50530, "text": "attachment() βˆ’ This method is used to retain the attached object from the channel." }, { "code": null, "e": 50696, "s": 50613, "text": "attachment() βˆ’ This method is used to retain the attached object from the channel." }, { "code": null, "e": 50788, "s": 50696, "text": "channel() βˆ’ This method is used to get the channel for which the particular key is created." }, { "code": null, "e": 50880, "s": 50788, "text": "channel() βˆ’ This method is used to get the channel for which the particular key is created." }, { "code": null, "e": 50974, "s": 50880, "text": "selector() βˆ’ This method is used to get the selector for which the particular key is created." }, { "code": null, "e": 51068, "s": 50974, "text": "selector() βˆ’ This method is used to get the selector for which the particular key is created." }, { "code": null, "e": 51133, "s": 51068, "text": "isValid() βˆ’ This method returns weather the key is valid or not." }, { "code": null, "e": 51198, "s": 51133, "text": "isValid() βˆ’ This method returns weather the key is valid or not." }, { "code": null, "e": 51285, "s": 51198, "text": "isReadable() βˆ’ This method states that weather key's channel is ready for read or not." }, { "code": null, "e": 51372, "s": 51285, "text": "isReadable() βˆ’ This method states that weather key's channel is ready for read or not." }, { "code": null, "e": 51460, "s": 51372, "text": "isWritable() βˆ’ This method states that weather key's channel is ready for write or not." }, { "code": null, "e": 51548, "s": 51460, "text": "isWritable() βˆ’ This method states that weather key's channel is ready for write or not." }, { "code": null, "e": 51662, "s": 51548, "text": "isAcceptable() βˆ’ This method states that weather key's channel is ready for accepting incoming connection or not." }, { "code": null, "e": 51776, "s": 51662, "text": "isAcceptable() βˆ’ This method states that weather key's channel is ready for accepting incoming connection or not." }, { "code": null, "e": 51914, "s": 51776, "text": "isConnectable() βˆ’ This method tests whether this key's channel has either finished, or failed to finish, its socket-connection operation." }, { "code": null, "e": 52052, "s": 51914, "text": "isConnectable() βˆ’ This method tests whether this key's channel has either finished, or failed to finish, its socket-connection operation." }, { "code": null, "e": 52158, "s": 52052, "text": "isAcceptable() βˆ’ This method tests whether this key's channel is ready to accept a new socket connection." }, { "code": null, "e": 52264, "s": 52158, "text": "isAcceptable() βˆ’ This method tests whether this key's channel is ready to accept a new socket connection." }, { "code": null, "e": 52327, "s": 52264, "text": "interestOps() βˆ’ This method retrieves this key's interest set." }, { "code": null, "e": 52390, "s": 52327, "text": "interestOps() βˆ’ This method retrieves this key's interest set." }, { "code": null, "e": 52496, "s": 52390, "text": "readyOps() βˆ’ This method retrieves the ready set which is the set of operations the channel is ready for." }, { "code": null, "e": 52602, "s": 52496, "text": "readyOps() βˆ’ This method retrieves the ready set which is the set of operations the channel is ready for." }, { "code": null, "e": 52723, "s": 52602, "text": "We can select a channel from selector by calling its static method select().Select method of selector is overloaded as βˆ’" }, { "code": null, "e": 52845, "s": 52723, "text": "select() βˆ’ This method blocks the current thread until at least one channel is ready for the events it is registered for." }, { "code": null, "e": 52967, "s": 52845, "text": "select() βˆ’ This method blocks the current thread until at least one channel is ready for the events it is registered for." }, { "code": null, "e": 53111, "s": 52967, "text": "select(long timeout) βˆ’ This method does the same as select() except it blocks the thread for a maximum of timeout milliseconds (the parameter)." }, { "code": null, "e": 53255, "s": 53111, "text": "select(long timeout) βˆ’ This method does the same as select() except it blocks the thread for a maximum of timeout milliseconds (the parameter)." }, { "code": null, "e": 53359, "s": 53255, "text": "selectNow() βˆ’ This method doesn't block at all.It returns immediately with whatever channels are ready." }, { "code": null, "e": 53463, "s": 53359, "text": "selectNow() βˆ’ This method doesn't block at all.It returns immediately with whatever channels are ready." }, { "code": null, "e": 53662, "s": 53463, "text": "Also in order to leave a blocked thread which call out select method,wakeup() method can be called from selector instance after which the thread waiting inside select() will then return immediately." }, { "code": null, "e": 53835, "s": 53662, "text": "In last we can close the selector by calling close() method which also invalidates all SelectionKey instances registered with this Selector along with closing the selector." }, { "code": null, "e": 55774, "s": 53835, "text": "import java.io.FileInputStream;\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.FileChannel;\nimport java.nio.channels.SelectionKey;\nimport java.nio.channels.Selector;\nimport java.nio.channels.ServerSocketChannel;\nimport java.nio.channels.SocketChannel;\nimport java.util.Iterator;\nimport java.util.Set;\n\npublic class SelectorDemo {\n public static void main(String[] args) throws IOException {\n String demo_text = \"This is a demo String\";\t\n Selector selector = Selector.open();\n ServerSocketChannel serverSocket = ServerSocketChannel.open();\n serverSocket.bind(new InetSocketAddress(\"localhost\", 5454));\n serverSocket.configureBlocking(false);\n serverSocket.register(selector, SelectionKey.OP_ACCEPT);\n ByteBuffer buffer = ByteBuffer.allocate(256);\n while (true) {\n selector.select();\n Set<SelectionKey> selectedKeys = selector.selectedKeys();\n Iterator<SelectionKey> iter = selectedKeys.iterator();\n while (iter.hasNext()) {\n SelectionKey key = iter.next();\n int interestOps = key.interestOps();\n System.out.println(interestOps);\n if (key.isAcceptable()) {\n SocketChannel client = serverSocket.accept();\n client.configureBlocking(false);\n client.register(selector, SelectionKey.OP_READ);\n }\n if (key.isReadable()) {\n SocketChannel client = (SocketChannel) key.channel();\n client.read(buffer);\n if (new String(buffer.array()).trim().equals(demo_text)) {\n client.close();\n System.out.println(\"Not accepting client messages anymore\");\n }\n buffer.flip();\n client.write(buffer);\n buffer.clear();\n }\n iter.remove();\n }\n }\n }\n}" }, { "code": null, "e": 55943, "s": 55774, "text": "In Java NIO pipe is a component which is used to write and read data between two threads.Pipe mainly consist of two channels which are responsible for data propagation." }, { "code": null, "e": 56119, "s": 55943, "text": "Among two constituent channels one is called as Sink channel which is mainly for writing data and other is Source channel whose main purpose is to read data from Sink channel." }, { "code": null, "e": 56286, "s": 56119, "text": "Data synchronization is kept in order during data writing and reading as it must be ensured that data must be read in a same order in which it is written to the Pipe." }, { "code": null, "e": 56443, "s": 56286, "text": "It must kept in notice that it is a unidirectional flow of data in Pipe i.e data is written in Sink channel only and could only be read from Source channel." }, { "code": null, "e": 56548, "s": 56443, "text": "In Java NIO pipe is defined as a abstract class with mainly three methods out of which two are abstract." }, { "code": null, "e": 56659, "s": 56548, "text": "open() βˆ’ This method is used get an instance of Pipe or we can say pipe is created by calling out this method." }, { "code": null, "e": 56770, "s": 56659, "text": "open() βˆ’ This method is used get an instance of Pipe or we can say pipe is created by calling out this method." }, { "code": null, "e": 56880, "s": 56770, "text": "sink() βˆ’ This method returns the Pipe's sink channel which is used to write data by calling its write method." }, { "code": null, "e": 56990, "s": 56880, "text": "sink() βˆ’ This method returns the Pipe's sink channel which is used to write data by calling its write method." }, { "code": null, "e": 57102, "s": 56990, "text": "source() βˆ’ This method returns the Pipe's source channel which is used to read data by calling its read method." }, { "code": null, "e": 57214, "s": 57102, "text": "source() βˆ’ This method returns the Pipe's source channel which is used to read data by calling its read method." }, { "code": null, "e": 57279, "s": 57214, "text": "The following example shows the implementation of Java NIO pipe." }, { "code": null, "e": 58494, "s": 57279, "text": "import java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.Pipe;\n\npublic class PipeDemo {\n public static void main(String[] args) throws IOException {\n //An instance of Pipe is created\n Pipe pipe = Pipe.open();\n // gets the pipe's sink channel\n Pipe.SinkChannel skChannel = pipe.sink();\n String testData = \"Test Data to Check java NIO Channels Pipe.\";\n ByteBuffer buffer = ByteBuffer.allocate(512);\n buffer.clear();\n buffer.put(testData.getBytes());\n buffer.flip();\n //write data into sink channel.\n while(buffer.hasRemaining()) {\n skChannel.write(buffer);\n }\n //gets pipe's source channel\n Pipe.SourceChannel sourceChannel = pipe.source();\n buffer = ByteBuffer.allocate(512);\n //write data into console \n while(sourceChannel.read(buffer) > 0){\n //limit is set to current position and position is set to zero\n buffer.flip();\n while(buffer.hasRemaining()){\n char ch = (char) buffer.get();\n System.out.print(ch);\n }\n //position is set to zero and limit is set to capacity to clear the buffer.\n buffer.clear();\n }\n }\n}" }, { "code": null, "e": 58538, "s": 58494, "text": "Test Data to Check java NIO Channels Pipe.\n" }, { "code": null, "e": 58673, "s": 58538, "text": "Assuming we have a text file c:/test.txt, which has the following content. This file will be used as an input for our example program." }, { "code": null, "e": 58846, "s": 58673, "text": "As name suggests Path is the particular location of an entity such as file or a directory in a file system so that one can search and access it at that particular location." }, { "code": null, "e": 59121, "s": 58846, "text": "Technically in terms of Java, Path is an interface which is introduced in Java NIO file package during Java version 7,and is the representation of location in particular file system.As path interface is in Java NIO package so it get its qualified name as java.nio.file.Path." }, { "code": null, "e": 59514, "s": 59121, "text": "In general path of an entity could be of two types one is absolute path and other is relative path.As name of both paths suggests that absolute path is the location address from the root to the entity where it locates while relative path is the location address which is relative to some other path.Path uses delimiters in its definition as \"\\\" for Windows and \"/\" for unix operating systems." }, { "code": null, "e": 59835, "s": 59514, "text": "In order to get the instance of Path we can use static method of java.nio.file.Paths class get().This method converts a path string, or a sequence of strings that when joined form a path string, to a Path instance.This method also throws runtime InvalidPathException if the arguments passed contains illegal characters." }, { "code": null, "e": 60120, "s": 59835, "text": "As mentioned above absolute path is retrieved by passing root element and the complete directory list required to locate the file.While relative path could be retrieved by combining the base path with the relative path.Retrieval of both paths would be illustrated in following example" }, { "code": null, "e": 60644, "s": 60120, "text": "package com.java.nio;\nimport java.io.IOException;\nimport java.nio.Buffer;\nimport java.nio.ByteBuffer;\nimport java.nio.file.FileSystem;\nimport java.nio.file.LinkOption;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\npublic class PathDemo {\n public static void main(String[] args) throws IOException {\n Path relative = Paths.get(\"file2.txt\");\n System.out.println(\"Relative path: \" + relative);\n Path absolute = relative.toAbsolutePath();\n System.out.println(\"Absolute path: \" + absolute);\n }\n}" }, { "code": null, "e": 60816, "s": 60644, "text": "So far we know that what is path interface why do we need that and how could we access it.Now we would know what are the important methods which Path interface provide us." }, { "code": null, "e": 60882, "s": 60816, "text": "getFileName() βˆ’ Returns the file system that created this object." }, { "code": null, "e": 60948, "s": 60882, "text": "getFileName() βˆ’ Returns the file system that created this object." }, { "code": null, "e": 61014, "s": 60948, "text": "getName() βˆ’ Returns a name element of this path as a Path object." }, { "code": null, "e": 61080, "s": 61014, "text": "getName() βˆ’ Returns a name element of this path as a Path object." }, { "code": null, "e": 61147, "s": 61080, "text": "getNameCount() βˆ’ Returns the number of name elements in the path." }, { "code": null, "e": 61214, "s": 61147, "text": "getNameCount() βˆ’ Returns the number of name elements in the path." }, { "code": null, "e": 61307, "s": 61214, "text": "subpath() βˆ’ Returns a relative Path that is a subsequence of the name elements of this path." }, { "code": null, "e": 61400, "s": 61307, "text": "subpath() βˆ’ Returns a relative Path that is a subsequence of the name elements of this path." }, { "code": null, "e": 61484, "s": 61400, "text": "getParent() βˆ’ Returns the parent path, or null if this path does not have a parent." }, { "code": null, "e": 61568, "s": 61484, "text": "getParent() βˆ’ Returns the parent path, or null if this path does not have a parent." }, { "code": null, "e": 61691, "s": 61568, "text": "getRoot() βˆ’ Returns the root component of this path as a Path object, or null if this path does not have a root component." }, { "code": null, "e": 61814, "s": 61691, "text": "getRoot() βˆ’ Returns the root component of this path as a Path object, or null if this path does not have a root component." }, { "code": null, "e": 61900, "s": 61814, "text": "toAbsolutePath() βˆ’ Returns a Path object representing the absolute path of this path." }, { "code": null, "e": 61986, "s": 61900, "text": "toAbsolutePath() βˆ’ Returns a Path object representing the absolute path of this path." }, { "code": null, "e": 62044, "s": 61986, "text": "toRealPath() βˆ’ Returns the real path of an existing file." }, { "code": null, "e": 62102, "s": 62044, "text": "toRealPath() βˆ’ Returns the real path of an existing file." }, { "code": null, "e": 62159, "s": 62102, "text": "toFile() βˆ’ Returns a File object representing this path." }, { "code": null, "e": 62216, "s": 62159, "text": "toFile() βˆ’ Returns a File object representing this path." }, { "code": null, "e": 62304, "s": 62216, "text": "normalize() βˆ’ Returns a path that is this path with redundant name elements eliminated." }, { "code": null, "e": 62392, "s": 62304, "text": "normalize() βˆ’ Returns a path that is this path with redundant name elements eliminated." }, { "code": null, "e": 62697, "s": 62392, "text": "compareTo(Path other) βˆ’ Compares two abstract paths lexicographically.This method returns zero if the argument is equal to this path, a value less than zero if this path is lexicographically less than the argument, or a value greater than zero if this path is lexicographically greater than the argument." }, { "code": null, "e": 63002, "s": 62697, "text": "compareTo(Path other) βˆ’ Compares two abstract paths lexicographically.This method returns zero if the argument is equal to this path, a value less than zero if this path is lexicographically less than the argument, or a value greater than zero if this path is lexicographically greater than the argument." }, { "code": null, "e": 63300, "s": 63002, "text": "endsWith(Path other) βˆ’ Tests if this path ends with the given path.If the given path has N elements, and no root component, and this path has N or more elements, then this path ends with the given path if the last N elements of each path, starting at the element farthest from the root, are equal." }, { "code": null, "e": 63598, "s": 63300, "text": "endsWith(Path other) βˆ’ Tests if this path ends with the given path.If the given path has N elements, and no root component, and this path has N or more elements, then this path ends with the given path if the last N elements of each path, starting at the element farthest from the root, are equal." }, { "code": null, "e": 63771, "s": 63598, "text": "endsWith(String other) βˆ’ Tests if this path ends with a Path, constructed by converting the given path string, in exactly the manner specified by the endsWith(Path) method." }, { "code": null, "e": 63944, "s": 63771, "text": "endsWith(String other) βˆ’ Tests if this path ends with a Path, constructed by converting the given path string, in exactly the manner specified by the endsWith(Path) method." }, { "code": null, "e": 64042, "s": 63944, "text": "Following example illustartes the different methods of Path interface which are mentioned above βˆ’" }, { "code": null, "e": 65300, "s": 64042, "text": "package com.java.nio;\nimport java.io.IOException;\nimport java.nio.Buffer;\nimport java.nio.ByteBuffer;\nimport java.nio.file.FileSystem;\nimport java.nio.file.LinkOption;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\npublic class PathDemo {\n public static void main(String[] args) throws IOException {\n Path path = Paths.get(\"D:/workspace/ContentW/Saurav_CV.docx\");\n FileSystem fs = path.getFileSystem();\n System.out.println(fs.toString());\n System.out.println(path.isAbsolute());\n System.out.println(path.getFileName());\n System.out.println(path.toAbsolutePath().toString());\n System.out.println(path.getRoot());\n System.out.println(path.getParent());\n System.out.println(path.getNameCount());\n System.out.println(path.getName(0));\n System.out.println(path.subpath(0, 2));\n System.out.println(path.toString());\n System.out.println(path.getNameCount());\n Path realPath = path.toRealPath(LinkOption.NOFOLLOW_LINKS);\n System.out.println(realPath.toString());\n String originalPath = \"d:\\\\data\\\\projects\\\\a-project\\\\..\\\\another-project\";\n Path path1 = Paths.get(originalPath);\n Path path2 = path1.normalize();\n System.out.println(\"path2 = \" + path2);\n }\n}" }, { "code": null, "e": 65484, "s": 65300, "text": "Java NIO package provide one more utility API named as Files which is basically used for manipulating files and directories using its static methods which mostly works on Path object." }, { "code": null, "e": 65649, "s": 65484, "text": "As mentioned in Path tutorial that Path interface is introduced in Java NIO package during Java 7 version in file package.So this tutorial is for same File package." }, { "code": null, "e": 65884, "s": 65649, "text": "This class consists exclusively of static methods that operate on files, directories, or other types of files.In most cases, the methods defined here will delegate to the associated file system provider to perform the file operations." }, { "code": null, "e": 66089, "s": 65884, "text": "There are many methods defined in the Files class which could also be read from Java docs.In this tutorial we tried to cover some of the important methods among all of the methods of Java NIO Files class." }, { "code": null, "e": 66158, "s": 66089, "text": "Following are the important methods defined in Java NIO Files class." }, { "code": null, "e": 66277, "s": 66158, "text": "createFile(Path filePath, FileAttribute attrs) βˆ’ Files class provides this method to create file using specified Path." }, { "code": null, "e": 66396, "s": 66277, "text": "createFile(Path filePath, FileAttribute attrs) βˆ’ Files class provides this method to create file using specified Path." }, { "code": null, "e": 66914, "s": 66396, "text": "package com.java.nio;\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\npublic class CreateFile {\n public static void main(String[] args) {\n //initialize Path object\n Path path = Paths.get(\"D:file.txt\");\n //create file\n try {\n Path createdFilePath = Files.createFile(path);\n System.out.println(\"Created a file at : \"+createdFilePath);\n } \n catch (IOException e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 66952, "s": 66914, "text": "Created a file at : D:\\data\\file.txt\n" }, { "code": null, "e": 67220, "s": 66952, "text": "copy(InputStream in, Path target, CopyOption... options) βˆ’ This method is used to copies all bytes from specified input stream to specified target file and returns number of bytes read or written as long value.LinkOption for this parameter with the following values βˆ’" }, { "code": null, "e": 67488, "s": 67220, "text": "copy(InputStream in, Path target, CopyOption... options) βˆ’ This method is used to copies all bytes from specified input stream to specified target file and returns number of bytes read or written as long value.LinkOption for this parameter with the following values βˆ’" }, { "code": null, "e": 67575, "s": 67488, "text": "COPY_ATTRIBUTES βˆ’ copy attributes to the new file, e.g. last-modified-time attribute." }, { "code": null, "e": 67662, "s": 67575, "text": "COPY_ATTRIBUTES βˆ’ copy attributes to the new file, e.g. last-modified-time attribute." }, { "code": null, "e": 67720, "s": 67662, "text": "REPLACE_EXISTING βˆ’ replace an existing file if it exists." }, { "code": null, "e": 67778, "s": 67720, "text": "REPLACE_EXISTING βˆ’ replace an existing file if it exists." }, { "code": null, "e": 67886, "s": 67778, "text": "NOFOLLOW_LINKS βˆ’ If a file is a symbolic link, then the link itself, not the target of the link, is copied." }, { "code": null, "e": 67994, "s": 67886, "text": "NOFOLLOW_LINKS βˆ’ If a file is a symbolic link, then the link itself, not the target of the link, is copied." }, { "code": null, "e": 68966, "s": 67994, "text": "package com.java.nio;\nimport java.io.IOException;\nimport java.nio.charset.Charset;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.nio.file.StandardCopyOption;\nimport java.util.List;\npublic class WriteFile {\n public static void main(String[] args) {\n Path sourceFile = Paths.get(\"D:file.txt\");\n Path targetFile = Paths.get(\"D:fileCopy.txt\");\n try {\n Files.copy(sourceFile, targetFile,\n StandardCopyOption.REPLACE_EXISTING);\n }\n catch (IOException ex) {\n System.err.format(\"I/O Error when copying file\");\n }\n Path wiki_path = Paths.get(\"D:fileCopy.txt\");\n Charset charset = Charset.forName(\"ISO-8859-1\");\n try {\n List<String> lines = Files.readAllLines(wiki_path, charset);\n for (String line : lines) {\n System.out.println(line);\n }\n } \n catch (IOException e) {\n System.out.println(e);\n }\n }\t\n}" }, { "code": null, "e": 68987, "s": 68966, "text": "To be or not to be?\n" }, { "code": null, "e": 69150, "s": 68987, "text": "createDirectories(Path dir, FileAttribute<?>...attrs) βˆ’ This method is used to create directories using given path by creating all nonexistent parent directories." }, { "code": null, "e": 69313, "s": 69150, "text": "createDirectories(Path dir, FileAttribute<?>...attrs) βˆ’ This method is used to create directories using given path by creating all nonexistent parent directories." }, { "code": null, "e": 69539, "s": 69313, "text": "delete(Path path) βˆ’ This method is used to deletes the file from specified path.It throws NoSuchFileException if the file is not exists at specified path or if the file is directory and it may not empty and cannot be deleted." }, { "code": null, "e": 69765, "s": 69539, "text": "delete(Path path) βˆ’ This method is used to deletes the file from specified path.It throws NoSuchFileException if the file is not exists at specified path or if the file is directory and it may not empty and cannot be deleted." }, { "code": null, "e": 69916, "s": 69765, "text": "exists(Path path) βˆ’ This method is used to check if file exists at specified path and if the file exists it will return true or else it returns false." }, { "code": null, "e": 70067, "s": 69916, "text": "exists(Path path) βˆ’ This method is used to check if file exists at specified path and if the file exists it will return true or else it returns false." }, { "code": null, "e": 70232, "s": 70067, "text": "readAllBytes(Path path) βˆ’ This method is used to reads all the bytes from the file at given path and returns the byte array containing the bytes read from the file." }, { "code": null, "e": 70397, "s": 70232, "text": "readAllBytes(Path path) βˆ’ This method is used to reads all the bytes from the file at given path and returns the byte array containing the bytes read from the file." }, { "code": null, "e": 71012, "s": 70397, "text": "package com.java.nio;\nimport java.io.IOException;\nimport java.nio.charset.Charset;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.List;\npublic class ReadFile {\n public static void main(String[] args) {\n Path wiki_path = Paths.get(\"D:file.txt\");\n Charset charset = Charset.forName(\"ISO-8859-1\");\n try {\n List<String> lines = Files.readAllLines(wiki_path, charset);\n for (String line : lines) {\n System.out.println(line);\n }\n } \n catch (IOException e) {\n System.out.println(e);\n }\n }\t\n}" }, { "code": null, "e": 71030, "s": 71012, "text": "Welcome to file.\n" }, { "code": null, "e": 71124, "s": 71030, "text": "size(Path path) βˆ’ This method is used to get the size of the file at specified path in bytes." }, { "code": null, "e": 71218, "s": 71124, "text": "size(Path path) βˆ’ This method is used to get the size of the file at specified path in bytes." }, { "code": null, "e": 71339, "s": 71218, "text": "write(Path path, byte[] bytes, OpenOption... options) βˆ’ This method is used to writes bytes to a file at specified path." }, { "code": null, "e": 71460, "s": 71339, "text": "write(Path path, byte[] bytes, OpenOption... options) βˆ’ This method is used to writes bytes to a file at specified path." }, { "code": null, "e": 72161, "s": 71460, "text": "package com.java.nio;\nimport java.io.IOException;\nimport java.nio.charset.Charset;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.List;\npublic class WriteFile {\n public static void main(String[] args) {\n Path path = Paths.get(\"D:file.txt\");\n String question = \"To be or not to be?\";\n Charset charset = Charset.forName(\"ISO-8859-1\");\n try {\n Files.write(path, question.getBytes());\n List<String> lines = Files.readAllLines(path, charset);\n for (String line : lines) {\n System.out.println(line);\n }\n } \n catch (IOException e) {\n System.out.println(e);\n }\n }\n}" }, { "code": null, "e": 72182, "s": 72161, "text": "To be or not to be?\n" }, { "code": null, "e": 72549, "s": 72182, "text": "As we know that Java NIO supports concurrency and multi-threading which allows us to deal with different channels concurrently at same time.So the API which is responsible for this in Java NIO package is AsynchronousFileChannel which is defined under NIO channels package.Hence qualified name for AsynchronousFileChannel is java.nio.channels.AsynchronousFileChannel." }, { "code": null, "e": 72885, "s": 72549, "text": "AsynchronousFileChannel is similar to that of the NIO's FileChannel,except that this channel enables file operations to execute asynchronously unlike of synchronous I/O operation in which a thread enters into an action and waits until the request is completed.Thus asynchronous channels are safe for use by multiple concurrent threads." }, { "code": null, "e": 73188, "s": 72885, "text": "In asynchronous the request is passed by thread to the operating system's kernel to get it done while thread continues to process another job.Once the job of kernel is done it signals the thread then the thread acknowledged the signal and interrupts the current job and processes the I/O job as needed." }, { "code": null, "e": 73413, "s": 73188, "text": "For achieving concurrency this channel provides two approaches which includes one as returning a java.util.concurrent.Future object and other is Passing to the operation an object of type java.nio.channels.CompletionHandler." }, { "code": null, "e": 73487, "s": 73413, "text": "We will understand both the approaches with help of examples one by one.\n" }, { "code": null, "e": 73832, "s": 73487, "text": "Future Object βˆ’ In this an instance of Future Interface is returned from channel.In Future interface there is get() method which returns the status of operation that is handled asynchronously on the basis of which further execution of other task could get decided.We can also check whether task is completed or not by calling its isDone method." }, { "code": null, "e": 74177, "s": 73832, "text": "Future Object βˆ’ In this an instance of Future Interface is returned from channel.In Future interface there is get() method which returns the status of operation that is handled asynchronously on the basis of which further execution of other task could get decided.We can also check whether task is completed or not by calling its isDone method." }, { "code": null, "e": 74262, "s": 74177, "text": "The following example shows the how to use Future object and to task asynchronously." }, { "code": null, "e": 76108, "s": 74262, "text": "package com.java.nio;\nimport java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.AsynchronousFileChannel;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.nio.file.StandardOpenOption;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.Future;\n\npublic class FutureObject {\n public static void main(String[] args) throws Exception {\n readFile();\n }\n private static void readFile() throws IOException, InterruptedException, ExecutionException {\n String filePath = \"D:fileCopy.txt\";\n printFileContents(filePath);\n Path path = Paths.get(filePath);\t\t\n AsynchronousFileChannel channel =AsynchronousFileChannel.open(path, StandardOpenOption.READ);\n ByteBuffer buffer = ByteBuffer.allocate(400);\n Future<Integer> result = channel.read(buffer, 0); // position = 0\n while (! result.isDone()) {\n System.out.println(\"Task of reading file is in progress asynchronously.\");\n }\n System.out.println(\"Reading done: \" + result.isDone());\n System.out.println(\"Bytes read from file: \" + result.get()); \n buffer.flip();\n System.out.print(\"Buffer contents: \");\n while (buffer.hasRemaining()) {\n System.out.print((char) buffer.get()); \n }\n System.out.println(\" \");\n buffer.clear();\n channel.close();\n }\n private static void printFileContents(String path) throws IOException {\n FileReader fr = new FileReader(path);\n BufferedReader br = new BufferedReader(fr);\n String textRead = br.readLine();\n System.out.println(\"File contents: \");\n while (textRead != null) {\n System.out.println(\" \" + textRead);\n textRead = br.readLine();\n }\n fr.close();\n br.close();\n }\n}" }, { "code": null, "e": 76349, "s": 76108, "text": "File contents: \n To be or not to be?\n Task of reading file is in progress asynchronously.\n Task of reading file is in progress asynchronously.\n Reading done: true\n Bytes read from file: 19\n Buffer contents: To be or not to be? \n" }, { "code": null, "e": 76812, "s": 76349, "text": "Completion Handler βˆ’ This approach is pretty simple as in this we uses CompletionHandler interface and overrides its two methods one is completed() method which is invoked when the I/O operation completes successfully and other is failed() method which is invoked if the I/O operations fails.In this a handler is created for consuming the result of an asynchronous I/O operation as once a task is completed then only the handler has functions that are executed." }, { "code": null, "e": 76834, "s": 76812, "text": "Completion Handler βˆ’ " }, { "code": null, "e": 77276, "s": 76834, "text": " This approach is pretty simple as in this we uses CompletionHandler interface and overrides its two methods one is completed() method which is invoked when the I/O operation completes successfully and other is failed() method which is invoked if the I/O operations fails.In this a handler is created for consuming the result of an asynchronous I/O operation as once a task is completed then only the handler has functions that are executed." }, { "code": null, "e": 77361, "s": 77276, "text": "The following example shows the how to use CompletionHandler to task asynchronously." }, { "code": null, "e": 79236, "s": 77361, "text": "package com.java.nio;\nimport java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.AsynchronousFileChannel;\nimport java.nio.channels.CompletionHandler;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.nio.file.StandardOpenOption;\n\npublic class CompletionHandlerDemo {\n public static void main (String [] args) throws Exception {\n writeFile();\n }\n private static void writeFile() throws IOException {\n String input = \"Content to be written to the file.\";\n System.out.println(\"Input string: \" + input);\n byte [] byteArray = input.getBytes();\n ByteBuffer buffer = ByteBuffer.wrap(byteArray);\n Path path = Paths.get(\"D:fileCopy.txt\");\n AsynchronousFileChannel channel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE);\n CompletionHandler handler = new CompletionHandler() {\n @Override\n public void completed(Object result, Object attachment) {\n System.out.println(attachment + \" completed and \" + result + \" bytes are written.\");\n }\n @Override\n public void failed(Throwable exc, Object attachment) {\n System.out.println(attachment + \" failed with exception:\");\n exc.printStackTrace();\n }\n };\n channel.write(buffer, 0, \"Async Task\", handler);\n channel.close();\n printFileContents(path.toString());\n }\n private static void printFileContents(String path) throws IOException {\n FileReader fr = new FileReader(path);\n BufferedReader br = new BufferedReader(fr);\n String textRead = br.readLine();\n System.out.println(\"File contents: \");\n while (textRead != null) {\n System.out.println(\" \" + textRead);\n textRead = br.readLine();\n }\n fr.close();\n br.close();\n }\n}" }, { "code": null, "e": 79384, "s": 79236, "text": "Input string: Content to be written to the file.\nAsync Task completed and 34 bytes are written.\nFile contents: \nContent to be written to the file.\n" }, { "code": null, "e": 79624, "s": 79384, "text": "In Java for every character there is a well defined unicode code units which is internally handled by JVM.So Java NIO package defines an abstract class named as Charset which is mainly used for encoding and decoding of charset and UNICODE." }, { "code": null, "e": 79671, "s": 79624, "text": "The supported Charset in java are given below." }, { "code": null, "e": 79710, "s": 79671, "text": "US-ASCII βˆ’ Seven bit ASCII characters." }, { "code": null, "e": 79749, "s": 79710, "text": "US-ASCII βˆ’ Seven bit ASCII characters." }, { "code": null, "e": 79782, "s": 79749, "text": "ISO-8859-1 βˆ’ ISO Latin alphabet." }, { "code": null, "e": 79815, "s": 79782, "text": "ISO-8859-1 βˆ’ ISO Latin alphabet." }, { "code": null, "e": 79864, "s": 79815, "text": "UTF-8 βˆ’ This is 8 bit UCS transformation format." }, { "code": null, "e": 79913, "s": 79864, "text": "UTF-8 βˆ’ This is 8 bit UCS transformation format." }, { "code": null, "e": 79993, "s": 79913, "text": "UTF-16BE βˆ’ This is 16 bit UCS transformation format with big endian byte order." }, { "code": null, "e": 80073, "s": 79993, "text": "UTF-16BE βˆ’ This is 16 bit UCS transformation format with big endian byte order." }, { "code": null, "e": 80149, "s": 80073, "text": "UTF-16LE βˆ’ This is 16 bit UCS transformation with little endian byte order." }, { "code": null, "e": 80225, "s": 80149, "text": "UTF-16LE βˆ’ This is 16 bit UCS transformation with little endian byte order." }, { "code": null, "e": 80268, "s": 80225, "text": "UTF-16 βˆ’ 16 bit UCS transformation format." }, { "code": null, "e": 80311, "s": 80268, "text": "UTF-16 βˆ’ 16 bit UCS transformation format." }, { "code": null, "e": 80428, "s": 80313, "text": "forName() βˆ’ This method creates a charset object for the given charset name.The name can be canonical or an alias." }, { "code": null, "e": 80543, "s": 80428, "text": "forName() βˆ’ This method creates a charset object for the given charset name.The name can be canonical or an alias." }, { "code": null, "e": 80617, "s": 80543, "text": "displayName() βˆ’ This method returns the canonical name of given charset." }, { "code": null, "e": 80691, "s": 80617, "text": "displayName() βˆ’ This method returns the canonical name of given charset." }, { "code": null, "e": 80776, "s": 80691, "text": "canEncode() βˆ’ This method checks whether the given charset supports encoding or not." }, { "code": null, "e": 80861, "s": 80776, "text": "canEncode() βˆ’ This method checks whether the given charset supports encoding or not." }, { "code": null, "e": 80958, "s": 80861, "text": "decode() βˆ’ This method decodes the string of a given charset into charbuffer of Unicode charset." }, { "code": null, "e": 81055, "s": 80958, "text": "decode() βˆ’ This method decodes the string of a given charset into charbuffer of Unicode charset." }, { "code": null, "e": 81155, "s": 81055, "text": "encode() βˆ’ This method encodes charbuffer of unicode charset into the byte buffer of given charset." }, { "code": null, "e": 81255, "s": 81155, "text": "encode() βˆ’ This method encodes charbuffer of unicode charset into the byte buffer of given charset." }, { "code": null, "e": 81320, "s": 81255, "text": "Following example illustrate important methods of Charset class." }, { "code": null, "e": 82183, "s": 81320, "text": "package com.java.nio;\nimport java.nio.ByteBuffer;\nimport java.nio.CharBuffer;\nimport java.nio.charset.Charset;\npublic class CharsetExample {\n public static void main(String[] args) {\n Charset charset = Charset.forName(\"US-ASCII\");\n System.out.println(charset.displayName());\n System.out.println(charset.canEncode());\n String str = \"Demo text for conversion.\";\n //convert byte buffer in given charset to char buffer in unicode\n ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes());\n CharBuffer charBuffer = charset.decode(byteBuffer);\n //convert char buffer in unicode to byte buffer in given charset\n ByteBuffer newByteBuffer = charset.encode(charBuffer);\n while(newbb.hasRemaining()){\n char ch = (char) newByteBuffer.get();\n System.out.print(ch);\n }\n newByteBuffer.clear();\n }\n}" }, { "code": null, "e": 82219, "s": 82183, "text": "US-ASCII\nDemo text for conversion.\n" }, { "code": null, "e": 82481, "s": 82219, "text": "As we know that Java NIO supports concurrency and multi threading which enables it to deal with the multiple threads operating on multiple files at same time.But in some cases we require that our file would not get share by any of thread and get non accessible." }, { "code": null, "e": 82672, "s": 82481, "text": "For such requirement NIO again provides an API known as FileLock which is used to provide lock over whole file or on a part of file,so that file or its part doesn't get shared or accessible." }, { "code": null, "e": 82869, "s": 82672, "text": "in order to provide or apply such lock we have to use FileChannel or AsynchronousFileChannel,which provides two methods lock() and tryLock()for this purpose.The lock provided may be of two types βˆ’" }, { "code": null, "e": 82979, "s": 82869, "text": "Exclusive Lock βˆ’ An exclusive lock prevents other programs from acquiring an overlapping lock of either type." }, { "code": null, "e": 83089, "s": 82979, "text": "Exclusive Lock βˆ’ An exclusive lock prevents other programs from acquiring an overlapping lock of either type." }, { "code": null, "e": 83265, "s": 83089, "text": "Shared Lock βˆ’ A shared lock prevents other concurrently-running programs from acquiring an overlapping exclusive lock, but does allow them to acquire overlapping shared locks." }, { "code": null, "e": 83441, "s": 83265, "text": "Shared Lock βˆ’ A shared lock prevents other concurrently-running programs from acquiring an overlapping exclusive lock, but does allow them to acquire overlapping shared locks." }, { "code": null, "e": 83485, "s": 83441, "text": "Methods used for obtaining lock over file βˆ’" }, { "code": null, "e": 83716, "s": 83485, "text": "lock() βˆ’ This method of FileChannel or AsynchronousFileChannel acquires an exclusive lock over a file associated with the given channel.Return type of this method is FileLock which is further used for monitoring the obtained lock." }, { "code": null, "e": 83947, "s": 83716, "text": "lock() βˆ’ This method of FileChannel or AsynchronousFileChannel acquires an exclusive lock over a file associated with the given channel.Return type of this method is FileLock which is further used for monitoring the obtained lock." }, { "code": null, "e": 84103, "s": 83947, "text": "lock(long position, long size, boolean shared) βˆ’ This method again is the overloaded method of lock method and is used to lock a particular part of a file." }, { "code": null, "e": 84259, "s": 84103, "text": "lock(long position, long size, boolean shared) βˆ’ This method again is the overloaded method of lock method and is used to lock a particular part of a file." }, { "code": null, "e": 84425, "s": 84259, "text": "tryLock() βˆ’ This method return a FileLock or a null if the lock could not be acquired and it attempts to acquire an explicitly exclusive lock on this channel's file." }, { "code": null, "e": 84591, "s": 84425, "text": "tryLock() βˆ’ This method return a FileLock or a null if the lock could not be acquired and it attempts to acquire an explicitly exclusive lock on this channel's file." }, { "code": null, "e": 84771, "s": 84591, "text": "tryLock(long position, long size, boolean shared) βˆ’ This method attempts to acquires a lock on the given region of this channel's file which may be an exclusive or of shared type." }, { "code": null, "e": 84951, "s": 84771, "text": "tryLock(long position, long size, boolean shared) βˆ’ This method attempts to acquires a lock on the given region of this channel's file which may be an exclusive or of shared type." }, { "code": null, "e": 85031, "s": 84951, "text": "acquiredBy() βˆ’ This method returns the channel on whose file lock was acquired." }, { "code": null, "e": 85111, "s": 85031, "text": "acquiredBy() βˆ’ This method returns the channel on whose file lock was acquired." }, { "code": null, "e": 85376, "s": 85111, "text": "position() βˆ’ This method returns the position within the file of the first byte of the locked region.A locked region need not be contained within, or even overlap, the actual underlying file, so the value returned by this method may exceed the file's current size." }, { "code": null, "e": 85641, "s": 85376, "text": "position() βˆ’ This method returns the position within the file of the first byte of the locked region.A locked region need not be contained within, or even overlap, the actual underlying file, so the value returned by this method may exceed the file's current size." }, { "code": null, "e": 85873, "s": 85641, "text": "size() βˆ’ This method returns the size of the locked region in bytes.A locked region need not be contained within, or even overlap, the actual underlying file, so the value returned by this method may exceed the file's current size." }, { "code": null, "e": 86105, "s": 85873, "text": "size() βˆ’ This method returns the size of the locked region in bytes.A locked region need not be contained within, or even overlap, the actual underlying file, so the value returned by this method may exceed the file's current size." }, { "code": null, "e": 86187, "s": 86105, "text": "isShared() βˆ’ This method is used to determine that whether lock is shared or not." }, { "code": null, "e": 86269, "s": 86187, "text": "isShared() βˆ’ This method is used to determine that whether lock is shared or not." }, { "code": null, "e": 86379, "s": 86269, "text": "overlaps(long position,long size) βˆ’ This method tells whether or not this lock overlaps the given lock range." }, { "code": null, "e": 86489, "s": 86379, "text": "overlaps(long position,long size) βˆ’ This method tells whether or not this lock overlaps the given lock range." }, { "code": null, "e": 86675, "s": 86489, "text": "isValid() βˆ’ This method tells whether or not the obtained lock is valid.A lock object remains valid until it is released or the associated file channel is closed, whichever comes first." }, { "code": null, "e": 86861, "s": 86675, "text": "isValid() βˆ’ This method tells whether or not the obtained lock is valid.A lock object remains valid until it is released or the associated file channel is closed, whichever comes first." }, { "code": null, "e": 87076, "s": 86861, "text": "release() βˆ’ Releases the obtained lock.If the lock object is valid then invoking this method releases the lock and renders the object invalid. If this lock object is invalid then invoking this method has no effect." }, { "code": null, "e": 87291, "s": 87076, "text": "release() βˆ’ Releases the obtained lock.If the lock object is valid then invoking this method releases the lock and renders the object invalid. If this lock object is invalid then invoking this method has no effect." }, { "code": null, "e": 87465, "s": 87291, "text": "close() βˆ’ This method invokes the release() method. It was added to the class so that it could be used in conjunction with the automatic resource management block construct." }, { "code": null, "e": 87639, "s": 87465, "text": "close() βˆ’ This method invokes the release() method. It was added to the class so that it could be used in conjunction with the automatic resource management block construct." }, { "code": null, "e": 87705, "s": 87639, "text": "Following example create lock over a file and write content to it" }, { "code": null, "e": 88851, "s": 87705, "text": "package com.java.nio;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.FileChannel;\nimport java.nio.channels.FileLock;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.nio.file.StandardOpenOption;\npublic class FileLockExample {\n public static void main(String[] args) throws IOException {\n String input = \"Demo text to be written in locked mode.\"; \n System.out.println(\"Input string to the test file is: \" + input); \n ByteBuffer buf = ByteBuffer.wrap(input.getBytes()); \n String fp = \"D:file.txt\"; \n Path pt = Paths.get(fp); \n FileChannel channel = FileChannel.open(pt, StandardOpenOption.WRITE,StandardOpenOption.APPEND); \n channel.position(channel.size() - 1); // position of a cursor at the end of file \n FileLock lock = channel.lock(); \n System.out.println(\"The Lock is shared: \" + lock.isShared()); \n channel.write(buf); \n channel.close(); // Releases the Lock \n System.out.println(\"Content Writing is complete. Therefore close the channel and release the lock.\"); \n PrintFileCreated.print(fp); \n } \n}" }, { "code": null, "e": 89491, "s": 88851, "text": "package com.java.nio;\nimport java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\npublic class PrintFileCreated {\n public static void print(String path) throws IOException { \n FileReader filereader = new FileReader(path); \n BufferedReader bufferedreader = new BufferedReader(filereader); \n String tr = bufferedreader.readLine(); \n System.out.println(\"The Content of testout.txt file is: \"); \n while (tr != null) { \n System.out.println(\" \" + tr); \n tr = bufferedreader.readLine(); \n } \n filereader.close(); \n bufferedreader.close(); \n } \n}" } ]
Mongoose | findByIdAndUpdate() Function
20 May, 2020 The findByIdAndUpdate() function is used to find a matching document, updates it according to the update arg, passing any options, and returns the found document (if any) to the callback. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter that, you can just 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 to Install mongoose module. You can install this package by using this command.npm install mongoose npm install mongoose After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose npm version mongoose After that, you can just 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 mongoose = require('mongoose'); // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true, useFindAndModify: false}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); // Find a document whose // user_id=5eb985d440bd2155e4d788e2 and update it// Updating name field of this user_id to name='Gourav'var user_id = '5eb985d440bd2155e4d788e2';User.findByIdAndUpdate(user_id, { name: 'Gourav' }, function (err, docs) { if (err){ console.log(err) } else{ console.log("Updated User : ", docs); }}); Steps to run the program: The project structure will look like this:Make sure you have installed mongoose module using following command:npm install mongooseBelow is the sample data in the database before the function is executed. You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:Run index.js file using below command:node index.jsAfter the function is executed, You can see in the database that the particular user is removed as shown below: The project structure will look like this: Make sure you have installed mongoose module using following command:npm install mongoose npm install mongoose Below is the sample data in the database before the function is executed. You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below: Run index.js file using below command:node index.js node index.js After the function is executed, You can see in the database that the particular user is removed as shown below: So this is how you can use the mongoose findByIdAndUpdate() function which finds a matching document, updates it according to the update arg, passing any options, and returns the found document (if any) to the callback. Mongoose MongoDB Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Spring Boot JpaRepository with Example Mongoose Populate() Method MongoDB - db.collection.Find() Method Aggregation in MongoDB MongoDB - Check the existence of the fields in the specified collection How to update Node.js and NPM to next version ? Installation of Node.js on Linux Node.js fs.readFileSync() Method Node.js fs.writeFile() Method How to install the previous version of node.js and npm ?
[ { "code": null, "e": 52, "s": 24, "text": "\n20 May, 2020" }, { "code": null, "e": 240, "s": 52, "text": "The findByIdAndUpdate() function is used to find a matching document, updates it according to the update arg, passing any options, and returns the found document (if any) to the callback." }, { "code": null, "e": 273, "s": 240, "text": "Installation of mongoose module:" }, { "code": null, "e": 669, "s": 273, "text": "You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter that, you can just 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": 792, "s": 669, "text": "You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongoose" }, { "code": null, "e": 813, "s": 792, "text": "npm install mongoose" }, { "code": null, "e": 940, "s": 813, "text": "After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose" }, { "code": null, "e": 961, "s": 940, "text": "npm version mongoose" }, { "code": null, "e": 1109, "s": 961, "text": "After that, you can just 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": 1123, "s": 1109, "text": "node index.js" }, { "code": null, "e": 1142, "s": 1123, "text": "Filename: index.js" }, { "code": "const mongoose = require('mongoose'); // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true, useFindAndModify: false}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); // Find a document whose // user_id=5eb985d440bd2155e4d788e2 and update it// Updating name field of this user_id to name='Gourav'var user_id = '5eb985d440bd2155e4d788e2';User.findByIdAndUpdate(user_id, { name: 'Gourav' }, function (err, docs) { if (err){ console.log(err) } else{ console.log(\"Updated User : \", docs); }});", "e": 1859, "s": 1142, "text": null }, { "code": null, "e": 1885, "s": 1859, "text": "Steps to run the program:" }, { "code": null, "e": 2360, "s": 1885, "text": "The project structure will look like this:Make sure you have installed mongoose module using following command:npm install mongooseBelow is the sample data in the database before the function is executed. You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:Run index.js file using below command:node index.jsAfter the function is executed, You can see in the database that the particular user is removed as shown below:" }, { "code": null, "e": 2403, "s": 2360, "text": "The project structure will look like this:" }, { "code": null, "e": 2493, "s": 2403, "text": "Make sure you have installed mongoose module using following command:npm install mongoose" }, { "code": null, "e": 2514, "s": 2493, "text": "npm install mongoose" }, { "code": null, "e": 2696, "s": 2514, "text": "Below is the sample data in the database before the function is executed. You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:" }, { "code": null, "e": 2748, "s": 2696, "text": "Run index.js file using below command:node index.js" }, { "code": null, "e": 2762, "s": 2748, "text": "node index.js" }, { "code": null, "e": 2874, "s": 2762, "text": "After the function is executed, You can see in the database that the particular user is removed as shown below:" }, { "code": null, "e": 3094, "s": 2874, "text": "So this is how you can use the mongoose findByIdAndUpdate() function which finds a matching document, updates it according to the update arg, passing any options, and returns the found document (if any) to the callback." }, { "code": null, "e": 3103, "s": 3094, "text": "Mongoose" }, { "code": null, "e": 3111, "s": 3103, "text": "MongoDB" }, { "code": null, "e": 3119, "s": 3111, "text": "Node.js" }, { "code": null, "e": 3136, "s": 3119, "text": "Web Technologies" }, { "code": null, "e": 3234, "s": 3136, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3273, "s": 3234, "text": "Spring Boot JpaRepository with Example" }, { "code": null, "e": 3300, "s": 3273, "text": "Mongoose Populate() Method" }, { "code": null, "e": 3338, "s": 3300, "text": "MongoDB - db.collection.Find() Method" }, { "code": null, "e": 3361, "s": 3338, "text": "Aggregation in MongoDB" }, { "code": null, "e": 3433, "s": 3361, "text": "MongoDB - Check the existence of the fields in the specified collection" }, { "code": null, "e": 3481, "s": 3433, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 3514, "s": 3481, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3547, "s": 3514, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 3577, "s": 3547, "text": "Node.js fs.writeFile() Method" } ]
Python - GUI Programming (Tkinter)
Python provides various options for developing graphical user interfaces (GUIs). Most important are listed below. Tkinter βˆ’ Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We would look this option in this chapter. Tkinter βˆ’ Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We would look this option in this chapter. wxPython βˆ’ This is an open-source Python interface for wxWindows http://wxpython.org. wxPython βˆ’ This is an open-source Python interface for wxWindows http://wxpython.org. JPython βˆ’ JPython is a Python port for Java which gives Python scripts seamless access to Java class libraries on the local machine http://www.jython.org. JPython βˆ’ JPython is a Python port for Java which gives Python scripts seamless access to Java class libraries on the local machine http://www.jython.org. There are many other interfaces available, which you can find them on the net. Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented interface to the Tk GUI toolkit. Creating a GUI application using Tkinter is an easy task. All you need to do is perform the following steps βˆ’ Import the Tkinter module. Import the Tkinter module. Create the GUI application main window. Create the GUI application main window. Add one or more of the above-mentioned widgets to the GUI application. Add one or more of the above-mentioned widgets to the GUI application. Enter the main event loop to take action against each event triggered by the user. Enter the main event loop to take action against each event triggered by the user. #!/usr/bin/python import Tkinter top = Tkinter.Tk() # Code to add widgets will go here... top.mainloop() This would create a following window βˆ’ Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI application. These controls are commonly called widgets. There are currently 15 types of widgets in Tkinter. We present these widgets as well as a brief description in the following table βˆ’ The Button widget is used to display buttons in your application. The Canvas widget is used to draw shapes, such as lines, ovals, polygons and rectangles, in your application. The Checkbutton widget is used to display a number of options as checkboxes. The user can select multiple options at a time. The Entry widget is used to display a single-line text field for accepting values from a user. The Frame widget is used as a container widget to organize other widgets. The Label widget is used to provide a single-line caption for other widgets. It can also contain images. The Listbox widget is used to provide a list of options to a user. The Menubutton widget is used to display menus in your application. The Menu widget is used to provide various commands to a user. These commands are contained inside Menubutton. The Message widget is used to display multiline text fields for accepting values from a user. The Radiobutton widget is used to display a number of options as radio buttons. The user can select only one option at a time. The Scale widget is used to provide a slider widget. The Scrollbar widget is used to add scrolling capability to various widgets, such as list boxes. The Text widget is used to display text in multiple lines. The Toplevel widget is used to provide a separate window container. The Spinbox widget is a variant of the standard Tkinter Entry widget, which can be used to select from a fixed number of values. A PanedWindow is a container widget that may contain any number of panes, arranged horizontally or vertically. A labelframe is a simple container widget. Its primary purpose is to act as a spacer or container for complex window layouts. This module is used to display message boxes in your applications. Let us study these widgets in detail βˆ’ Let us take a look at how some of their common attributes.such as sizes, colors and fonts are specified. Dimensions Dimensions Colors Colors Fonts Fonts Anchors Anchors Relief styles Relief styles Bitmaps Bitmaps Cursors Cursors Let us study them briefly βˆ’ All Tkinter widgets have access to specific geometry management methods, which have the purpose of organizing widgets throughout the parent widget area. Tkinter exposes the following geometry manager classes: pack, grid, and place. The pack() Method βˆ’ This geometry manager organizes widgets in blocks before placing them in the parent widget. The pack() Method βˆ’ This geometry manager organizes widgets in blocks before placing them in the parent widget. The grid() Method βˆ’ This geometry manager organizes widgets in a table-like structure in the parent widget. The grid() Method βˆ’ This geometry manager organizes widgets in a table-like structure in the parent widget. The place() Method βˆ’ This geometry manager organizes widgets by placing them in a specific position in the parent widget. The place() Method βˆ’ This geometry manager organizes widgets by placing them in a specific position in the parent widget. Let us study the geometry management methods briefly βˆ’
[ { "code": null, "e": 2492, "s": 2378, "text": "Python provides various options for developing graphical user interfaces (GUIs). Most important are listed below." }, { "code": null, "e": 2620, "s": 2492, "text": "Tkinter βˆ’ Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We would look this option in this chapter." }, { "code": null, "e": 2748, "s": 2620, "text": "Tkinter βˆ’ Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We would look this option in this chapter." }, { "code": null, "e": 2834, "s": 2748, "text": "wxPython βˆ’ This is an open-source Python interface for wxWindows http://wxpython.org." }, { "code": null, "e": 2920, "s": 2834, "text": "wxPython βˆ’ This is an open-source Python interface for wxWindows http://wxpython.org." }, { "code": null, "e": 3075, "s": 2920, "text": "JPython βˆ’ JPython is a Python port for Java which gives Python scripts seamless access to Java class libraries on the local machine http://www.jython.org." }, { "code": null, "e": 3230, "s": 3075, "text": "JPython βˆ’ JPython is a Python port for Java which gives Python scripts seamless access to Java class libraries on the local machine http://www.jython.org." }, { "code": null, "e": 3309, "s": 3230, "text": "There are many other interfaces available, which you can find them on the net." }, { "code": null, "e": 3525, "s": 3309, "text": "Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented interface to the Tk GUI toolkit." }, { "code": null, "e": 3635, "s": 3525, "text": "Creating a GUI application using Tkinter is an easy task. All you need to do is perform the following steps βˆ’" }, { "code": null, "e": 3662, "s": 3635, "text": "Import the Tkinter module." }, { "code": null, "e": 3689, "s": 3662, "text": "Import the Tkinter module." }, { "code": null, "e": 3729, "s": 3689, "text": "Create the GUI application main window." }, { "code": null, "e": 3769, "s": 3729, "text": "Create the GUI application main window." }, { "code": null, "e": 3840, "s": 3769, "text": "Add one or more of the above-mentioned widgets to the GUI application." }, { "code": null, "e": 3911, "s": 3840, "text": "Add one or more of the above-mentioned widgets to the GUI application." }, { "code": null, "e": 3994, "s": 3911, "text": "Enter the main event loop to take action against each event triggered by the user." }, { "code": null, "e": 4077, "s": 3994, "text": "Enter the main event loop to take action against each event triggered by the user." }, { "code": null, "e": 4184, "s": 4077, "text": "#!/usr/bin/python\n\nimport Tkinter\ntop = Tkinter.Tk()\n# Code to add widgets will go here...\ntop.mainloop()\n" }, { "code": null, "e": 4223, "s": 4184, "text": "This would create a following window βˆ’" }, { "code": null, "e": 4368, "s": 4223, "text": "Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI application. These controls are commonly called widgets." }, { "code": null, "e": 4501, "s": 4368, "text": "There are currently 15 types of widgets in Tkinter. We present these widgets as well as a brief description in the following table βˆ’" }, { "code": null, "e": 4567, "s": 4501, "text": "The Button widget is used to display buttons in your application." }, { "code": null, "e": 4677, "s": 4567, "text": "The Canvas widget is used to draw shapes, such as lines, ovals, polygons and rectangles, in your application." }, { "code": null, "e": 4802, "s": 4677, "text": "The Checkbutton widget is used to display a number of options as checkboxes. The user can select multiple options at a time." }, { "code": null, "e": 4897, "s": 4802, "text": "The Entry widget is used to display a single-line text field for accepting values from a user." }, { "code": null, "e": 4971, "s": 4897, "text": "The Frame widget is used as a container widget to organize other widgets." }, { "code": null, "e": 5076, "s": 4971, "text": "The Label widget is used to provide a single-line caption for other widgets. It can also contain images." }, { "code": null, "e": 5143, "s": 5076, "text": "The Listbox widget is used to provide a list of options to a user." }, { "code": null, "e": 5211, "s": 5143, "text": "The Menubutton widget is used to display menus in your application." }, { "code": null, "e": 5322, "s": 5211, "text": "The Menu widget is used to provide various commands to a user. These commands are contained inside Menubutton." }, { "code": null, "e": 5416, "s": 5322, "text": "The Message widget is used to display multiline text fields for accepting values from a user." }, { "code": null, "e": 5543, "s": 5416, "text": "The Radiobutton widget is used to display a number of options as radio buttons. The user can select only one option at a time." }, { "code": null, "e": 5596, "s": 5543, "text": "The Scale widget is used to provide a slider widget." }, { "code": null, "e": 5693, "s": 5596, "text": "The Scrollbar widget is used to add scrolling capability to various widgets, such as list boxes." }, { "code": null, "e": 5752, "s": 5693, "text": "The Text widget is used to display text in multiple lines." }, { "code": null, "e": 5820, "s": 5752, "text": "The Toplevel widget is used to provide a separate window container." }, { "code": null, "e": 5949, "s": 5820, "text": "The Spinbox widget is a variant of the standard Tkinter Entry widget, which can be used to select from a fixed number of values." }, { "code": null, "e": 6060, "s": 5949, "text": "A PanedWindow is a container widget that may contain any number of panes, arranged horizontally or vertically." }, { "code": null, "e": 6186, "s": 6060, "text": "A labelframe is a simple container widget. Its primary purpose is to act as a spacer or container for complex window layouts." }, { "code": null, "e": 6253, "s": 6186, "text": "This module is used to display message boxes in your applications." }, { "code": null, "e": 6292, "s": 6253, "text": "Let us study these widgets in detail βˆ’" }, { "code": null, "e": 6397, "s": 6292, "text": "Let us take a look at how some of their common attributes.such as sizes, colors and fonts are specified." }, { "code": null, "e": 6408, "s": 6397, "text": "Dimensions" }, { "code": null, "e": 6419, "s": 6408, "text": "Dimensions" }, { "code": null, "e": 6426, "s": 6419, "text": "Colors" }, { "code": null, "e": 6433, "s": 6426, "text": "Colors" }, { "code": null, "e": 6439, "s": 6433, "text": "Fonts" }, { "code": null, "e": 6445, "s": 6439, "text": "Fonts" }, { "code": null, "e": 6453, "s": 6445, "text": "Anchors" }, { "code": null, "e": 6461, "s": 6453, "text": "Anchors" }, { "code": null, "e": 6475, "s": 6461, "text": "Relief styles" }, { "code": null, "e": 6489, "s": 6475, "text": "Relief styles" }, { "code": null, "e": 6497, "s": 6489, "text": "Bitmaps" }, { "code": null, "e": 6505, "s": 6497, "text": "Bitmaps" }, { "code": null, "e": 6513, "s": 6505, "text": "Cursors" }, { "code": null, "e": 6521, "s": 6513, "text": "Cursors" }, { "code": null, "e": 6549, "s": 6521, "text": "Let us study them briefly βˆ’" }, { "code": null, "e": 6781, "s": 6549, "text": "All Tkinter widgets have access to specific geometry management methods, which have the purpose of organizing widgets throughout the parent widget area. Tkinter exposes the following geometry manager classes: pack, grid, and place." }, { "code": null, "e": 6893, "s": 6781, "text": "The pack() Method βˆ’ This geometry manager organizes widgets in blocks before placing them in the parent widget." }, { "code": null, "e": 7005, "s": 6893, "text": "The pack() Method βˆ’ This geometry manager organizes widgets in blocks before placing them in the parent widget." }, { "code": null, "e": 7113, "s": 7005, "text": "The grid() Method βˆ’ This geometry manager organizes widgets in a table-like structure in the parent widget." }, { "code": null, "e": 7221, "s": 7113, "text": "The grid() Method βˆ’ This geometry manager organizes widgets in a table-like structure in the parent widget." }, { "code": null, "e": 7343, "s": 7221, "text": "The place() Method βˆ’ This geometry manager organizes widgets by placing them in a specific position in the parent widget." }, { "code": null, "e": 7465, "s": 7343, "text": "The place() Method βˆ’ This geometry manager organizes widgets by placing them in a specific position in the parent widget." } ]
Bash Scripting – Substring
24 May, 2022 sIn this article, we will discuss how to write a bash script to extract substring from a string. There are various ways to obtain substring based on the index of characters in the string: Using cut command Using Bash substring Using expr substr command Using awk command Cut command is used to perform the slicing operation to get the desired result. Syntax: cut [option] range [string/filename] -c option is used to cut out the string by character. It is necessary to specify list or range of character numbers of otherwise it gives an error with this option. In range, specify the range of indexes of original to get the substring. It uses 1-based index(indexing starts from 1) system. Example 1: For demonstration purposes let’s extract the character’s last 0 in string β€˜01010string’. Code: cut -c 6-11<<< '01010string' <<< is known as here-string. Using this, one can pass a pre-made string of text to a program. We have specified the range 6-11 because 6 is the starting index and 11 is the ending index of our desired result. Output: Example 2: Now extract characters before β€˜s’ in string β€˜01010string’. Code: cut -c 1-5<<< '01010string' We have specified the range 1-5, because 1 is the starting index and 5 is the ending index of our desired result. Output: Syntax: ${VAR:start_index:length} It uses 0-based index system. Example 1: For demonstration, we will extract the substring from a string β€˜My name is ROMY’ from index 11 to index 15. For 11 to 15 index, length of substring will become 4. Code: STR="My name is ROMY" echo ${STR:11:4} Output: Example 2: Extract the string that lie before index 10. As this method uses 0 based index system, length of desired string will be 10. Code: STR="My name is ROMY" echo ${STR:0:10} Output: It is used to perform: addition, subtraction, multiplication, division and modulus like operations. Evaluation of regular expressions, string operations like substring. It uses 1-based index system. Example 1: For demonstration, we will extract the substring from a string β€˜My name is ROMY’ from index 12 to index 16. For 12 to 16 index, the length of the substring will become 4. Syntax: expr substr <input_string> <start_index> <length> Code: expr substr "My name is ROMY" 12 4 Output: Example 2: Extract a substring from the start of a string start till index 10. As this method uses 1-based index system, the length of the string till index 10 is 9. Code: expr substr "My name is ROMY" 1 9 Output: It is a scripting language used for manipulating data. It does not require compilation and allows string functions, variable, etc. It has a built-in substr() function which can be used directly to get the substring. The substr(s, i, n) function accepts three arguments. s : The input string i : The start index of the substring n : The length of the substring. It uses 1-based index system. Syntax: awk '{print substr($var,start_index, length)}' Example 1: Extract substring of length 5 starting from index 12. Code: awk '{print substr($0, 12, 5)}' <<< 'My name is ROMY' Output: Example 2: Extract string of length 10, starting from index 1. Code: awk '{print substr($0, 1, 10)}' <<< 'My name is ROMY' Output: There are various ways to obtain substring based on the patterns of the string: using cut command using awk command For demonstration, take input strings to be comma-separated values: β€œRomy, Pushkar, Kareena, Katrina”. (-d ,) option is to be used with cut command to tell the command that the input string is comma separated values. -f option tell the cut command to extract the string based on the field like (-f 3) is for third field in the string. Syntax: cut [option] field_position <<< "comma_seperated_string" Code: cut -d, -f 3 <<< β€œRomy,Pushkar,Kareena,Katrina”. This will extract third field. Output: Syntax: awk [option] field_separator β€˜{print $field_position}’ <<< β€œinput_string” Code: To extract third field from string awk -F’,’ β€˜{print $1}’ <<< β€œRomy,Pushkar,Kareena,Katrina” Output: It is not necessary that the input string is always a comma-separated value. In this method, we will see the method to obtain substring that lies between two patterns in a string. This problem can be solved using awk command. sub(/.*start/, β€œβ€) – It removes everything before beginning till β€˜start’. sub(/end.*/, β€œβ€) – It removes everything from β€œend” along with end. Syntax: awk β€˜{ sub(/.*BEGIN:/, β€œβ€); sub(/END:.*/, β€œβ€); print }’ <<< β€œinput_string” Code: STR="Hello!! My name is ROMY kumari" awk '{ sub(/.*!!/, ""); sub(/kumari.*/, ""); print }' <<< "$STR" Output: surinderdawra388 Bash-Script Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 nohup Command in Linux with Examples mv command in Linux with examples chmod command in Linux with examples Array Basics in Shell Scripting | Set 1 Introduction to Linux Operating System Basic Operators in Shell Scripting
[ { "code": null, "e": 28, "s": 0, "text": "\n24 May, 2022" }, { "code": null, "e": 125, "s": 28, "text": "sIn this article, we will discuss how to write a bash script to extract substring from a string." }, { "code": null, "e": 216, "s": 125, "text": "There are various ways to obtain substring based on the index of characters in the string:" }, { "code": null, "e": 234, "s": 216, "text": "Using cut command" }, { "code": null, "e": 255, "s": 234, "text": "Using Bash substring" }, { "code": null, "e": 281, "s": 255, "text": "Using expr substr command" }, { "code": null, "e": 299, "s": 281, "text": "Using awk command" }, { "code": null, "e": 379, "s": 299, "text": "Cut command is used to perform the slicing operation to get the desired result." }, { "code": null, "e": 387, "s": 379, "text": "Syntax:" }, { "code": null, "e": 424, "s": 387, "text": "cut [option] range [string/filename]" }, { "code": null, "e": 717, "s": 424, "text": "-c option is used to cut out the string by character. It is necessary to specify list or range of character numbers of otherwise it gives an error with this option. In range, specify the range of indexes of original to get the substring. It uses 1-based index(indexing starts from 1) system." }, { "code": null, "e": 817, "s": 717, "text": "Example 1: For demonstration purposes let’s extract the character’s last 0 in string β€˜01010string’." }, { "code": null, "e": 823, "s": 817, "text": "Code:" }, { "code": null, "e": 852, "s": 823, "text": "cut -c 6-11<<< '01010string'" }, { "code": null, "e": 1061, "s": 852, "text": "<<< is known as here-string. Using this, one can pass a pre-made string of text to a program. We have specified the range 6-11 because 6 is the starting index and 11 is the ending index of our desired result." }, { "code": null, "e": 1069, "s": 1061, "text": "Output:" }, { "code": null, "e": 1139, "s": 1069, "text": "Example 2: Now extract characters before β€˜s’ in string β€˜01010string’." }, { "code": null, "e": 1145, "s": 1139, "text": "Code:" }, { "code": null, "e": 1173, "s": 1145, "text": "cut -c 1-5<<< '01010string'" }, { "code": null, "e": 1288, "s": 1173, "text": " We have specified the range 1-5, because 1 is the starting index and 5 is the ending index of our desired result." }, { "code": null, "e": 1296, "s": 1288, "text": "Output:" }, { "code": null, "e": 1304, "s": 1296, "text": "Syntax:" }, { "code": null, "e": 1330, "s": 1304, "text": "${VAR:start_index:length}" }, { "code": null, "e": 1360, "s": 1330, "text": "It uses 0-based index system." }, { "code": null, "e": 1534, "s": 1360, "text": "Example 1: For demonstration, we will extract the substring from a string β€˜My name is ROMY’ from index 11 to index 15. For 11 to 15 index, length of substring will become 4." }, { "code": null, "e": 1540, "s": 1534, "text": "Code:" }, { "code": null, "e": 1579, "s": 1540, "text": "STR=\"My name is ROMY\"\necho ${STR:11:4}" }, { "code": null, "e": 1587, "s": 1579, "text": "Output:" }, { "code": null, "e": 1723, "s": 1587, "text": "Example 2: Extract the string that lie before index 10. As this method uses 0 based index system, length of desired string will be 10." }, { "code": null, "e": 1729, "s": 1723, "text": "Code:" }, { "code": null, "e": 1768, "s": 1729, "text": "STR=\"My name is ROMY\"\necho ${STR:0:10}" }, { "code": null, "e": 1776, "s": 1768, "text": "Output:" }, { "code": null, "e": 1799, "s": 1776, "text": "It is used to perform:" }, { "code": null, "e": 1876, "s": 1799, "text": "addition, subtraction, multiplication, division and modulus like operations." }, { "code": null, "e": 1945, "s": 1876, "text": "Evaluation of regular expressions, string operations like substring." }, { "code": null, "e": 1975, "s": 1945, "text": "It uses 1-based index system." }, { "code": null, "e": 2157, "s": 1975, "text": "Example 1: For demonstration, we will extract the substring from a string β€˜My name is ROMY’ from index 12 to index 16. For 12 to 16 index, the length of the substring will become 4." }, { "code": null, "e": 2165, "s": 2157, "text": "Syntax:" }, { "code": null, "e": 2215, "s": 2165, "text": "expr substr <input_string> <start_index> <length>" }, { "code": null, "e": 2221, "s": 2215, "text": "Code:" }, { "code": null, "e": 2256, "s": 2221, "text": "expr substr \"My name is ROMY\" 12 4" }, { "code": null, "e": 2264, "s": 2256, "text": "Output:" }, { "code": null, "e": 2430, "s": 2264, "text": "Example 2: Extract a substring from the start of a string start till index 10. As this method uses 1-based index system, the length of the string till index 10 is 9." }, { "code": null, "e": 2436, "s": 2430, "text": "Code:" }, { "code": null, "e": 2470, "s": 2436, "text": "expr substr \"My name is ROMY\" 1 9" }, { "code": null, "e": 2478, "s": 2470, "text": "Output:" }, { "code": null, "e": 2695, "s": 2478, "text": "It is a scripting language used for manipulating data. It does not require compilation and allows string functions, variable, etc. It has a built-in substr() function which can be used directly to get the substring. " }, { "code": null, "e": 2749, "s": 2695, "text": "The substr(s, i, n) function accepts three arguments." }, { "code": null, "e": 2770, "s": 2749, "text": "s : The input string" }, { "code": null, "e": 2807, "s": 2770, "text": "i : The start index of the substring" }, { "code": null, "e": 2840, "s": 2807, "text": "n : The length of the substring." }, { "code": null, "e": 2870, "s": 2840, "text": "It uses 1-based index system." }, { "code": null, "e": 2878, "s": 2870, "text": "Syntax:" }, { "code": null, "e": 2925, "s": 2878, "text": "awk '{print substr($var,start_index, length)}'" }, { "code": null, "e": 2990, "s": 2925, "text": "Example 1: Extract substring of length 5 starting from index 12." }, { "code": null, "e": 2996, "s": 2990, "text": "Code:" }, { "code": null, "e": 3050, "s": 2996, "text": "awk '{print substr($0, 12, 5)}' <<< 'My name is ROMY'" }, { "code": null, "e": 3058, "s": 3050, "text": "Output:" }, { "code": null, "e": 3121, "s": 3058, "text": "Example 2: Extract string of length 10, starting from index 1." }, { "code": null, "e": 3127, "s": 3121, "text": "Code:" }, { "code": null, "e": 3181, "s": 3127, "text": "awk '{print substr($0, 1, 10)}' <<< 'My name is ROMY'" }, { "code": null, "e": 3189, "s": 3181, "text": "Output:" }, { "code": null, "e": 3269, "s": 3189, "text": "There are various ways to obtain substring based on the patterns of the string:" }, { "code": null, "e": 3287, "s": 3269, "text": "using cut command" }, { "code": null, "e": 3305, "s": 3287, "text": "using awk command" }, { "code": null, "e": 3640, "s": 3305, "text": "For demonstration, take input strings to be comma-separated values: β€œRomy, Pushkar, Kareena, Katrina”. (-d ,) option is to be used with cut command to tell the command that the input string is comma separated values. -f option tell the cut command to extract the string based on the field like (-f 3) is for third field in the string." }, { "code": null, "e": 3648, "s": 3640, "text": "Syntax:" }, { "code": null, "e": 3705, "s": 3648, "text": "cut [option] field_position <<< \"comma_seperated_string\"" }, { "code": null, "e": 3711, "s": 3705, "text": "Code:" }, { "code": null, "e": 3760, "s": 3711, "text": "cut -d, -f 3 <<< β€œRomy,Pushkar,Kareena,Katrina”." }, { "code": null, "e": 3791, "s": 3760, "text": "This will extract third field." }, { "code": null, "e": 3799, "s": 3791, "text": "Output:" }, { "code": null, "e": 3807, "s": 3799, "text": "Syntax:" }, { "code": null, "e": 3881, "s": 3807, "text": "awk [option] field_separator β€˜{print $field_position}’ <<< β€œinput_string”" }, { "code": null, "e": 3887, "s": 3881, "text": "Code:" }, { "code": null, "e": 3922, "s": 3887, "text": "To extract third field from string" }, { "code": null, "e": 3980, "s": 3922, "text": "awk -F’,’ β€˜{print $1}’ <<< β€œRomy,Pushkar,Kareena,Katrina”" }, { "code": null, "e": 3988, "s": 3980, "text": "Output:" }, { "code": null, "e": 4065, "s": 3988, "text": "It is not necessary that the input string is always a comma-separated value." }, { "code": null, "e": 4214, "s": 4065, "text": "In this method, we will see the method to obtain substring that lies between two patterns in a string. This problem can be solved using awk command." }, { "code": null, "e": 4288, "s": 4214, "text": "sub(/.*start/, β€œβ€) – It removes everything before beginning till β€˜start’." }, { "code": null, "e": 4356, "s": 4288, "text": "sub(/end.*/, β€œβ€) – It removes everything from β€œend” along with end." }, { "code": null, "e": 4364, "s": 4356, "text": "Syntax:" }, { "code": null, "e": 4439, "s": 4364, "text": "awk β€˜{ sub(/.*BEGIN:/, β€œβ€); sub(/END:.*/, β€œβ€); print }’ <<< β€œinput_string”" }, { "code": null, "e": 4445, "s": 4439, "text": "Code:" }, { "code": null, "e": 4547, "s": 4445, "text": "STR=\"Hello!! My name is ROMY kumari\"\nawk '{ sub(/.*!!/, \"\"); sub(/kumari.*/, \"\"); print }' <<< \"$STR\"" }, { "code": null, "e": 4555, "s": 4547, "text": "Output:" }, { "code": null, "e": 4572, "s": 4555, "text": "surinderdawra388" }, { "code": null, "e": 4584, "s": 4572, "text": "Bash-Script" }, { "code": null, "e": 4591, "s": 4584, "text": "Picked" }, { "code": null, "e": 4602, "s": 4591, "text": "Linux-Unix" }, { "code": null, "e": 4700, "s": 4602, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4726, "s": 4700, "text": "Docker - COPY Instruction" }, { "code": null, "e": 4761, "s": 4726, "text": "scp command in Linux with Examples" }, { "code": null, "e": 4798, "s": 4761, "text": "chown command in Linux with Examples" }, { "code": null, "e": 4827, "s": 4798, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 4864, "s": 4827, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 4898, "s": 4864, "text": "mv command in Linux with examples" }, { "code": null, "e": 4935, "s": 4898, "text": "chmod command in Linux with examples" }, { "code": null, "e": 4975, "s": 4935, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 5014, "s": 4975, "text": "Introduction to Linux Operating System" } ]
NPDA for accepting the language L = {am b(2m) | m>=1}
08 Jun, 2022 Prerequisite – Pushdown automata, Pushdown automata acceptance by final state Problem – Design a non deterministic PDA for accepting the language L = {[Tex]b^{2m} [/Tex]: m>=1}, i.e., L = {abb, aabbbb, aaabbbbbb, aaaabbbbbbbb, ......} In each of the string, the number of a’s are followed by double number of b’s. Explanation – Here, we need to maintain the order of a’s and b’s.That is, all the a’s are coming first and then all the b’s are coming. Thus, we need a stack along with the state diagram. The count of a’s and b’s is maintained by the stack.Here, the number of b’s are exactly double of the number of a’s. We will take 2 stack alphabets: = { a, z } Where, = set of all the stack alphabet z = stack start symbol Approach used in the construction of PDA – As we want to design a NPDA, thus every time β€˜a’ comes before β€˜b’. When β€˜a’ comes then push it in stack and if again β€˜a’ comes then also push it. After that, when β€˜b’ comes then pop one β€˜a’ from the stack. But we do this popping operation for alternate position of b’s, i.e., for two b’s we pop one β€˜a’ and for four b’s we pop two β€˜a’. So, at the end if the stack becomes empty then we can say that the string is accepted by the PDA. Stack transition functions – (q0, a, z) (q0, az)(q0, a, a) (q0, aa)[ Indicates no operation only state change ](q0, b, a) (q1, a) [ Indicates pop operation for alternate 'b'] (q1, b, a) (q2, ) [ Indicates no operation only state change ] (q2, b, a) (q1, a) [ Indicates pop operation for alternate 'b'] (q1, b, a) (q2, ) (q2, , z) (qf, z) Where, q0 = Initial state qf = Final state = indicates pop operation So, this is our required non deterministic PDA for accepting the language L = {[Tex]b^{2m} [/Tex]: m>=1}. simmytarika5 GATE CS Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS Difference between DFA and NFA Boyer-Moore Majority Voting Algorithm Variation of Turing Machine Design 101 sequence detector (Mealy machine) Post Correspondence Problem
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Jun, 2022" }, { "code": null, "e": 132, "s": 53, "text": "Prerequisite – Pushdown automata, Pushdown automata acceptance by final state " }, { "code": null, "e": 240, "s": 132, "text": "Problem – Design a non deterministic PDA for accepting the language L = {[Tex]b^{2m} [/Tex]: m>=1}, i.e.," }, { "code": null, "e": 292, "s": 240, "text": "L = {abb, aabbbb, aaabbbbbb, aaaabbbbbbbb, ......} " }, { "code": null, "e": 372, "s": 292, "text": "In each of the string, the number of a’s are followed by double number of b’s. " }, { "code": null, "e": 709, "s": 372, "text": "Explanation – Here, we need to maintain the order of a’s and b’s.That is, all the a’s are coming first and then all the b’s are coming. Thus, we need a stack along with the state diagram. The count of a’s and b’s is maintained by the stack.Here, the number of b’s are exactly double of the number of a’s. We will take 2 stack alphabets:" }, { "code": null, "e": 722, "s": 709, "text": " = { a, z } " }, { "code": null, "e": 785, "s": 722, "text": "Where, = set of all the stack alphabet z = stack start symbol " }, { "code": null, "e": 1263, "s": 785, "text": "Approach used in the construction of PDA – As we want to design a NPDA, thus every time β€˜a’ comes before β€˜b’. When β€˜a’ comes then push it in stack and if again β€˜a’ comes then also push it. After that, when β€˜b’ comes then pop one β€˜a’ from the stack. But we do this popping operation for alternate position of b’s, i.e., for two b’s we pop one β€˜a’ and for four b’s we pop two β€˜a’. So, at the end if the stack becomes empty then we can say that the string is accepted by the PDA. " }, { "code": null, "e": 1292, "s": 1263, "text": "Stack transition functions –" }, { "code": null, "e": 1622, "s": 1292, "text": "(q0, a, z) (q0, az)(q0, a, a) (q0, aa)[ Indicates no operation only state change ](q0, b, a) (q1, a) [ Indicates pop operation for alternate 'b'] (q1, b, a) (q2, ) [ Indicates no operation only state change ] (q2, b, a) (q1, a) [ Indicates pop operation for alternate 'b'] (q1, b, a) (q2, ) (q2, , z) (qf, z) " }, { "code": null, "e": 1800, "s": 1622, "text": "Where, q0 = Initial state qf = Final state = indicates pop operation So, this is our required non deterministic PDA for accepting the language L = {[Tex]b^{2m} [/Tex]: m>=1}." }, { "code": null, "e": 1813, "s": 1800, "text": "simmytarika5" }, { "code": null, "e": 1821, "s": 1813, "text": "GATE CS" }, { "code": null, "e": 1854, "s": 1821, "text": "Theory of Computation & Automata" }, { "code": null, "e": 1952, "s": 1854, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1972, "s": 1952, "text": "Layers of OSI Model" }, { "code": null, "e": 1996, "s": 1972, "text": "ACID Properties in DBMS" }, { "code": null, "e": 2009, "s": 1996, "text": "TCP/IP Model" }, { "code": null, "e": 2036, "s": 2009, "text": "Types of Operating Systems" }, { "code": null, "e": 2057, "s": 2036, "text": "Normal Forms in DBMS" }, { "code": null, "e": 2088, "s": 2057, "text": "Difference between DFA and NFA" }, { "code": null, "e": 2126, "s": 2088, "text": "Boyer-Moore Majority Voting Algorithm" }, { "code": null, "e": 2154, "s": 2126, "text": "Variation of Turing Machine" }, { "code": null, "e": 2199, "s": 2154, "text": "Design 101 sequence detector (Mealy machine)" } ]
Table Partitioning in Cassandra
31 Aug, 2020 In this article, we are going to cover how we can our data access on the basis of partitioning and how we can store our data uniquely in a cluster. Let’s discuss one by one. Pre-requisite β€” Data Distribution Table Partitioning :In table partitioning, data can be distributed on the basis of the partition key. If you did not specify any partitioning key then it might be the chance of losing data. And It will be difficult to access data as per requirement. Example :Let’s consider if your requirement where you want to query user data by the first name. Now, first, you have to create a table where the role of the partitioning key is very important. CREATE TABLE User_data_by_first_name ( Usr_id UUID, first_name text, last_name text, primary key (first_name) ); Let’s insert some data for the above-created table. Insert into User_data_by_id(Usr_id, first_name, last_name) values(uuid(), 'Ashish', 'A'); Insert into User_data_by_id(Usr_id, first_name, last_name) values(uuid(), 'Ashish', 'A'); Insert into User_data_by_id(Usr_id, first_name, last_name) values(uuid(), 'Ashish', 'B'); Now, if you want to read data then used the following cqlsh query. select * from User_data_by_id; Output : In the above example, If you have specified it’s partitioning key by the first name then it is not the recommended way to specify the only first name as partitioning key. Otherwise, it might be a chance not uniquely identified your data and your data will be lost if you have multiple entries with same name. Now, to resolve this issue specify Usr_id and first_name as the partitioning key. CREATE TABLE User_data_by_first_name_modify ( Usr_id UUID, first_name text, last_name text, primary key (first_name, Usr_id) ); Now, Insert the same data as you have to insert for User_data_by_first_name. Insert into User_data_by_first_name_modify(Usr_id, first_name, last_name) values(uuid(), 'Ashish', 'A'); Insert into User_data_by_first_name_modify(Usr_id, first_name, last_name) values(uuid(), 'Ashish', 'A'); Insert into User_data_by_first_name_modify(Usr_id, first_name, last_name) values(uuid(), 'Ashish', 'B'); Now, If you will read your data then it will uniquely be identified and your data will be not lost. select * from User_data_by_first_name_modify; Output : Apache NoSQL DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Functional dependencies in DBMS MySQL | Regular expressions (Regexp) Difference between OLAP and OLTP in DBMS What is Temporary Table in SQL? Difference between Where and Having Clause in SQL SQL | DDL, DML, TCL and DCL Introduction of Relational Algebra in DBMS Relational Model in DBMS Difference between Star Schema and Snowflake Schema Difference between File System and DBMS
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Aug, 2020" }, { "code": null, "e": 202, "s": 28, "text": "In this article, we are going to cover how we can our data access on the basis of partitioning and how we can store our data uniquely in a cluster. Let’s discuss one by one." }, { "code": null, "e": 236, "s": 202, "text": "Pre-requisite β€” Data Distribution" }, { "code": null, "e": 486, "s": 236, "text": "Table Partitioning :In table partitioning, data can be distributed on the basis of the partition key. If you did not specify any partitioning key then it might be the chance of losing data. And It will be difficult to access data as per requirement." }, { "code": null, "e": 680, "s": 486, "text": "Example :Let’s consider if your requirement where you want to query user data by the first name. Now, first, you have to create a table where the role of the partitioning key is very important." }, { "code": null, "e": 793, "s": 680, "text": "CREATE TABLE User_data_by_first_name\n(\nUsr_id UUID,\nfirst_name text,\nlast_name text,\nprimary key (first_name)\n);" }, { "code": null, "e": 845, "s": 793, "text": "Let’s insert some data for the above-created table." }, { "code": null, "e": 1118, "s": 845, "text": "Insert into User_data_by_id(Usr_id, first_name, last_name) \nvalues(uuid(), 'Ashish', 'A');\nInsert into User_data_by_id(Usr_id, first_name, last_name) \nvalues(uuid(), 'Ashish', 'A');\nInsert into User_data_by_id(Usr_id, first_name, last_name) \nvalues(uuid(), 'Ashish', 'B');" }, { "code": null, "e": 1185, "s": 1118, "text": "Now, if you want to read data then used the following cqlsh query." }, { "code": null, "e": 1216, "s": 1185, "text": "select * from User_data_by_id;" }, { "code": null, "e": 1225, "s": 1216, "text": "Output :" }, { "code": null, "e": 1534, "s": 1225, "text": "In the above example, If you have specified it’s partitioning key by the first name then it is not the recommended way to specify the only first name as partitioning key. Otherwise, it might be a chance not uniquely identified your data and your data will be lost if you have multiple entries with same name." }, { "code": null, "e": 1616, "s": 1534, "text": "Now, to resolve this issue specify Usr_id and first_name as the partitioning key." }, { "code": null, "e": 1744, "s": 1616, "text": "CREATE TABLE User_data_by_first_name_modify\n(\nUsr_id UUID,\nfirst_name text,\nlast_name text,\nprimary key (first_name, Usr_id)\n);" }, { "code": null, "e": 1821, "s": 1744, "text": "Now, Insert the same data as you have to insert for User_data_by_first_name." }, { "code": null, "e": 2139, "s": 1821, "text": "Insert into User_data_by_first_name_modify(Usr_id, first_name, last_name) \nvalues(uuid(), 'Ashish', 'A');\nInsert into User_data_by_first_name_modify(Usr_id, first_name, last_name) \nvalues(uuid(), 'Ashish', 'A');\nInsert into User_data_by_first_name_modify(Usr_id, first_name, last_name) \nvalues(uuid(), 'Ashish', 'B');" }, { "code": null, "e": 2239, "s": 2139, "text": "Now, If you will read your data then it will uniquely be identified and your data will be not lost." }, { "code": null, "e": 2285, "s": 2239, "text": "select * from User_data_by_first_name_modify;" }, { "code": null, "e": 2294, "s": 2285, "text": "Output :" }, { "code": null, "e": 2301, "s": 2294, "text": "Apache" }, { "code": null, "e": 2307, "s": 2301, "text": "NoSQL" }, { "code": null, "e": 2312, "s": 2307, "text": "DBMS" }, { "code": null, "e": 2317, "s": 2312, "text": "DBMS" }, { "code": null, "e": 2415, "s": 2317, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2456, "s": 2415, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 2493, "s": 2456, "text": "MySQL | Regular expressions (Regexp)" }, { "code": null, "e": 2534, "s": 2493, "text": "Difference between OLAP and OLTP in DBMS" }, { "code": null, "e": 2566, "s": 2534, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 2616, "s": 2566, "text": "Difference between Where and Having Clause in SQL" }, { "code": null, "e": 2644, "s": 2616, "text": "SQL | DDL, DML, TCL and DCL" }, { "code": null, "e": 2687, "s": 2644, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 2712, "s": 2687, "text": "Relational Model in DBMS" }, { "code": null, "e": 2764, "s": 2712, "text": "Difference between Star Schema and Snowflake Schema" } ]
Data types in Java
31 May, 2022 Data types are different sizes and values that can be stored in the variable that is made as per convenience and circumstances to cover up all test cases. Also, let us cover up other important ailments that there are majorly two types of languages that are as follows: First, one is a Statically typed language where each variable and expression type is already known at compile time. Once a variable is declared to be of a certain data type, it cannot hold values of other data types. For example C, C++, Java.The other is Dynamically typed languages. These languages can receive different data types over time. For example Ruby, Python First, one is a Statically typed language where each variable and expression type is already known at compile time. Once a variable is declared to be of a certain data type, it cannot hold values of other data types. For example C, C++, Java. The other is Dynamically typed languages. These languages can receive different data types over time. For example Ruby, Python Java is statically typed and also a strongly typed language because, in Java, each type of data (such as integer, character, hexadecimal, packed decimal, and so forth) is predefined as part of the programming language and all constants or variables defined for a given program must be described with one of the data types. Java has two categories in which data types are segregated Primitive Data Type: such as boolean, char, int, short, byte, long, float, and doubleNon-Primitive Data Type or Object Data type: such as String, Array, etc. Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double Non-Primitive Data Type or Object Data type: such as String, Array, etc. Primitive data are only single values and have no special capabilities. There are 8 primitive data types. They are depicted below in tabular format below as follows: 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. Let us discuss and implement each one of the following data types that are as follows: Boolean data type represents only one bit of information either true or false which is intended to represent the two truth values of logic and Boolean algebra, but the size of the boolean data type is virtual machine-dependent. Values of type boolean are not converted implicitly or explicitly (with casts) to any other type. But the programmer can easily write conversion code. Syntax: boolean booleanVar; Size: Virtual machine dependent Values: Boolean such as true, false Default Value: false Example: Java // Java Program to Demonstrate Boolean Primitive DataType // Classclass GFG { // Main driver method public static void main(String args[]) { //Boolean data type is a data type that has one of two possible values (usually denoted true and false). // Setting boolean to false and true initially boolean a = false; boolean b = true; // If condition holds if (b == true){ // Print statement System.out.println("Hi Geek"); } // If condition holds if(a == false){ // Print statement System.out.println("Hello Geek"); } }} Output Hi Geek Hello Geek The byte data type is an 8-bit signed two’s complement integer. The byte data type is useful for saving memory in large arrays. Syntax: byte byteVar; Size: 1 byte (8 bits) Values: -128 to 127 Default Value: 0 Example: Java // Java Program to demonstrate Byte Data Type // Classclass GFG { // Main driver method public static void main(String args[]) { byte a = 126; // byte is 8 bit value System.out.println(a); a++; System.out.println(a); // It overflows here because // byte can hold values from -128 to 127 a++; System.out.println(a); // Looping back within the range a++; System.out.println(a); }} 126 127 -128 -127 The short data type is a 16-bit signed two’s complement integer. Similar to byte, use a short to save memory in large arrays, in situations where the memory savings actually matters. Syntax: short shortVar; Size: 2 byte (16 bits) Values: -32, 768 to 32, 767 (inclusive) Default Value: 0 It is a 32-bit signed two’s complement integer. Syntax: int intVar; Size: 4 byte ( 32 bits ) Values: -2, 147, 483, 648 to 2, 147, 483, 647 (inclusive) Note: The default value is β€˜0’ Remember: In Java SE 8 and later, we can use the int data type to represent an unsigned 32-bit integer, which has a value in the range [0, 232-1]. Use the Integer class to use the int data type as an unsigned integer. The range of a long is quite large. The long data type is a 64-bit two’s complement integer and is useful for those occasions where an int type is not large enough to hold the desired value. Syntax: long longVar; Size: 8 byte (64 bits) Values: {-9, 223, 372, 036, 854, 775, 808} to {9, 223, 372, 036, 854, 775, 807} (inclusive) Note: The default value is β€˜0’. Remember: In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1. The Long class also contains methods like comparing Unsigned, divide Unsigned, etc to support arithmetic operations for unsigned long. The float data type is a single-precision 32-bit IEEE 754 floating-point. Use a float (instead of double) if you need to save memory in large arrays of floating-point numbers. Syntax: float floatVar; Size: 4 byte (32 bits) Values: upto 7 decimal digits Note: The default value is β€˜0.0’. Example: Java // Java Program to Illustrate Float Primitive Data Type // Importing required classesimport java.io.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing float value // float value1 = 9.87; // Print statement // System.out.println(value1); float value2 = 9.87f; System.out.println(value2); }} 9.87 If we uncomment lines no 14,15,16 then the output would have been totally different as we would have faced an error. The double data type is a double-precision 64-bit IEEE 754 floating-point. For decimal values, this data type is generally the default choice. Syntax: double doubleVar; Size: 8 bytes or 64 bits Values: Upto 16 decimal digits Note: The default value is taken as β€˜0.0’. Both float and double data types were designed especially for scientific calculations, where approximation errors are acceptable. If accuracy is the most prior concern then, it is recommended not to use these data types and use BigDecimal class instead. It is recommended to go through rounding off errors in java. The char data type is a single 16-bit Unicode character. Syntax: char charVar; Size: 2 byte (16 bits) Values: β€˜\u0000’ (0) to β€˜\uffff’ (65535) Note: The default value is β€˜\u0000’ You must be wondering why is the size of char 2 bytes in Java? So, in other languages like C/C++ uses only ASCII characters, and to represent all ASCII characters 8-bits is enough. But java uses the Unicode system not the ASCII code system and to represent the Unicode system 8 bits is not enough to represent all characters so java uses 2 bytes for characters. Unicode defines a fully international character set that can represent most of the world’s written languages. It is a unification of dozens of character sets, such as Latin, Greeks, Cyrillic, Katakana, Arabic, and many more. Example: Java // Java Program to Demonstrate Char Primitive Data Type // Classclass GFG { // Main driver method public static void main(String args[]) { // Creating and initializing custom character char a = 'G'; // Integer data type is generally // used for numeric values int i = 89; // use byte and short // if memory is a constraint byte b = 4; // this will give error as number is // larger than byte range // byte b1 = 7888888955; short s = 56; // this will give error as number is // larger than short range // short s1 = 87878787878; // by default fraction value // is double in java double d = 4.355453532; // for float use 'f' as suffix as standard float f = 4.7333434f; //need to hold big range of numbers then we need this data type long l = 12121; System.out.println("char: " + a); System.out.println("integer: " + i); System.out.println("byte: " + b); System.out.println("short: " + s); System.out.println("float: " + f); System.out.println("double: " + d); System.out.println("long: " + l); }} Output char: G integer: 89 byte: 4 short: 56 float: 4.7333436 double: 4.355453532 long: 12121 The Reference Data Types will contain a memory address of variable values because the reference types won’t store the variable value directly in memory. They are strings, objects, arrays, etc. Strings are defined as an array of characters. The difference between a character array and a string in Java is, that the string is designed to hold a sequence of characters in a single variable whereas, a character array is a collection of separate char type entities. Unlike C/C++, Java strings are not terminated with a null character. Syntax: Declaring a string <String_Type> <string_variable> = β€œ<sequence_of_string>”; Example: // Declare String without using new operator String s = "GeeksforGeeks"; // Declare String using new operator String s1 = new String("GeeksforGeeks"); A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order: Modifiers: A class can be public or has default access. Refer to access specifiers for classes or interfaces in JavaClass name: The name should begin with an initial letter (capitalized by convention).Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.Body: The class body is surrounded by braces, { }. Modifiers: A class can be public or has default access. Refer to access specifiers for classes or interfaces in Java Class name: The name should begin with an initial letter (capitalized by convention). Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface. Body: The class body is surrounded by braces, { }. It is a basic unit of Object-Oriented Programming and represents real-life entities. A typical Java program creates many objects, which as you know, interact by invoking methods. An object consists of : State: It is represented by the attributes of an object. It also reflects the properties of an object.Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects.Identity: It gives a unique name to an object and enables one object to interact with other objects. State: It is represented by the attributes of an object. It also reflects the properties of an object. Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects. Identity: It gives a unique name to an object and enables one object to interact with other objects. Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract (only method signature, nobody). Interfaces specify what a class must do and not how. It is the blueprint of the class. An Interface is about capabilities like a Player may be an interface and any class implementing Player must be able to (or must implement) move(). So it specifies a set of methods that the class has to implement. If a class implements an interface and does not provide method bodies for all functions specified in the interface, then the class must be declared abstract. A Java library example is Comparator Interface. If a class implements this interface, then it can be used to sort a collection. An array is a group of like-typed variables that are referred to by a common name. Arrays in Java work differently than they do in C/C++. The following are some important points about Java arrays. In Java, all arrays are dynamically allocated. (discussed below) Since arrays are objects in Java, we can find their length using member length. This is different from C/C++ where we find length using size. A Java array variable can also be declared like other variables with [] after the data type. The variables in the array are ordered and each has an index beginning from 0. Java array can also be used as a static field, a local variable, or a method parameter. The size of an array must be specified by an int value and not long or short. The direct superclass of an array type is Object. Every array type implements the interfaces Cloneable and java.io.Serializable. Java Programming Tutorial | Data Types in Java | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersJava Programming Tutorial | Data Types in Java | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:28β€’Liveβ€’<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=dY2LQcE-Qvc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Check Out: Quiz on Data Type in Java This article is contributed by Shubham Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. ShreyasWaghmare RishabhPrabhu pranitamahandule sofiaa nishkarshgandhi solankimayank nandinigujral Java School Programming Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java How to iterate any Map in Java Stream In Java Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Inheritance in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n31 May, 2022" }, { "code": null, "e": 321, "s": 52, "text": "Data types are different sizes and values that can be stored in the variable that is made as per convenience and circumstances to cover up all test cases. Also, let us cover up other important ailments that there are majorly two types of languages that are as follows:" }, { "code": null, "e": 690, "s": 321, "text": "First, one is a Statically typed language where each variable and expression type is already known at compile time. Once a variable is declared to be of a certain data type, it cannot hold values of other data types. For example C, C++, Java.The other is Dynamically typed languages. These languages can receive different data types over time. For example Ruby, Python" }, { "code": null, "e": 933, "s": 690, "text": "First, one is a Statically typed language where each variable and expression type is already known at compile time. Once a variable is declared to be of a certain data type, it cannot hold values of other data types. For example C, C++, Java." }, { "code": null, "e": 1060, "s": 933, "text": "The other is Dynamically typed languages. These languages can receive different data types over time. For example Ruby, Python" }, { "code": null, "e": 1383, "s": 1060, "text": "Java is statically typed and also a strongly typed language because, in Java, each type of data (such as integer, character, hexadecimal, packed decimal, and so forth) is predefined as part of the programming language and all constants or variables defined for a given program must be described with one of the data types." }, { "code": null, "e": 1443, "s": 1383, "text": "Java has two categories in which data types are segregated " }, { "code": null, "e": 1601, "s": 1443, "text": "Primitive Data Type: such as boolean, char, int, short, byte, long, float, and doubleNon-Primitive Data Type or Object Data type: such as String, Array, etc." }, { "code": null, "e": 1687, "s": 1601, "text": "Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double" }, { "code": null, "e": 1760, "s": 1687, "text": "Non-Primitive Data Type or Object Data type: such as String, Array, etc." }, { "code": null, "e": 1927, "s": 1760, "text": "Primitive data are only single values and have no special capabilities. There are 8 primitive data types. They are depicted below in tabular format below as follows: " }, { "code": null, "e": 1936, "s": 1927, "text": "Chapters" }, { "code": null, "e": 1963, "s": 1936, "text": "descriptions off, selected" }, { "code": null, "e": 2013, "s": 1963, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 2036, "s": 2013, "text": "captions off, selected" }, { "code": null, "e": 2044, "s": 2036, "text": "English" }, { "code": null, "e": 2068, "s": 2044, "text": "This is a modal window." }, { "code": null, "e": 2137, "s": 2068, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 2159, "s": 2137, "text": "End of dialog window." }, { "code": null, "e": 2246, "s": 2159, "text": "Let us discuss and implement each one of the following data types that are as follows:" }, { "code": null, "e": 2625, "s": 2246, "text": "Boolean data type represents only one bit of information either true or false which is intended to represent the two truth values of logic and Boolean algebra, but the size of the boolean data type is virtual machine-dependent. Values of type boolean are not converted implicitly or explicitly (with casts) to any other type. But the programmer can easily write conversion code." }, { "code": null, "e": 2634, "s": 2625, "text": "Syntax: " }, { "code": null, "e": 2654, "s": 2634, "text": "boolean booleanVar;" }, { "code": null, "e": 2686, "s": 2654, "text": "Size: Virtual machine dependent" }, { "code": null, "e": 2722, "s": 2686, "text": "Values: Boolean such as true, false" }, { "code": null, "e": 2743, "s": 2722, "text": "Default Value: false" }, { "code": null, "e": 2752, "s": 2743, "text": "Example:" }, { "code": null, "e": 2757, "s": 2752, "text": "Java" }, { "code": "// Java Program to Demonstrate Boolean Primitive DataType // Classclass GFG { // Main driver method public static void main(String args[]) { //Boolean data type is a data type that has one of two possible values (usually denoted true and false). // Setting boolean to false and true initially boolean a = false; boolean b = true; // If condition holds if (b == true){ // Print statement System.out.println(\"Hi Geek\"); } // If condition holds if(a == false){ // Print statement System.out.println(\"Hello Geek\"); } }}", "e": 3429, "s": 2757, "text": null }, { "code": null, "e": 3436, "s": 3429, "text": "Output" }, { "code": null, "e": 3455, "s": 3436, "text": "Hi Geek\nHello Geek" }, { "code": null, "e": 3583, "s": 3455, "text": "The byte data type is an 8-bit signed two’s complement integer. The byte data type is useful for saving memory in large arrays." }, { "code": null, "e": 3592, "s": 3583, "text": "Syntax: " }, { "code": null, "e": 3606, "s": 3592, "text": "byte byteVar;" }, { "code": null, "e": 3628, "s": 3606, "text": "Size: 1 byte (8 bits)" }, { "code": null, "e": 3648, "s": 3628, "text": "Values: -128 to 127" }, { "code": null, "e": 3665, "s": 3648, "text": "Default Value: 0" }, { "code": null, "e": 3674, "s": 3665, "text": "Example:" }, { "code": null, "e": 3679, "s": 3674, "text": "Java" }, { "code": "// Java Program to demonstrate Byte Data Type // Classclass GFG { // Main driver method public static void main(String args[]) { byte a = 126; // byte is 8 bit value System.out.println(a); a++; System.out.println(a); // It overflows here because // byte can hold values from -128 to 127 a++; System.out.println(a); // Looping back within the range a++; System.out.println(a); }}", "e": 4157, "s": 3679, "text": null }, { "code": null, "e": 4175, "s": 4157, "text": "126\n127\n-128\n-127" }, { "code": null, "e": 4358, "s": 4175, "text": "The short data type is a 16-bit signed two’s complement integer. Similar to byte, use a short to save memory in large arrays, in situations where the memory savings actually matters." }, { "code": null, "e": 4367, "s": 4358, "text": "Syntax: " }, { "code": null, "e": 4383, "s": 4367, "text": "short shortVar;" }, { "code": null, "e": 4406, "s": 4383, "text": "Size: 2 byte (16 bits)" }, { "code": null, "e": 4446, "s": 4406, "text": "Values: -32, 768 to 32, 767 (inclusive)" }, { "code": null, "e": 4463, "s": 4446, "text": "Default Value: 0" }, { "code": null, "e": 4511, "s": 4463, "text": "It is a 32-bit signed two’s complement integer." }, { "code": null, "e": 4520, "s": 4511, "text": "Syntax: " }, { "code": null, "e": 4532, "s": 4520, "text": "int intVar;" }, { "code": null, "e": 4557, "s": 4532, "text": "Size: 4 byte ( 32 bits )" }, { "code": null, "e": 4615, "s": 4557, "text": "Values: -2, 147, 483, 648 to 2, 147, 483, 647 (inclusive)" }, { "code": null, "e": 4646, "s": 4615, "text": "Note: The default value is β€˜0’" }, { "code": null, "e": 4865, "s": 4646, "text": "Remember: In Java SE 8 and later, we can use the int data type to represent an unsigned 32-bit integer, which has a value in the range [0, 232-1]. Use the Integer class to use the int data type as an unsigned integer. " }, { "code": null, "e": 5057, "s": 4865, "text": " The range of a long is quite large. The long data type is a 64-bit two’s complement integer and is useful for those occasions where an int type is not large enough to hold the desired value." }, { "code": null, "e": 5066, "s": 5057, "text": "Syntax: " }, { "code": null, "e": 5080, "s": 5066, "text": "long longVar;" }, { "code": null, "e": 5103, "s": 5080, "text": "Size: 8 byte (64 bits)" }, { "code": null, "e": 5195, "s": 5103, "text": "Values: {-9, 223, 372, 036, 854, 775, 808} to {9, 223, 372, 036, 854, 775, 807} (inclusive)" }, { "code": null, "e": 5227, "s": 5195, "text": "Note: The default value is β€˜0’." }, { "code": null, "e": 5527, "s": 5227, "text": "Remember: In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1. The Long class also contains methods like comparing Unsigned, divide Unsigned, etc to support arithmetic operations for unsigned long. " }, { "code": null, "e": 5703, "s": 5527, "text": "The float data type is a single-precision 32-bit IEEE 754 floating-point. Use a float (instead of double) if you need to save memory in large arrays of floating-point numbers." }, { "code": null, "e": 5712, "s": 5703, "text": "Syntax: " }, { "code": null, "e": 5728, "s": 5712, "text": "float floatVar;" }, { "code": null, "e": 5751, "s": 5728, "text": "Size: 4 byte (32 bits)" }, { "code": null, "e": 5781, "s": 5751, "text": "Values: upto 7 decimal digits" }, { "code": null, "e": 5815, "s": 5781, "text": "Note: The default value is β€˜0.0’." }, { "code": null, "e": 5824, "s": 5815, "text": "Example:" }, { "code": null, "e": 5829, "s": 5824, "text": "Java" }, { "code": "// Java Program to Illustrate Float Primitive Data Type // Importing required classesimport java.io.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing float value // float value1 = 9.87; // Print statement // System.out.println(value1); float value2 = 9.87f; System.out.println(value2); }}", "e": 6240, "s": 5829, "text": null }, { "code": null, "e": 6245, "s": 6240, "text": "9.87" }, { "code": null, "e": 6362, "s": 6245, "text": "If we uncomment lines no 14,15,16 then the output would have been totally different as we would have faced an error." }, { "code": null, "e": 6507, "s": 6364, "text": "The double data type is a double-precision 64-bit IEEE 754 floating-point. For decimal values, this data type is generally the default choice." }, { "code": null, "e": 6515, "s": 6507, "text": "Syntax:" }, { "code": null, "e": 6533, "s": 6515, "text": "double doubleVar;" }, { "code": null, "e": 6558, "s": 6533, "text": "Size: 8 bytes or 64 bits" }, { "code": null, "e": 6589, "s": 6558, "text": "Values: Upto 16 decimal digits" }, { "code": null, "e": 6596, "s": 6589, "text": "Note: " }, { "code": null, "e": 6633, "s": 6596, "text": "The default value is taken as β€˜0.0’." }, { "code": null, "e": 6888, "s": 6633, "text": "Both float and double data types were designed especially for scientific calculations, where approximation errors are acceptable. If accuracy is the most prior concern then, it is recommended not to use these data types and use BigDecimal class instead. " }, { "code": null, "e": 6949, "s": 6888, "text": "It is recommended to go through rounding off errors in java." }, { "code": null, "e": 7006, "s": 6949, "text": "The char data type is a single 16-bit Unicode character." }, { "code": null, "e": 7015, "s": 7006, "text": "Syntax: " }, { "code": null, "e": 7029, "s": 7015, "text": "char charVar;" }, { "code": null, "e": 7052, "s": 7029, "text": "Size: 2 byte (16 bits)" }, { "code": null, "e": 7093, "s": 7052, "text": "Values: β€˜\\u0000’ (0) to β€˜\\uffff’ (65535)" }, { "code": null, "e": 7129, "s": 7093, "text": "Note: The default value is β€˜\\u0000’" }, { "code": null, "e": 7193, "s": 7129, "text": "You must be wondering why is the size of char 2 bytes in Java? " }, { "code": null, "e": 7717, "s": 7193, "text": "So, in other languages like C/C++ uses only ASCII characters, and to represent all ASCII characters 8-bits is enough. But java uses the Unicode system not the ASCII code system and to represent the Unicode system 8 bits is not enough to represent all characters so java uses 2 bytes for characters. Unicode defines a fully international character set that can represent most of the world’s written languages. It is a unification of dozens of character sets, such as Latin, Greeks, Cyrillic, Katakana, Arabic, and many more." }, { "code": null, "e": 7726, "s": 7717, "text": "Example:" }, { "code": null, "e": 7731, "s": 7726, "text": "Java" }, { "code": "// Java Program to Demonstrate Char Primitive Data Type // Classclass GFG { // Main driver method public static void main(String args[]) { // Creating and initializing custom character char a = 'G'; // Integer data type is generally // used for numeric values int i = 89; // use byte and short // if memory is a constraint byte b = 4; // this will give error as number is // larger than byte range // byte b1 = 7888888955; short s = 56; // this will give error as number is // larger than short range // short s1 = 87878787878; // by default fraction value // is double in java double d = 4.355453532; // for float use 'f' as suffix as standard float f = 4.7333434f; //need to hold big range of numbers then we need this data type long l = 12121; System.out.println(\"char: \" + a); System.out.println(\"integer: \" + i); System.out.println(\"byte: \" + b); System.out.println(\"short: \" + s); System.out.println(\"float: \" + f); System.out.println(\"double: \" + d); System.out.println(\"long: \" + l); }}", "e": 8977, "s": 7731, "text": null }, { "code": null, "e": 8984, "s": 8977, "text": "Output" }, { "code": null, "e": 9071, "s": 8984, "text": "char: G\ninteger: 89\nbyte: 4\nshort: 56\nfloat: 4.7333436\ndouble: 4.355453532\nlong: 12121" }, { "code": null, "e": 9265, "s": 9071, "text": "The Reference Data Types will contain a memory address of variable values because the reference types won’t store the variable value directly in memory. They are strings, objects, arrays, etc. " }, { "code": null, "e": 9604, "s": 9265, "text": "Strings are defined as an array of characters. The difference between a character array and a string in Java is, that the string is designed to hold a sequence of characters in a single variable whereas, a character array is a collection of separate char type entities. Unlike C/C++, Java strings are not terminated with a null character." }, { "code": null, "e": 9631, "s": 9604, "text": "Syntax: Declaring a string" }, { "code": null, "e": 9689, "s": 9631, "text": "<String_Type> <string_variable> = β€œ<sequence_of_string>”;" }, { "code": null, "e": 9699, "s": 9689, "text": "Example: " }, { "code": null, "e": 9855, "s": 9699, "text": "// Declare String without using new operator \nString s = \"GeeksforGeeks\"; \n\n// Declare String using new operator \nString s1 = new String(\"GeeksforGeeks\"); " }, { "code": null, "e": 10100, "s": 9855, "text": "A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order: " }, { "code": null, "e": 10677, "s": 10100, "text": "Modifiers: A class can be public or has default access. Refer to access specifiers for classes or interfaces in JavaClass name: The name should begin with an initial letter (capitalized by convention).Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.Body: The class body is surrounded by braces, { }." }, { "code": null, "e": 10794, "s": 10677, "text": "Modifiers: A class can be public or has default access. Refer to access specifiers for classes or interfaces in Java" }, { "code": null, "e": 10880, "s": 10794, "text": "Class name: The name should begin with an initial letter (capitalized by convention)." }, { "code": null, "e": 11033, "s": 10880, "text": "Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent." }, { "code": null, "e": 11207, "s": 11033, "text": "Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface." }, { "code": null, "e": 11258, "s": 11207, "text": "Body: The class body is surrounded by braces, { }." }, { "code": null, "e": 11462, "s": 11258, "text": "It is a basic unit of Object-Oriented Programming and represents real-life entities. A typical Java program creates many objects, which as you know, interact by invoking methods. An object consists of :" }, { "code": null, "e": 11782, "s": 11462, "text": "State: It is represented by the attributes of an object. It also reflects the properties of an object.Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects.Identity: It gives a unique name to an object and enables one object to interact with other objects." }, { "code": null, "e": 11885, "s": 11782, "text": "State: It is represented by the attributes of an object. It also reflects the properties of an object." }, { "code": null, "e": 12003, "s": 11885, "text": "Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects." }, { "code": null, "e": 12104, "s": 12003, "text": "Identity: It gives a unique name to an object and enables one object to interact with other objects." }, { "code": null, "e": 12264, "s": 12104, "text": "Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract (only method signature, nobody). " }, { "code": null, "e": 12351, "s": 12264, "text": "Interfaces specify what a class must do and not how. It is the blueprint of the class." }, { "code": null, "e": 12564, "s": 12351, "text": "An Interface is about capabilities like a Player may be an interface and any class implementing Player must be able to (or must implement) move(). So it specifies a set of methods that the class has to implement." }, { "code": null, "e": 12722, "s": 12564, "text": "If a class implements an interface and does not provide method bodies for all functions specified in the interface, then the class must be declared abstract." }, { "code": null, "e": 12850, "s": 12722, "text": "A Java library example is Comparator Interface. If a class implements this interface, then it can be used to sort a collection." }, { "code": null, "e": 13048, "s": 12850, "text": "An array is a group of like-typed variables that are referred to by a common name. Arrays in Java work differently than they do in C/C++. The following are some important points about Java arrays. " }, { "code": null, "e": 13113, "s": 13048, "text": "In Java, all arrays are dynamically allocated. (discussed below)" }, { "code": null, "e": 13255, "s": 13113, "text": "Since arrays are objects in Java, we can find their length using member length. This is different from C/C++ where we find length using size." }, { "code": null, "e": 13348, "s": 13255, "text": "A Java array variable can also be declared like other variables with [] after the data type." }, { "code": null, "e": 13427, "s": 13348, "text": "The variables in the array are ordered and each has an index beginning from 0." }, { "code": null, "e": 13515, "s": 13427, "text": "Java array can also be used as a static field, a local variable, or a method parameter." }, { "code": null, "e": 13593, "s": 13515, "text": "The size of an array must be specified by an int value and not long or short." }, { "code": null, "e": 13643, "s": 13593, "text": "The direct superclass of an array type is Object." }, { "code": null, "e": 13722, "s": 13643, "text": "Every array type implements the interfaces Cloneable and java.io.Serializable." }, { "code": null, "e": 14632, "s": 13722, "text": "Java Programming Tutorial | Data Types in Java | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersJava Programming Tutorial | Data Types in Java | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:28β€’Liveβ€’<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=dY2LQcE-Qvc\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 14669, "s": 14632, "text": "Check Out: Quiz on Data Type in Java" }, { "code": null, "e": 15093, "s": 14669, "text": "This article is contributed by Shubham Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 15109, "s": 15093, "text": "ShreyasWaghmare" }, { "code": null, "e": 15123, "s": 15109, "text": "RishabhPrabhu" }, { "code": null, "e": 15140, "s": 15123, "text": "pranitamahandule" }, { "code": null, "e": 15147, "s": 15140, "text": "sofiaa" }, { "code": null, "e": 15163, "s": 15147, "text": "nishkarshgandhi" }, { "code": null, "e": 15177, "s": 15163, "text": "solankimayank" }, { "code": null, "e": 15191, "s": 15177, "text": "nandinigujral" }, { "code": null, "e": 15196, "s": 15191, "text": "Java" }, { "code": null, "e": 15215, "s": 15196, "text": "School Programming" }, { "code": null, "e": 15220, "s": 15215, "text": "Java" }, { "code": null, "e": 15318, "s": 15220, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15362, "s": 15318, "text": "Split() String method in Java with examples" }, { "code": null, "e": 15398, "s": 15362, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 15423, "s": 15398, "text": "Reverse a string in Java" }, { "code": null, "e": 15454, "s": 15423, "text": "How to iterate any Map in Java" }, { "code": null, "e": 15469, "s": 15454, "text": "Stream In Java" }, { "code": null, "e": 15487, "s": 15469, "text": "Python Dictionary" }, { "code": null, "e": 15512, "s": 15487, "text": "Reverse a string in Java" }, { "code": null, "e": 15528, "s": 15512, "text": "Arrays in C/C++" }, { "code": null, "e": 15551, "s": 15528, "text": "Introduction To PYTHON" } ]
JSF - ui:param Tag
Using ui:param tag, we can pass parameters to template file or an included file. In JSF - template tags chapter, we've learned how to create and use template tags. We defined various section such as header, footer, content, and a template combining all the sections. Now we'll learn βˆ’ How to pass parameter(s) to various section of a template How to pass parameter(s) to various section of a template How to pass parameter(s) to a template How to pass parameter(s) to a template Add parameter to ui:include tag. Use ui:param tag to define a parameter containing a value to be passed to Header section. <ui:insert name = "header" > <ui:include src = "/templates/header.xhtml" > <ui:param name = "defaultHeader" value = "Default Header" /> </ui:include> </ui:insert> <ui:composition> <h1>#{defaultHeader}</h1> </ui:composition> Add parameter to ui:composition tag. Use ui:param tag to define a parameter containing a value to be passed to template. <ui:composition template = "templates/common.xhtml"> <ui:param name = "title" value = "Home" /> </ui:composition> <h:body> <h2>#{title}</h2> </h:body> Let us create a test JSF application to test the template tags in JSF. <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:ui = "http://java.sun.com/jsf/facelets"> <body> <ui:composition> <h1>#{defaultHeader}</h1> </ui:composition> </body> </html> <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html" xmlns:ui = "http://java.sun.com/jsf/facelets"> <h:head></h:head> <h:body> <h2>#{title}</h2> <div style = "border-width:2px; border-color:green; border-style:solid;"> <ui:insert name = "header" > <ui:include src = "/templates/header.xhtml" > <ui:param name = "defaultHeader" value = "Default Header" /> </ui:include> </ui:insert> </div> <br/> <div style = "border-width:2px; border-color:black; border-style:solid;"> <ui:insert name = "content" > <ui:include src = "/templates/contents.xhtml" /> </ui:insert> </div> <br/> <div style = "border-width:2px; border-color:red; border-style:solid;"> <ui:insert name = "footer" > <ui:include src = "/templates/footer.xhtml" /> </ui:insert> </div> </h:body> </html> <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html" xmlns:ui = "http://java.sun.com/jsf/facelets"> <h:body> <ui:composition template = "templates/common.xhtml"> <ui:param name = "title" value = "Home" /> <ui:define name = "content"> <br/><br/> <h:link value = "Page 1" outcome = "page1" /> <h:link value = "Page 2" outcome = "page2" /> <br/><br/> </ui:define> </ui:composition> </h:body> </html> Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result. 37 Lectures 3.5 hours Chaand Sheikh Print Add Notes Bookmark this page
[ { "code": null, "e": 2033, "s": 1952, "text": "Using ui:param tag, we can pass parameters to template file or an included file." }, { "code": null, "e": 2219, "s": 2033, "text": "In JSF - template tags chapter, we've learned how to create and use template tags. We defined various section such as header, footer, content, and a template combining all the sections." }, { "code": null, "e": 2237, "s": 2219, "text": "Now we'll learn βˆ’" }, { "code": null, "e": 2295, "s": 2237, "text": "How to pass parameter(s) to various section of a template" }, { "code": null, "e": 2353, "s": 2295, "text": "How to pass parameter(s) to various section of a template" }, { "code": null, "e": 2392, "s": 2353, "text": "How to pass parameter(s) to a template" }, { "code": null, "e": 2431, "s": 2392, "text": "How to pass parameter(s) to a template" }, { "code": null, "e": 2554, "s": 2431, "text": "Add parameter to ui:include tag. Use ui:param tag to define a parameter containing a value to be passed to Header section." }, { "code": null, "e": 2730, "s": 2554, "text": "<ui:insert name = \"header\" >\n <ui:include src = \"/templates/header.xhtml\" >\n <ui:param name = \"defaultHeader\" value = \"Default Header\" />\n </ui:include>\n</ui:insert> " }, { "code": null, "e": 2798, "s": 2730, "text": "<ui:composition> \t\t\n <h1>#{defaultHeader}</h1>\n</ui:composition>\t" }, { "code": null, "e": 2919, "s": 2798, "text": "Add parameter to ui:composition tag. Use ui:param tag to define a parameter containing a value to be passed to template." }, { "code": null, "e": 3037, "s": 2919, "text": "<ui:composition template = \"templates/common.xhtml\">\t\n <ui:param name = \"title\" value = \"Home\" />\n</ui:composition>" }, { "code": null, "e": 3078, "s": 3037, "text": "<h:body> \n <h2>#{title}</h2>\n</h:body>" }, { "code": null, "e": 3149, "s": 3078, "text": "Let us create a test JSF application to test the template tags in JSF." }, { "code": null, "e": 3531, "s": 3149, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:ui = \"http://java.sun.com/jsf/facelets\">\n \n <body>\n <ui:composition> \n <h1>#{defaultHeader}</h1>\n </ui:composition>\t\n </body>\n</html>" }, { "code": null, "e": 4715, "s": 3531, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:h = \"http://java.sun.com/jsf/html\"\n xmlns:ui = \"http://java.sun.com/jsf/facelets\"> \n \n <h:head></h:head>\n <h:body>\n <h2>#{title}</h2>\n \n <div style = \"border-width:2px; border-color:green; border-style:solid;\">\n <ui:insert name = \"header\" >\n <ui:include src = \"/templates/header.xhtml\" >\n <ui:param name = \"defaultHeader\" value = \"Default Header\" />\n </ui:include>\n </ui:insert> \n </div>\n <br/>\n \n <div style = \"border-width:2px; border-color:black; border-style:solid;\">\n <ui:insert name = \"content\" >\n <ui:include src = \"/templates/contents.xhtml\" />\n </ui:insert> \n </div>\n <br/>\n \n <div style = \"border-width:2px; border-color:red; border-style:solid;\">\n <ui:insert name = \"footer\" >\n <ui:include src = \"/templates/footer.xhtml\" />\n </ui:insert>\n </div>\n \n </h:body>\n</html>" }, { "code": null, "e": 5438, "s": 4715, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:h = \"http://java.sun.com/jsf/html\"\n xmlns:ui = \"http://java.sun.com/jsf/facelets\">\n \n <h:body>\n <ui:composition template = \"templates/common.xhtml\">\n <ui:param name = \"title\" value = \"Home\" />\n \n <ui:define name = \"content\">\t\t\t\t\n <br/><br/>\n <h:link value = \"Page 1\" outcome = \"page1\" />\n <h:link value = \"Page 2\" outcome = \"page2\" />\t\t\t\n <br/><br/>\n </ui:define>\n </ui:composition>\n </h:body>\n</html>\t" }, { "code": null, "e": 5654, "s": 5438, "text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result." }, { "code": null, "e": 5689, "s": 5654, "text": "\n 37 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5704, "s": 5689, "text": " Chaand Sheikh" }, { "code": null, "e": 5711, "s": 5704, "text": " Print" }, { "code": null, "e": 5722, "s": 5711, "text": " Add Notes" } ]
PREVIOUSMONTH function
Returns a table that contains a column of all dates from the previous month, based on the first date in the dates column, in the current context. PREVIOUSMONTH (<dates>) dates A column that contains dates. A table containing a single column of date values. The dates parameter can be any of the following βˆ’ A reference to a date/time column. A reference to a date/time column. A table expression that returns a single column of date/time values. A table expression that returns a single column of date/time values. A Boolean expression that defines a single-column table of date/time values. A Boolean expression that defines a single-column table of date/time values. Constraints on Boolean expressions βˆ’ The expression cannot reference a calculated field. The expression cannot reference a calculated field. The expression cannot use CALCULATE function. The expression cannot use CALCULATE function. The expression cannot use any function that scans a table or returns a table, including aggregation functions. The expression cannot use any function that scans a table or returns a table, including aggregation functions. However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value. Previous Month Sales: = CALCULATE ( SUM (Sales[Sales Amount]), PREVIOUSMONTH (Sales[Date]) ) 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2147, "s": 2001, "text": "Returns a table that contains a column of all dates from the previous month, based on the first date in the dates column, in the current context." }, { "code": null, "e": 2173, "s": 2147, "text": "PREVIOUSMONTH (<dates>) \n" }, { "code": null, "e": 2179, "s": 2173, "text": "dates" }, { "code": null, "e": 2209, "s": 2179, "text": "A column that contains dates." }, { "code": null, "e": 2260, "s": 2209, "text": "A table containing a single column of date values." }, { "code": null, "e": 2310, "s": 2260, "text": "The dates parameter can be any of the following βˆ’" }, { "code": null, "e": 2345, "s": 2310, "text": "A reference to a date/time column." }, { "code": null, "e": 2380, "s": 2345, "text": "A reference to a date/time column." }, { "code": null, "e": 2449, "s": 2380, "text": "A table expression that returns a single column of date/time values." }, { "code": null, "e": 2518, "s": 2449, "text": "A table expression that returns a single column of date/time values." }, { "code": null, "e": 2595, "s": 2518, "text": "A Boolean expression that defines a single-column table of date/time values." }, { "code": null, "e": 2672, "s": 2595, "text": "A Boolean expression that defines a single-column table of date/time values." }, { "code": null, "e": 2709, "s": 2672, "text": "Constraints on Boolean expressions βˆ’" }, { "code": null, "e": 2761, "s": 2709, "text": "The expression cannot reference a calculated field." }, { "code": null, "e": 2813, "s": 2761, "text": "The expression cannot reference a calculated field." }, { "code": null, "e": 2859, "s": 2813, "text": "The expression cannot use CALCULATE function." }, { "code": null, "e": 2905, "s": 2859, "text": "The expression cannot use CALCULATE function." }, { "code": null, "e": 3016, "s": 2905, "text": "The expression cannot use any function that scans a table or returns a table, including aggregation functions." }, { "code": null, "e": 3127, "s": 3016, "text": "The expression cannot use any function that scans a table or returns a table, including aggregation functions." }, { "code": null, "e": 3243, "s": 3127, "text": "However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value." }, { "code": null, "e": 3341, "s": 3243, "text": "Previous Month Sales: = CALCULATE ( \n SUM (Sales[Sales Amount]), PREVIOUSMONTH (Sales[Date])\n) " }, { "code": null, "e": 3376, "s": 3341, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3390, "s": 3376, "text": " Abhay Gadiya" }, { "code": null, "e": 3423, "s": 3390, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3437, "s": 3423, "text": " Randy Minder" }, { "code": null, "e": 3472, "s": 3437, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3486, "s": 3472, "text": " Randy Minder" }, { "code": null, "e": 3493, "s": 3486, "text": " Print" }, { "code": null, "e": 3504, "s": 3493, "text": " Add Notes" } ]
C++ Map Library - lower_bound() Function
The C++ function std::map::lower_bound() returns an iterator pointing to the first element which is not less than key k. Following is the declaration for std::map::lower_bound() function form std::map header. iterator lower_bound (const key_type& k); const_iterator lower_bound (const key_type& k) const; k βˆ’ Key to be searched. If object is constant qualified then method returns a constant iterator otherwise non-constant iterator. This member function doesn't throw exception. Logarithmic i.e. O(log n) The following example shows the usage of std::map::lower_bound() function. #include <iostream> #include <map> using namespace std; int main(void) { map<char, int> m = { {'a', 1}, {'b', 2}, {'c', 3}, {'d', 4}, {'e', 5}, }; auto it = m.lower_bound('b'); cout << "Lower bound is " << it->first << " = " << it->second << endl; return 0; } Let us compile and run the above program, this will produce the following result βˆ’ Lower bound is b = 2 Print Add Notes Bookmark this page
[ { "code": null, "e": 2724, "s": 2603, "text": "The C++ function std::map::lower_bound() returns an iterator pointing to the first element which is not less than key k." }, { "code": null, "e": 2812, "s": 2724, "text": "Following is the declaration for std::map::lower_bound() function form std::map header." }, { "code": null, "e": 2909, "s": 2812, "text": "iterator lower_bound (const key_type& k);\nconst_iterator lower_bound (const key_type& k) const;\n" }, { "code": null, "e": 2933, "s": 2909, "text": "k βˆ’ Key to be searched." }, { "code": null, "e": 3038, "s": 2933, "text": "If object is constant qualified then method returns a constant iterator otherwise non-constant iterator." }, { "code": null, "e": 3084, "s": 3038, "text": "This member function doesn't throw exception." }, { "code": null, "e": 3110, "s": 3084, "text": "Logarithmic i.e. O(log n)" }, { "code": null, "e": 3185, "s": 3110, "text": "The following example shows the usage of std::map::lower_bound() function." }, { "code": null, "e": 3541, "s": 3185, "text": "#include <iostream>\n#include <map>\n\nusing namespace std;\n\nint main(void) {\n map<char, int> m = {\n {'a', 1},\n {'b', 2},\n {'c', 3},\n {'d', 4},\n {'e', 5},\n };\n\n auto it = m.lower_bound('b');\n\n cout << \"Lower bound is \" << it->first << \n \" = \" << it->second << endl;\n\n return 0;\n}" }, { "code": null, "e": 3624, "s": 3541, "text": "Let us compile and run the above program, this will produce the following result βˆ’" }, { "code": null, "e": 3646, "s": 3624, "text": "Lower bound is b = 2\n" }, { "code": null, "e": 3653, "s": 3646, "text": " Print" }, { "code": null, "e": 3664, "s": 3653, "text": " Add Notes" } ]
How to cover legend in a box using ggplot2 in R?
To cover legend in a box using ggplot2 in R, we can use theme function with legend.box.background and legend.box.margin argument. The legend.box.background will have a rectangular element with the help of element_rect and margin values will be set in legend.box.margin. Check out the Example given below to understand how it can be done. Following snippet creates a sample data frame βˆ’ Score<-sample(1:100,20) Rank<-sample(1:10,20,replace=TRUE) Gender<-sample(c("Male","Female"),20,replace=TRUE) df<-data.frame(Score,Rank,Gender) df The following dataframe is created Score Rank Gender 1 80 9 Male 2 82 1 Female 3 13 5 Male 4 91 1 Female 5 62 6 Male 6 52 2 Female 7 72 7 Male 8 15 2 Male 9 44 2 Male 10 78 5 Male 11 5 10 Male 12 22 1 Female 13 92 8 Female 14 94 2 Male 15 40 3 Male 16 73 8 Female 17 66 6 Male 18 70 6 Male 19 69 6 Male 20 47 7 Male To load ggplot2 package and create scatterplot between Score and Rank with points colored by Gender on the above created data frame, add the following code to the above snippet βˆ’ Score<-sample(1:100,20) Rank<-sample(1:10,20,replace=TRUE) Gender<-sample(c("Male","Female"),20,replace=TRUE) df<-data.frame(Score,Rank,Gender) library(ggplot2) ggplot(df,aes(Score,Rank))+geom_point(aes(colour=factor(Gender))) If you execute all the above given snippets as a single program, it generates the following Output βˆ’ To create scatterplot between Score and Rank with points colored by Gender having legend covered in a box on the above created data frame, add the following code to the above snippet βˆ’ Score<-sample(1:100,20) Rank<-sample(1:10,20,replace=TRUE) Gender<-sample(c("Male","Female"),20,replace=TRUE) df<-data.frame(Score,Rank,Gender) library(ggplot2) ggplot(df,aes(Score,Rank))+geom_point(aes(colour=factor(Gender)))+theme(legend. box.background=element_rect(),legend.box.margin=margin(5,5,5,5)) If you execute all the above given snippets as a single program, it generates the following Output βˆ’
[ { "code": null, "e": 1332, "s": 1062, "text": "To cover legend in a box using ggplot2 in R, we can use theme function with\nlegend.box.background and legend.box.margin argument. The legend.box.background\nwill have a rectangular element with the help of element_rect and margin values will be\nset in legend.box.margin." }, { "code": null, "e": 1400, "s": 1332, "text": "Check out the Example given below to understand how it can be done." }, { "code": null, "e": 1448, "s": 1400, "text": "Following snippet creates a sample data frame βˆ’" }, { "code": null, "e": 1595, "s": 1448, "text": "Score<-sample(1:100,20)\nRank<-sample(1:10,20,replace=TRUE)\nGender<-sample(c(\"Male\",\"Female\"),20,replace=TRUE)\ndf<-data.frame(Score,Rank,Gender)\ndf" }, { "code": null, "e": 1630, "s": 1595, "text": "The following dataframe is created" }, { "code": null, "e": 2002, "s": 1630, "text": " Score Rank Gender\n 1 80 9 Male\n 2 82 1 Female\n 3 13 5 Male\n 4 91 1 Female\n 5 62 6 Male\n 6 52 2 Female\n 7 72 7 Male\n 8 15 2 Male\n 9 44 2 Male \n10 78 5 Male\n11 5 10 Male\n12 22 1 Female\n13 92 8 Female\n14 94 2 Male\n15 40 3 Male\n16 73 8 Female\n17 66 6 Male\n18 70 6 Male\n19 69 6 Male\n20 47 7 Male" }, { "code": null, "e": 2181, "s": 2002, "text": "To load ggplot2 package and create scatterplot between Score and Rank with points\ncolored by Gender on the above created data frame, add the following code to the above\nsnippet βˆ’" }, { "code": null, "e": 2408, "s": 2181, "text": "Score<-sample(1:100,20)\nRank<-sample(1:10,20,replace=TRUE)\nGender<-sample(c(\"Male\",\"Female\"),20,replace=TRUE)\ndf<-data.frame(Score,Rank,Gender)\nlibrary(ggplot2)\nggplot(df,aes(Score,Rank))+geom_point(aes(colour=factor(Gender)))" }, { "code": null, "e": 2509, "s": 2408, "text": "If you execute all the above given snippets as a single program, it generates the following Output βˆ’" }, { "code": null, "e": 2694, "s": 2509, "text": "To create scatterplot between Score and Rank with points colored by Gender having\nlegend covered in a box on the above created data frame, add the following code to the\nabove snippet βˆ’" }, { "code": null, "e": 3000, "s": 2694, "text": "Score<-sample(1:100,20)\nRank<-sample(1:10,20,replace=TRUE)\nGender<-sample(c(\"Male\",\"Female\"),20,replace=TRUE)\ndf<-data.frame(Score,Rank,Gender)\nlibrary(ggplot2)\nggplot(df,aes(Score,Rank))+geom_point(aes(colour=factor(Gender)))+theme(legend.\nbox.background=element_rect(),legend.box.margin=margin(5,5,5,5))" }, { "code": null, "e": 3101, "s": 3000, "text": "If you execute all the above given snippets as a single program, it generates the following Output βˆ’" } ]
Facing the sun | Practice | GeeksforGeeks
Given an array H representing heights of buildings. You have to count the buildings which will see the sunrise (Assume : Sun rise on the side of array starting point). Example 1: Input: N = 5 H[] = {7, 4, 8, 2, 9} Output: 3 Explanation: As 7 is the first element, it can see the sunrise. 4 can't see the sunrise as 7 is hiding it. 8 can see. 2 can't see the sunrise. 9 also can see the sunrise. Example 2: Input: N = 4 H[] = {2, 3, 4, 5} Output: 4 Explanation: As 2 is the first element, it can see the sunrise. 3 can see the sunrise as 2 is not hiding it. Same for 4 and 5, they also can see the sunrise. Your Task: You don't need to read input or print anything. Your task is to complete the function countBuildings() which takes the array of integers h and n as parameters and returns an integer denoting the answer. Expected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints: 1 ≀ N ≀ 106 1 ≀ Hi ≀ 108 0 harshilrpanchal19981 day ago java solution class Solution { int countBuildings(int h[], int n) { // code here int ans = h[0]; int count =1; for (int i=1;i < n ; i++){ if (h[i] > ans){ ans = h[i]; count++; } } return count; }} 0 swapniltayal4221 month ago class Solution{public: // Returns count buildings that can see sunlightint countBuildings(int h[], int n) { // code here int maxh = 0; int count = 0; for (int i=0; i<n; i++){ if (h[i] > maxh){ maxh = h[i]; count++; } }return count;}}; -1 tyagis46061 month ago C++ Solution : int countBuildings(int h[], int n) { // code here int ans =0; int count =0; for(int i=0;i<n;i++){ if(h[i]>ans){ count++; ans = max(ans,h[i]); } } return count;} 0 torq242 months ago Simple Python Code def countBuildings(self,h, n): c=h[0] count=1 for i in range(1,n): if h[i]>c: count+=1 c=h[i] return count 0 aakasshuit2 months ago //Java Solution int max = 0; int count=0; for(int i=0;i<n;i++){ if(h[i]>max){ max=h[i]; count++; } } return count; 0 mail2arman20012 months ago int countBuildings(int h[], int n) { // code here int maxi=INT_MIN; int count=0; for(int i=0;i<n;i++) { if(h[i]>maxi) { maxi=h[i]; count++; } } return count;} 0 ramdurgasais2 months ago In Python def countBuildings(self,h, n): top_building_height = buildings_can_see_sunrice = 0 for building_height in h: if top_building_height < building_height : top_building_height = building_height buildings_can_see_sunrice += 1 return buildings_can_see_sunrice 0 singhalyash813 months ago // { Driver Code Starts#include <bits/stdc++.h> using namespace std; // } Driver Code Ends//User function template for C++class Solution{public: // Returns count buildings that can see sunlightint countBuildings(int h[], int n) { // code here int count=1; int temp=h[0]; for(int i=1;i<n;i++) { if(h[i]>temp) { temp=h[i]; count+=1; } } return count;}}; // { Driver Code Starts. int main() { int t; cin >> t; while (t--) { int n; cin >> n; int h[n]; for (int i = 0; i < n; i++) { cin >> h[i]; } Solution ob; auto ans = ob.countBuildings(h, n); cout << ans << "\n"; } return 0;} // } Driver Code Ends +1 ritikakumari596733 months ago solution inc++ //take avariable intialise it with 0;and take one variable max intialise it with h[0]and everytime when u get element <then max update max with h[i] element at that index and also increment it with 1. and at last return count. // { Driver Code Starts#include <bits/stdc++.h> using namespace std; // } Driver Code Ends//User function template for C++class Solution{public: // Returns count buildings that can see sunlightint countBuildings(int h[], int n) { // code here int count=1; int max=h[0]; for(int i=1;i<n;i++) { if(max<h[i]) { count++; max=h[i]; } } return count;}}; // { Driver Code Starts. int main() { int t; cin >> t; while (t--) { int n; cin >> n; int h[n]; for (int i = 0; i < n; i++) { cin >> h[i]; } Solution ob; auto ans = ob.countBuildings(h, n); cout << ans << "\n"; } return 0;} // } Driver Code Ends 0 indiakamanthan3 months ago class Solution { int countBuildings(int h[], int n) { int max=0; int count=1; max=h[0]; for(int i=1;i<n;i++) { if(max<h[i]) { count++; max=h[i]; } } return count; } } 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": 407, "s": 238, "text": "Given an array H representing heights of buildings. You have to count the buildings which will see the sunrise (Assume : Sun rise on the side of array starting point).\n" }, { "code": null, "e": 418, "s": 407, "text": "Example 1:" }, { "code": null, "e": 637, "s": 418, "text": "Input: \nN = 5\nH[] = {7, 4, 8, 2, 9}\nOutput: 3\nExplanation: As 7 is the first element, it\ncan see the sunrise. 4 can't see the\nsunrise as 7 is hiding it. 8 can see.\n2 can't see the sunrise. 9 also can see\nthe sunrise.\n" }, { "code": null, "e": 648, "s": 637, "text": "Example 2:" }, { "code": null, "e": 851, "s": 648, "text": "Input: \nN = 4\nH[] = {2, 3, 4, 5}\nOutput: 4\nExplanation: As 2 is the first element, it\ncan see the sunrise. 3 can see the\nsunrise as 2 is not hiding it. Same for 4\nand 5, they also can see the sunrise.\n" }, { "code": null, "e": 1067, "s": 851, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function countBuildings() which takes the array of integers h and n as parameters and returns an integer denoting the answer." }, { "code": null, "e": 1129, "s": 1067, "text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1167, "s": 1129, "text": "Constraints:\n1 ≀ N ≀ 106\n1 ≀ Hi ≀ 108" }, { "code": null, "e": 1171, "s": 1169, "text": "0" }, { "code": null, "e": 1200, "s": 1171, "text": "harshilrpanchal19981 day ago" }, { "code": null, "e": 1214, "s": 1200, "text": "java solution" }, { "code": null, "e": 1487, "s": 1216, "text": "class Solution { int countBuildings(int h[], int n) { // code here int ans = h[0]; int count =1; for (int i=1;i < n ; i++){ if (h[i] > ans){ ans = h[i]; count++; } } return count; }}" }, { "code": null, "e": 1489, "s": 1487, "text": "0" }, { "code": null, "e": 1516, "s": 1489, "text": "swapniltayal4221 month ago" }, { "code": null, "e": 1802, "s": 1516, "text": "class Solution{public: // Returns count buildings that can see sunlightint countBuildings(int h[], int n) { // code here int maxh = 0; int count = 0; for (int i=0; i<n; i++){ if (h[i] > maxh){ maxh = h[i]; count++; } }return count;}};" }, { "code": null, "e": 1805, "s": 1802, "text": "-1" }, { "code": null, "e": 1827, "s": 1805, "text": "tyagis46061 month ago" }, { "code": null, "e": 1842, "s": 1827, "text": "C++ Solution :" }, { "code": null, "e": 2063, "s": 1844, "text": "int countBuildings(int h[], int n) { // code here int ans =0; int count =0; for(int i=0;i<n;i++){ if(h[i]>ans){ count++; ans = max(ans,h[i]); } } return count;}" }, { "code": null, "e": 2065, "s": 2063, "text": "0" }, { "code": null, "e": 2084, "s": 2065, "text": "torq242 months ago" }, { "code": null, "e": 2103, "s": 2084, "text": "Simple Python Code" }, { "code": null, "e": 2274, "s": 2105, "text": "def countBuildings(self,h, n): c=h[0] count=1 for i in range(1,n): if h[i]>c: count+=1 c=h[i] return count" }, { "code": null, "e": 2276, "s": 2274, "text": "0" }, { "code": null, "e": 2299, "s": 2276, "text": "aakasshuit2 months ago" }, { "code": null, "e": 2511, "s": 2299, "text": "//Java Solution\n\n int max = 0;\n int count=0;\n for(int i=0;i<n;i++){\n if(h[i]>max){\n max=h[i];\n count++;\n }\n }\n return count;" }, { "code": null, "e": 2513, "s": 2511, "text": "0" }, { "code": null, "e": 2540, "s": 2513, "text": "mail2arman20012 months ago" }, { "code": null, "e": 2763, "s": 2540, "text": "int countBuildings(int h[], int n) { // code here int maxi=INT_MIN; int count=0; for(int i=0;i<n;i++) { if(h[i]>maxi) { maxi=h[i]; count++; } } return count;}" }, { "code": null, "e": 2765, "s": 2763, "text": "0" }, { "code": null, "e": 2790, "s": 2765, "text": "ramdurgasais2 months ago" }, { "code": null, "e": 2800, "s": 2790, "text": "In Python" }, { "code": null, "e": 3150, "s": 2800, "text": "def countBuildings(self,h, n):\n top_building_height = buildings_can_see_sunrice = 0 \n \n for building_height in h:\n if top_building_height < building_height : \n top_building_height = building_height\n buildings_can_see_sunrice += 1\n \n return buildings_can_see_sunrice" }, { "code": null, "e": 3152, "s": 3150, "text": "0" }, { "code": null, "e": 3178, "s": 3152, "text": "singhalyash813 months ago" }, { "code": null, "e": 3226, "s": 3178, "text": "// { Driver Code Starts#include <bits/stdc++.h>" }, { "code": null, "e": 3247, "s": 3226, "text": "using namespace std;" }, { "code": null, "e": 3594, "s": 3247, "text": "// } Driver Code Ends//User function template for C++class Solution{public: // Returns count buildings that can see sunlightint countBuildings(int h[], int n) { // code here int count=1; int temp=h[0]; for(int i=1;i<n;i++) { if(h[i]>temp) { temp=h[i]; count+=1; } } return count;}};" }, { "code": null, "e": 3619, "s": 3594, "text": "// { Driver Code Starts." }, { "code": null, "e": 3908, "s": 3619, "text": "int main() { int t; cin >> t; while (t--) { int n; cin >> n; int h[n]; for (int i = 0; i < n; i++) { cin >> h[i]; } Solution ob; auto ans = ob.countBuildings(h, n); cout << ans << \"\\n\"; } return 0;} // } Driver Code Ends" }, { "code": null, "e": 3911, "s": 3908, "text": "+1" }, { "code": null, "e": 3941, "s": 3911, "text": "ritikakumari596733 months ago" }, { "code": null, "e": 3956, "s": 3941, "text": "solution inc++" }, { "code": null, "e": 4185, "s": 3956, "text": " //take avariable intialise it with 0;and take one variable max intialise it with h[0]and everytime when u get element <then max update max with h[i] element at that index and also increment it with 1. and at last return count." }, { "code": null, "e": 4233, "s": 4185, "text": "// { Driver Code Starts#include <bits/stdc++.h>" }, { "code": null, "e": 4254, "s": 4233, "text": "using namespace std;" }, { "code": null, "e": 4576, "s": 4254, "text": "// } Driver Code Ends//User function template for C++class Solution{public: // Returns count buildings that can see sunlightint countBuildings(int h[], int n) { // code here int count=1; int max=h[0]; for(int i=1;i<n;i++) { if(max<h[i]) { count++; max=h[i]; } } return count;}};" }, { "code": null, "e": 4601, "s": 4576, "text": "// { Driver Code Starts." }, { "code": null, "e": 4890, "s": 4601, "text": "int main() { int t; cin >> t; while (t--) { int n; cin >> n; int h[n]; for (int i = 0; i < n; i++) { cin >> h[i]; } Solution ob; auto ans = ob.countBuildings(h, n); cout << ans << \"\\n\"; } return 0;} // } Driver Code Ends" }, { "code": null, "e": 4892, "s": 4890, "text": "0" }, { "code": null, "e": 4919, "s": 4892, "text": "indiakamanthan3 months ago" }, { "code": null, "e": 5240, "s": 4919, "text": "class Solution {\n int countBuildings(int h[], int n) {\n \n int max=0;\n int count=1;\n max=h[0];\n for(int i=1;i<n;i++)\n {\n if(max<h[i])\n {\n count++;\n max=h[i];\n }\n \n }\n return count;\n }\n}" }, { "code": null, "e": 5386, "s": 5240, "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": 5422, "s": 5386, "text": " Login to access your submissions. " }, { "code": null, "e": 5432, "s": 5422, "text": "\nProblem\n" }, { "code": null, "e": 5442, "s": 5432, "text": "\nContest\n" }, { "code": null, "e": 5505, "s": 5442, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5653, "s": 5505, "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": 5861, "s": 5653, "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": 5967, "s": 5861, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Getting to know a black-box model: | by Adrian Botta | Towards Data Science
As the hype about AI has grown, so have discussions around Adversarial examples. An adversarial example, also referred to as an attack, is an input that has been crafted to be misclassified by a machine learning model. These inputs are usually a high dimensional input such as a photo, audio sample, string of text, or even software code. There are several wonderful blogs that cover adversarial attacks and defenses theoretically and at an introductory level. One of the keys to understanding adversarial examples is to first understand: How machine learning models make decisionsThe β€˜data manifold’ and higher dimensional spacesAdversarial noise or a perturbation How machine learning models make decisions The β€˜data manifold’ and higher dimensional spaces Adversarial noise or a perturbation Since these concepts are challenging to visualize in a high dimensional space, we’ll walk through an example of some of the core techniques used in adversarial attacks with a simple two-dimensional example. This will help us gain a better understanding of these concepts in higher dimensions. We’ll build a logistic regression classifier which will act as the model we intend to attack or trick, or our β€˜victim’ model. Then, we will walk through how use a gradient-based method to attack our victim and a black-box version of our victim. (All of the code used to produce this post can be seen here) Let’s borrow Martín Pellarolo’s example of building a logistic regression from a subset of the iris data set. We’ll call the two input variables X1 and X2 and the classes class 0 and class 1 to keep it simple. Our goal when training a machine learning model is to determine the line in this two-dimensional space that best separates the two classes. Luckily, it’s an easy task given that the two classes are visibly separated and there’s not much overlap. To do this, we’ll fit a logistic regression which will create a probability distribution of a data point belonging to class 1. Using the sigmoid function (represented as g) and some parameters ΞΈ, we’ll fit this probability distribution to our data. By changing the parameters in the matrix ΞΈ, we can adjust the function g to best fit our data X. def sigmoid(X, theta): return 1 / (1 + np.exp(-np.dot(X, theta[0]))) We’ll use binary cross entropy loss as the loss function to determine how close the model’s predictions are to the ground truth. def loss(X, theta, y): h = sigmoid(X, theta) return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean() The partial derivative of the loss function with respect to (w.r.t.) ΞΈ tells us the direction we need to change the values of ΞΈ to change the loss. In this case, we would like to minimize the loss. h = sigmoid(X, theta)gradient_wrt_theta = np.dot(X.T, (h - y)) / y.shape[0] Once we’ve minimized the loss function, by making directed updates to ΞΈ, our victim model is trained! The graph above shows the model’s probability distribution for any point in this space belonging to class 1, and inversely to class 0 (1- P(y=1)). It also features our model’s decision boundary at a probability threshold of 0.5 β€” If a point is above the line, the probability of it belonging to class 1 will be below 50%. Since the model β€˜decides’ at this threshold, it will assign 0 as its label prediction. The objective of a jacobian or gradient based attack, described in Explaining and Harnessing Adversarial Examples by Goodfellow et. al., is to move a point over a victim model’s decision boundary. In our example, we’ll take a point that is normally classified as class 0 and β€˜push’ it over the victim model’s decision boundary to be classified as class 1. This change to the original point is also called a perturbation when using higher dimensional data because we’re making a very small change to the input. As you may recall, when training the logistic regression, we used the loss function and derivative of the loss function w.r.t. ΞΈ to determine how ΞΈ needs to change to minimize the loss. As an attacker, with full knowledge of how the victim model works, we can determine how to change the loss by changing the other input to our function. The derivative of the loss function w.r.t. X tells us exactly in which direction we need to change the values of X to change the victim model’s loss. h = sigmoid(X, theta)gradient_wrt_X = np.dot(np.expand_dims((h-y),1),theta)/y.shape[0] Since we want to attack the model, we need to maximize its loss. Changing the values of X essentially moves X in the 2-dimensional space. Direction is only one of the components in an adversarial perturbation. We also need to take into account how large of a step (represented as epsilon) is needed to move in that direction to cross the decision boundary. #Normalizing gradient vectors to make sure step size is consistent#necessary for our 2-d example, but not called for in the papergradient_magnitudes = np.expand_dims(np.asarray(list(map(lambda x: np.linalg.norm(x), gradient_wrt_X))),1)grads_norm = gradient_wrt_X/gradient_magnitudes#Creating the adversarial perturbationepsilon = 0.5 #The step size be adjusted X_advs = X+grads_norm*epsilon An adversary must consider which data points or inputs to use as well as the smallest epsilon necessary to successfully push a point over the decision boundary. If the adversary starts with points that are very far into the class 0 space they’ll need a larger and more noticeable perturbation to convert it into an adversarial example. Let’s convert some of our points closest to the decision boundary and from class 0. (Note: Other techniques allow for creating adversarial examples from random noise - paper & article) We’ve successfully created some adversarial examples! ...Well, you may be thinking: β€œWe just moved points around. These points are just different points now...β€β€œ... and we were able to do this because we knew everything about the victim model. What if we don’t know how a victim model works?” β€œWe just moved points around. These points are just different points now...” β€œ... and we were able to do this because we knew everything about the victim model. What if we don’t know how a victim model works?” and you would be right. We’ll come back to point 1, but the techniques from Practical Black-Box Attacks against Machine Learning by Nicolas Papernot et. al. will help us with point 2. When we know everything about a model, we refer to it as a β€˜white-box’ model. In comparison, when we know nothing about how a model works, we refer to it as a β€˜black-box’. We can imagine black-box models as an API that we ping by sending inputs and receiving some outputs (labels, class numbers, etc). Understanding black-box attacks are vital because they prove that models hidden behind an API may seem safe, but are in fact still vulnerable to attacks. Papernot’s paper discusses the jacobian-based dataset augmentation technique which aims to train another model, called the substitute model, to share very similar decision boundaries as the victim model. Once a substitute model is trained to have almost the same decision boundaries as the victim model, an adversarial perturbation that is created to move a point over the substitute model’s decision boundary will likely also cross the victim model’s decision boundary. They achieve this by exploring the space around the victim model’s decision space and determining how the victim responds. This technique can be described as a child learning to annoy their parents. The child starts with no preconception of what makes their parent angry or not, but they can test their parent by picking a random-set of actions over the course of a week and noting how their parent respond to those actions. While a parent may exhibit a non-binary response for each of these, let’s pretend that the child’s actions are either bad or good (two classes). After the first week, the child has learned a bit about what bothers their parents and makes an educated guess as to what else would bother their parents. The next week, the child dials down the actions which were successful and takes actions that weren’t successful a step further. The child repeats this, each week, noting their parents’ responses and adjusting their understanding of what will bother their parents until they know exactly what annoys them and what doesn’t. Jacobian-based dataset augmentation works in the same way where a random sample of the initial data is taken and used to train a very poor substitute model. The adversarial examples are created from the dataset (using the gradient based attacks from earlier). Here, the adversarial examples are a step in the direction of the model’s gradient to determine if the black-box model will classify the new data points the same way as the substitute model. The augmented data is labeled by the black-box model and used to train a better substitute model. Just like the child, the substitute model gets a more precise understanding of where the black-box model’s decision boundary is. After a few iterations of this, the substitute model shares almost the exact same decision boundaries as the black-box model. The substitute model doesn’t even need to be the same type of ML model as the black-box. In fact, a simple Multi-Layer Perceptron is enough to learn close enough decision boundaries of a complex Convolutional Neural Network. Ultimately, with a small sample of data, a few iterations of the data augmentation and labeling, a black-box model can be successfully attacked. Now, back to point 1: You’re right, I was moving points in a 2-dimensional space. While that was for the sake of keeping the example simple, adversarial attacks take advantage of a property of neural networks that amplifies signals. Andrej Karpathy explains the effect of the dot-product in more detail here. In our two dimensional example, to move the point across the victim model’s decision boundary, we need to move it with step size epsilon. When weights matrices of a neural network are multiplied with a normal input, the product of each weight and each input value are summed. However, with an adversarial input, the additional summation of the adversarial signal amplifies the signal as a function of the total input dimensionality. Meaning, to achieve the step size needed to cross the decision boundary, we need to make smaller changes to each X value as the number of input dimensions increase. The larger the input dimensionality, the harder it is for us to notice the adversarial perturbations β€”this effect is one of the reasons why adversarial examples with MNIST are more noticeable than adversarial examples with ImageNet. Gradient-based attacks have proven to be effective techniques that exploit the way deep learning models process high dimensional inputs into probability distributions. Black-box attacks demonstrate that as long as we have access to a victim model’s inputs and outputs, we can create a good enough copy of the model to use for an attack. However, these techniques have weaknesses. To use a gradient based attack, we need to know exactly how inputs are embedded (turned into a machine readable format like a vector). For instance, an image is usually represented as a 2-d matrix of pixels or a 3-d matrix, a consistent representation of information. On the other hand, other types of unstructured data like text may be embedded using some secret pre-trained word embeddings or learned embeddings. Since we can’t take the derivative of something w.r.t. a word, we need to know how that word is being represented. Training a substitute model requires a set of possibly detectable pings to the black-box model. And researchers are finding more and more ways to defend their models against adversarial attacks. Regardless, we must be proactive in understanding the vulnerabilities of our models.
[ { "code": null, "e": 511, "s": 172, "text": "As the hype about AI has grown, so have discussions around Adversarial examples. An adversarial example, also referred to as an attack, is an input that has been crafted to be misclassified by a machine learning model. These inputs are usually a high dimensional input such as a photo, audio sample, string of text, or even software code." }, { "code": null, "e": 711, "s": 511, "text": "There are several wonderful blogs that cover adversarial attacks and defenses theoretically and at an introductory level. One of the keys to understanding adversarial examples is to first understand:" }, { "code": null, "e": 838, "s": 711, "text": "How machine learning models make decisionsThe β€˜data manifold’ and higher dimensional spacesAdversarial noise or a perturbation" }, { "code": null, "e": 881, "s": 838, "text": "How machine learning models make decisions" }, { "code": null, "e": 931, "s": 881, "text": "The β€˜data manifold’ and higher dimensional spaces" }, { "code": null, "e": 967, "s": 931, "text": "Adversarial noise or a perturbation" }, { "code": null, "e": 1260, "s": 967, "text": "Since these concepts are challenging to visualize in a high dimensional space, we’ll walk through an example of some of the core techniques used in adversarial attacks with a simple two-dimensional example. This will help us gain a better understanding of these concepts in higher dimensions." }, { "code": null, "e": 1566, "s": 1260, "text": "We’ll build a logistic regression classifier which will act as the model we intend to attack or trick, or our β€˜victim’ model. Then, we will walk through how use a gradient-based method to attack our victim and a black-box version of our victim. (All of the code used to produce this post can be seen here)" }, { "code": null, "e": 1777, "s": 1566, "text": "Let’s borrow Martín Pellarolo’s example of building a logistic regression from a subset of the iris data set. We’ll call the two input variables X1 and X2 and the classes class 0 and class 1 to keep it simple." }, { "code": null, "e": 2272, "s": 1777, "text": "Our goal when training a machine learning model is to determine the line in this two-dimensional space that best separates the two classes. Luckily, it’s an easy task given that the two classes are visibly separated and there’s not much overlap. To do this, we’ll fit a logistic regression which will create a probability distribution of a data point belonging to class 1. Using the sigmoid function (represented as g) and some parameters ΞΈ, we’ll fit this probability distribution to our data." }, { "code": null, "e": 2369, "s": 2272, "text": "By changing the parameters in the matrix ΞΈ, we can adjust the function g to best fit our data X." }, { "code": null, "e": 2441, "s": 2369, "text": "def sigmoid(X, theta): return 1 / (1 + np.exp(-np.dot(X, theta[0])))" }, { "code": null, "e": 2570, "s": 2441, "text": "We’ll use binary cross entropy loss as the loss function to determine how close the model’s predictions are to the ground truth." }, { "code": null, "e": 2678, "s": 2570, "text": "def loss(X, theta, y): h = sigmoid(X, theta) return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean()" }, { "code": null, "e": 2876, "s": 2678, "text": "The partial derivative of the loss function with respect to (w.r.t.) ΞΈ tells us the direction we need to change the values of ΞΈ to change the loss. In this case, we would like to minimize the loss." }, { "code": null, "e": 2952, "s": 2876, "text": "h = sigmoid(X, theta)gradient_wrt_theta = np.dot(X.T, (h - y)) / y.shape[0]" }, { "code": null, "e": 3054, "s": 2952, "text": "Once we’ve minimized the loss function, by making directed updates to ΞΈ, our victim model is trained!" }, { "code": null, "e": 3463, "s": 3054, "text": "The graph above shows the model’s probability distribution for any point in this space belonging to class 1, and inversely to class 0 (1- P(y=1)). It also features our model’s decision boundary at a probability threshold of 0.5 β€” If a point is above the line, the probability of it belonging to class 1 will be below 50%. Since the model β€˜decides’ at this threshold, it will assign 0 as its label prediction." }, { "code": null, "e": 3973, "s": 3463, "text": "The objective of a jacobian or gradient based attack, described in Explaining and Harnessing Adversarial Examples by Goodfellow et. al., is to move a point over a victim model’s decision boundary. In our example, we’ll take a point that is normally classified as class 0 and β€˜push’ it over the victim model’s decision boundary to be classified as class 1. This change to the original point is also called a perturbation when using higher dimensional data because we’re making a very small change to the input." }, { "code": null, "e": 4311, "s": 3973, "text": "As you may recall, when training the logistic regression, we used the loss function and derivative of the loss function w.r.t. ΞΈ to determine how ΞΈ needs to change to minimize the loss. As an attacker, with full knowledge of how the victim model works, we can determine how to change the loss by changing the other input to our function." }, { "code": null, "e": 4461, "s": 4311, "text": "The derivative of the loss function w.r.t. X tells us exactly in which direction we need to change the values of X to change the victim model’s loss." }, { "code": null, "e": 4548, "s": 4461, "text": "h = sigmoid(X, theta)gradient_wrt_X = np.dot(np.expand_dims((h-y),1),theta)/y.shape[0]" }, { "code": null, "e": 4905, "s": 4548, "text": "Since we want to attack the model, we need to maximize its loss. Changing the values of X essentially moves X in the 2-dimensional space. Direction is only one of the components in an adversarial perturbation. We also need to take into account how large of a step (represented as epsilon) is needed to move in that direction to cross the decision boundary." }, { "code": null, "e": 5296, "s": 4905, "text": "#Normalizing gradient vectors to make sure step size is consistent#necessary for our 2-d example, but not called for in the papergradient_magnitudes = np.expand_dims(np.asarray(list(map(lambda x: np.linalg.norm(x), gradient_wrt_X))),1)grads_norm = gradient_wrt_X/gradient_magnitudes#Creating the adversarial perturbationepsilon = 0.5 #The step size be adjusted X_advs = X+grads_norm*epsilon" }, { "code": null, "e": 5817, "s": 5296, "text": "An adversary must consider which data points or inputs to use as well as the smallest epsilon necessary to successfully push a point over the decision boundary. If the adversary starts with points that are very far into the class 0 space they’ll need a larger and more noticeable perturbation to convert it into an adversarial example. Let’s convert some of our points closest to the decision boundary and from class 0. (Note: Other techniques allow for creating adversarial examples from random noise - paper & article)" }, { "code": null, "e": 5871, "s": 5817, "text": "We’ve successfully created some adversarial examples!" }, { "code": null, "e": 5901, "s": 5871, "text": "...Well, you may be thinking:" }, { "code": null, "e": 6110, "s": 5901, "text": "β€œWe just moved points around. These points are just different points now...β€β€œ... and we were able to do this because we knew everything about the victim model. What if we don’t know how a victim model works?”" }, { "code": null, "e": 6187, "s": 6110, "text": "β€œWe just moved points around. These points are just different points now...”" }, { "code": null, "e": 6320, "s": 6187, "text": "β€œ... and we were able to do this because we knew everything about the victim model. What if we don’t know how a victim model works?”" }, { "code": null, "e": 6504, "s": 6320, "text": "and you would be right. We’ll come back to point 1, but the techniques from Practical Black-Box Attacks against Machine Learning by Nicolas Papernot et. al. will help us with point 2." }, { "code": null, "e": 6960, "s": 6504, "text": "When we know everything about a model, we refer to it as a β€˜white-box’ model. In comparison, when we know nothing about how a model works, we refer to it as a β€˜black-box’. We can imagine black-box models as an API that we ping by sending inputs and receiving some outputs (labels, class numbers, etc). Understanding black-box attacks are vital because they prove that models hidden behind an API may seem safe, but are in fact still vulnerable to attacks." }, { "code": null, "e": 7554, "s": 6960, "text": "Papernot’s paper discusses the jacobian-based dataset augmentation technique which aims to train another model, called the substitute model, to share very similar decision boundaries as the victim model. Once a substitute model is trained to have almost the same decision boundaries as the victim model, an adversarial perturbation that is created to move a point over the substitute model’s decision boundary will likely also cross the victim model’s decision boundary. They achieve this by exploring the space around the victim model’s decision space and determining how the victim responds." }, { "code": null, "e": 8478, "s": 7554, "text": "This technique can be described as a child learning to annoy their parents. The child starts with no preconception of what makes their parent angry or not, but they can test their parent by picking a random-set of actions over the course of a week and noting how their parent respond to those actions. While a parent may exhibit a non-binary response for each of these, let’s pretend that the child’s actions are either bad or good (two classes). After the first week, the child has learned a bit about what bothers their parents and makes an educated guess as to what else would bother their parents. The next week, the child dials down the actions which were successful and takes actions that weren’t successful a step further. The child repeats this, each week, noting their parents’ responses and adjusting their understanding of what will bother their parents until they know exactly what annoys them and what doesn’t." }, { "code": null, "e": 8929, "s": 8478, "text": "Jacobian-based dataset augmentation works in the same way where a random sample of the initial data is taken and used to train a very poor substitute model. The adversarial examples are created from the dataset (using the gradient based attacks from earlier). Here, the adversarial examples are a step in the direction of the model’s gradient to determine if the black-box model will classify the new data points the same way as the substitute model." }, { "code": null, "e": 9282, "s": 8929, "text": "The augmented data is labeled by the black-box model and used to train a better substitute model. Just like the child, the substitute model gets a more precise understanding of where the black-box model’s decision boundary is. After a few iterations of this, the substitute model shares almost the exact same decision boundaries as the black-box model." }, { "code": null, "e": 9652, "s": 9282, "text": "The substitute model doesn’t even need to be the same type of ML model as the black-box. In fact, a simple Multi-Layer Perceptron is enough to learn close enough decision boundaries of a complex Convolutional Neural Network. Ultimately, with a small sample of data, a few iterations of the data augmentation and labeling, a black-box model can be successfully attacked." }, { "code": null, "e": 9961, "s": 9652, "text": "Now, back to point 1: You’re right, I was moving points in a 2-dimensional space. While that was for the sake of keeping the example simple, adversarial attacks take advantage of a property of neural networks that amplifies signals. Andrej Karpathy explains the effect of the dot-product in more detail here." }, { "code": null, "e": 10792, "s": 9961, "text": "In our two dimensional example, to move the point across the victim model’s decision boundary, we need to move it with step size epsilon. When weights matrices of a neural network are multiplied with a normal input, the product of each weight and each input value are summed. However, with an adversarial input, the additional summation of the adversarial signal amplifies the signal as a function of the total input dimensionality. Meaning, to achieve the step size needed to cross the decision boundary, we need to make smaller changes to each X value as the number of input dimensions increase. The larger the input dimensionality, the harder it is for us to notice the adversarial perturbations β€”this effect is one of the reasons why adversarial examples with MNIST are more noticeable than adversarial examples with ImageNet." } ]
How can I round down a number in JavaScript?
The Math.floor() method returns the value of a number rounded downwards to the nearest integer. You can try to run the following code to round down numbers βˆ’ Live Demo <html> <head> <title>JavaScript Math floor() Method</title> </head> <body> <script> var value = Math.floor( 2.7 ); document.write("First Test Value : " + value ); var value = Math.floor( 20.9 ); document.write("<br />Second Test Value : " + value ); var value = Math.floor( 15.4 ); document.write("<br />Third Test Value : " + value ); </script> </body> </html> First Test Value : 2 Second Test Value : 20 Third Test Value : 15
[ { "code": null, "e": 1158, "s": 1062, "text": "The Math.floor() method returns the value of a number rounded downwards to the nearest integer." }, { "code": null, "e": 1220, "s": 1158, "text": "You can try to run the following code to round down numbers βˆ’" }, { "code": null, "e": 1230, "s": 1220, "text": "Live Demo" }, { "code": null, "e": 1678, "s": 1230, "text": "<html>\n <head>\n <title>JavaScript Math floor() Method</title>\n </head>\n <body>\n <script>\n var value = Math.floor( 2.7 );\n document.write(\"First Test Value : \" + value );\n\n var value = Math.floor( 20.9 );\n document.write(\"<br />Second Test Value : \" + value );\n\n var value = Math.floor( 15.4 );\n document.write(\"<br />Third Test Value : \" + value );\n </script>\n </body>\n</html>" }, { "code": null, "e": 1744, "s": 1678, "text": "First Test Value : 2\nSecond Test Value : 20\nThird Test Value : 15" } ]
numpy.isreal() in Python - GeeksforGeeks
28 Mar, 2022 numpy.isreal(array) : Test element-wise whether it is a real number or not(not infinity or not Not a Number) and return the result as a boolean array. Parameters : array : [array_like] Input array whose element we want to test Return : boolean array containing the result Code 1 : Python # Python Program illustrating# numpy.isreal() method import numpy as geek print("Is Real : ", geek.isreal([1+1j, 0j]), "\n") print("Is Real : ", geek.isreal([1, 0]), "\n") Output : Is Real : [False True] Is Real : [ True True] Code 2 : Python # Python Program illustrating# numpy.isreal() method import numpy as geek # Returns True/False value for each elementa = geek.arange(20).reshape(5, 4)print("Is Real : \n", geek.isreal(a), "\n") # Returns True/False value as ans# because we have mentioned dtype in the beginninga = geek.arange(20).reshape(5, 4).dtype = floatprint("\nIs Real : ", geek.isreal(a)) Output : Is Real : [[ True True True True] [ True True True True] [ True True True True] [ True True True True] [ True True True True]] Is Real : True References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.isreal.html#numpy.isrealNote : These codes won’t run on online IDE’s. So please, run them on your systems to explore the working. This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Akanksha_Rai surinderdawra388 vinayedula Python numpy-Logic Functions Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Python OOPs Concepts Python | Get unique values from a list Check if element exists in list in Python Python Classes and Objects Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Pandas dataframe.groupby() Create a directory in Python
[ { "code": null, "e": 24212, "s": 24184, "text": "\n28 Mar, 2022" }, { "code": null, "e": 24378, "s": 24212, "text": "numpy.isreal(array) : Test element-wise whether it is a real number or not(not infinity or not Not a Number) and return the result as a boolean array. Parameters : " }, { "code": null, "e": 24441, "s": 24378, "text": "array : [array_like] Input array whose element we want to test" }, { "code": null, "e": 24452, "s": 24441, "text": "Return : " }, { "code": null, "e": 24488, "s": 24452, "text": "boolean array containing the result" }, { "code": null, "e": 24498, "s": 24488, "text": "Code 1 : " }, { "code": null, "e": 24505, "s": 24498, "text": "Python" }, { "code": "# Python Program illustrating# numpy.isreal() method import numpy as geek print(\"Is Real : \", geek.isreal([1+1j, 0j]), \"\\n\") print(\"Is Real : \", geek.isreal([1, 0]), \"\\n\")", "e": 24678, "s": 24505, "text": null }, { "code": null, "e": 24689, "s": 24678, "text": "Output : " }, { "code": null, "e": 24742, "s": 24689, "text": "Is Real : [False True] \n\nIs Real : [ True True] " }, { "code": null, "e": 24753, "s": 24742, "text": "Code 2 : " }, { "code": null, "e": 24760, "s": 24753, "text": "Python" }, { "code": "# Python Program illustrating# numpy.isreal() method import numpy as geek # Returns True/False value for each elementa = geek.arange(20).reshape(5, 4)print(\"Is Real : \\n\", geek.isreal(a), \"\\n\") # Returns True/False value as ans# because we have mentioned dtype in the beginninga = geek.arange(20).reshape(5, 4).dtype = floatprint(\"\\nIs Real : \", geek.isreal(a))", "e": 25126, "s": 24760, "text": null }, { "code": null, "e": 25137, "s": 25126, "text": "Output : " }, { "code": null, "e": 25304, "s": 25137, "text": "Is Real : \n [[ True True True True]\n [ True True True True]\n [ True True True True]\n [ True True True True]\n [ True True True True]] \n\n\nIs Real : True" }, { "code": null, "e": 25510, "s": 25304, "text": "References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.isreal.html#numpy.isrealNote : These codes won’t run on online IDE’s. So please, run them on your systems to explore the working." }, { "code": null, "e": 25935, "s": 25510, "text": "This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 25948, "s": 25935, "text": "Akanksha_Rai" }, { "code": null, "e": 25965, "s": 25948, "text": "surinderdawra388" }, { "code": null, "e": 25976, "s": 25965, "text": "vinayedula" }, { "code": null, "e": 26005, "s": 25976, "text": "Python numpy-Logic Functions" }, { "code": null, "e": 26018, "s": 26005, "text": "Python-numpy" }, { "code": null, "e": 26025, "s": 26018, "text": "Python" }, { "code": null, "e": 26123, "s": 26025, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26132, "s": 26123, "text": "Comments" }, { "code": null, "e": 26145, "s": 26132, "text": "Old Comments" }, { "code": null, "e": 26177, "s": 26145, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26233, "s": 26177, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26254, "s": 26233, "text": "Python OOPs Concepts" }, { "code": null, "e": 26293, "s": 26254, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26335, "s": 26293, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26362, "s": 26335, "text": "Python Classes and Objects" }, { "code": null, "e": 26393, "s": 26362, "text": "Python | os.path.join() method" }, { "code": null, "e": 26435, "s": 26393, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26471, "s": 26435, "text": "Python | Pandas dataframe.groupby()" } ]
Rename column name in MySQL?
To rename column name in MySQL, you need to use the ALTER and CHANGE commands. Let us first create a table βˆ’ mysql> create table DemoTable796 ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, Name varchar(100), StudentAge int ); Query OK, 0 rows affected (0.56 sec) Let us check the description of table βˆ’ mysql> desc DemoTable796; This will produce the following output - +------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+--------------+------+-----+---------+----------------+ | StudentId | int(11) | NO | PRI | NULL | auto_increment | | Name | varchar(100) | YES | | NULL | | | StudentAge | int(11) | YES | | NULL | | +------------+--------------+------+-----+---------+----------------+ 3 rows in set (0.00 sec) Following is the query to rename column name in MySQL βˆ’ mysql> alter table DemoTable796 change Name StudentName varchar(100); Query OK, 0 rows affected (0.29 sec) Records: 0 Duplicates: 0 Warnings: 0 Let us check the description of table once again βˆ’ mysql> desc DemoTable796; This will produce the following output - +-------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+--------------+------+-----+---------+----------------+ | StudentId | int(11) | NO | PRI | NULL | auto_increment | | StudentName | varchar(100) | YES | | NULL | | | StudentAge | int(11) | YES | | NULL | | +-------------+--------------+------+-----+---------+----------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1141, "s": 1062, "text": "To rename column name in MySQL, you need to use the ALTER and CHANGE commands." }, { "code": null, "e": 1171, "s": 1141, "text": "Let us first create a table βˆ’" }, { "code": null, "e": 1340, "s": 1171, "text": "mysql> create table DemoTable796 (\n StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n Name varchar(100),\n StudentAge int\n);\nQuery OK, 0 rows affected (0.56 sec)" }, { "code": null, "e": 1380, "s": 1340, "text": "Let us check the description of table βˆ’" }, { "code": null, "e": 1406, "s": 1380, "text": "mysql> desc DemoTable796;" }, { "code": null, "e": 1447, "s": 1406, "text": "This will produce the following output -" }, { "code": null, "e": 1962, "s": 1447, "text": "+------------+--------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+------------+--------------+------+-----+---------+----------------+\n| StudentId | int(11) | NO | PRI | NULL | auto_increment |\n| Name | varchar(100) | YES | | NULL | |\n| StudentAge | int(11) | YES | | NULL | |\n+------------+--------------+------+-----+---------+----------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2018, "s": 1962, "text": "Following is the query to rename column name in MySQL βˆ’" }, { "code": null, "e": 2162, "s": 2018, "text": "mysql> alter table DemoTable796 change Name StudentName varchar(100);\nQuery OK, 0 rows affected (0.29 sec)\nRecords: 0 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 2213, "s": 2162, "text": "Let us check the description of table once again βˆ’" }, { "code": null, "e": 2239, "s": 2213, "text": "mysql> desc DemoTable796;" }, { "code": null, "e": 2280, "s": 2239, "text": "This will produce the following output -" }, { "code": null, "e": 2802, "s": 2280, "text": "+-------------+--------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+-------------+--------------+------+-----+---------+----------------+\n| StudentId | int(11) | NO | PRI | NULL | auto_increment |\n| StudentName | varchar(100) | YES | | NULL | |\n| StudentAge | int(11) | YES | | NULL | |\n+-------------+--------------+------+-----+---------+----------------+\n3 rows in set (0.00 sec)" } ]
How to read data from user using the Console class in Java?
This class is used to write/read data from the console (keyboard/screen) devices. It provides a readLine() method which reads a line from the key-board. You can get an object of the Console class using the console() method. Note βˆ’ If you try to execute this program in a non-interactive environment like IDE it doesn’t work. Following Java program reads data from user using the Console class. Live Demo import java.io.BufferedReader; import java.io.Console; import java.io.IOException; import java.io.InputStreamReader; class Student { String name; int age; float percent; boolean isLocal; char grade; Student(String name, int age, float percent, boolean isLocal, char grade) { this.name = name; this.age = age; this.percent = percent; this.isLocal = isLocal; this.grade = grade; } public void displayDetails() { System.out.println("Details.............."); System.out.println("Name: "+this.name); System.out.println("Age: "+this.age); System.out.println("Percent: "+this.percent); if(this.isLocal) { System.out.println("Nationality: Indian"); } else { System.out.println("Nationality: Foreigner"); } System.out.println("Grade: "+this.grade); } } public class ReadData { public static void main(String args[]) throws IOException { Console console = System.console(); if (console == null) { System.out.println("Console is not supported"); System.exit(1); } System.out.println("Enter your name: "); String name = console.readLine(); System.out.println("Enter your age: "); int age = Integer.parseInt(console.readLine()); System.out.println("Enter your percent: "); float percent = Float.parseFloat(console.readLine()); System.out.println("Are you local (enter true or false): "); boolean isLocal = Boolean.parseBoolean(console.readLine()); System.out.println("Enter your grade(enter A, or, B or, C or, D): "); char grade = console.readLine().toCharArray()[0]; Student std = new Student(name, age, percent, isLocal, grade); std.displayDetails(); } } Enter your name: Krishna Enter your age: 26 Enter your percent: 86 Are you local (enter true or false): true Enter your grade(enter A, or, B or, C or, D): A Details.............. Name: Krishna Age: 26 Percent: 86.0 Nationality: Indian Grade: A
[ { "code": null, "e": 1286, "s": 1062, "text": "This class is used to write/read data from the console (keyboard/screen) devices. It provides a readLine() method which reads a line from the key-board. You can get an object of the Console class using the console() method." }, { "code": null, "e": 1387, "s": 1286, "text": "Note βˆ’ If you try to execute this program in a non-interactive environment like IDE it doesn’t work." }, { "code": null, "e": 1456, "s": 1387, "text": "Following Java program reads data from user using the Console class." }, { "code": null, "e": 1467, "s": 1456, "text": " Live Demo" }, { "code": null, "e": 3248, "s": 1467, "text": "import java.io.BufferedReader;\nimport java.io.Console;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nclass Student {\n String name;\n int age;\n float percent;\n boolean isLocal;\n char grade;\n Student(String name, int age, float percent, boolean isLocal, char grade) {\n this.name = name;\n this.age = age;\n this.percent = percent;\n this.isLocal = isLocal;\n this.grade = grade;\n }\n public void displayDetails() {\n System.out.println(\"Details..............\");\n System.out.println(\"Name: \"+this.name);\n System.out.println(\"Age: \"+this.age);\n System.out.println(\"Percent: \"+this.percent);\n if(this.isLocal) {\n System.out.println(\"Nationality: Indian\");\n } else {\n System.out.println(\"Nationality: Foreigner\");\n }\n System.out.println(\"Grade: \"+this.grade);\n }\n}\npublic class ReadData {\n public static void main(String args[]) throws IOException {\n Console console = System.console();\n if (console == null) {\n System.out.println(\"Console is not supported\");\n System.exit(1);\n }\n System.out.println(\"Enter your name: \");\n String name = console.readLine();\n System.out.println(\"Enter your age: \");\n int age = Integer.parseInt(console.readLine());\n System.out.println(\"Enter your percent: \");\n float percent = Float.parseFloat(console.readLine());\n System.out.println(\"Are you local (enter true or false): \");\n boolean isLocal = Boolean.parseBoolean(console.readLine());\n System.out.println(\"Enter your grade(enter A, or, B or, C or, D): \");\n char grade = console.readLine().toCharArray()[0];\n Student std = new Student(name, age, percent, isLocal, grade);\n std.displayDetails();\n }\n}" }, { "code": null, "e": 3492, "s": 3248, "text": "Enter your name:\nKrishna\nEnter your age:\n26\nEnter your percent:\n86\nAre you local (enter true or false):\ntrue\nEnter your grade(enter A, or, B or, C or, D):\nA\nDetails..............\nName: Krishna\nAge: 26\nPercent: 86.0\nNationality: Indian\nGrade: A" } ]
C Program to Reverse Array of Strings
In this problem, we are given an array of string. Our task is to create a c program to reverse array of strings. We will reverse the array elements i.e. last element to the first value and so on. Let’s take an example to understand the problem, strarr[] = {"learn", "programming", "at", "tutorialspoint"} strarr[] = {"tutorialspoint", "at", "programming", "learn"} To solve this problem, we will create an array of pointers and use two pointers from start and end. then move the pointers towards the opposite side, and keep on swapping the pointer values. //c program to reverse array of strings. Live Demo #include <stdio.h> #include <string.h> void ReverseStringArray(char* strarr[], int n) { char* temp; int end = n - 1; for (int start = 0; start < end; start++) { temp = strarr[start]; strarr[start] = strarr[end]; strarr[end] = temp; end--; } } int main() { char* strarr[] = {"learn", "programming", "at", "tutorialspoint"}; int n = sizeof(strarr) / sizeof(strarr[0]); for (int i = 0; i < n; i++) printf("%s ", strarr[i]); printf("\n"); ReverseStringArray(strarr, n); for (int i = 0; i < n; i++) printf("%s ", strarr[i]); return 0; } learn programming at tutorialspoint tutorialspoint at programming learn
[ { "code": null, "e": 1175, "s": 1062, "text": "In this problem, we are given an array of string. Our task is to create a c program to reverse array of strings." }, { "code": null, "e": 1258, "s": 1175, "text": "We will reverse the array elements i.e. last element to the first value and so on." }, { "code": null, "e": 1307, "s": 1258, "text": "Let’s take an example to understand the problem," }, { "code": null, "e": 1367, "s": 1307, "text": "strarr[] = {\"learn\", \"programming\", \"at\", \"tutorialspoint\"}" }, { "code": null, "e": 1427, "s": 1367, "text": "strarr[] = {\"tutorialspoint\", \"at\", \"programming\", \"learn\"}" }, { "code": null, "e": 1618, "s": 1427, "text": "To solve this problem, we will create an array of pointers and use two pointers from start and end. then move the pointers towards the opposite side, and keep on swapping the pointer values." }, { "code": null, "e": 1659, "s": 1618, "text": "//c program to reverse array of strings." }, { "code": null, "e": 1670, "s": 1659, "text": " Live Demo" }, { "code": null, "e": 2271, "s": 1670, "text": "#include <stdio.h>\n#include <string.h>\nvoid ReverseStringArray(char* strarr[], int n) {\n char* temp;\n int end = n - 1;\n for (int start = 0; start < end; start++) {\n temp = strarr[start];\n strarr[start] = strarr[end];\n strarr[end] = temp;\n end--;\n }\n}\nint main() {\n char* strarr[] = {\"learn\", \"programming\", \"at\", \"tutorialspoint\"};\n int n = sizeof(strarr) / sizeof(strarr[0]);\n for (int i = 0; i < n; i++)\n printf(\"%s \", strarr[i]);\n printf(\"\\n\");\n ReverseStringArray(strarr, n);\n for (int i = 0; i < n; i++)\n printf(\"%s \", strarr[i]);\n return 0;\n}" }, { "code": null, "e": 2343, "s": 2271, "text": "learn programming at tutorialspoint\ntutorialspoint at programming learn" } ]
How to make an existing field Unique in MySQL?
To make an existing field unique in MySQL, we can use the ALTER command and set UNIQUE constraint for the field. Let us see an example. First, we will create a table. mysql> create table AddingUnique -> ( -> Id int, -> name varchar(100) -> ); Query OK, 0 rows affected (0.44 sec) Syntax to add UNIQUE to an existing field. alter table yourTableName add UNIQUE(yourColumnName); Applying the above syntax in order to add UNIQUE to column β€˜name’. mysql> alter table AddingUnique add UNIQUE(name); Query OK, 0 rows affected (0.60 sec) Records: 0 Duplicates: 0 Warnings: 0 Now we cannot insert duplicate records into the table, since we have set the field to be unique. If we try to add duplicate records then it raises an error. mysql> alter table AddingUnique add UNIQUE(name); Query OK, 0 rows affected (0.60 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> insert into AddingUnique values(1,'John'); Query OK, 1 row affected (0.15 sec) mysql> insert into AddingUnique values(1,'John'); ERROR 1062 (23000): Duplicate entry 'John' for key 'name' mysql> insert into AddingUnique values(2,'Carol'); Query OK, 1 row affected (0.18 sec) mysql> insert into AddingUnique values(3,'John'); ERROR 1062 (23000): Duplicate entry 'John' for key 'name' mysql> insert into AddingUnique values(4,'Smith'); Query OK, 1 row affected (0.18 sec) To display all records. mysql> select *from AddingUnique; The following is the output. +------+-------+ | Id | name | +------+-------+ | 1 | John | | 2 | Carol | | 4 | Smith | +------+-------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1229, "s": 1062, "text": "To make an existing field unique in MySQL, we can use the ALTER command and set UNIQUE constraint for the field. Let us see an example. First, we will create a table." }, { "code": null, "e": 1354, "s": 1229, "text": "mysql> create table AddingUnique\n -> (\n -> Id int,\n -> name varchar(100)\n -> );\nQuery OK, 0 rows affected (0.44 sec)" }, { "code": null, "e": 1397, "s": 1354, "text": "Syntax to add UNIQUE to an existing field." }, { "code": null, "e": 1451, "s": 1397, "text": "alter table yourTableName add UNIQUE(yourColumnName);" }, { "code": null, "e": 1518, "s": 1451, "text": "Applying the above syntax in order to add UNIQUE to column β€˜name’." }, { "code": null, "e": 1644, "s": 1518, "text": "mysql> alter table AddingUnique add UNIQUE(name);\nQuery OK, 0 rows affected (0.60 sec)\nRecords: 0 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 1801, "s": 1644, "text": "Now we cannot insert duplicate records into the table, since we have set the field to be unique. If we try to add duplicate records then it raises an error." }, { "code": null, "e": 2408, "s": 1801, "text": "mysql> alter table AddingUnique add UNIQUE(name);\nQuery OK, 0 rows affected (0.60 sec)\nRecords: 0 Duplicates: 0 Warnings: 0\n\nmysql> insert into AddingUnique values(1,'John');\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into AddingUnique values(1,'John');\nERROR 1062 (23000): Duplicate entry 'John' for key 'name'\n\nmysql> insert into AddingUnique values(2,'Carol');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into AddingUnique values(3,'John');\nERROR 1062 (23000): Duplicate entry 'John' for key 'name'\n\nmysql> insert into AddingUnique values(4,'Smith');\nQuery OK, 1 row affected (0.18 sec)" }, { "code": null, "e": 2432, "s": 2408, "text": "To display all records." }, { "code": null, "e": 2466, "s": 2432, "text": "mysql> select *from AddingUnique;" }, { "code": null, "e": 2495, "s": 2466, "text": "The following is the output." }, { "code": null, "e": 2640, "s": 2495, "text": "+------+-------+\n| Id | name |\n+------+-------+\n| 1 | John |\n| 2 | Carol |\n| 4 | Smith |\n+------+-------+\n3 rows in set (0.00 sec)\n" } ]
Binary Tree to DLL | Practice | GeeksforGeeks
Given a Binary Tree (BT), convert it to a Doubly Linked List(DLL) In-Place. The left and right pointers in nodes are to be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be same as Inorder of the given Binary Tree. The first node of Inorder traversal (leftmost node in BT) must be the head node of the DLL. Example 1: Input: 1 / \ 3 2 Output: 3 1 2 2 1 3 Explanation: DLL would be 3<=>1<=>2 Example 2: Input: 10 / \ 20 30 / \ 40 60 Output: 40 20 60 10 30 30 10 60 20 40 Explanation: DLL would be 40<=>20<=>60<=>10<=>30. Your Task: You don't have to take input. Complete the function bToDLL() that takes root node of the tree as a parameter and returns the head of DLL . The driver code prints the DLL both ways. Expected Time Complexity: O(N). Expected Auxiliary Space: O(H). Note: H is the height of the tree and this space is used implicitly for the recursion stack. Constraints: 1 ≀ Number of nodes ≀ 105 1 ≀ Data of a node ≀ 105 0 ssprateekgaur9993 days ago class Solution{ public: //Function to convert binary tree to doubly linked list and return it. Node* solve(Node* root){ //base cases if(root==NULL) return root; if( !root->left && !root->right){ return root; } if(root->left==NULL){ Node* r=solve(root->right); while(r->left){ r=r->left; } r->left=root; root->right=r; return root; } if(root->right==NULL){ Node* l=solve(root->left); while(l->right){ l=l->right; } l->right=root; root->left=l; return root; } //Hypothesis Node* l=solve(root->left); Node* r=solve(root->right); //Induction while(l->right!=NULL) { l=l->right; } l->right=root; root->left=l; while(r->left!=NULL){ r=r->left; } r->left=root; root->right=r; return root; } Node * bToDLL(Node *root) { // your code here solve(root); while(root->left!=NULL){ root=root->left; } return root; }}; 0 rmn51245 days ago class Solution { public: //Function to convert binary tree to doubly linked list and return it. void inorder(Node*root,Node* &head,Node* &prev,int& f){ if(!root) return; inorder(root->left,head,prev,f); if(f==0){ head=root; prev=head; f=1; } else{ prev->right=root; prev->right->left=prev; prev=prev->right; } inorder(root->right,head,prev,f); } //Function to convert binary tree to doubly linked list and return it. Node * bToDLL(Node *root) { // your code here int f=0; Node*head=NULL; Node*prev=NULL; inorder(root,head,prev,f); return head; } }; 0 harshilgupta00996 days ago Node* prev=NULL; Node * bToDLL(Node *root) { if(root==NULL) return root; Node* head=bToDLL(root->left); if(prev==NULL) head=root; else{ root->left=prev; prev->right=root; } prev=root; bToDLL(root->right); return head; } +2 madhukartemba2 weeks ago JAVA SOLUTION: class Pair { Node minNode, maxNode; Pair(Node minNode, Node maxNode) { this.minNode = minNode; this.maxNode = maxNode; } } class Solution { private Pair rec(Node root) { if(root==null) return null; Pair left_pair = rec(root.left); Pair right_pair = rec(root.right); if(left_pair!=null) { left_pair.maxNode.right = root; root.left = left_pair.maxNode; } if(right_pair!=null) { right_pair.minNode.left = root; root.right = right_pair.minNode; } if(left_pair==null && right_pair==null) return new Pair(root, root); if(left_pair!=null && right_pair==null) return new Pair(left_pair.minNode, root); if(left_pair==null && right_pair!=null) return new Pair(root, right_pair.maxNode); else return new Pair(left_pair.minNode, right_pair.maxNode); } //Function to convert binary tree to doubly linked list and return it. Node bToDLL(Node root) { Pair ans = rec(root); return ans.minNode; } } +1 harshitgarhewal4562 weeks ago Java class Solution{ Node prev = null; Node head = null; void inorder(Node node){ if(node == null){ return; } inorder(node.left); node.left = prev; if(prev!=null) prev.right = node; prev = node; inorder(node.right); } //Function to convert binary tree to doubly linked list and return it. Node bToDLL(Node root) {// Your code her Node curr = root; while(curr!=null){ head = curr; curr = curr.left; } inorder(root); return head; } } +2 user_990i2 weeks ago Node* head=NULL,*prev=NULL; void bd(Node* root){ if(!root)return; bd(root->left); if(!head){ head=root; prev=root; } else{ prev->right=root; root->left=prev; } prev=root; bd(root->right); } Node * bToDLL(Node *root) { head=NULL; prev=NULL; bd(root); return head; } 0 akshitt125 This comment was deleted. 0 tthakare732 weeks ago //Java Solution //hint -> inorder & queue class Solution{ Queue<Node> q=new LinkedList<>(); void inOrder(Node root){ if(root==null){ return; } inOrder(root.left); q.add(root); inOrder(root.right); } Node bToDLL(Node root){ //Variables Node pre = null, current = null, ResultH = null; inOrder(root); if(q.isEmpty()) return null; while(!q.isEmpty()){ current = q.poll(); if(pre == null) ResultH = current; //for first Node ref to head else { pre.right = current; //a -> b current.left = pre; //a <- a } pre = current; } return ResultH; } } 0 tthakare73 This comment was deleted. 0 ishan1010013 weeks ago This method is giving Abort signal from abort(3) (SIGABRT) error? Node * bToDLL(Node *root) { // your code Node * head = NULL; Node * tail = NULL; stack<Node *> stk; while(!stk.empty() || root!=NULL){ if(root!=NULL){ stk.push(root); root = root->left; } else{ root = stk.top(); stk.pop(); if(head == NULL){ head = root; tail = root; } else{ tail->right = root; root->left = tail; tail = root; root = root->right; } } } return head; } 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": 595, "s": 238, "text": "Given a Binary Tree (BT), convert it to a Doubly Linked List(DLL) In-Place. The left and right pointers in nodes are to be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be same as Inorder of the given Binary Tree. The first node of Inorder traversal (leftmost node in BT) must be the head node of the DLL." }, { "code": null, "e": 606, "s": 595, "text": "Example 1:" }, { "code": null, "e": 699, "s": 606, "text": "Input:\n 1\n / \\\n 3 2\nOutput:\n3 1 2 \n2 1 3 \nExplanation: DLL would be 3<=>1<=>2\n" }, { "code": null, "e": 710, "s": 699, "text": "Example 2:" }, { "code": null, "e": 862, "s": 710, "text": "Input:\n 10\n / \\\n 20 30\n / \\\n 40 60\nOutput:\n40 20 60 10 30 \n30 10 60 20 40\nExplanation: DLL would be \n40<=>20<=>60<=>10<=>30." }, { "code": null, "e": 1054, "s": 862, "text": "Your Task:\nYou don't have to take input. Complete the function bToDLL() that takes root node of the tree as a parameter and returns the head of DLL . The driver code prints the DLL both ways." }, { "code": null, "e": 1211, "s": 1054, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(H).\nNote: H is the height of the tree and this space is used implicitly for the recursion stack." }, { "code": null, "e": 1275, "s": 1211, "text": "Constraints:\n1 ≀ Number of nodes ≀ 105\n1 ≀ Data of a node ≀ 105" }, { "code": null, "e": 1277, "s": 1275, "text": "0" }, { "code": null, "e": 1304, "s": 1277, "text": "ssprateekgaur9993 days ago" }, { "code": null, "e": 1437, "s": 1304, "text": "class Solution{ public: //Function to convert binary tree to doubly linked list and return it. Node* solve(Node* root){" }, { "code": null, "e": 1465, "s": 1445, "text": " //base cases" }, { "code": null, "e": 1790, "s": 1465, "text": " if(root==NULL) return root; if( !root->left && !root->right){ return root; } if(root->left==NULL){ Node* r=solve(root->right); while(r->left){ r=r->left; } r->left=root; root->right=r; return root; }" }, { "code": null, "e": 2020, "s": 1790, "text": " if(root->right==NULL){ Node* l=solve(root->left); while(l->right){ l=l->right; } l->right=root; root->left=l; return root; } " }, { "code": null, "e": 2040, "s": 2020, "text": " //Hypothesis" }, { "code": null, "e": 2115, "s": 2040, "text": " Node* l=solve(root->left); Node* r=solve(root->right); " }, { "code": null, "e": 2534, "s": 2115, "text": " //Induction while(l->right!=NULL) { l=l->right; } l->right=root; root->left=l; while(r->left!=NULL){ r=r->left; } r->left=root; root->right=r; return root; } Node * bToDLL(Node *root) { // your code here solve(root); while(root->left!=NULL){ root=root->left; } return root; }};" }, { "code": null, "e": 2536, "s": 2534, "text": "0" }, { "code": null, "e": 2554, "s": 2536, "text": "rmn51245 days ago" }, { "code": null, "e": 3333, "s": 2554, "text": "class Solution\n{\n public: \n //Function to convert binary tree to doubly linked list and return it.\n void inorder(Node*root,Node* &head,Node* &prev,int& f){\n if(!root) return;\n inorder(root->left,head,prev,f);\n if(f==0){\n head=root;\n prev=head;\n f=1;\n }\n else{\n prev->right=root;\n prev->right->left=prev;\n prev=prev->right;\n \n }\n inorder(root->right,head,prev,f);\n }\n //Function to convert binary tree to doubly linked list and return it.\n Node * bToDLL(Node *root)\n {\n // your code here\n int f=0;\n Node*head=NULL;\n Node*prev=NULL;\n inorder(root,head,prev,f);\n return head;\n }\n\n};" }, { "code": null, "e": 3335, "s": 3333, "text": "0" }, { "code": null, "e": 3362, "s": 3335, "text": "harshilgupta00996 days ago" }, { "code": null, "e": 3706, "s": 3362, "text": "Node* prev=NULL;\n Node * bToDLL(Node *root)\n {\n if(root==NULL)\n return root;\n Node* head=bToDLL(root->left);\n if(prev==NULL)\n head=root;\n else{\n root->left=prev;\n prev->right=root;\n }\n prev=root;\n bToDLL(root->right);\n return head;\n }" }, { "code": null, "e": 3709, "s": 3706, "text": "+2" }, { "code": null, "e": 3734, "s": 3709, "text": "madhukartemba2 weeks ago" }, { "code": null, "e": 3749, "s": 3734, "text": "JAVA SOLUTION:" }, { "code": null, "e": 4961, "s": 3749, "text": "class Pair\n{\n Node minNode, maxNode;\n \n Pair(Node minNode, Node maxNode)\n {\n this.minNode = minNode;\n this.maxNode = maxNode;\n }\n}\n\nclass Solution\n{\n \n private Pair rec(Node root)\n {\n if(root==null) return null;\n \n Pair left_pair = rec(root.left);\n \n Pair right_pair = rec(root.right);\n \n if(left_pair!=null)\n {\n left_pair.maxNode.right = root;\n root.left = left_pair.maxNode;\n }\n \n if(right_pair!=null)\n {\n right_pair.minNode.left = root;\n root.right = right_pair.minNode;\n }\n \n if(left_pair==null && right_pair==null) return new Pair(root, root);\n if(left_pair!=null && right_pair==null) return new Pair(left_pair.minNode, root);\n if(left_pair==null && right_pair!=null) return new Pair(root, right_pair.maxNode);\n else return new Pair(left_pair.minNode, right_pair.maxNode);\n \n \n \n }\n \n \n //Function to convert binary tree to doubly linked list and return it.\n Node bToDLL(Node root)\n {\n Pair ans = rec(root);\n \n return ans.minNode;\n }\n}" }, { "code": null, "e": 4964, "s": 4961, "text": "+1" }, { "code": null, "e": 4994, "s": 4964, "text": "harshitgarhewal4562 weeks ago" }, { "code": null, "e": 4999, "s": 4994, "text": "Java" }, { "code": null, "e": 5615, "s": 5001, "text": "class Solution{ Node prev = null; Node head = null; void inorder(Node node){ if(node == null){ return; } inorder(node.left); node.left = prev; if(prev!=null) prev.right = node; prev = node; inorder(node.right); } //Function to convert binary tree to doubly linked list and return it. Node bToDLL(Node root) {// Your code her Node curr = root; while(curr!=null){ head = curr; curr = curr.left; } inorder(root); return head; } }" }, { "code": null, "e": 5618, "s": 5615, "text": "+2" }, { "code": null, "e": 5639, "s": 5618, "text": "user_990i2 weeks ago" }, { "code": null, "e": 6041, "s": 5639, "text": " Node* head=NULL,*prev=NULL; void bd(Node* root){ if(!root)return; bd(root->left); if(!head){ head=root; prev=root; } else{ prev->right=root; root->left=prev; } prev=root; bd(root->right); } Node * bToDLL(Node *root) { head=NULL; prev=NULL; bd(root); return head; }" }, { "code": null, "e": 6043, "s": 6041, "text": "0" }, { "code": null, "e": 6054, "s": 6043, "text": "akshitt125" }, { "code": null, "e": 6080, "s": 6054, "text": "This comment was deleted." }, { "code": null, "e": 6082, "s": 6080, "text": "0" }, { "code": null, "e": 6104, "s": 6082, "text": "tthakare732 weeks ago" }, { "code": null, "e": 6874, "s": 6104, "text": "//Java Solution \n//hint -> inorder & queue\nclass Solution{ \n Queue<Node> q=new LinkedList<>();\n void inOrder(Node root){\n if(root==null){\n return;\n }\n inOrder(root.left);\n q.add(root);\n inOrder(root.right);\n }\n \n Node bToDLL(Node root){\n //Variables\n Node pre = null, current = null, ResultH = null;\n \n inOrder(root);\n if(q.isEmpty()) return null;\n while(!q.isEmpty()){\n current = q.poll(); \n if(pre == null)\n ResultH = current; //for first Node ref to head\n else {\n pre.right = current; //a -> b\n current.left = pre; //a <- a \n }\n pre = current;\n }\n return ResultH; \n }\n}" }, { "code": null, "e": 6876, "s": 6874, "text": "0" }, { "code": null, "e": 6887, "s": 6876, "text": "tthakare73" }, { "code": null, "e": 6913, "s": 6887, "text": "This comment was deleted." }, { "code": null, "e": 6915, "s": 6913, "text": "0" }, { "code": null, "e": 6938, "s": 6915, "text": "ishan1010013 weeks ago" }, { "code": null, "e": 7004, "s": 6938, "text": "This method is giving Abort signal from abort(3) (SIGABRT) error?" }, { "code": null, "e": 7681, "s": 7006, "text": "Node * bToDLL(Node *root) { // your code Node * head = NULL; Node * tail = NULL; stack<Node *> stk; while(!stk.empty() || root!=NULL){ if(root!=NULL){ stk.push(root); root = root->left; } else{ root = stk.top(); stk.pop(); if(head == NULL){ head = root; tail = root; } else{ tail->right = root; root->left = tail; tail = root; root = root->right; } } } return head; }" }, { "code": null, "e": 7827, "s": 7681, "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": 7863, "s": 7827, "text": " Login to access your submissions. " }, { "code": null, "e": 7873, "s": 7863, "text": "\nProblem\n" }, { "code": null, "e": 7883, "s": 7873, "text": "\nContest\n" }, { "code": null, "e": 7946, "s": 7883, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8094, "s": 7946, "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": 8302, "s": 8094, "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": 8408, "s": 8302, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
C++ Program to Implement Queue using Array
A queue is an abstract data structure that contains a collection of elements. Queue implements the FIFO mechanism i.e. the element that is inserted first is also deleted first. In other words, the least recently added element is removed first in a queue. A program that implements the queue using an array is given as follows βˆ’ #include <iostream> using namespace std; int queue[100], n = 100, front = - 1, rear = - 1; void Insert() { int val; if (rear == n - 1) cout<<"Queue Overflow"<<endl; else { if (front == - 1) front = 0; cout<<"Insert the element in queue : "<<endl; cin>>val; rear++; queue[rear] = val; } } void Delete() { if (front == - 1 || front > rear) { cout<<"Queue Underflow "; return ; } else { cout<<"Element deleted from queue is : "<< queue[front] <<endl; front++;; } } void Display() { if (front == - 1) cout<<"Queue is empty"<<endl; else { cout<<"Queue elements are : "; for (int i = front; i <= rear; i++) cout<<queue[i]<<" "; cout<<endl; } } int main() { int ch; cout<<"1) Insert element to queue"<<endl; cout<<"2) Delete element from queue"<<endl; cout<<"3) Display all the elements of queue"<<endl; cout<<"4) Exit"<<endl; do { cout<<"Enter your choice : "<<endl; cin>>ch; switch (ch) { case 1: Insert(); break; case 2: Delete(); break; case 3: Display(); break; case 4: cout<<"Exit"<<endl; break; default: cout<<"Invalid choice"<<endl; } } while(ch!=4); return 0; } The output of the above program is as follows 1) Insert element to queue 2) Delete element from queue 3) Display all the elements of queue 4) Exit Enter your choice : 1 Insert the element in queue : 4 Enter your choice : 1 Insert the element in queue : 3 Enter your choice : 1 Insert the element in queue : 5 Enter your choice : 2 Element deleted from queue is : 4 Enter your choice : 3 Queue elements are : 3 5 Enter your choice : 7 Invalid choice Enter your choice : 4 Exit In the above program, the function Insert() inserts an element into the queue. If the rear is equal to n-1, then the queue is full and overflow is displayed. If front is -1, it is incremented by 1. Then rear is incremented by 1 and the element is inserted in index of rear. This is shown below βˆ’ void Insert() { int val; if (rear == n - 1) cout<<"Queue Overflow"<<endl; else { if (front == - 1) front = 0; cout<<"Insert the element in queue : "<<endl; cin>>val; rear++; queue[rear] = val; } } In the function Delete(), if there are no elements in the queue then it is underflow condition. Otherwise the element at front is displayed and front is incremented by one. This is shown below βˆ’ void Delete() { if (front == - 1 || front > rear) { cout<<"Queue Underflow "; return ; } else { cout<<"Element deleted from queue is : "<< queue[front] <<endl; front++;; } } In the function display(), if front is -1 then queue is empty. Otherwise all the queue elements are displayed using a for loop. This is shown below βˆ’ void Display() { if (front == - 1) cout<<"Queue is empty"<<endl; else { cout<<"Queue elements are : "; for (int i = front; i <= rear; i++) cout<<queue[i]<<" "; cout<<endl; } } The function main() provides a choice to the user if they want to insert, delete or display the queue. According to the user response, the appropriate function is called using switch. If the user enters an invalid response, then that is printed. The code snippet for this is given below βˆ’ int main() { int ch; cout<<"1) Insert element to queue"<<endl; cout<<"2) Delete element from queue"<<endl; cout<<"3) Display all the elements of queue"<<endl; cout<<"4) Exit"<<endl; do { cout<<"Enter your choice : "<<endl; cin>>ch; switch (ch) { case 1: Insert(); break; case 2: Delete(); break; case 3: Display(); break; case 4: cout<<"Exit"<<endl; break; default: cout<<"Invalid choice"<<endl; } } while(ch!=4); return 0; }
[ { "code": null, "e": 1317, "s": 1062, "text": "A queue is an abstract data structure that contains a collection of elements. Queue implements\nthe FIFO mechanism i.e. the element that is inserted first is also deleted first. In other words, the\nleast recently added element is removed first in a queue." }, { "code": null, "e": 1390, "s": 1317, "text": "A program that implements the queue using an array is given as follows βˆ’" }, { "code": null, "e": 2706, "s": 1390, "text": "#include <iostream>\nusing namespace std;\nint queue[100], n = 100, front = - 1, rear = - 1;\nvoid Insert() {\n int val;\n if (rear == n - 1)\n cout<<\"Queue Overflow\"<<endl;\n else {\n if (front == - 1)\n front = 0;\n cout<<\"Insert the element in queue : \"<<endl;\n cin>>val;\n rear++;\n queue[rear] = val;\n }\n}\nvoid Delete() {\n if (front == - 1 || front > rear) {\n cout<<\"Queue Underflow \";\n return ;\n } else {\n cout<<\"Element deleted from queue is : \"<< queue[front] <<endl;\n front++;;\n }\n}\nvoid Display() {\n if (front == - 1)\n cout<<\"Queue is empty\"<<endl;\n else {\n cout<<\"Queue elements are : \";\n for (int i = front; i <= rear; i++)\n cout<<queue[i]<<\" \";\n cout<<endl;\n }\n}\nint main() {\n int ch;\n cout<<\"1) Insert element to queue\"<<endl;\n cout<<\"2) Delete element from queue\"<<endl;\n cout<<\"3) Display all the elements of queue\"<<endl;\n cout<<\"4) Exit\"<<endl;\n do {\n cout<<\"Enter your choice : \"<<endl;\n cin>>ch;\n switch (ch) {\n case 1: Insert();\n break;\n case 2: Delete();\n break;\n case 3: Display();\n break;\n case 4: cout<<\"Exit\"<<endl;\n break;\n default: cout<<\"Invalid choice\"<<endl;\n }\n } while(ch!=4);\n return 0;\n}" }, { "code": null, "e": 2752, "s": 2706, "text": "The output of the above program is as follows" }, { "code": null, "e": 3182, "s": 2752, "text": "1) Insert element to queue\n2) Delete element from queue\n3) Display all the elements of queue\n4) Exit\nEnter your choice : 1\nInsert the element in queue : 4\nEnter your choice : 1\nInsert the element in queue : 3\nEnter your choice : 1\nInsert the element in queue : 5\nEnter your choice : 2\nElement deleted from queue is : 4\nEnter your choice : 3\nQueue elements are : 3 5\nEnter your choice : 7\nInvalid choice\nEnter your choice : 4\nExit" }, { "code": null, "e": 3478, "s": 3182, "text": "In the above program, the function Insert() inserts an element into the queue. If the rear is equal\nto n-1, then the queue is full and overflow is displayed. If front is -1, it is incremented by 1. Then\nrear is incremented by 1 and the element is inserted in index of rear. This is shown below βˆ’" }, { "code": null, "e": 3726, "s": 3478, "text": "void Insert() {\n int val;\n if (rear == n - 1)\n cout<<\"Queue Overflow\"<<endl;\n else {\n if (front == - 1)\n front = 0;\n cout<<\"Insert the element in queue : \"<<endl;\n cin>>val;\n rear++;\n queue[rear] = val;\n }\n}" }, { "code": null, "e": 3921, "s": 3726, "text": "In the function Delete(), if there are no elements in the queue then it is underflow condition.\nOtherwise the element at front is displayed and front is incremented by one. This is shown\nbelow βˆ’" }, { "code": null, "e": 4131, "s": 3921, "text": "void Delete() {\n if (front == - 1 || front > rear) {\n cout<<\"Queue Underflow \";\n return ;\n }\n else {\n cout<<\"Element deleted from queue is : \"<< queue[front] <<endl;\n front++;;\n }\n}" }, { "code": null, "e": 4281, "s": 4131, "text": "In the function display(), if front is -1 then queue is empty. Otherwise all the queue elements are\ndisplayed using a for loop. This is shown below βˆ’" }, { "code": null, "e": 4493, "s": 4281, "text": "void Display() {\n if (front == - 1)\n cout<<\"Queue is empty\"<<endl;\n else {\n cout<<\"Queue elements are : \";\n for (int i = front; i <= rear; i++)\n cout<<queue[i]<<\" \";\n cout<<endl;\n }\n}" }, { "code": null, "e": 4782, "s": 4493, "text": "The function main() provides a choice to the user if they want to insert, delete or display the queue. According to the user response, the appropriate function is called using switch. If the\nuser enters an invalid response, then that is printed. The code snippet for this is given below βˆ’" }, { "code": null, "e": 5337, "s": 4782, "text": "int main() {\n int ch;\n cout<<\"1) Insert element to queue\"<<endl;\n cout<<\"2) Delete element from queue\"<<endl;\n cout<<\"3) Display all the elements of queue\"<<endl;\n cout<<\"4) Exit\"<<endl;\n do {\n cout<<\"Enter your choice : \"<<endl;\n cin>>ch;\n switch (ch) {\n case 1: Insert();\n break;\n case 2: Delete();\n break;\n case 3: Display();\n break;\n case 4: cout<<\"Exit\"<<endl;\n break;\n default: cout<<\"Invalid choice\"<<endl;\n }\n } while(ch!=4);\n return 0;\n}" } ]
Modeling customer churn for an e-commerce company with Python | by Collin Ching | Towards Data Science
It’s more cost effective to retain existing customers than to acquire new ones, which is why it’s important to track customers at high risk of turnover (churn) and target them with retention strategies. In this project, I’ll build a customer churn model based off of data from Olist, a Brazilian e-commerce site. I’ll use that to identify high risk customers and inform retention strategies and marketing experiments. There’s one complication with e-commerce. While it’s straightforward to measure churn for a contractual (subscription-based) business, churns aren’t explicitly observed in non-contractual businesses (e-commerce). In these scenarios, probabilistic models come in handy for estimating time of customer death. The probabilistic model that I’ll use is the BG/NBD model from the Lifetimes package. import pandas as pdimport numpy as npimport datetime as dtimport seaborn as snsimport matplotlib.pyplot as pltfrom lifetimes.utils import *from lifetimes import BetaGeoFitter,GammaGammaFitterfrom lifetimes.plotting import plot_probability_alive_matrix, plot_frequency_recency_matrix, plot_period_transactions, plot_cumulative_transactions,plot_incremental_transactionsfrom lifetimes.generate_data import beta_geometric_nbd_modelfrom lifetimes.plotting import plot_calibration_purchases_vs_holdout_purchases, plot_period_transactions,plot_history_aliveorders = pd.read_csv(β€˜brazilian-ecommerce/olist_orders_dataset.csv’)items = pd.read_csv(β€˜brazilian-ecommerce/olist_order_items_dataset.csv’)cust = pd.read_csv(β€˜brazilian-ecommerce/olist_customers_dataset.csv’) The lifetimes package relies on recency-frequency-monetary (RFM) analysis to model churn and customer lifetime value (CLV). To make our models, we’ll need a a dataframe that consists of recency, frequency, and monetary columns. The definitions of each are below. Recency: time between initial purchase and most recent (last) purchase Frequency: number of repeat purchases made by a customer (total purchases β€” 1) Monetary: total spent on purchases Customer ID information will come from cust. Order date will come from orders. Price will come from items. print(cust.columns) There are two columns used to identify customers. customer_id is a customer ID token that is generated for every order. If the same customer makes multiple orders, he has multiple customer_id identifiers. What we want to use for this analysis is customer_unique_id, which is unique to each purchaser and can be used to track their purchases over time. Here is the distribution of purchases made by customers. cust.groupby('customer_unique_id').size().value_counts() The majority of customers made only a single purchase. orders = pd.merge(orders,cust[['customer_id','customer_unique_id']],on='customer_id')orders.columns In the items dataset, each item in an order gets its separate row. The price column refers cumulative order purchase rather than individual item price. Since I only need order price, I'll keep the first item from each order. print(items.columns) items.drop_duplicates('order_id',keep='first',inplace=True) Next, I’ll join orders with items to append price information. transaction_data = pd.merge(orders,items,'inner','order_id')transaction_data = transaction_data[['customer_unique_id','order_purchase_timestamp','price']]## convert timestamp to date; only need the daytransaction_data['date'] = pd.to_datetime(transaction_data['order_purchase_timestamp']).dt.datetransaction_data = transaction_data.drop('order_purchase_timestamp',axis=1)transaction_data.head() Now that I have my transaction data, I want to convert this into dataframe with the RFM variables that I mentioned in the introduction. The Lifetimes package has a function for converting transaction data into an RFM DataFrame. summary = summary_data_from_transaction_data(transaction_data,'customer_unique_id','date',monetary_value_col='price',)summary.describe() summary.head() The summary function converted customer transactions into an aggregated table. Many of the customers have frequency, recency, and monetary = 0, like customer 0000366f3b9a7992bf8c76cfdf3221e2. That's because Lifetimes only considers customers who have made repeat purchases into account. Using days as time periods (can also be defined as weeks or months), variables are defined like so for the Lifetimes model: frequency: # of days in which a customer made a repeat purchase T: customer's age in days recency: customer's age in days at time of most recent purchase monetary_value: mean of a customer's purchases, excluding the 1st purchase frequency excludes the customer's first purchase because that is considered the day the customer is born. Afterwards, you can begin to question whether or not that customer is alive. summary[summary['frequency']>0].head() transaction_data[transaction_data['customer_unique_id']=='004288347e5e88a27ded2bb23747066c'] Note how customer 004288347e5e88a27ded2bb23747066c made two purchases with Olist but his frequency is 1 and monetary_value is $87.90 based on how frequency and monetary_value are defined. We’re going to use the Beta-Geometric/NBD (BG/NBD) model for customer churn. The BG/NBD model is an adaptation of the Pareto/NBD model. Both models describe repeat purchasing patterns in businesses where customer turnover is unobserved; however, the BG/NBD is much more computationally feasible. Assumptions of the BG/NBD model: A customer’s relationship has two phases: β€œalive” for an unobserved period of time, then β€œdead” While alive, the number of transactions made by a customer follows a Poisson distribution with transaction rate lambda Heterogeneity in lambda follows a gamma distribution After any transaction, a customer dies with probability p; the probability that a customer dies after a number of transactions follows a geometric distribution p follows a beta distribution Lambda and p vary independently across customers For more information on the BG/NBD model, check out this paper by Peter Fader and this post by Cam Davidson-Pilon. bgf = BetaGeoFitter(penalizer_coef=0.0)bgf.fit(summary['frequency'], summary['recency'], summary['T']); plot_frequency_recency_matrix(bgf); plot_probability_alive_matrix(bgf); Next we want to evaluate the model to see how well it performs in the future. I’ll split the data into a training (calibration) period and a holdout (observation) period, train the BG/NBD model and evaluate performance with four plots that Peter Fader outlines in this talk (@ 26:10). These plots are: 1) Calibration period histogram: does the model fit the training data? 2) Cumulative transaction plot: does the model predict cumulative sales well? 3) Incremental transaction plot: does the model capture the overall trend in transactions? 4) Conditional expectations plot: can the model predict the number of purchases a customer will make based on the training data? plot_period_transactions(bgf).set_yscale('log'); The model is fairly representative of the real data up until four repeat transactions. There are few customers who make more purchases. summary_cal_holdout = calibration_and_holdout_data(transaction_data, 'customer_unique_id', 'date',calibration_period_end='2017-09-03', observation_period_end='2018-09-03' ) We can evaluate how the dataset works by plotting both of them. bgf.fit(summary_cal_holdout['frequency_cal'], summary_cal_holdout['recency_cal'], summary_cal_holdout['T_cal'])plot_cumulative_transactions(bgf, transaction_data, 'date', 'customer_unique_id', 730, 365); The red line represents the boundary between the calibration period on the left and the holdout period on the right. As you can see, the BG/NBD model does a pretty swell job at predicting cumulative transactions. plot_incremental_transactions(bgf, transaction_data, 'date', 'customer_unique_id', 730, 365); This plot shows that the model does a decent job capturing general trends in the data. plot_calibration_purchases_vs_holdout_purchases(bgf, summary_cal_holdout); The model performs well up to three calibration period purchases, but diverges from the holdout data because of the distribution of the data. cust.groupby('customer_unique_id').size().value_counts() Less than 1% of customers have made four or more purchases, so there’s not much data for the BG/NBD model to learn about customers who have made many repeat transactions. In practice, I would consider collecting more data if I were to proceed with modeling customer churn. But for learning purposes, it will still be a good exercise to predict churn. The BG/NBD model assumes that death can only occur after a repeat purchase, since the customer leaving occurs during a purchase and the first purchase is reserved to signal a customer’s birth. Because of this, customers with only one transactions will have a 100% probability of being alive, which is suspect. To account for this limitation, we’ll only predict churn risk on customers who have made at least one repeat transaction. df = summary[summary['frequency']>0]df['prob_alive'] = bgf.conditional_probability_alive(df['frequency'],df['recency'],df['T'])sns.distplot(df['prob_alive']); From here, we can visualize customers based on the probability that they’re β€œalive”. Using domain knowledge we might be able to set a threshold for customers who probably have already churned, and also identify customers who are at risk for churning, but haven’t yet disappeared. Next, I would like to set a decision threshold for customer churn. This is an opportunity to inject personal expertise or talk with domain experts. Assume I speak with the sales and marketing managers, and we agree to consider a customer with <10% chance of being alive to have churned. df['churn'] = ['churned' if p < .1 else 'not churned' for p in df['prob_alive']]sns.countplot(df['churn']); A little over 92% of customers have churned, meaning that there’s a lot of opportunity for improvement regarding retention. We can assume that the customers who have churned are already lost. But what is interesting in a business setting is the customers who are at high risk for churn, but haven’t churned yet. Later on, it might still be a good idea to apply different treatments to the churned group. If I can identify them, maybe I can encourage the marketing team to target them with promotions. sns.distplot(df[df['churn']=='not churned']['prob_alive']).set_title('Probability alive, not churned'); It seems reasonable to bucket customers with 80% or more churn risk to be considered high risk for churn. df['churn'][(df['prob_alive']>=.1) & (df['prob_alive']<.2)] = "high risk"df['churn'].value_counts() Now that I have these churn groupings, I can move forward and apply special treatments to these groups. Ideally there would be more data and a bigger population of high-risk customers. We’ve modeled churn risk in a non-contractual setting, and now have three customer segments β€” not churned, high risk, and churned. This could feed into a dashboard to give stakeholders a glimpse of β€œat-risk” customers. It also provides three different groups that we can run specific actions. Some ideas: 1) Reach out to churned customers to figure out why they left. 2) Send different types of targeted emails and special offers to the high risk group. If the sample size of high risk customers is large enough, you could split off a few small treatment groups and compare how their retention and CLV change with different promotional or customer relationship strategies. 3) Determine the the highest value customers in the non-churn group, and serve them additional benefits to ensure that they remain loyal customers. Thanks for reading! If you want to follow along with the code, here’s the GitHub repo. Always open to feedback and questions. Comment below!
[ { "code": null, "e": 375, "s": 172, "text": "It’s more cost effective to retain existing customers than to acquire new ones, which is why it’s important to track customers at high risk of turnover (churn) and target them with retention strategies." }, { "code": null, "e": 590, "s": 375, "text": "In this project, I’ll build a customer churn model based off of data from Olist, a Brazilian e-commerce site. I’ll use that to identify high risk customers and inform retention strategies and marketing experiments." }, { "code": null, "e": 983, "s": 590, "text": "There’s one complication with e-commerce. While it’s straightforward to measure churn for a contractual (subscription-based) business, churns aren’t explicitly observed in non-contractual businesses (e-commerce). In these scenarios, probabilistic models come in handy for estimating time of customer death. The probabilistic model that I’ll use is the BG/NBD model from the Lifetimes package." }, { "code": null, "e": 1744, "s": 983, "text": "import pandas as pdimport numpy as npimport datetime as dtimport seaborn as snsimport matplotlib.pyplot as pltfrom lifetimes.utils import *from lifetimes import BetaGeoFitter,GammaGammaFitterfrom lifetimes.plotting import plot_probability_alive_matrix, plot_frequency_recency_matrix, plot_period_transactions, plot_cumulative_transactions,plot_incremental_transactionsfrom lifetimes.generate_data import beta_geometric_nbd_modelfrom lifetimes.plotting import plot_calibration_purchases_vs_holdout_purchases, plot_period_transactions,plot_history_aliveorders = pd.read_csv(β€˜brazilian-ecommerce/olist_orders_dataset.csv’)items = pd.read_csv(β€˜brazilian-ecommerce/olist_order_items_dataset.csv’)cust = pd.read_csv(β€˜brazilian-ecommerce/olist_customers_dataset.csv’)" }, { "code": null, "e": 2007, "s": 1744, "text": "The lifetimes package relies on recency-frequency-monetary (RFM) analysis to model churn and customer lifetime value (CLV). To make our models, we’ll need a a dataframe that consists of recency, frequency, and monetary columns. The definitions of each are below." }, { "code": null, "e": 2078, "s": 2007, "text": "Recency: time between initial purchase and most recent (last) purchase" }, { "code": null, "e": 2157, "s": 2078, "text": "Frequency: number of repeat purchases made by a customer (total purchases β€” 1)" }, { "code": null, "e": 2192, "s": 2157, "text": "Monetary: total spent on purchases" }, { "code": null, "e": 2299, "s": 2192, "text": "Customer ID information will come from cust. Order date will come from orders. Price will come from items." }, { "code": null, "e": 2319, "s": 2299, "text": "print(cust.columns)" }, { "code": null, "e": 2671, "s": 2319, "text": "There are two columns used to identify customers. customer_id is a customer ID token that is generated for every order. If the same customer makes multiple orders, he has multiple customer_id identifiers. What we want to use for this analysis is customer_unique_id, which is unique to each purchaser and can be used to track their purchases over time." }, { "code": null, "e": 2728, "s": 2671, "text": "Here is the distribution of purchases made by customers." }, { "code": null, "e": 2785, "s": 2728, "text": "cust.groupby('customer_unique_id').size().value_counts()" }, { "code": null, "e": 2840, "s": 2785, "text": "The majority of customers made only a single purchase." }, { "code": null, "e": 2940, "s": 2840, "text": "orders = pd.merge(orders,cust[['customer_id','customer_unique_id']],on='customer_id')orders.columns" }, { "code": null, "e": 3165, "s": 2940, "text": "In the items dataset, each item in an order gets its separate row. The price column refers cumulative order purchase rather than individual item price. Since I only need order price, I'll keep the first item from each order." }, { "code": null, "e": 3186, "s": 3165, "text": "print(items.columns)" }, { "code": null, "e": 3246, "s": 3186, "text": "items.drop_duplicates('order_id',keep='first',inplace=True)" }, { "code": null, "e": 3309, "s": 3246, "text": "Next, I’ll join orders with items to append price information." }, { "code": null, "e": 3704, "s": 3309, "text": "transaction_data = pd.merge(orders,items,'inner','order_id')transaction_data = transaction_data[['customer_unique_id','order_purchase_timestamp','price']]## convert timestamp to date; only need the daytransaction_data['date'] = pd.to_datetime(transaction_data['order_purchase_timestamp']).dt.datetransaction_data = transaction_data.drop('order_purchase_timestamp',axis=1)transaction_data.head()" }, { "code": null, "e": 3932, "s": 3704, "text": "Now that I have my transaction data, I want to convert this into dataframe with the RFM variables that I mentioned in the introduction. The Lifetimes package has a function for converting transaction data into an RFM DataFrame." }, { "code": null, "e": 4069, "s": 3932, "text": "summary = summary_data_from_transaction_data(transaction_data,'customer_unique_id','date',monetary_value_col='price',)summary.describe()" }, { "code": null, "e": 4084, "s": 4069, "text": "summary.head()" }, { "code": null, "e": 4371, "s": 4084, "text": "The summary function converted customer transactions into an aggregated table. Many of the customers have frequency, recency, and monetary = 0, like customer 0000366f3b9a7992bf8c76cfdf3221e2. That's because Lifetimes only considers customers who have made repeat purchases into account." }, { "code": null, "e": 4495, "s": 4371, "text": "Using days as time periods (can also be defined as weeks or months), variables are defined like so for the Lifetimes model:" }, { "code": null, "e": 4559, "s": 4495, "text": "frequency: # of days in which a customer made a repeat purchase" }, { "code": null, "e": 4585, "s": 4559, "text": "T: customer's age in days" }, { "code": null, "e": 4649, "s": 4585, "text": "recency: customer's age in days at time of most recent purchase" }, { "code": null, "e": 4724, "s": 4649, "text": "monetary_value: mean of a customer's purchases, excluding the 1st purchase" }, { "code": null, "e": 4907, "s": 4724, "text": "frequency excludes the customer's first purchase because that is considered the day the customer is born. Afterwards, you can begin to question whether or not that customer is alive." }, { "code": null, "e": 4946, "s": 4907, "text": "summary[summary['frequency']>0].head()" }, { "code": null, "e": 5039, "s": 4946, "text": "transaction_data[transaction_data['customer_unique_id']=='004288347e5e88a27ded2bb23747066c']" }, { "code": null, "e": 5227, "s": 5039, "text": "Note how customer 004288347e5e88a27ded2bb23747066c made two purchases with Olist but his frequency is 1 and monetary_value is $87.90 based on how frequency and monetary_value are defined." }, { "code": null, "e": 5523, "s": 5227, "text": "We’re going to use the Beta-Geometric/NBD (BG/NBD) model for customer churn. The BG/NBD model is an adaptation of the Pareto/NBD model. Both models describe repeat purchasing patterns in businesses where customer turnover is unobserved; however, the BG/NBD is much more computationally feasible." }, { "code": null, "e": 5556, "s": 5523, "text": "Assumptions of the BG/NBD model:" }, { "code": null, "e": 5652, "s": 5556, "text": "A customer’s relationship has two phases: β€œalive” for an unobserved period of time, then β€œdead”" }, { "code": null, "e": 5771, "s": 5652, "text": "While alive, the number of transactions made by a customer follows a Poisson distribution with transaction rate lambda" }, { "code": null, "e": 5824, "s": 5771, "text": "Heterogeneity in lambda follows a gamma distribution" }, { "code": null, "e": 5984, "s": 5824, "text": "After any transaction, a customer dies with probability p; the probability that a customer dies after a number of transactions follows a geometric distribution" }, { "code": null, "e": 6014, "s": 5984, "text": "p follows a beta distribution" }, { "code": null, "e": 6063, "s": 6014, "text": "Lambda and p vary independently across customers" }, { "code": null, "e": 6178, "s": 6063, "text": "For more information on the BG/NBD model, check out this paper by Peter Fader and this post by Cam Davidson-Pilon." }, { "code": null, "e": 6282, "s": 6178, "text": "bgf = BetaGeoFitter(penalizer_coef=0.0)bgf.fit(summary['frequency'], summary['recency'], summary['T']);" }, { "code": null, "e": 6318, "s": 6282, "text": "plot_frequency_recency_matrix(bgf);" }, { "code": null, "e": 6354, "s": 6318, "text": "plot_probability_alive_matrix(bgf);" }, { "code": null, "e": 6656, "s": 6354, "text": "Next we want to evaluate the model to see how well it performs in the future. I’ll split the data into a training (calibration) period and a holdout (observation) period, train the BG/NBD model and evaluate performance with four plots that Peter Fader outlines in this talk (@ 26:10). These plots are:" }, { "code": null, "e": 6727, "s": 6656, "text": "1) Calibration period histogram: does the model fit the training data?" }, { "code": null, "e": 6805, "s": 6727, "text": "2) Cumulative transaction plot: does the model predict cumulative sales well?" }, { "code": null, "e": 6896, "s": 6805, "text": "3) Incremental transaction plot: does the model capture the overall trend in transactions?" }, { "code": null, "e": 7025, "s": 6896, "text": "4) Conditional expectations plot: can the model predict the number of purchases a customer will make based on the training data?" }, { "code": null, "e": 7074, "s": 7025, "text": "plot_period_transactions(bgf).set_yscale('log');" }, { "code": null, "e": 7210, "s": 7074, "text": "The model is fairly representative of the real data up until four repeat transactions. There are few customers who make more purchases." }, { "code": null, "e": 7383, "s": 7210, "text": "summary_cal_holdout = calibration_and_holdout_data(transaction_data, 'customer_unique_id', 'date',calibration_period_end='2017-09-03', observation_period_end='2018-09-03' )" }, { "code": null, "e": 7447, "s": 7383, "text": "We can evaluate how the dataset works by plotting both of them." }, { "code": null, "e": 7651, "s": 7447, "text": "bgf.fit(summary_cal_holdout['frequency_cal'], summary_cal_holdout['recency_cal'], summary_cal_holdout['T_cal'])plot_cumulative_transactions(bgf, transaction_data, 'date', 'customer_unique_id', 730, 365);" }, { "code": null, "e": 7864, "s": 7651, "text": "The red line represents the boundary between the calibration period on the left and the holdout period on the right. As you can see, the BG/NBD model does a pretty swell job at predicting cumulative transactions." }, { "code": null, "e": 7958, "s": 7864, "text": "plot_incremental_transactions(bgf, transaction_data, 'date', 'customer_unique_id', 730, 365);" }, { "code": null, "e": 8045, "s": 7958, "text": "This plot shows that the model does a decent job capturing general trends in the data." }, { "code": null, "e": 8120, "s": 8045, "text": "plot_calibration_purchases_vs_holdout_purchases(bgf, summary_cal_holdout);" }, { "code": null, "e": 8262, "s": 8120, "text": "The model performs well up to three calibration period purchases, but diverges from the holdout data because of the distribution of the data." }, { "code": null, "e": 8319, "s": 8262, "text": "cust.groupby('customer_unique_id').size().value_counts()" }, { "code": null, "e": 8490, "s": 8319, "text": "Less than 1% of customers have made four or more purchases, so there’s not much data for the BG/NBD model to learn about customers who have made many repeat transactions." }, { "code": null, "e": 8670, "s": 8490, "text": "In practice, I would consider collecting more data if I were to proceed with modeling customer churn. But for learning purposes, it will still be a good exercise to predict churn." }, { "code": null, "e": 8863, "s": 8670, "text": "The BG/NBD model assumes that death can only occur after a repeat purchase, since the customer leaving occurs during a purchase and the first purchase is reserved to signal a customer’s birth." }, { "code": null, "e": 9102, "s": 8863, "text": "Because of this, customers with only one transactions will have a 100% probability of being alive, which is suspect. To account for this limitation, we’ll only predict churn risk on customers who have made at least one repeat transaction." }, { "code": null, "e": 9261, "s": 9102, "text": "df = summary[summary['frequency']>0]df['prob_alive'] = bgf.conditional_probability_alive(df['frequency'],df['recency'],df['T'])sns.distplot(df['prob_alive']);" }, { "code": null, "e": 9541, "s": 9261, "text": "From here, we can visualize customers based on the probability that they’re β€œalive”. Using domain knowledge we might be able to set a threshold for customers who probably have already churned, and also identify customers who are at risk for churning, but haven’t yet disappeared." }, { "code": null, "e": 9828, "s": 9541, "text": "Next, I would like to set a decision threshold for customer churn. This is an opportunity to inject personal expertise or talk with domain experts. Assume I speak with the sales and marketing managers, and we agree to consider a customer with <10% chance of being alive to have churned." }, { "code": null, "e": 9936, "s": 9828, "text": "df['churn'] = ['churned' if p < .1 else 'not churned' for p in df['prob_alive']]sns.countplot(df['churn']);" }, { "code": null, "e": 10060, "s": 9936, "text": "A little over 92% of customers have churned, meaning that there’s a lot of opportunity for improvement regarding retention." }, { "code": null, "e": 10340, "s": 10060, "text": "We can assume that the customers who have churned are already lost. But what is interesting in a business setting is the customers who are at high risk for churn, but haven’t churned yet. Later on, it might still be a good idea to apply different treatments to the churned group." }, { "code": null, "e": 10437, "s": 10340, "text": "If I can identify them, maybe I can encourage the marketing team to target them with promotions." }, { "code": null, "e": 10541, "s": 10437, "text": "sns.distplot(df[df['churn']=='not churned']['prob_alive']).set_title('Probability alive, not churned');" }, { "code": null, "e": 10647, "s": 10541, "text": "It seems reasonable to bucket customers with 80% or more churn risk to be considered high risk for churn." }, { "code": null, "e": 10747, "s": 10647, "text": "df['churn'][(df['prob_alive']>=.1) & (df['prob_alive']<.2)] = \"high risk\"df['churn'].value_counts()" }, { "code": null, "e": 10932, "s": 10747, "text": "Now that I have these churn groupings, I can move forward and apply special treatments to these groups. Ideally there would be more data and a bigger population of high-risk customers." }, { "code": null, "e": 11237, "s": 10932, "text": "We’ve modeled churn risk in a non-contractual setting, and now have three customer segments β€” not churned, high risk, and churned. This could feed into a dashboard to give stakeholders a glimpse of β€œat-risk” customers. It also provides three different groups that we can run specific actions. Some ideas:" }, { "code": null, "e": 11300, "s": 11237, "text": "1) Reach out to churned customers to figure out why they left." }, { "code": null, "e": 11605, "s": 11300, "text": "2) Send different types of targeted emails and special offers to the high risk group. If the sample size of high risk customers is large enough, you could split off a few small treatment groups and compare how their retention and CLV change with different promotional or customer relationship strategies." }, { "code": null, "e": 11753, "s": 11605, "text": "3) Determine the the highest value customers in the non-churn group, and serve them additional benefits to ensure that they remain loyal customers." } ]
What is the correct way to use printf to print a size_t in C/C++?
We should use β€œ%zu” to print the variables of size_t length. We can use β€œ%d” also to print size_t variables, it will not show any error. The correct way to print size_t variables is use of β€œ%zu”. In β€œ%zu” format, z is a length modifier and u stand for unsigned type. The following is an example to print size_t variable. Live Demo #include <stdio.h> int main() { size_t a = 20; printf("The value of a : %zu", a); return 0; } The value of a : 20 In the above program, a variable of size_t length is declared and initialized with a value. size_t a = 20; The variables of size_t length is printed as follows βˆ’ printf("The value of a : %zu", a);
[ { "code": null, "e": 1258, "s": 1062, "text": "We should use β€œ%zu” to print the variables of size_t length. We can use β€œ%d” also to print size_t variables, it will not show any error. The correct way to print size_t variables is use of β€œ%zu”." }, { "code": null, "e": 1329, "s": 1258, "text": "In β€œ%zu” format, z is a length modifier and u stand for unsigned type." }, { "code": null, "e": 1383, "s": 1329, "text": "The following is an example to print size_t variable." }, { "code": null, "e": 1394, "s": 1383, "text": " Live Demo" }, { "code": null, "e": 1497, "s": 1394, "text": "#include <stdio.h>\nint main() {\n size_t a = 20;\n printf(\"The value of a : %zu\", a);\n return 0;\n}" }, { "code": null, "e": 1517, "s": 1497, "text": "The value of a : 20" }, { "code": null, "e": 1609, "s": 1517, "text": "In the above program, a variable of size_t length is declared and initialized with a value." }, { "code": null, "e": 1624, "s": 1609, "text": "size_t a = 20;" }, { "code": null, "e": 1679, "s": 1624, "text": "The variables of size_t length is printed as follows βˆ’" }, { "code": null, "e": 1714, "s": 1679, "text": "printf(\"The value of a : %zu\", a);" } ]
HTML5 MathML framespacing Attribute - GeeksforGeeks
20 Nov, 2020 This attribute defines the space between the table and the frame. This attribute is accepted by <mtable> tag only. Syntax: <element framespacing="number"> Attributes Value: number: This attribute defines the space between the table and the frame. Below example illustrate the framespacing attribute in HTML5 MathML: Example: <!DOCTYPE html><html> <head> <title> HTML5 MathML framespacing Attribute </title></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <h3>HTML5 MathML framespacing Attribute</h3> <math> <mi>GeeksforGeeks</mi> <mo>=</mo> <mtable frame="solid" columnlines="dashed" framespacing="2" align="axis 1"> <mtr mathbackground="green;"> <mtd>Course</mtd> <mtd>Fee</mtd> </mtr> <mtr> <mtd> <mi>C++ STL</mi> </mtd> <mtd> <mi> 1499</mi> </mtd> </mtr> <mtr> <mtd> <mi>Placement 100 </mi> </mtd> <mtd> <mi>9999 </mi> </mtd> </mtr> <mtr> <mtd> <mi>DSA Foundation </mi> </mtd> <mtd> <mi>7999</mi> </mtd> </mtr> </mtable> </math> </center></body> </html> Output: Supported Browsers: The browsers supported by HTML5 MathML framespacing attribute are listed below: Firefox Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-MathML HTML5 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 Form validation using jQuery How to place text on image using HTML and CSS? How to auto-resize an image to fit a div container using CSS? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript
[ { "code": null, "e": 24503, "s": 24475, "text": "\n20 Nov, 2020" }, { "code": null, "e": 24618, "s": 24503, "text": "This attribute defines the space between the table and the frame. This attribute is accepted by <mtable> tag only." }, { "code": null, "e": 24626, "s": 24618, "text": "Syntax:" }, { "code": null, "e": 24658, "s": 24626, "text": "<element framespacing=\"number\">" }, { "code": null, "e": 24676, "s": 24658, "text": "Attributes Value:" }, { "code": null, "e": 24751, "s": 24676, "text": "number: This attribute defines the space between the table and the frame." }, { "code": null, "e": 24820, "s": 24751, "text": "Below example illustrate the framespacing attribute in HTML5 MathML:" }, { "code": null, "e": 24829, "s": 24820, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML5 MathML framespacing Attribute </title></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h3>HTML5 MathML framespacing Attribute</h3> <math> <mi>GeeksforGeeks</mi> <mo>=</mo> <mtable frame=\"solid\" columnlines=\"dashed\" framespacing=\"2\" align=\"axis 1\"> <mtr mathbackground=\"green;\"> <mtd>Course</mtd> <mtd>Fee</mtd> </mtr> <mtr> <mtd> <mi>C++ STL</mi> </mtd> <mtd> <mi> 1499</mi> </mtd> </mtr> <mtr> <mtd> <mi>Placement 100 </mi> </mtd> <mtd> <mi>9999 </mi> </mtd> </mtr> <mtr> <mtd> <mi>DSA Foundation </mi> </mtd> <mtd> <mi>7999</mi> </mtd> </mtr> </mtable> </math> </center></body> </html>", "e": 26154, "s": 24829, "text": null }, { "code": null, "e": 26162, "s": 26154, "text": "Output:" }, { "code": null, "e": 26262, "s": 26162, "text": "Supported Browsers: The browsers supported by HTML5 MathML framespacing attribute are listed below:" }, { "code": null, "e": 26270, "s": 26262, "text": "Firefox" }, { "code": null, "e": 26407, "s": 26270, "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": 26419, "s": 26407, "text": "HTML-MathML" }, { "code": null, "e": 26425, "s": 26419, "text": "HTML5" }, { "code": null, "e": 26430, "s": 26425, "text": "HTML" }, { "code": null, "e": 26447, "s": 26430, "text": "Web Technologies" }, { "code": null, "e": 26452, "s": 26447, "text": "HTML" }, { "code": null, "e": 26550, "s": 26452, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26559, "s": 26550, "text": "Comments" }, { "code": null, "e": 26572, "s": 26559, "text": "Old Comments" }, { "code": null, "e": 26596, "s": 26572, "text": "REST API (Introduction)" }, { "code": null, "e": 26633, "s": 26596, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 26662, "s": 26633, "text": "Form validation using jQuery" }, { "code": null, "e": 26709, "s": 26662, "text": "How to place text on image using HTML and CSS?" }, { "code": null, "e": 26771, "s": 26709, "text": "How to auto-resize an image to fit a div container using CSS?" }, { "code": null, "e": 26827, "s": 26771, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26860, "s": 26827, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26903, "s": 26860, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26964, "s": 26903, "text": "Difference between var, let and const keywords in JavaScript" } ]
Defining Custom Suffix Rules in Makefile
Make can automatically create a.o file, using cc -c on the corresponding .c file. These rules are built-in the make, and you can take this advantage to shorten your Makefile. If you indicate just the .h files in the dependency line of the Makefile on which the current target is dependent on, make will know that the corresponding .cfile is already required. You do not have to include the command for the compiler. This reduces the Makefile further, as shown below βˆ’ OBJECTS = main.o hello.o factorial.o hello: $(OBJECTS) cc $(OBJECTS) -o hello hellp.o: functions.h main.o: functions.h factorial.o: functions.h Make uses a special target, named .SUFFIXES to allow you to define your own suffixes. For example, refer the dependency line given below βˆ’ .SUFFIXES: .foo .bar It informs make that you will be using these special suffixes to make your own rules. Similar to how make already knows how to make a .o file from a .c file, you can define rules in the following manner βˆ’ .foo.bar: tr '[A-Z][a-z]' '[N-Z][A-M][n-z][a-m]' < $< > $@ .c.o: $(CC) $(CFLAGS) -c $< The first rule allows you to create a .bar file from a .foo file. It basically scrambles the file. The second rule is the default rule used by make to create a .o file from a .c file. Print Add Notes Bookmark this page
[ { "code": null, "e": 2200, "s": 1784, "text": "Make can automatically create a.o file, using cc -c on the corresponding .c file. These rules are built-in the make, and you can take this advantage to shorten your Makefile. If you indicate just the .h files in the dependency line of the Makefile on which the current target is dependent on, make will know that the corresponding .cfile is already required. You do not have to include the command for the compiler." }, { "code": null, "e": 2252, "s": 2200, "text": "This reduces the Makefile further, as shown below βˆ’" }, { "code": null, "e": 2403, "s": 2252, "text": "OBJECTS = main.o hello.o factorial.o\nhello: $(OBJECTS)\n cc $(OBJECTS) -o hello\nhellp.o: functions.h\n\nmain.o: functions.h \nfactorial.o: functions.h \n" }, { "code": null, "e": 2542, "s": 2403, "text": "Make uses a special target, named .SUFFIXES to allow you to define your own suffixes. For example, refer the dependency line given below βˆ’" }, { "code": null, "e": 2564, "s": 2542, "text": ".SUFFIXES: .foo .bar\n" }, { "code": null, "e": 2650, "s": 2564, "text": "It informs make that you will be using these special suffixes to make your own rules." }, { "code": null, "e": 2769, "s": 2650, "text": "Similar to how make already knows how to make a .o file from a .c file, you can define rules in the following manner βˆ’" }, { "code": null, "e": 2863, "s": 2769, "text": ".foo.bar:\n tr '[A-Z][a-z]' '[N-Z][A-M][n-z][a-m]' < $< > $@\n.c.o:\n $(CC) $(CFLAGS) -c $<\n" }, { "code": null, "e": 3047, "s": 2863, "text": "The first rule allows you to create a .bar file from a .foo file. It basically scrambles the file. The second rule is the default rule used by make to create a .o file from a .c file." }, { "code": null, "e": 3054, "s": 3047, "text": " Print" }, { "code": null, "e": 3065, "s": 3054, "text": " Add Notes" } ]
Defining generic method inside Non-generic class in Java
You can write a single generic method declaration that can be called with arguments of different types. Based on the types of the arguments passed to the generic method, the compiler handles each method call appropriately. Following are the rules to define Generic Methods βˆ’ All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example). All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example). Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name. Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments. A generic method's body is declared like that of any other method. Note that type parameters can represent only reference types, not primitive types (like int, double and char). A generic method's body is declared like that of any other method. Note that type parameters can represent only reference types, not primitive types (like int, double and char). Yes, you can define a generic method in a non-generic class in Java. Live Demo public class GenericMethod { <T>void sampleMethod(T[] array) { for(int i=0; i<array.length; i++) { System.out.println(array[i]); } } public static void main(String args[]) { GenericMethod obj = new GenericMethod(); Integer intArray[] = {45, 26, 89, 96}; obj.sampleMethod(intArray); String stringArray[] = {"Krishna", "Raju", "Seema", "Geeta"}; obj.sampleMethod(stringArray); } } 45 26 89 96 Krishna Raju Seema Geeta
[ { "code": null, "e": 1337, "s": 1062, "text": "You can write a single generic method declaration that can be called with arguments of different types. Based on the types of the arguments passed to the generic method, the compiler handles each method call appropriately. Following are the rules to define Generic Methods βˆ’" }, { "code": null, "e": 1506, "s": 1337, "text": "All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example)." }, { "code": null, "e": 1675, "s": 1506, "text": "All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example)." }, { "code": null, "e": 1863, "s": 1675, "text": "Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name." }, { "code": null, "e": 2051, "s": 1863, "text": "Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name." }, { "code": null, "e": 2237, "s": 2051, "text": "The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments." }, { "code": null, "e": 2423, "s": 2237, "text": "The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments." }, { "code": null, "e": 2601, "s": 2423, "text": "A generic method's body is declared like that of any other method. Note that type parameters can represent only reference types, not primitive types (like int, double and char)." }, { "code": null, "e": 2779, "s": 2601, "text": "A generic method's body is declared like that of any other method. Note that type parameters can represent only reference types, not primitive types (like int, double and char)." }, { "code": null, "e": 2848, "s": 2779, "text": "Yes, you can define a generic method in a non-generic class in Java." }, { "code": null, "e": 2859, "s": 2848, "text": " Live Demo" }, { "code": null, "e": 3301, "s": 2859, "text": "public class GenericMethod {\n <T>void sampleMethod(T[] array) {\n for(int i=0; i<array.length; i++) {\n System.out.println(array[i]);\n }\n }\n public static void main(String args[]) {\n GenericMethod obj = new GenericMethod();\n Integer intArray[] = {45, 26, 89, 96};\n obj.sampleMethod(intArray);\n String stringArray[] = {\"Krishna\", \"Raju\", \"Seema\", \"Geeta\"};\n obj.sampleMethod(stringArray);\n }\n}" }, { "code": null, "e": 3338, "s": 3301, "text": "45\n26\n89\n96\nKrishna\nRaju\nSeema\nGeeta" } ]
Elasticsearch - Rollup Data
A rollup job is a periodic task that summarizes data from indices specified by an index pattern and rolls it into a new index. In the following example, we create an index named sensor with different date time stamps. Then we create a rollup job to rollup the data from these indices periodically using cron job. PUT /sensor/_doc/1 { "timestamp": 1516729294000, "temperature": 200, "voltage": 5.2, "node": "a" } On running the above code, we get the following result βˆ’ { "_index" : "sensor", "_type" : "_doc", "_id" : "1", "_version" : 1, "result" : "created", "_shards" : { "total" : 2, "successful" : 1, "failed" : 0 }, "_seq_no" : 0, "_primary_term" : 1 } Now, add a second document and so on for other documents as well. PUT /sensor-2018-01-01/_doc/2 { "timestamp": 1413729294000, "temperature": 201, "voltage": 5.9, "node": "a" } PUT _rollup/job/sensor { "index_pattern": "sensor-*", "rollup_index": "sensor_rollup", "cron": "*/30 * * * * ?", "page_size" :1000, "groups" : { "date_histogram": { "field": "timestamp", "interval": "60m" }, "terms": { "fields": ["node"] } }, "metrics": [ { "field": "temperature", "metrics": ["min", "max", "sum"] }, { "field": "voltage", "metrics": ["avg"] } ] } The cron parameter controls when and how often the job activates. When a rollup job’s cron schedule triggers, it will begin rolling up from where it left off after the last activation After the job has run and processed some data, we can use the DSL Query to do some searching. GET /sensor_rollup/_rollup_search { "size": 0, "aggregations": { "max_temperature": { "max": { "field": "temperature" } } } } 14 Lectures 5 hours Manuj Aggarwal 20 Lectures 1 hours Faizan Tayyab Print Add Notes Bookmark this page
[ { "code": null, "e": 2894, "s": 2581, "text": "A rollup job is a periodic task that summarizes data from indices specified by an index pattern and rolls it into a new index. In the following example, we create an index named sensor with different date time stamps. Then we create a rollup job to rollup the data from these indices periodically using cron job." }, { "code": null, "e": 3005, "s": 2894, "text": "PUT /sensor/_doc/1\n{\n \"timestamp\": 1516729294000,\n \"temperature\": 200,\n \"voltage\": 5.2,\n \"node\": \"a\"\n}" }, { "code": null, "e": 3062, "s": 3005, "text": "On running the above code, we get the following result βˆ’" }, { "code": null, "e": 3298, "s": 3062, "text": "{\n \"_index\" : \"sensor\",\n \"_type\" : \"_doc\",\n \"_id\" : \"1\",\n \"_version\" : 1,\n \"result\" : \"created\",\n \"_shards\" : {\n \"total\" : 2,\n \"successful\" : 1,\n \"failed\" : 0\n },\n \"_seq_no\" : 0,\n \"_primary_term\" : 1\n}\n" }, { "code": null, "e": 3364, "s": 3298, "text": "Now, add a second document and so on for other documents as well." }, { "code": null, "e": 3486, "s": 3364, "text": "PUT /sensor-2018-01-01/_doc/2\n{\n \"timestamp\": 1413729294000,\n \"temperature\": 201,\n \"voltage\": 5.9,\n \"node\": \"a\"\n}" }, { "code": null, "e": 3987, "s": 3486, "text": "PUT _rollup/job/sensor\n{\n \"index_pattern\": \"sensor-*\",\n \"rollup_index\": \"sensor_rollup\",\n \"cron\": \"*/30 * * * * ?\",\n \"page_size\" :1000,\n \"groups\" : {\n \"date_histogram\": {\n \"field\": \"timestamp\",\n \"interval\": \"60m\"\n },\n \"terms\": {\n \"fields\": [\"node\"]\n }\n },\n \"metrics\": [\n {\n \"field\": \"temperature\",\n \"metrics\": [\"min\", \"max\", \"sum\"]\n },\n {\n \"field\": \"voltage\",\n \"metrics\": [\"avg\"]\n }\n ]\n}\n" }, { "code": null, "e": 4171, "s": 3987, "text": "The cron parameter controls when and how often the job activates. When a rollup job’s cron schedule triggers, it will begin rolling up from where it left off after the last activation" }, { "code": null, "e": 4265, "s": 4171, "text": "After the job has run and processed some data, we can use the DSL Query to do some searching." }, { "code": null, "e": 4443, "s": 4265, "text": "GET /sensor_rollup/_rollup_search\n{\n \"size\": 0,\n \"aggregations\": {\n \"max_temperature\": {\n \"max\": {\n \"field\": \"temperature\"\n }\n }\n }\n}\n" }, { "code": null, "e": 4476, "s": 4443, "text": "\n 14 Lectures \n 5 hours \n" }, { "code": null, "e": 4492, "s": 4476, "text": " Manuj Aggarwal" }, { "code": null, "e": 4525, "s": 4492, "text": "\n 20 Lectures \n 1 hours \n" }, { "code": null, "e": 4540, "s": 4525, "text": " Faizan Tayyab" }, { "code": null, "e": 4547, "s": 4540, "text": " Print" }, { "code": null, "e": 4558, "s": 4547, "text": " Add Notes" } ]
Count number of times value appears in particular column in MySQL?
You can use aggregate function count() with group by. The syntax is as follows. select yourColumnName,count(*) as anyVariableName from yourtableName group by yourColumnName; To understand the above syntax, let us create a table. The query to create a table is as follows. mysql> create table CountSameValue -> ( -> Id int, -> Name varchar(100), -> Marks int -> ); Query OK, 0 rows affected (0.70 sec) Insert records in the table using insert command. The query is as follows. mysql> insert into CountSameValue values(1,'Sam',67); Query OK, 1 row affected (0.17 sec) mysql> insert into CountSameValue values(2,'Mike',87); Query OK, 1 row affected (0.19 sec) mysql> insert into CountSameValue values(3,'Carol',67); Query OK, 1 row affected (0.24 sec) mysql> insert into CountSameValue values(4,'Bob',87); Query OK, 1 row affected (0.18 sec) mysql> insert into CountSameValue values(5,'John',71); Query OK, 1 row affected (0.17 sec) mysql> insert into CountSameValue values(6,'Adam',66); Query OK, 1 row affected (0.18 sec) mysql> insert into CountSameValue values(7,'David',71); Query OK, 1 row affected (0.20 sec) mysql> insert into CountSameValue values(8,'Maria',67); Query OK, 1 row affected (0.16 sec) Display all records from the table using select statement. The query is as follows. mysql> select *from CountSameValue; The following is the output. +------+-------+-------+ | Id | Name | Marks | +------+-------+-------+ | 1 | Sam | 67 | | 2 | Mike | 87 | | 3 | Carol | 67 | | 4 | Bob | 87 | | 5 | John | 71 | | 6 | Adam | 66 | | 7 | David | 71 | | 8 | Maria | 67 | +------+-------+-------+ 8 rows in set (0.00 sec) Here is the query to count the number of times value (marks) appears in a column. The query is as follows. mysql> select Marks,count(*) as Total from CountSameValue group by Marks; The following is the output. +-------+-------+ | Marks | Total | +-------+-------+ | 67 | 3 | | 87 | 2 | | 71 | 2 | | 66 | 1 | +-------+-------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1142, "s": 1062, "text": "You can use aggregate function count() with group by. The syntax is as follows." }, { "code": null, "e": 1236, "s": 1142, "text": "select yourColumnName,count(*) as anyVariableName from yourtableName group by yourColumnName;" }, { "code": null, "e": 1334, "s": 1236, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows." }, { "code": null, "e": 1463, "s": 1334, "text": "mysql> create table CountSameValue\n-> (\n-> Id int,\n-> Name varchar(100),\n-> Marks int\n-> );\nQuery OK, 0 rows affected (0.70 sec)" }, { "code": null, "e": 1538, "s": 1463, "text": "Insert records in the table using insert command. The query is as follows." }, { "code": null, "e": 2274, "s": 1538, "text": "mysql> insert into CountSameValue values(1,'Sam',67);\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into CountSameValue values(2,'Mike',87);\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into CountSameValue values(3,'Carol',67);\nQuery OK, 1 row affected (0.24 sec)\n\nmysql> insert into CountSameValue values(4,'Bob',87);\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into CountSameValue values(5,'John',71);\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into CountSameValue values(6,'Adam',66);\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into CountSameValue values(7,'David',71);\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into CountSameValue values(8,'Maria',67);\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 2358, "s": 2274, "text": "Display all records from the table using select statement. The query is as follows." }, { "code": null, "e": 2394, "s": 2358, "text": "mysql> select *from CountSameValue;" }, { "code": null, "e": 2423, "s": 2394, "text": "The following is the output." }, { "code": null, "e": 2748, "s": 2423, "text": "+------+-------+-------+\n| Id | Name | Marks |\n+------+-------+-------+\n| 1 | Sam | 67 |\n| 2 | Mike | 87 |\n| 3 | Carol | 67 |\n| 4 | Bob | 87 |\n| 5 | John | 71 |\n| 6 | Adam | 66 |\n| 7 | David | 71 |\n| 8 | Maria | 67 |\n+------+-------+-------+\n8 rows in set (0.00 sec)" }, { "code": null, "e": 2855, "s": 2748, "text": "Here is the query to count the number of times value (marks) appears in a column. The query is as follows." }, { "code": null, "e": 2929, "s": 2855, "text": "mysql> select Marks,count(*) as Total from CountSameValue group by Marks;" }, { "code": null, "e": 2958, "s": 2929, "text": "The following is the output." }, { "code": null, "e": 3127, "s": 2958, "text": "+-------+-------+\n| Marks | Total |\n+-------+-------+\n| 67 | 3 |\n| 87 | 2 |\n| 71 | 2 |\n| 66 | 1 |\n+-------+-------+\n4 rows in set (0.00 sec)" } ]
Ways of implementing Polymorphism in Python - GeeksforGeeks
30 Jun, 2021 In programming, Polymorphism is a concept of Object-Oriented Programming. It enables using a single interface with the input of different data types, different classes or maybe for a different number of inputs. Example: In this case, the function len() is polymorphic as it is taking a string as input in the first case and is taking a list as input in the second case. Python3 # length of stringx = len('Geeks')print(x) # length of listy = len([1, 2, 3, 4])print(y) Output: 5 4 In Python, Polymorphism is a way of making a function accept objects of different classes if they behave similarly. There are four ways of implementing Polymorphism in Python: 1. Duck Typing: Duck typing is a concept that says that the β€œtype” of the object is a matter of concern only at runtime and you don’t need to explicitly mention the type of the object before you perform any kind of operation on that object, unlike normal typing where the suitability of an object is determined by its type. In Python, we have the concept of Dynamic typing i.e we can mention the type of variable/object later. The idea is that you don’t need a type in order to invoke an existing method on an object if a method is defined on it, you can invoke it. Python3 class Geeks1: def code (self, ide): ide.execute() class Geeks2: def execute (self): print("GeeksForGeeks is the best Platform for learning") # create object of Geeks2 ide = Geeks2() # create object of class Geeks1G1 = Geeks1() # calling the function by giving ide as the argument.G1.code(ide) Output: GeeksForGeeks is the best Platform for learning 2. Method Overloading: By default, Python does not support method overloading, but we can achieve it by modifying out methods. Given a single function sum (), the number of parameters can be specified by you. This process of calling the same method in different ways is called method overloading. Concept of Method overloading Python3 class GFG: def sum(self, a = None, b = None, c = None): s = 0 if a != None and b != None and c != None: s = a + b + c elif a != None and b != None: s = a + b else: s = a return s s = GFG() # sum of 1 integerprint(s.sum(1)) # sum of 2 integersprint(s.sum(3, 5)) # sum of 3 integersprint(s.sum(1, 2, 3)) Output: 1 8 6 3. Operator Overloading: Operator overloading in Python is the ability of a single operator to perform more than one operation based on the class (type) of operands. So, basically defining methods for operators is known as operator overloading. For e.g: To use the + operator with custom objects you need to define a method called __add__. We know + operator is used for adding numbers and at the same time to concatenate strings. It is possible because the + operator is overloaded by both int class and str class. The operators are actually methods defined in respective classes. So if you want to use the + operator to add two objects of some user-defined class then you will have to define that behavior yourself and inform Python about that. Python3 class Student: def __init__(self, m1, m2): self.m1 = m1 self.m2 = m2 S1 = Student (58, 60)S2 = Student (60, 58) # this will generate an errorS3 = S1 + S2 Output: TypeError: unsupported operand type(s) for +: 'Student' and 'Student' So we can see that the + operator is not supported in a user-defined class. But we can do the same by overloading the + operator for our class. Python3 class Student: # defining init method for class def __init__(self, m1, m2): self.m1 = m1 self.m2 = m2 # overloading the + operator def __add__(self, other): m1 = self.m1 + other.m1 m2 = self.m2 + other.m2 s3 = Student(m1, m2) return s3 s1 = Student(58, 59)s2 = Student(60, 65)s3 = s1 + s2print(s3.m1) Output: 118 4. Method Overriding: By using method overriding a class may β€œcopy” another class, avoiding duplicated code, and at the same time enhance or customize a part of it. Method overriding is thus a part of the inheritance mechanism. In Python, method overriding occurs by simply defining the child class in a method with the same name as a method in the parent class. Python3 # parent classclass Programming: # properties DataStructures = True Algorithms = True # function practice def practice(self): print("Practice makes a man perfect") # function consistency def consistency(self): print("Hard work along with consistency can defeat Talent") # child class class Python(Programming): # function def consistency(self): print("Hard work along with consistency can defeat Talent.") Py = Python()Py.consistency()Py.practice() Output: Hard work along with consistency can defeat Talent. Practice makes a man perfect simmytarika5 python-oop-concepts Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Get unique values from a list Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25689, "s": 25661, "text": "\n30 Jun, 2021" }, { "code": null, "e": 25900, "s": 25689, "text": "In programming, Polymorphism is a concept of Object-Oriented Programming. It enables using a single interface with the input of different data types, different classes or maybe for a different number of inputs." }, { "code": null, "e": 26059, "s": 25900, "text": "Example: In this case, the function len() is polymorphic as it is taking a string as input in the first case and is taking a list as input in the second case." }, { "code": null, "e": 26067, "s": 26059, "text": "Python3" }, { "code": "# length of stringx = len('Geeks')print(x) # length of listy = len([1, 2, 3, 4])print(y)", "e": 26156, "s": 26067, "text": null }, { "code": null, "e": 26164, "s": 26156, "text": "Output:" }, { "code": null, "e": 26168, "s": 26164, "text": "5\n4" }, { "code": null, "e": 26284, "s": 26168, "text": "In Python, Polymorphism is a way of making a function accept objects of different classes if they behave similarly." }, { "code": null, "e": 26344, "s": 26284, "text": "There are four ways of implementing Polymorphism in Python:" }, { "code": null, "e": 26668, "s": 26344, "text": "1. Duck Typing: Duck typing is a concept that says that the β€œtype” of the object is a matter of concern only at runtime and you don’t need to explicitly mention the type of the object before you perform any kind of operation on that object, unlike normal typing where the suitability of an object is determined by its type." }, { "code": null, "e": 26910, "s": 26668, "text": "In Python, we have the concept of Dynamic typing i.e we can mention the type of variable/object later. The idea is that you don’t need a type in order to invoke an existing method on an object if a method is defined on it, you can invoke it." }, { "code": null, "e": 26918, "s": 26910, "text": "Python3" }, { "code": "class Geeks1: def code (self, ide): ide.execute() class Geeks2: def execute (self): print(\"GeeksForGeeks is the best Platform for learning\") # create object of Geeks2 ide = Geeks2() # create object of class Geeks1G1 = Geeks1() # calling the function by giving ide as the argument.G1.code(ide)", "e": 27229, "s": 26918, "text": null }, { "code": null, "e": 27237, "s": 27229, "text": "Output:" }, { "code": null, "e": 27285, "s": 27237, "text": "GeeksForGeeks is the best Platform for learning" }, { "code": null, "e": 27412, "s": 27285, "text": "2. Method Overloading: By default, Python does not support method overloading, but we can achieve it by modifying out methods." }, { "code": null, "e": 27582, "s": 27412, "text": "Given a single function sum (), the number of parameters can be specified by you. This process of calling the same method in different ways is called method overloading." }, { "code": null, "e": 27613, "s": 27582, "text": "Concept of Method overloading " }, { "code": null, "e": 27621, "s": 27613, "text": "Python3" }, { "code": "class GFG: def sum(self, a = None, b = None, c = None): s = 0 if a != None and b != None and c != None: s = a + b + c elif a != None and b != None: s = a + b else: s = a return s s = GFG() # sum of 1 integerprint(s.sum(1)) # sum of 2 integersprint(s.sum(3, 5)) # sum of 3 integersprint(s.sum(1, 2, 3))", "e": 28008, "s": 27621, "text": null }, { "code": null, "e": 28016, "s": 28008, "text": "Output:" }, { "code": null, "e": 28022, "s": 28016, "text": "1\n8\n6" }, { "code": null, "e": 28363, "s": 28022, "text": "3. Operator Overloading: Operator overloading in Python is the ability of a single operator to perform more than one operation based on the class (type) of operands. So, basically defining methods for operators is known as operator overloading. For e.g: To use the + operator with custom objects you need to define a method called __add__." }, { "code": null, "e": 28607, "s": 28363, "text": " We know + operator is used for adding numbers and at the same time to concatenate strings. It is possible because the + operator is overloaded by both int class and str class. The operators are actually methods defined in respective classes. " }, { "code": null, "e": 28772, "s": 28607, "text": "So if you want to use the + operator to add two objects of some user-defined class then you will have to define that behavior yourself and inform Python about that." }, { "code": null, "e": 28780, "s": 28772, "text": "Python3" }, { "code": "class Student: def __init__(self, m1, m2): self.m1 = m1 self.m2 = m2 S1 = Student (58, 60)S2 = Student (60, 58) # this will generate an errorS3 = S1 + S2", "e": 28951, "s": 28780, "text": null }, { "code": null, "e": 28959, "s": 28951, "text": "Output:" }, { "code": null, "e": 29029, "s": 28959, "text": "TypeError: unsupported operand type(s) for +: 'Student' and 'Student'" }, { "code": null, "e": 29173, "s": 29029, "text": "So we can see that the + operator is not supported in a user-defined class. But we can do the same by overloading the + operator for our class." }, { "code": null, "e": 29181, "s": 29173, "text": "Python3" }, { "code": "class Student: # defining init method for class def __init__(self, m1, m2): self.m1 = m1 self.m2 = m2 # overloading the + operator def __add__(self, other): m1 = self.m1 + other.m1 m2 = self.m2 + other.m2 s3 = Student(m1, m2) return s3 s1 = Student(58, 59)s2 = Student(60, 65)s3 = s1 + s2print(s3.m1)", "e": 29540, "s": 29181, "text": null }, { "code": null, "e": 29548, "s": 29540, "text": "Output:" }, { "code": null, "e": 29552, "s": 29548, "text": "118" }, { "code": null, "e": 29780, "s": 29552, "text": "4. Method Overriding: By using method overriding a class may β€œcopy” another class, avoiding duplicated code, and at the same time enhance or customize a part of it. Method overriding is thus a part of the inheritance mechanism." }, { "code": null, "e": 29915, "s": 29780, "text": "In Python, method overriding occurs by simply defining the child class in a method with the same name as a method in the parent class." }, { "code": null, "e": 29923, "s": 29915, "text": "Python3" }, { "code": "# parent classclass Programming: # properties DataStructures = True Algorithms = True # function practice def practice(self): print(\"Practice makes a man perfect\") # function consistency def consistency(self): print(\"Hard work along with consistency can defeat Talent\") # child class class Python(Programming): # function def consistency(self): print(\"Hard work along with consistency can defeat Talent.\") Py = Python()Py.consistency()Py.practice()", "e": 30452, "s": 29923, "text": null }, { "code": null, "e": 30460, "s": 30452, "text": "Output:" }, { "code": null, "e": 30541, "s": 30460, "text": "Hard work along with consistency can defeat Talent.\nPractice makes a man perfect" }, { "code": null, "e": 30554, "s": 30541, "text": "simmytarika5" }, { "code": null, "e": 30574, "s": 30554, "text": "python-oop-concepts" }, { "code": null, "e": 30581, "s": 30574, "text": "Python" }, { "code": null, "e": 30679, "s": 30581, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30711, "s": 30679, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30753, "s": 30711, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30795, "s": 30753, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30851, "s": 30795, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30878, "s": 30851, "text": "Python Classes and Objects" }, { "code": null, "e": 30909, "s": 30878, "text": "Python | os.path.join() method" }, { "code": null, "e": 30938, "s": 30909, "text": "Create a directory in Python" }, { "code": null, "e": 30960, "s": 30938, "text": "Defaultdict in Python" }, { "code": null, "e": 30999, "s": 30960, "text": "Python | Get unique values from a list" } ]
Convert an Object to a String in R Programming - toString() Function - GeeksforGeeks
17 Jun, 2020 toString() function in R Language is used to convert an object into a single character string. Syntax: toString(x, width) Parameters:x: Objectwidth: maximum string width Example 1: # R program to convert an object to string # Creating a vectorx <- c("Geeks", "for", "geeks") # Calling toString() FunctiontoString(x)toString(x, width = 12) Output: [1] "Geeks, for, geeks" [1] "Geeks, f...." Example 2: # R program to convert an object to string # Creating a matrixx <- matrix(c(1:9), 3, 3) # Calling toString() FunctiontoString(x) Output: [1] "1, 2, 3, 4, 5, 6, 7, 8, 9" R String-Functions R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) How to change Row Names of DataFrame in R ? Group by function in R using Dplyr Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? How to Change Axis Scales in R Plots? K-Means Clustering in R Programming R Programming Language - Introduction Remove rows with NA in one column of R DataFrame
[ { "code": null, "e": 25074, "s": 25046, "text": "\n17 Jun, 2020" }, { "code": null, "e": 25169, "s": 25074, "text": "toString() function in R Language is used to convert an object into a single character string." }, { "code": null, "e": 25196, "s": 25169, "text": "Syntax: toString(x, width)" }, { "code": null, "e": 25244, "s": 25196, "text": "Parameters:x: Objectwidth: maximum string width" }, { "code": null, "e": 25255, "s": 25244, "text": "Example 1:" }, { "code": "# R program to convert an object to string # Creating a vectorx <- c(\"Geeks\", \"for\", \"geeks\") # Calling toString() FunctiontoString(x)toString(x, width = 12)", "e": 25416, "s": 25255, "text": null }, { "code": null, "e": 25424, "s": 25416, "text": "Output:" }, { "code": null, "e": 25468, "s": 25424, "text": "[1] \"Geeks, for, geeks\"\n[1] \"Geeks, f....\"\n" }, { "code": null, "e": 25479, "s": 25468, "text": "Example 2:" }, { "code": "# R program to convert an object to string # Creating a matrixx <- matrix(c(1:9), 3, 3) # Calling toString() FunctiontoString(x)", "e": 25610, "s": 25479, "text": null }, { "code": null, "e": 25618, "s": 25610, "text": "Output:" }, { "code": null, "e": 25651, "s": 25618, "text": "[1] \"1, 2, 3, 4, 5, 6, 7, 8, 9\"\n" }, { "code": null, "e": 25670, "s": 25651, "text": "R String-Functions" }, { "code": null, "e": 25681, "s": 25670, "text": "R Language" }, { "code": null, "e": 25779, "s": 25681, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25831, "s": 25779, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 25863, "s": 25831, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 25907, "s": 25863, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 25942, "s": 25907, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 25994, "s": 25942, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26052, "s": 25994, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 26090, "s": 26052, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26126, "s": 26090, "text": "K-Means Clustering in R Programming" }, { "code": null, "e": 26164, "s": 26126, "text": "R Programming Language - Introduction" } ]
Introduction of Stack based CPU Organization - GeeksforGeeks
13 Jan, 2022 The computers which use Stack-based CPU Organization are based on a data structure called a stack. The stack is a list of data words. It uses the Last In First Out (LIFO) access method which is the most popular access method in most of the CPU. A register is used to store the address of the topmost element of the stack which is known as Stack pointer (SP). In this organization, ALU operations are performed on stack data. It means both the operands are always required on the stack. After manipulation, the result is placed in the stack. The main two operations that are performed on the operators of the stack are Push and Pop. These two operations are performed from one end only. 1. Push – This operation results in inserting one operand at the top of the stack and it decreases the stack pointer register. The format of the PUSH instruction is: PUSH It inserts the data word at a specified address to the top of the stack. It can be implemented as: //decrement SP by 1 SP <-- SP - 1 //store the content of specified memory address //into SP; i.e, at top of stack SP <-- (memory address) 2. Pop – This operation results in deleting one operand from the top of the stack and increasing the stack pointer register. The format of the POP instruction is: POP It deletes the data word at the top of the stack to the specified address. It can be implemented as: //transfer the content of SP (i.e, at top most data) //into specified memory location (memory address) <-- SP //increment SP by 1 SP <-- SP + 1 Operation type instruction does not need the address field in this CPU organization. This is because the operation is performed on the two operands that are on the top of the stack. For example: SUB This instruction contains the opcode only with no address field. It pops the two top data from the stack, subtracting the data, and pushing the result into the stack at the top. PDP-11, Intel’s 8085, and HP 3000 are some examples of stack-organized computers. The advantages of Stack-based CPU organization – Efficient computation of complex arithmetic expressions. Execution of instructions is fast because operand data are stored in consecutive memory locations. The length of instruction is short as they do not have an address field. The disadvantages of Stack-based CPU organization – The size of the program increases. Note: Stack-based CPU organization uses zero address instruction. VaibhavRai3 TanyaGautam2 tanwarsinghvaibhav Computer Organization & Architecture Stack Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Logical and Physical Address in Operating System Program for Decimal to Binary Conversion Flag register of 8086 microprocessor Direct Access Media (DMA) Controller in Computer Architecture Interrupts Stack Data Structure (Introduction and Program) Stack Class in Java Stack in Python Check for Balanced Brackets in an expression (well-formedness) using Stack Stack | Set 2 (Infix to Postfix)
[ { "code": null, "e": 27638, "s": 27610, "text": "\n13 Jan, 2022" }, { "code": null, "e": 28180, "s": 27638, "text": "The computers which use Stack-based CPU Organization are based on a data structure called a stack. The stack is a list of data words. It uses the Last In First Out (LIFO) access method which is the most popular access method in most of the CPU. A register is used to store the address of the topmost element of the stack which is known as Stack pointer (SP). In this organization, ALU operations are performed on stack data. It means both the operands are always required on the stack. After manipulation, the result is placed in the stack. " }, { "code": null, "e": 28326, "s": 28180, "text": "The main two operations that are performed on the operators of the stack are Push and Pop. These two operations are performed from one end only. " }, { "code": null, "e": 28493, "s": 28326, "text": "1. Push – This operation results in inserting one operand at the top of the stack and it decreases the stack pointer register. The format of the PUSH instruction is: " }, { "code": null, "e": 28499, "s": 28493, "text": "PUSH " }, { "code": null, "e": 28599, "s": 28499, "text": "It inserts the data word at a specified address to the top of the stack. It can be implemented as: " }, { "code": null, "e": 28741, "s": 28599, "text": "//decrement SP by 1\nSP <-- SP - 1 \n\n//store the content of specified memory address \n//into SP; i.e, at top of stack\nSP <-- (memory address) " }, { "code": null, "e": 28905, "s": 28741, "text": "2. Pop – This operation results in deleting one operand from the top of the stack and increasing the stack pointer register. The format of the POP instruction is: " }, { "code": null, "e": 28910, "s": 28905, "text": "POP " }, { "code": null, "e": 29012, "s": 28910, "text": "It deletes the data word at the top of the stack to the specified address. It can be implemented as: " }, { "code": null, "e": 29179, "s": 29012, "text": "//transfer the content of SP (i.e, at top most data) \n//into specified memory location \n(memory address) <-- SP\n\n//increment SP by 1\nSP <-- SP + 1 " }, { "code": null, "e": 29375, "s": 29179, "text": "Operation type instruction does not need the address field in this CPU organization. This is because the operation is performed on the two operands that are on the top of the stack. For example: " }, { "code": null, "e": 29380, "s": 29375, "text": "SUB " }, { "code": null, "e": 29559, "s": 29380, "text": "This instruction contains the opcode only with no address field. It pops the two top data from the stack, subtracting the data, and pushing the result into the stack at the top. " }, { "code": null, "e": 29642, "s": 29559, "text": "PDP-11, Intel’s 8085, and HP 3000 are some examples of stack-organized computers. " }, { "code": null, "e": 29692, "s": 29642, "text": "The advantages of Stack-based CPU organization – " }, { "code": null, "e": 29750, "s": 29692, "text": "Efficient computation of complex arithmetic expressions. " }, { "code": null, "e": 29850, "s": 29750, "text": "Execution of instructions is fast because operand data are stored in consecutive memory locations. " }, { "code": null, "e": 29924, "s": 29850, "text": "The length of instruction is short as they do not have an address field. " }, { "code": null, "e": 29976, "s": 29924, "text": "The disadvantages of Stack-based CPU organization –" }, { "code": null, "e": 30012, "s": 29976, "text": "The size of the program increases. " }, { "code": null, "e": 30078, "s": 30012, "text": "Note: Stack-based CPU organization uses zero address instruction." }, { "code": null, "e": 30090, "s": 30078, "text": "VaibhavRai3" }, { "code": null, "e": 30103, "s": 30090, "text": "TanyaGautam2" }, { "code": null, "e": 30122, "s": 30103, "text": "tanwarsinghvaibhav" }, { "code": null, "e": 30159, "s": 30122, "text": "Computer Organization & Architecture" }, { "code": null, "e": 30165, "s": 30159, "text": "Stack" }, { "code": null, "e": 30171, "s": 30165, "text": "Stack" }, { "code": null, "e": 30269, "s": 30171, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30318, "s": 30269, "text": "Logical and Physical Address in Operating System" }, { "code": null, "e": 30359, "s": 30318, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 30396, "s": 30359, "text": "Flag register of 8086 microprocessor" }, { "code": null, "e": 30458, "s": 30396, "text": "Direct Access Media (DMA) Controller in Computer Architecture" }, { "code": null, "e": 30469, "s": 30458, "text": "Interrupts" }, { "code": null, "e": 30517, "s": 30469, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 30537, "s": 30517, "text": "Stack Class in Java" }, { "code": null, "e": 30553, "s": 30537, "text": "Stack in Python" }, { "code": null, "e": 30628, "s": 30553, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" } ]
Adding Boundary to an Object in Pygame - GeeksforGeeks
01 Aug, 2020 Boundaries to any game are very important. In snake games, space invaders, ping pong game, etc. the boundary condition is very important. The ball bounces at the boundaries of the screen in ping pong games. So, the idea behind this boundaries is to change the position of the ball or object in reverse direction as soon as it hits the wall. Let us see how to add boundary for a game in which a ball bounces off that boundary. 1. First of all, we will make the PyGame window. # importing the moduleimport pygame # instantiating the classpygame.init() # dimension of the screenwidth = 700height = 550 # colourswhite = (255, 255, 255)red = (255, 0, 0)green = (0, 255, 0)blue = (0, 0, 255)black = (0, 0, 0) # creating a Screenscreen = pygame.display.set_mode((width, height)) # title of the screenpygame.display.set_caption("Bouncy Ball") 2. Now, we are creating a ball. The ball is just a circle drawn on the screen. That will be written in a while loop. Here we are declaring its position and its speed. Initially, the ball will be placed at the center (width/2 and height/2). Then we will increase the speed of the ball by respective values of XChange and YChange. As both X and Y directions are changing, the ball will move in a diagonal direction and its further path will be dependent on the colliding body. # importing the moduleimport random # declaring variables for the ballball_X = width/2 - 12ball_Y = height/2 - 12ball_XChange = 3* random.choice((1, -1))ball_YChange = 3ballPixel = 24 3. Now we will start the basic game running loop. We are also giving a background color to our screen. # gaming Looprunning = Truewhile running: # background color screen.fill(red) # to exit the loop for event in pygame.event.get(): if event.type == pygame.QUIT: running = False 4. Here comes the major part of our game. We are providing a condition that if the ball’s X Position is greater than the width of the screen or less than 0 (i.e if the ball is colliding or coming at its right or left end of the screen), then we multiply the X direction speed by negative 1. It means that the direction is reversed. If the ball is coming at a speed of 3 pixels, then on colliding at left or right wall, it’s speed will be -3 pixels, i.e in the reverse direction, and again when it hits the walls, then again its speed will be positive 3, i.e reverse of -3. Hence, this will give a boundary to a ball. Also, the same logic will be applied for the upper and the lower wall. If the ball’s Y value is greater than the screen’s height or less than 0, then reverse its direction.And then we move the ball by incrementing the position of the ball by XChange and YChange respectively. (the code below is under the gaming loop) # inside the gaming Loop # bouncing the ball if ball_X + ballPixel >= width or ball_X <= 0: ball_XChange *= -1 if ball_Y + ballPixel >= height or ball_Y <= 0: ball_YChange *= -1 # moving the ball ball_X += ball_XChange ball_Y += ball_YChange 5. Now, we will be drawing the ball in the while loop so that it will be displayed in each loop. We are drawing the circle at the ballX and ballY position, so that we the ball’s X and Y position are incrementing in each loop and the ball will be drawn at next position in each loop and hence the ball will move inside the screen. And at the end we update the screen. # inside the gaming Loop # drawing the ball ballImg = pygame.draw.circle(screen, (0,0,255), (int(ball_X), int(ball_Y)), 15) pygame.display.update() This is how we add a boundary to an object in PyGame. The complete code is as follows : # importing the modulesimport pygameimport random # instantiating the classpygame.init() # dimension of the screenwidth = 700height = 550 # colourswhite = (255, 255, 255)red = (255, 0, 0)green = (0, 255, 0)blue = (0, 0, 255)black = (0, 0, 0) # creating a Screenscreen = pygame.display.set_mode((width, height)) # title of the screenpygame.display.set_caption("Bouncy Ball") # declaring variables for the ballball_X = width/2 - 12ball_Y = height/2 - 12ball_XChange = 3* random.choice((1, -1))ball_YChange = 3ballPixel = 24 # gaming Looprunning = Truewhile running: # background color screen.fill(red) # to exit the loop for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # bouncing the ball if ball_X + ballPixel >= width or ball_X <= 0: ball_XChange *= -1 if ball_Y + ballPixel >= height or ball_Y <= 0: ball_YChange *= -1 # moving the ball ball_X += ball_XChange ball_Y += ball_YChange # drawing the ball ballImg = pygame.draw.circle(screen, (0,0,255), (int(ball_X), int(ball_Y)), 15) pygame.display.update() Output : Python-PyGame Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n01 Aug, 2020" }, { "code": null, "e": 25854, "s": 25647, "text": "Boundaries to any game are very important. In snake games, space invaders, ping pong game, etc. the boundary condition is very important. The ball bounces at the boundaries of the screen in ping pong games." }, { "code": null, "e": 25988, "s": 25854, "text": "So, the idea behind this boundaries is to change the position of the ball or object in reverse direction as soon as it hits the wall." }, { "code": null, "e": 26073, "s": 25988, "text": "Let us see how to add boundary for a game in which a ball bounces off that boundary." }, { "code": null, "e": 26122, "s": 26073, "text": "1. First of all, we will make the PyGame window." }, { "code": "# importing the moduleimport pygame # instantiating the classpygame.init() # dimension of the screenwidth = 700height = 550 # colourswhite = (255, 255, 255)red = (255, 0, 0)green = (0, 255, 0)blue = (0, 0, 255)black = (0, 0, 0) # creating a Screenscreen = pygame.display.set_mode((width, height)) # title of the screenpygame.display.set_caption(\"Bouncy Ball\")", "e": 26490, "s": 26122, "text": null }, { "code": null, "e": 26965, "s": 26490, "text": "2. Now, we are creating a ball. The ball is just a circle drawn on the screen. That will be written in a while loop. Here we are declaring its position and its speed. Initially, the ball will be placed at the center (width/2 and height/2). Then we will increase the speed of the ball by respective values of XChange and YChange. As both X and Y directions are changing, the ball will move in a diagonal direction and its further path will be dependent on the colliding body." }, { "code": "# importing the moduleimport random # declaring variables for the ballball_X = width/2 - 12ball_Y = height/2 - 12ball_XChange = 3* random.choice((1, -1))ball_YChange = 3ballPixel = 24", "e": 27150, "s": 26965, "text": null }, { "code": null, "e": 27253, "s": 27150, "text": "3. Now we will start the basic game running loop. We are also giving a background color to our screen." }, { "code": "# gaming Looprunning = Truewhile running: # background color screen.fill(red) # to exit the loop for event in pygame.event.get(): if event.type == pygame.QUIT: running = False", "e": 27463, "s": 27253, "text": null }, { "code": null, "e": 28080, "s": 27463, "text": "4. Here comes the major part of our game. We are providing a condition that if the ball’s X Position is greater than the width of the screen or less than 0 (i.e if the ball is colliding or coming at its right or left end of the screen), then we multiply the X direction speed by negative 1. It means that the direction is reversed. If the ball is coming at a speed of 3 pixels, then on colliding at left or right wall, it’s speed will be -3 pixels, i.e in the reverse direction, and again when it hits the walls, then again its speed will be positive 3, i.e reverse of -3. Hence, this will give a boundary to a ball." }, { "code": null, "e": 28151, "s": 28080, "text": "Also, the same logic will be applied for the upper and the lower wall." }, { "code": null, "e": 28356, "s": 28151, "text": "If the ball’s Y value is greater than the screen’s height or less than 0, then reverse its direction.And then we move the ball by incrementing the position of the ball by XChange and YChange respectively." }, { "code": null, "e": 28398, "s": 28356, "text": "(the code below is under the gaming loop)" }, { "code": "# inside the gaming Loop # bouncing the ball if ball_X + ballPixel >= width or ball_X <= 0: ball_XChange *= -1 if ball_Y + ballPixel >= height or ball_Y <= 0: ball_YChange *= -1 # moving the ball ball_X += ball_XChange ball_Y += ball_YChange", "e": 28676, "s": 28398, "text": null }, { "code": null, "e": 29043, "s": 28676, "text": "5. Now, we will be drawing the ball in the while loop so that it will be displayed in each loop. We are drawing the circle at the ballX and ballY position, so that we the ball’s X and Y position are incrementing in each loop and the ball will be drawn at next position in each loop and hence the ball will move inside the screen. And at the end we update the screen." }, { "code": "# inside the gaming Loop # drawing the ball ballImg = pygame.draw.circle(screen, (0,0,255), (int(ball_X), int(ball_Y)), 15) pygame.display.update()", "e": 29266, "s": 29043, "text": null }, { "code": null, "e": 29320, "s": 29266, "text": "This is how we add a boundary to an object in PyGame." }, { "code": null, "e": 29354, "s": 29320, "text": "The complete code is as follows :" }, { "code": "# importing the modulesimport pygameimport random # instantiating the classpygame.init() # dimension of the screenwidth = 700height = 550 # colourswhite = (255, 255, 255)red = (255, 0, 0)green = (0, 255, 0)blue = (0, 0, 255)black = (0, 0, 0) # creating a Screenscreen = pygame.display.set_mode((width, height)) # title of the screenpygame.display.set_caption(\"Bouncy Ball\") # declaring variables for the ballball_X = width/2 - 12ball_Y = height/2 - 12ball_XChange = 3* random.choice((1, -1))ball_YChange = 3ballPixel = 24 # gaming Looprunning = Truewhile running: # background color screen.fill(red) # to exit the loop for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # bouncing the ball if ball_X + ballPixel >= width or ball_X <= 0: ball_XChange *= -1 if ball_Y + ballPixel >= height or ball_Y <= 0: ball_YChange *= -1 # moving the ball ball_X += ball_XChange ball_Y += ball_YChange # drawing the ball ballImg = pygame.draw.circle(screen, (0,0,255), (int(ball_X), int(ball_Y)), 15) pygame.display.update()", "e": 30560, "s": 29354, "text": null }, { "code": null, "e": 30569, "s": 30560, "text": "Output :" }, { "code": null, "e": 30583, "s": 30569, "text": "Python-PyGame" }, { "code": null, "e": 30590, "s": 30583, "text": "Python" }, { "code": null, "e": 30688, "s": 30590, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30720, "s": 30688, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30762, "s": 30720, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30804, "s": 30762, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30860, "s": 30804, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30887, "s": 30860, "text": "Python Classes and Objects" }, { "code": null, "e": 30918, "s": 30887, "text": "Python | os.path.join() method" }, { "code": null, "e": 30947, "s": 30918, "text": "Create a directory in Python" }, { "code": null, "e": 30969, "s": 30947, "text": "Defaultdict in Python" }, { "code": null, "e": 31005, "s": 30969, "text": "Python | Pandas dataframe.groupby()" } ]
Python | Geographical plotting using plotly - GeeksforGeeks
26 Jun, 2018 Geographical plotting is used for world map as well as states under a country. Mainly used by data analysts to check the agriculture exports or to visualize such data. plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. cufflink connects plotly with pandas to create graphs and charts of dataframes directly. choropleth is used to describe geographical plotting of USA. choropleth is used in the plotting of world maps and many more. Command to install plotly: pip install plotly Below is the implementation: # Python program to plot # geographical data using plotly # importing all necessary librariesimport plotly.plotly as pyimport plotly.graph_objs as goimport pandas as pd # some more libraries to plot graphfrom plotly.offline import download_plotlyjs, init_notebook_mode, iplot, plot # To establish connectioninit_notebook_mode(connected = True) # type defined is choropleth to# plot geographical plotsdata = dict(type = 'choropleth', # location: Arizoana, California, Newyork locations = ['AZ', 'CA', 'NY'], # States of USA locationmode = 'USA-states', # colorscale can be added as per requirement colorscale = 'Portland', # text can be given anything you like text = ['text 1', 'text 2', 'text 3'], z = [1.0, 2.0, 3.0], colorbar = {'title': 'Colorbar Title Goes Here'}) layout = dict(geo ={'scope': 'usa'}) # passing data dictionary as a list choromap = go.Figure(data = [data], layout = layout) # plotting graphiplot(choromap) Output: python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25354, "s": 25326, "text": "\n26 Jun, 2018" }, { "code": null, "e": 25522, "s": 25354, "text": "Geographical plotting is used for world map as well as states under a country. Mainly used by data analysts to check the agriculture exports or to visualize such data." }, { "code": null, "e": 25824, "s": 25522, "text": "plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library." }, { "code": null, "e": 26038, "s": 25824, "text": "cufflink connects plotly with pandas to create graphs and charts of dataframes directly. choropleth is used to describe geographical plotting of USA. choropleth is used in the plotting of world maps and many more." }, { "code": null, "e": 26065, "s": 26038, "text": "Command to install plotly:" }, { "code": null, "e": 26085, "s": 26065, "text": "pip install plotly " }, { "code": null, "e": 26116, "s": 26087, "text": "Below is the implementation:" }, { "code": "# Python program to plot # geographical data using plotly # importing all necessary librariesimport plotly.plotly as pyimport plotly.graph_objs as goimport pandas as pd # some more libraries to plot graphfrom plotly.offline import download_plotlyjs, init_notebook_mode, iplot, plot # To establish connectioninit_notebook_mode(connected = True) # type defined is choropleth to# plot geographical plotsdata = dict(type = 'choropleth', # location: Arizoana, California, Newyork locations = ['AZ', 'CA', 'NY'], # States of USA locationmode = 'USA-states', # colorscale can be added as per requirement colorscale = 'Portland', # text can be given anything you like text = ['text 1', 'text 2', 'text 3'], z = [1.0, 2.0, 3.0], colorbar = {'title': 'Colorbar Title Goes Here'}) layout = dict(geo ={'scope': 'usa'}) # passing data dictionary as a list choromap = go.Figure(data = [data], layout = layout) # plotting graphiplot(choromap)", "e": 27219, "s": 26116, "text": null }, { "code": null, "e": 27227, "s": 27219, "text": "Output:" }, { "code": null, "e": 27242, "s": 27227, "text": "python-modules" }, { "code": null, "e": 27249, "s": 27242, "text": "Python" }, { "code": null, "e": 27347, "s": 27249, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27356, "s": 27347, "text": "Comments" }, { "code": null, "e": 27369, "s": 27356, "text": "Old Comments" }, { "code": null, "e": 27387, "s": 27369, "text": "Python Dictionary" }, { "code": null, "e": 27409, "s": 27387, "text": "Enumerate() in Python" }, { "code": null, "e": 27444, "s": 27409, "text": "Read a file line by line in Python" }, { "code": null, "e": 27476, "s": 27444, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27506, "s": 27476, "text": "Iterate over a list in Python" }, { "code": null, "e": 27548, "s": 27506, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27574, "s": 27548, "text": "Python String | replace()" }, { "code": null, "e": 27617, "s": 27574, "text": "Python program to convert a list to string" }, { "code": null, "e": 27661, "s": 27617, "text": "Reading and Writing to text files in Python" } ]
Java program to print all duplicate characters in a string - GeeksforGeeks
13 Jul, 2020 Given a string, the task is to write Java program to print all the duplicate characters with their frequency Example: Input: str = β€œgeeksforgeeks”Output:s : 2e : 4g : 2k : 2 Input: str = β€œjava”Output:a : 2 Approach: The idea is to do hashing using HashMap. Create a hashMap of type {char, int}. Traverse the string, check if the hashMap already contains the traversed character or not. If it is present, then increment the count or else insert the character in the hashmap with frequency = 1. Now traverse through the hashmap and look for the characters with frequency more than 1. Print these characters with their respective frequencies. Below is the implementation of the above approach: Java // Java program for the above approachimport java.util.*;class GFG { // Function to print all duplicate // characters in string using HashMap public static void countDuplicateCharacters(String str) { // Creating a HashMap containing char // as a key and occurrences as a value Map<Character, Integer> map = new HashMap<Character, Integer>(); // Converting given string into // a char array char[] charArray = str.toCharArray(); // Checking each character // of charArray for (char c : charArray) { if (map.containsKey(c)) { // If character is present // in map incrementing it's // count by 1 map.put(c, map.get(c) + 1); } else { // If character is not present // in map putting this // character into map with // 1 as it's value. map.put(c, 1); } } // Traverse the HashMap, check // if the count of the character // is greater than 1 then print // the character and its frequency for (Map.Entry<Character, Integer> entry : map.entrySet()) { if (entry.getValue() > 1) { System.out.println(entry.getKey() + " : " + entry.getValue()); } } } // Driver Code public static void main(String args[]) { // Given String str String str = "geeksforgeeks"; // Function Call countDuplicateCharacters(str); }} s : 2 e : 4 g : 2 k : 2 Time Complexity: O(N)Auxiliary Space: O(1) Hash Java-HashMap Hash Java Programs Strings Hash Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Quadratic Probing in Hashing Hashing in Java Rearrange an array such that arr[i] = i Load Factor and Rehashing Advantages of BST over Hash Table Initializing a List in Java Convert a String to Character array in Java Java Programming Examples Implementing a Linked List in Java using Class Convert Double to Integer in Java
[ { "code": null, "e": 25078, "s": 25050, "text": "\n13 Jul, 2020" }, { "code": null, "e": 25187, "s": 25078, "text": "Given a string, the task is to write Java program to print all the duplicate characters with their frequency" }, { "code": null, "e": 25197, "s": 25187, "text": "Example: " }, { "code": null, "e": 25253, "s": 25197, "text": "Input: str = β€œgeeksforgeeks”Output:s : 2e : 4g : 2k : 2" }, { "code": null, "e": 25285, "s": 25253, "text": "Input: str = β€œjava”Output:a : 2" }, { "code": null, "e": 25336, "s": 25285, "text": "Approach: The idea is to do hashing using HashMap." }, { "code": null, "e": 25374, "s": 25336, "text": "Create a hashMap of type {char, int}." }, { "code": null, "e": 25465, "s": 25374, "text": "Traverse the string, check if the hashMap already contains the traversed character or not." }, { "code": null, "e": 25572, "s": 25465, "text": "If it is present, then increment the count or else insert the character in the hashmap with frequency = 1." }, { "code": null, "e": 25719, "s": 25572, "text": "Now traverse through the hashmap and look for the characters with frequency more than 1. Print these characters with their respective frequencies." }, { "code": null, "e": 25770, "s": 25719, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25775, "s": 25770, "text": "Java" }, { "code": "// Java program for the above approachimport java.util.*;class GFG { // Function to print all duplicate // characters in string using HashMap public static void countDuplicateCharacters(String str) { // Creating a HashMap containing char // as a key and occurrences as a value Map<Character, Integer> map = new HashMap<Character, Integer>(); // Converting given string into // a char array char[] charArray = str.toCharArray(); // Checking each character // of charArray for (char c : charArray) { if (map.containsKey(c)) { // If character is present // in map incrementing it's // count by 1 map.put(c, map.get(c) + 1); } else { // If character is not present // in map putting this // character into map with // 1 as it's value. map.put(c, 1); } } // Traverse the HashMap, check // if the count of the character // is greater than 1 then print // the character and its frequency for (Map.Entry<Character, Integer> entry : map.entrySet()) { if (entry.getValue() > 1) { System.out.println(entry.getKey() + \" : \" + entry.getValue()); } } } // Driver Code public static void main(String args[]) { // Given String str String str = \"geeksforgeeks\"; // Function Call countDuplicateCharacters(str); }}", "e": 27473, "s": 25775, "text": null }, { "code": null, "e": 27498, "s": 27473, "text": "s : 2\ne : 4\ng : 2\nk : 2\n" }, { "code": null, "e": 27541, "s": 27498, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 27546, "s": 27541, "text": "Hash" }, { "code": null, "e": 27559, "s": 27546, "text": "Java-HashMap" }, { "code": null, "e": 27564, "s": 27559, "text": "Hash" }, { "code": null, "e": 27578, "s": 27564, "text": "Java Programs" }, { "code": null, "e": 27586, "s": 27578, "text": "Strings" }, { "code": null, "e": 27591, "s": 27586, "text": "Hash" }, { "code": null, "e": 27599, "s": 27591, "text": "Strings" }, { "code": null, "e": 27697, "s": 27599, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27706, "s": 27697, "text": "Comments" }, { "code": null, "e": 27719, "s": 27706, "text": "Old Comments" }, { "code": null, "e": 27748, "s": 27719, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 27764, "s": 27748, "text": "Hashing in Java" }, { "code": null, "e": 27804, "s": 27764, "text": "Rearrange an array such that arr[i] = i" }, { "code": null, "e": 27830, "s": 27804, "text": "Load Factor and Rehashing" }, { "code": null, "e": 27864, "s": 27830, "text": "Advantages of BST over Hash Table" }, { "code": null, "e": 27892, "s": 27864, "text": "Initializing a List in Java" }, { "code": null, "e": 27936, "s": 27892, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 27962, "s": 27936, "text": "Java Programming Examples" }, { "code": null, "e": 28009, "s": 27962, "text": "Implementing a Linked List in Java using Class" } ]
Find elements within range in numpy in Python
Sometime while processing data using the numpy library, we may need to filter out certain numbers in a specific range. This can be achieved by using some in-built methods available in numpy. In this approach we take an numpy array then apply the logical_and function to it. The where clause in numpy is also used to apply the and condition. The result is an array showing the position of the elements satisfying the required range conditions. import numpy as np A = np.array([5, 9, 11, 4, 31, 27,8]) # printing initial array print("Given Array : ", A) # Range 6 to 15 res = np.where(np.logical_and(A >= 6, A <= 15)) # Result print("Array with condition : ", res) Running the above code gives us the following result βˆ’ Given Array : [ 5 9 11 4 31 27 8] Array with condition : (array([1, 2, 6], dtype=int32),) In this approach we use the * operator. It gives the result as actual values instead of the position of the values in the array. import numpy as np A = np.array([5, 9, 11, 4, 31, 27,8]) # printing initial array print("Given Array : ", A) # Range 6 to 15 res = A [ (A >=6) * (A <= 15)] # Result print("Array with condition : ", res) Running the above code gives us the following result βˆ’ Given Array : [ 5 9 11 4 31 27 8] Array with condition : [ 9 11 8]
[ { "code": null, "e": 1253, "s": 1062, "text": "Sometime while processing data using the numpy library, we may need to filter out certain numbers in a specific range. This can be achieved by using some in-built methods available in numpy." }, { "code": null, "e": 1505, "s": 1253, "text": "In this approach we take an numpy array then apply the logical_and function to it. The where clause in numpy is also used to apply the and condition. The result is an array showing the position of the elements satisfying the required range conditions." }, { "code": null, "e": 1729, "s": 1505, "text": "import numpy as np\n\nA = np.array([5, 9, 11, 4, 31, 27,8])\n\n# printing initial array\nprint(\"Given Array : \", A)\n\n# Range 6 to 15\nres = np.where(np.logical_and(A >= 6, A <= 15))\n\n# Result\nprint(\"Array with condition : \", res)" }, { "code": null, "e": 1784, "s": 1729, "text": "Running the above code gives us the following result βˆ’" }, { "code": null, "e": 1874, "s": 1784, "text": "Given Array : [ 5 9 11 4 31 27 8]\nArray with condition : (array([1, 2, 6], dtype=int32),)" }, { "code": null, "e": 2003, "s": 1874, "text": "In this approach we use the * operator. It gives the result as actual values instead of the position of the values in the array." }, { "code": null, "e": 2210, "s": 2003, "text": "import numpy as np\n\nA = np.array([5, 9, 11, 4, 31, 27,8])\n\n# printing initial array\nprint(\"Given Array : \", A)\n\n# Range 6 to 15\nres = A [ (A >=6) * (A <= 15)]\n\n# Result\nprint(\"Array with condition : \", res)" }, { "code": null, "e": 2265, "s": 2210, "text": "Running the above code gives us the following result βˆ’" }, { "code": null, "e": 2332, "s": 2265, "text": "Given Array : [ 5 9 11 4 31 27 8]\nArray with condition : [ 9 11 8]" } ]
MFC - Radio Buttons
A radio button is a control that appears as a dot surrounded by a round box. In reality, a radio button is accompanied by one or more other radio buttons that appear and behave as a group. Create Creates the Windows button control and attaches it to the CButton object. DrawItem Override to draw an owner-drawn CButton object. GetBitmap Retrieves the handle of the bitmap previously set with SetBitmap. GetButtonStyle Retrieves information about the button control style GetCursor Retrieves the handle of the cursor image previously set with SetCursor. GetIcon Retrieves the handle of the icon previously set with SetIcon. GetIdealSize Retrieves the ideal size of the button contro. GetImageList Retrieves the image list of the button control. GetNote Retrieves the note component of the current command link control. GetNoteLength Retrieves the length of the note text for the current command link control. GetSplitGlyph Retrieves the glyph associated with the current split button control. GetSplitImageList Retrieves the image list for the current split button control. GetSplitInfo Retrieves information that defines the current split button control. GetSplitSize Retrieves the bounding rectangle of the drop-down component of the current split button control. GetSplitStyle Retrieves the split button styles that define the current split button control. GetState Retrieves the check state, highlight state, and focus state of a button control. GetTextMargin Retrieves the text margin of the button control. SetBitmap Specifies a bitmap to be displayed on the button. SetButtonStyle Changes the style of a button. SetCheck Sets the check state of a button control. SetCursor Specifies a cursor image to be displayed on the button. SetDropDownState Sets the drop-down state of the current split button control. SetIcon Specifies an icon to be displayed on the button. SetImageList Sets the image list of the button control. SetNote Sets the note on the current command link control. SetSplitGlyph Associates a specified glyph with the current split button control. SetSplitImageList Associates an image list with the current split button control. SetSplitInfo Specifies information that defines the current split button control. SetSplitSize Sets the bounding rectangle of the drop-down component of the current split button control. SetSplitStyle Sets the bounding rectangle of the drop-down component of the current split button control. SetState Sets the highlighting state of a button control. SetTextMargin Sets the text margin of the button control. Here is the list of messages mapping for Radio Button control βˆ’ Let us look into an example of Radio button by creating a new MFC dialog based application. Step 1 βˆ’ Drag a group box and three radio buttons and remove the Caption of Static Text control. Step 2 βˆ’ Add event handler for all the three radio buttons. Step 3 βˆ’ Add the Value variable for the Static Text control. Step 4 βˆ’ Here is the implementation of three event handlers. void CMFCRadioButtonDlg::OnBnClickedRadio1() { // TODO: Add your control notification handler code here m_strTextControl = _T("Radio Button 1 Clicked"); UpdateData(FALSE); } void CMFCRadioButtonDlg::OnBnClickedRadio2() { // TODO: Add your control notification handler code here m_strTextControl = _T("Radio Button 2 Clicked"); UpdateData(FALSE); } void CMFCRadioButtonDlg::OnBnClickedRadio3() { // TODO: Add your control notification handler code here m_strTextControl = _T("Radio Button 3 Clicked"); UpdateData(FALSE); } Step 5 βˆ’ When the above code is compiled and executed, you will see the following output. When you select any radio button, the message is displayed on Static Text control. Print Add Notes Bookmark this page
[ { "code": null, "e": 2256, "s": 2067, "text": "A radio button is a control that appears as a dot surrounded by a round box. In reality, a radio button is accompanied by one or more other radio buttons that appear and behave as a group." }, { "code": null, "e": 2263, "s": 2256, "text": "Create" }, { "code": null, "e": 2337, "s": 2263, "text": "Creates the Windows button control and attaches it to the CButton object." }, { "code": null, "e": 2346, "s": 2337, "text": "DrawItem" }, { "code": null, "e": 2394, "s": 2346, "text": "Override to draw an owner-drawn CButton object." }, { "code": null, "e": 2404, "s": 2394, "text": "GetBitmap" }, { "code": null, "e": 2470, "s": 2404, "text": "Retrieves the handle of the bitmap previously set with SetBitmap." }, { "code": null, "e": 2485, "s": 2470, "text": "GetButtonStyle" }, { "code": null, "e": 2538, "s": 2485, "text": "Retrieves information about the button control style" }, { "code": null, "e": 2548, "s": 2538, "text": "GetCursor" }, { "code": null, "e": 2621, "s": 2548, "text": "Retrieves the handle of the cursor image previously set with SetCursor. " }, { "code": null, "e": 2629, "s": 2621, "text": "GetIcon" }, { "code": null, "e": 2691, "s": 2629, "text": "Retrieves the handle of the icon previously set with SetIcon." }, { "code": null, "e": 2704, "s": 2691, "text": "GetIdealSize" }, { "code": null, "e": 2751, "s": 2704, "text": "Retrieves the ideal size of the button contro." }, { "code": null, "e": 2764, "s": 2751, "text": "GetImageList" }, { "code": null, "e": 2812, "s": 2764, "text": "Retrieves the image list of the button control." }, { "code": null, "e": 2820, "s": 2812, "text": "GetNote" }, { "code": null, "e": 2886, "s": 2820, "text": "Retrieves the note component of the current command link control." }, { "code": null, "e": 2900, "s": 2886, "text": "GetNoteLength" }, { "code": null, "e": 2976, "s": 2900, "text": "Retrieves the length of the note text for the current command link control." }, { "code": null, "e": 2990, "s": 2976, "text": "GetSplitGlyph" }, { "code": null, "e": 3060, "s": 2990, "text": "Retrieves the glyph associated with the current split button control." }, { "code": null, "e": 3078, "s": 3060, "text": "GetSplitImageList" }, { "code": null, "e": 3141, "s": 3078, "text": "Retrieves the image list for the current split button control." }, { "code": null, "e": 3154, "s": 3141, "text": "GetSplitInfo" }, { "code": null, "e": 3223, "s": 3154, "text": "Retrieves information that defines the current split button control." }, { "code": null, "e": 3236, "s": 3223, "text": "GetSplitSize" }, { "code": null, "e": 3333, "s": 3236, "text": "Retrieves the bounding rectangle of the drop-down component of the current split button control." }, { "code": null, "e": 3347, "s": 3333, "text": "GetSplitStyle" }, { "code": null, "e": 3427, "s": 3347, "text": "Retrieves the split button styles that define the current split button control." }, { "code": null, "e": 3436, "s": 3427, "text": "GetState" }, { "code": null, "e": 3517, "s": 3436, "text": "Retrieves the check state, highlight state, and focus state of a button control." }, { "code": null, "e": 3531, "s": 3517, "text": "GetTextMargin" }, { "code": null, "e": 3580, "s": 3531, "text": "Retrieves the text margin of the button control." }, { "code": null, "e": 3590, "s": 3580, "text": "SetBitmap" }, { "code": null, "e": 3640, "s": 3590, "text": "Specifies a bitmap to be displayed on the button." }, { "code": null, "e": 3655, "s": 3640, "text": "SetButtonStyle" }, { "code": null, "e": 3686, "s": 3655, "text": "Changes the style of a button." }, { "code": null, "e": 3695, "s": 3686, "text": "SetCheck" }, { "code": null, "e": 3737, "s": 3695, "text": "Sets the check state of a button control." }, { "code": null, "e": 3747, "s": 3737, "text": "SetCursor" }, { "code": null, "e": 3803, "s": 3747, "text": "Specifies a cursor image to be displayed on the button." }, { "code": null, "e": 3820, "s": 3803, "text": "SetDropDownState" }, { "code": null, "e": 3882, "s": 3820, "text": "Sets the drop-down state of the current split button control." }, { "code": null, "e": 3890, "s": 3882, "text": "SetIcon" }, { "code": null, "e": 3939, "s": 3890, "text": "Specifies an icon to be displayed on the button." }, { "code": null, "e": 3952, "s": 3939, "text": "SetImageList" }, { "code": null, "e": 3995, "s": 3952, "text": "Sets the image list of the button control." }, { "code": null, "e": 4003, "s": 3995, "text": "SetNote" }, { "code": null, "e": 4054, "s": 4003, "text": "Sets the note on the current command link control." }, { "code": null, "e": 4068, "s": 4054, "text": "SetSplitGlyph" }, { "code": null, "e": 4136, "s": 4068, "text": "Associates a specified glyph with the current split button control." }, { "code": null, "e": 4154, "s": 4136, "text": "SetSplitImageList" }, { "code": null, "e": 4218, "s": 4154, "text": "Associates an image list with the current split button control." }, { "code": null, "e": 4231, "s": 4218, "text": "SetSplitInfo" }, { "code": null, "e": 4300, "s": 4231, "text": "Specifies information that defines the current split button control." }, { "code": null, "e": 4313, "s": 4300, "text": "SetSplitSize" }, { "code": null, "e": 4405, "s": 4313, "text": "Sets the bounding rectangle of the drop-down component of the current split button control." }, { "code": null, "e": 4419, "s": 4405, "text": "SetSplitStyle" }, { "code": null, "e": 4511, "s": 4419, "text": "Sets the bounding rectangle of the drop-down component of the current split button control." }, { "code": null, "e": 4520, "s": 4511, "text": "SetState" }, { "code": null, "e": 4569, "s": 4520, "text": "Sets the highlighting state of a button control." }, { "code": null, "e": 4583, "s": 4569, "text": "SetTextMargin" }, { "code": null, "e": 4627, "s": 4583, "text": "Sets the text margin of the button control." }, { "code": null, "e": 4691, "s": 4627, "text": "Here is the list of messages mapping for Radio Button control βˆ’" }, { "code": null, "e": 4783, "s": 4691, "text": "Let us look into an example of Radio button by creating a new MFC dialog based application." }, { "code": null, "e": 4880, "s": 4783, "text": "Step 1 βˆ’ Drag a group box and three radio buttons and remove the Caption of Static Text control." }, { "code": null, "e": 4940, "s": 4880, "text": "Step 2 βˆ’ Add event handler for all the three radio buttons." }, { "code": null, "e": 5001, "s": 4940, "text": "Step 3 βˆ’ Add the Value variable for the Static Text control." }, { "code": null, "e": 5062, "s": 5001, "text": "Step 4 βˆ’ Here is the implementation of three event handlers." }, { "code": null, "e": 5613, "s": 5062, "text": "void CMFCRadioButtonDlg::OnBnClickedRadio1() {\n // TODO: Add your control notification handler code here\n m_strTextControl = _T(\"Radio Button 1 Clicked\");\n UpdateData(FALSE);\n}\n\nvoid CMFCRadioButtonDlg::OnBnClickedRadio2() {\n // TODO: Add your control notification handler code here\n m_strTextControl = _T(\"Radio Button 2 Clicked\");\n UpdateData(FALSE);\n}\n\nvoid CMFCRadioButtonDlg::OnBnClickedRadio3() {\n // TODO: Add your control notification handler code here\n m_strTextControl = _T(\"Radio Button 3 Clicked\");\n UpdateData(FALSE);\n}" }, { "code": null, "e": 5786, "s": 5613, "text": "Step 5 βˆ’ When the above code is compiled and executed, you will see the following output. When you select any radio button, the message is displayed on Static Text control." }, { "code": null, "e": 5793, "s": 5786, "text": " Print" }, { "code": null, "e": 5804, "s": 5793, "text": " Add Notes" } ]
How to make a broken horizontal bar plot in Matplotlib?
We can take the following steps to make a broken bar plot, Set the figure size and adjust the padding between and around the subplots. Create a figure and a set of subplots. Plot a horizontal sequence of rectangles. Set x and y axes scale, X-axis label, Y ticks and Y tick labels. Configure the grid lines. Use annotate() method to show text that can refer to a specific position. To display the figure, use show() method. import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True fig, ax = plt.subplots() ax.broken_barh([(110, 30), (150, 10)], (10, 9), facecolors='tab:blue') ax.broken_barh([(10, 50), (100, 20), (130, 10)], (20, 9), facecolors=('tab:orange', 'tab:green', 'tab:red')) ax.set_ylim(5, 35) ax.set_xlim(0, 200) ax.set_xlabel('seconds since start') ax.set_yticks([15, 25]) ax.set_yticklabels(['Bill', 'Jim']) ax.grid(True) ax.annotate('race interrupted', (61, 25), xytext=(0.8, 0.9), textcoords='axes fraction', arrowprops=dict(facecolor='black', shrink=0.05), fontsize=16, horizontalalignment='right', verticalalignment='top') plt.show()
[ { "code": null, "e": 1121, "s": 1062, "text": "We can take the following steps to make a broken bar plot," }, { "code": null, "e": 1197, "s": 1121, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1236, "s": 1197, "text": "Create a figure and a set of subplots." }, { "code": null, "e": 1278, "s": 1236, "text": "Plot a horizontal sequence of rectangles." }, { "code": null, "e": 1343, "s": 1278, "text": "Set x and y axes scale, X-axis label, Y ticks and Y tick labels." }, { "code": null, "e": 1369, "s": 1343, "text": "Configure the grid lines." }, { "code": null, "e": 1443, "s": 1369, "text": "Use annotate() method to show text that can refer to a specific position." }, { "code": null, "e": 1485, "s": 1443, "text": "To display the figure, use show() method." }, { "code": null, "e": 2243, "s": 1485, "text": "import matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nfig, ax = plt.subplots()\n\nax.broken_barh([(110, 30), (150, 10)], (10, 9), facecolors='tab:blue')\nax.broken_barh([(10, 50), (100, 20), (130, 10)], (20, 9),\n facecolors=('tab:orange', 'tab:green', 'tab:red'))\nax.set_ylim(5, 35)\nax.set_xlim(0, 200)\nax.set_xlabel('seconds since start')\nax.set_yticks([15, 25])\nax.set_yticklabels(['Bill', 'Jim'])\nax.grid(True)\n\nax.annotate('race interrupted', (61, 25),\n xytext=(0.8, 0.9), textcoords='axes fraction',\n arrowprops=dict(facecolor='black', shrink=0.05),\n fontsize=16,\n horizontalalignment='right', verticalalignment='top')\n\nplt.show()" } ]
Tryit Editor v3.7
Tryit: no end tag
[]
JavaFX - Layout GridPane
If we use Grid Pane in our application, all the nodes that are added to it are arranged in a way that they form a grid of rows and columns. This layout comes handy while creating forms using JavaFX. The class named GridPane of the package javafx.scene.layout represents the GridPane. This class provides eleven properties, which are βˆ’ alignment βˆ’ This property represents the alignment of the pane and you can set value of this property using the setAlignment() method. alignment βˆ’ This property represents the alignment of the pane and you can set value of this property using the setAlignment() method. hgap βˆ’ This property is of the type double and it represents the horizontal gap between columns. hgap βˆ’ This property is of the type double and it represents the horizontal gap between columns. vgap βˆ’ This property is of the type double and it represents the vertical gap between rows. vgap βˆ’ This property is of the type double and it represents the vertical gap between rows. gridLinesVisible βˆ’ This property is of Boolean type. On true, the lines of the pane are set to be visible. gridLinesVisible βˆ’ This property is of Boolean type. On true, the lines of the pane are set to be visible. Following are the cell positions in the grid pane of JavaFX βˆ’ The following program is an example of the grid pane layout. In this, we are creating a form using a Grid Pane. Save this code in a file with the name GridPaneExample.java. import javafx.application.Application; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.GridPane; import javafx.scene.text.Text; import javafx.scene.control.TextField; import javafx.stage.Stage; public class GridPaneExample extends Application { @Override public void start(Stage stage) { //creating label email Text text1 = new Text("Email"); //creating label password Text text2 = new Text("Password"); //Creating Text Filed for email TextField textField1 = new TextField(); //Creating Text Filed for password TextField textField2 = new TextField(); //Creating Buttons Button button1 = new Button("Submit"); Button button2 = new Button("Clear"); //Creating a Grid Pane GridPane gridPane = new GridPane(); //Setting size for the pane gridPane.setMinSize(400, 200); //Setting the padding gridPane.setPadding(new Insets(10, 10, 10, 10)); //Setting the vertical and horizontal gaps between the columns gridPane.setVgap(5); gridPane.setHgap(5); //Setting the Grid alignment gridPane.setAlignment(Pos.CENTER); //Arranging all the nodes in the grid gridPane.add(text1, 0, 0); gridPane.add(textField1, 1, 0); gridPane.add(text2, 0, 1); gridPane.add(textField2, 1, 1); gridPane.add(button1, 0, 2); gridPane.add(button2, 1, 2); //Creating a scene object Scene scene = new Scene(gridPane); //Setting title to the Stage stage.setTitle("Grid Pane Example"); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. javac GridPaneExample.java java GridPaneExample On executing, the above program generates a JavaFX window as shown below. 33 Lectures 7.5 hours Syed Raza 64 Lectures 12.5 hours Emenwa Global, Ejike IfeanyiChukwu 20 Lectures 4 hours Emenwa Global, Ejike IfeanyiChukwu Print Add Notes Bookmark this page
[ { "code": null, "e": 2099, "s": 1900, "text": "If we use Grid Pane in our application, all the nodes that are added to it are arranged in a way that they form a grid of rows and columns. This layout comes handy while creating forms using JavaFX." }, { "code": null, "e": 2235, "s": 2099, "text": "The class named GridPane of the package javafx.scene.layout represents the GridPane. This class provides eleven properties, which are βˆ’" }, { "code": null, "e": 2370, "s": 2235, "text": "alignment βˆ’ This property represents the alignment of the pane and you can set value of this property using the setAlignment() method." }, { "code": null, "e": 2505, "s": 2370, "text": "alignment βˆ’ This property represents the alignment of the pane and you can set value of this property using the setAlignment() method." }, { "code": null, "e": 2602, "s": 2505, "text": "hgap βˆ’ This property is of the type double and it represents the horizontal gap between columns." }, { "code": null, "e": 2699, "s": 2602, "text": "hgap βˆ’ This property is of the type double and it represents the horizontal gap between columns." }, { "code": null, "e": 2791, "s": 2699, "text": "vgap βˆ’ This property is of the type double and it represents the vertical gap between rows." }, { "code": null, "e": 2883, "s": 2791, "text": "vgap βˆ’ This property is of the type double and it represents the vertical gap between rows." }, { "code": null, "e": 2990, "s": 2883, "text": "gridLinesVisible βˆ’ This property is of Boolean type. On true, the lines of the pane are set to be visible." }, { "code": null, "e": 3097, "s": 2990, "text": "gridLinesVisible βˆ’ This property is of Boolean type. On true, the lines of the pane are set to be visible." }, { "code": null, "e": 3159, "s": 3097, "text": "Following are the cell positions in the grid pane of JavaFX βˆ’" }, { "code": null, "e": 3271, "s": 3159, "text": "The following program is an example of the grid pane layout. In this, we are creating a form using a Grid Pane." }, { "code": null, "e": 3332, "s": 3271, "text": "Save this code in a file with the name GridPaneExample.java." }, { "code": null, "e": 5397, "s": 3332, "text": "import javafx.application.Application; \nimport javafx.geometry.Insets; \nimport javafx.geometry.Pos; \nimport javafx.scene.Scene; \nimport javafx.scene.control.Button; \nimport javafx.scene.layout.GridPane; \nimport javafx.scene.text.Text; \nimport javafx.scene.control.TextField; \nimport javafx.stage.Stage; \n\npublic class GridPaneExample extends Application { \n @Override \n public void start(Stage stage) { \n //creating label email \n Text text1 = new Text(\"Email\"); \n \n //creating label password \n Text text2 = new Text(\"Password\"); \n\t \n //Creating Text Filed for email \n TextField textField1 = new TextField(); \n \n //Creating Text Filed for password \n TextField textField2 = new TextField(); \n \n //Creating Buttons \n Button button1 = new Button(\"Submit\"); \n Button button2 = new Button(\"Clear\"); \n \n //Creating a Grid Pane \n GridPane gridPane = new GridPane(); \n \n //Setting size for the pane \n gridPane.setMinSize(400, 200); \n \n //Setting the padding \n gridPane.setPadding(new Insets(10, 10, 10, 10)); \n \n //Setting the vertical and horizontal gaps between the columns \n gridPane.setVgap(5); \n gridPane.setHgap(5); \n \n //Setting the Grid alignment \n gridPane.setAlignment(Pos.CENTER); \n \n //Arranging all the nodes in the grid \n gridPane.add(text1, 0, 0); \n gridPane.add(textField1, 1, 0); \n gridPane.add(text2, 0, 1); \n gridPane.add(textField2, 1, 1); \n gridPane.add(button1, 0, 2); \n gridPane.add(button2, 1, 2); \n \n //Creating a scene object \n Scene scene = new Scene(gridPane); \n \n //Setting title to the Stage \n stage.setTitle(\"Grid Pane Example\"); \n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n} " }, { "code": null, "e": 5491, "s": 5397, "text": "Compile and execute the saved java file from the command prompt using the following commands." }, { "code": null, "e": 5541, "s": 5491, "text": "javac GridPaneExample.java \njava GridPaneExample\n" }, { "code": null, "e": 5615, "s": 5541, "text": "On executing, the above program generates a JavaFX window as shown below." }, { "code": null, "e": 5650, "s": 5615, "text": "\n 33 Lectures \n 7.5 hours \n" }, { "code": null, "e": 5661, "s": 5650, "text": " Syed Raza" }, { "code": null, "e": 5697, "s": 5661, "text": "\n 64 Lectures \n 12.5 hours \n" }, { "code": null, "e": 5733, "s": 5697, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 5766, "s": 5733, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 5802, "s": 5766, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 5809, "s": 5802, "text": " Print" }, { "code": null, "e": 5820, "s": 5809, "text": " Add Notes" } ]
What exactly is Metaflow?. A high-level look Netflix’s Python... | by Rupert Thomas | Towards Data Science
Metaflow is a Python framework for data science developed by Netflix; it was released as an open source project in December 2019. It addresses some of the challenges data scientists face around scalability and version control. A processing pipeline is constructed as a sequence of steps in a graph. Metaflow makes it easy to move from running the pipeline on a local machine to running on cloud resources (currently AWS only). Each step can be run on a separate node, with unique dependencies, and Metaflow will handle the inter-communication. Below, I break down what I think are the key features. I’m always on the look out for ways to make life easier, particularly when working on data-driven projects. Metaflow claims to β€˜it quick and easy to build and manage real-life data science projects’, so I was all ears. My first question was: β€œWhat does it actually do?”, and I had to do a bit of digging to find out. After reading the documentation and working through the tutorials, I summarise my findings here. Metaflow makes it easy to move from running on a local machine to running on cloud resources. The main benefit (as I see it) is that Metaflow provides a layer of abstraction over the top of computing resources. This means you can focus on code, and Metaflow will take care of how to run it on one or more machines. In documentation-speak, it provides β€œa unified API to the infrastructure stack”. Metaflow provides this abstraction using a Directed Acyclic Graph (DAG) β€” the flow β€” that contains the operations to be run. Each operation in the pipeline is a step and is defined as a method inside a Python class with a decorator: Where steps are defined in parallel (such as the two model fitting steps in the figure above), Metaflow may run them in parallel if resources are available. When running on a single machine this is one route to parallel processing, similar to the multiprocessing package in Python. The main advantage comes, however, when you want to run on cloud resources. Once you have configured your cluster, a single additional command line argument will tell Metaflow to run the code in the cloud: --with batch. Currently only Amazon Web Services is supported though, but I imagine that will change in the future. A checkpoint is taken at the end of each step, and it is possible to resume execution at each one at a later stage to aid debugging. You can’t step through your code line-by-line though. Version control of machine learning models is a bit of a challenge, so Metaflow addresses this too. Both code and data are hashed. Each execution of the graph is logged and results are stored, along with the key hyperparameters: These can be easily manipulated as command line arguments: python metaflow_parameter.py run --alpha 0.001 Metadata is stored in the file system in JSON format, and you can access variable data stored at each step. Its also easy to read back the last run: run = Flow(flow_name).latest_successful_run Metaflow also provides a mechanism for managing dependencies, and they can be specified at the flow level or the step level using decorators. These can specify specific a Python version or specific packages: The conda environment flag is specified when running from the command line: python metaflow_conda.py --environment=conda run If you want to try out metaflow, its simple to install from the command line and there are a set of good tutorials in the documentation: pip install metaflow Metaflow aims for β€œseamless scalability”, and it looks like it does that pretty well. There is a bit of manual setup to get it working with AWS, but its reasonably well documented. If you are likely to need to scale your analytics project to the cloud and are concerned about deployment, you should probably have a look at Metaflow. I haven’t figured out yet how I would get maximum value from the versioning and fine-grained dependency management, but they look like powerful features. Have you tried Metaflow? Feel free to leave any experiences and feedback in the comments section below. Rupert Thomas is a technology consultant specialising in machine learning, machine vision, and data-driven products. Rupert Thomas https://docs.metaflow.org/getting-started/tutorials Open-Sourcing Metaflow, a Human-Centric Framework for Data Science Learn Metaflow in 10 mins
[ { "code": null, "e": 770, "s": 171, "text": "Metaflow is a Python framework for data science developed by Netflix; it was released as an open source project in December 2019. It addresses some of the challenges data scientists face around scalability and version control. A processing pipeline is constructed as a sequence of steps in a graph. Metaflow makes it easy to move from running the pipeline on a local machine to running on cloud resources (currently AWS only). Each step can be run on a separate node, with unique dependencies, and Metaflow will handle the inter-communication. Below, I break down what I think are the key features." }, { "code": null, "e": 1184, "s": 770, "text": "I’m always on the look out for ways to make life easier, particularly when working on data-driven projects. Metaflow claims to β€˜it quick and easy to build and manage real-life data science projects’, so I was all ears. My first question was: β€œWhat does it actually do?”, and I had to do a bit of digging to find out. After reading the documentation and working through the tutorials, I summarise my findings here." }, { "code": null, "e": 1278, "s": 1184, "text": "Metaflow makes it easy to move from running on a local machine to running on cloud resources." }, { "code": null, "e": 1580, "s": 1278, "text": "The main benefit (as I see it) is that Metaflow provides a layer of abstraction over the top of computing resources. This means you can focus on code, and Metaflow will take care of how to run it on one or more machines. In documentation-speak, it provides β€œa unified API to the infrastructure stack”." }, { "code": null, "e": 1813, "s": 1580, "text": "Metaflow provides this abstraction using a Directed Acyclic Graph (DAG) β€” the flow β€” that contains the operations to be run. Each operation in the pipeline is a step and is defined as a method inside a Python class with a decorator:" }, { "code": null, "e": 2417, "s": 1813, "text": "Where steps are defined in parallel (such as the two model fitting steps in the figure above), Metaflow may run them in parallel if resources are available. When running on a single machine this is one route to parallel processing, similar to the multiprocessing package in Python. The main advantage comes, however, when you want to run on cloud resources. Once you have configured your cluster, a single additional command line argument will tell Metaflow to run the code in the cloud: --with batch. Currently only Amazon Web Services is supported though, but I imagine that will change in the future." }, { "code": null, "e": 2604, "s": 2417, "text": "A checkpoint is taken at the end of each step, and it is possible to resume execution at each one at a later stage to aid debugging. You can’t step through your code line-by-line though." }, { "code": null, "e": 2833, "s": 2604, "text": "Version control of machine learning models is a bit of a challenge, so Metaflow addresses this too. Both code and data are hashed. Each execution of the graph is logged and results are stored, along with the key hyperparameters:" }, { "code": null, "e": 2892, "s": 2833, "text": "These can be easily manipulated as command line arguments:" }, { "code": null, "e": 2939, "s": 2892, "text": "python metaflow_parameter.py run --alpha 0.001" }, { "code": null, "e": 3088, "s": 2939, "text": "Metadata is stored in the file system in JSON format, and you can access variable data stored at each step. Its also easy to read back the last run:" }, { "code": null, "e": 3132, "s": 3088, "text": "run = Flow(flow_name).latest_successful_run" }, { "code": null, "e": 3340, "s": 3132, "text": "Metaflow also provides a mechanism for managing dependencies, and they can be specified at the flow level or the step level using decorators. These can specify specific a Python version or specific packages:" }, { "code": null, "e": 3416, "s": 3340, "text": "The conda environment flag is specified when running from the command line:" }, { "code": null, "e": 3465, "s": 3416, "text": "python metaflow_conda.py --environment=conda run" }, { "code": null, "e": 3602, "s": 3465, "text": "If you want to try out metaflow, its simple to install from the command line and there are a set of good tutorials in the documentation:" }, { "code": null, "e": 3623, "s": 3602, "text": "pip install metaflow" }, { "code": null, "e": 4110, "s": 3623, "text": "Metaflow aims for β€œseamless scalability”, and it looks like it does that pretty well. There is a bit of manual setup to get it working with AWS, but its reasonably well documented. If you are likely to need to scale your analytics project to the cloud and are concerned about deployment, you should probably have a look at Metaflow. I haven’t figured out yet how I would get maximum value from the versioning and fine-grained dependency management, but they look like powerful features." }, { "code": null, "e": 4214, "s": 4110, "text": "Have you tried Metaflow? Feel free to leave any experiences and feedback in the comments section below." }, { "code": null, "e": 4345, "s": 4214, "text": "Rupert Thomas is a technology consultant specialising in machine learning, machine vision, and data-driven products. Rupert Thomas" }, { "code": null, "e": 4397, "s": 4345, "text": "https://docs.metaflow.org/getting-started/tutorials" }, { "code": null, "e": 4464, "s": 4397, "text": "Open-Sourcing Metaflow, a Human-Centric Framework for Data Science" } ]
Different Ways to Take Input and Print a Float Value in C# - GeeksforGeeks
28 May, 2020 In C#, we know that Console.ReadLine() method is used to read string from the standard output device. Then this value is converted into the float type if it is not string type by default. There are different methods available to convert taken input to a float value. Following methods can be used for this purpose: Single.Parse() Method float.Parse() Method Convert.ToSingle() Method The Single.Parse() method is used to convert given string value to the float value. This method is consist of the following: Single is a class. Parse() is its method. Syntax: float_value = Single.Parse(Console.ReadLine()); Example: Take input of a float value using Single.Parse() Method C# // C# program to Take input // of a float value using // Single.Parse() Method using System;using System.Text; public class GFG{ // Main Method static void Main(string[] args) { //declaring a float variables float value = 0.0f; // use of Single.Parse() Method value = Single.Parse(Console.ReadLine()); //printing the value Console.WriteLine("Value = {0}", value); }} Console Input: 12.34 Output: Value = 12.34 The float.Parse() method is used to convert given string value to the float value. This method is consist of the following: float is an alias of Single class. Parse() is its method. Syntax: float_value = float.Parse(Console.ReadLine()); Example: Take input of a float value using float.Parse() Method C# // C# program to Take input // of a float value using // float.Parse() Method using System;using System.Text; public class GFG{ // Main Method static void Main(string[] args) { // declaring a float variables float value = 0.0f; // use of float.Parse() Method value = float.Parse(Console.ReadLine()); // printing the value Console.WriteLine("Value = {0}", value); }} Console Input: 12.34 Output: Value = 12.34 The Convert.ToSingle() Method is used to convert given object to the float value. This method is consist of the following: Convertis a class. ToSingle() is its method. Syntax: float_value = Convert.ToSingle(Console.ReadLine()); Example: Take input of a float value using Convert.ToSingle() Method C# // C# program to Take input // of a float value using // Convert.ToSingle() method using System;using System.Text; public class GFG{ // Main Method static void Main(string[] args) { // declaring a float variable float value = 0.0f; // use of Convert.ToSingle() Method value = Convert.ToSingle(Console.ReadLine()); // printing the value Console.WriteLine("Value = {0}", value); }} Console Input: 12.34 Output: Value = 12.34 C# C# Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# Dictionary with examples Difference between Ref and Out keywords in C# Introduction to .NET Framework C# | String.IndexOf( ) Method | Set - 1 Extension Method in C# Convert String to Character Array in C# Socket Programming in C# Program to Print a New Line in C# Getting a Month Name Using Month Number in C# Program to find absolute value of a given number
[ { "code": null, "e": 23986, "s": 23958, "text": "\n28 May, 2020" }, { "code": null, "e": 24302, "s": 23986, "text": "In C#, we know that Console.ReadLine() method is used to read string from the standard output device. Then this value is converted into the float type if it is not string type by default. There are different methods available to convert taken input to a float value. Following methods can be used for this purpose:" }, { "code": null, "e": 24324, "s": 24302, "text": "Single.Parse() Method" }, { "code": null, "e": 24345, "s": 24324, "text": "float.Parse() Method" }, { "code": null, "e": 24371, "s": 24345, "text": "Convert.ToSingle() Method" }, { "code": null, "e": 24497, "s": 24371, "text": "The Single.Parse() method is used to convert given string value to the float value. This method is consist of the following: " }, { "code": null, "e": 24517, "s": 24497, "text": " Single is a class." }, { "code": null, "e": 24541, "s": 24517, "text": " Parse() is its method." }, { "code": null, "e": 24549, "s": 24541, "text": "Syntax:" }, { "code": null, "e": 24598, "s": 24549, "text": "float_value = Single.Parse(Console.ReadLine());\n" }, { "code": null, "e": 24663, "s": 24598, "text": "Example: Take input of a float value using Single.Parse() Method" }, { "code": null, "e": 24666, "s": 24663, "text": "C#" }, { "code": "// C# program to Take input // of a float value using // Single.Parse() Method using System;using System.Text; public class GFG{ // Main Method static void Main(string[] args) { //declaring a float variables float value = 0.0f; // use of Single.Parse() Method value = Single.Parse(Console.ReadLine()); //printing the value Console.WriteLine(\"Value = {0}\", value); }}", "e": 25113, "s": 24666, "text": null }, { "code": null, "e": 25128, "s": 25113, "text": "Console Input:" }, { "code": null, "e": 25135, "s": 25128, "text": "12.34\n" }, { "code": null, "e": 25143, "s": 25135, "text": "Output:" }, { "code": null, "e": 25158, "s": 25143, "text": "Value = 12.34\n" }, { "code": null, "e": 25283, "s": 25158, "text": "The float.Parse() method is used to convert given string value to the float value. This method is consist of the following: " }, { "code": null, "e": 25319, "s": 25283, "text": " float is an alias of Single class." }, { "code": null, "e": 25343, "s": 25319, "text": " Parse() is its method." }, { "code": null, "e": 25351, "s": 25343, "text": "Syntax:" }, { "code": null, "e": 25399, "s": 25351, "text": "float_value = float.Parse(Console.ReadLine());\n" }, { "code": null, "e": 25463, "s": 25399, "text": "Example: Take input of a float value using float.Parse() Method" }, { "code": null, "e": 25466, "s": 25463, "text": "C#" }, { "code": "// C# program to Take input // of a float value using // float.Parse() Method using System;using System.Text; public class GFG{ // Main Method static void Main(string[] args) { // declaring a float variables float value = 0.0f; // use of float.Parse() Method value = float.Parse(Console.ReadLine()); // printing the value Console.WriteLine(\"Value = {0}\", value); }}", "e": 25912, "s": 25466, "text": null }, { "code": null, "e": 25927, "s": 25912, "text": "Console Input:" }, { "code": null, "e": 25934, "s": 25927, "text": "12.34\n" }, { "code": null, "e": 25942, "s": 25934, "text": "Output:" }, { "code": null, "e": 25957, "s": 25942, "text": "Value = 12.34\n" }, { "code": null, "e": 26081, "s": 25957, "text": "The Convert.ToSingle() Method is used to convert given object to the float value. This method is consist of the following: " }, { "code": null, "e": 26101, "s": 26081, "text": " Convertis a class." }, { "code": null, "e": 26128, "s": 26101, "text": " ToSingle() is its method." }, { "code": null, "e": 26136, "s": 26128, "text": "Syntax:" }, { "code": null, "e": 26189, "s": 26136, "text": "float_value = Convert.ToSingle(Console.ReadLine());\n" }, { "code": null, "e": 26258, "s": 26189, "text": "Example: Take input of a float value using Convert.ToSingle() Method" }, { "code": null, "e": 26261, "s": 26258, "text": "C#" }, { "code": "// C# program to Take input // of a float value using // Convert.ToSingle() method using System;using System.Text; public class GFG{ // Main Method static void Main(string[] args) { // declaring a float variable float value = 0.0f; // use of Convert.ToSingle() Method value = Convert.ToSingle(Console.ReadLine()); // printing the value Console.WriteLine(\"Value = {0}\", value); }}", "e": 26721, "s": 26261, "text": null }, { "code": null, "e": 26736, "s": 26721, "text": "Console Input:" }, { "code": null, "e": 26743, "s": 26736, "text": "12.34\n" }, { "code": null, "e": 26751, "s": 26743, "text": "Output:" }, { "code": null, "e": 26766, "s": 26751, "text": "Value = 12.34\n" }, { "code": null, "e": 26769, "s": 26766, "text": "C#" }, { "code": null, "e": 26781, "s": 26769, "text": "C# Programs" }, { "code": null, "e": 26879, "s": 26781, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26888, "s": 26879, "text": "Comments" }, { "code": null, "e": 26901, "s": 26888, "text": "Old Comments" }, { "code": null, "e": 26929, "s": 26901, "text": "C# Dictionary with examples" }, { "code": null, "e": 26975, "s": 26929, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 27006, "s": 26975, "text": "Introduction to .NET Framework" }, { "code": null, "e": 27046, "s": 27006, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 27069, "s": 27046, "text": "Extension Method in C#" }, { "code": null, "e": 27109, "s": 27069, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 27134, "s": 27109, "text": "Socket Programming in C#" }, { "code": null, "e": 27168, "s": 27134, "text": "Program to Print a New Line in C#" }, { "code": null, "e": 27214, "s": 27168, "text": "Getting a Month Name Using Month Number in C#" } ]
deque::at() and deque::swap() in C++ STL - GeeksforGeeks
13 Jan, 2018 Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. at() function is used reference the element present at the position given as the parameter to the function.Syntax : dequename.at(position) Parameters : Position of the element to be fetched. Returns : Direct reference to the element at the given position. Examples: Input : mydeque = 1, 2, 3 mydeque.at(2); Output : 3 Input : mydeque = 3, 4, 1, 7, 3 mydeque.at(3); Output : 7 Errors and Exceptions 1. If the position is not present in the deque, it throws out_of_range.2. It has a strong no exception throw guarantee otherwise. // CPP program to illustrate// Implementation of at() function#include <deque>#include <iostream>using namespace std; int main(){ deque<int> mydeque; mydeque.push_back(3); mydeque.push_back(4); mydeque.push_back(1); mydeque.push_back(7); mydeque.push_back(3); cout << mydeque.at(3); return 0;} Output: 7 ApplicationGiven a deque of integers, print all the integers present at even positions. Input :1, 2, 3, 4, 5, 6, 7, 8, 9 Output :1 3 5 7 9 Explanation - 1, 3, 5, 7 and 9 are at position 0, 2, 4, 6 and 8 which are even Algorithm1. Run a loop till the size of the array.2. Check if the position is divisible by 2, if yes, print the element at that position. // CPP program to illustrate// Application of at() function#include <deque>#include <iostream>using namespace std; int main(){ deque<int> mydeque; mydeque.push_back(1); mydeque.push_back(2); mydeque.push_back(3); mydeque.push_back(4); mydeque.push_back(5); mydeque.push_back(6); mydeque.push_back(7); mydeque.push_back(8); mydeque.push_back(9); // Deque becomes 1, 2, 3, 4, 5, 6, 7, 8, 9 for (int i = 0; i < mydeque.size(); ++i) { if (i % 2 == 0) { cout << mydeque.at(i); cout << " "; } } return 0;} Output: 1 3 5 7 9 This function is used to swap the contents of one deque with another deque of same type and size. Syntax : dequename1.swap(dequename2) Parameters : The name of the deque with which the contents have to be swapped. Result : All the elements of the 2 deque are swapped. Examples: Input : mydeque1 = {1, 2, 3, 4} mydeque2 = {3, 5, 7, 9} mydeque1.swap(mydeque2); Output : mydeque1 = {3, 5, 7, 9} mydeque2 = {1, 2, 3, 4} Input : mydeque1 = {1, 3, 5, 7} mydeque2 = {2, 4, 6, 8} mydeque1.swap(mydeque2); Output : mydeque1 = {2, 4, 6, 8} mydeque2 = {1, 3, 5, 7} Errors and Exceptions 1. It throws an error if the deque are not of the same type.2. It throws error if the deque are not of the same size.2. It has a basic no exception throw guarantee otherwise. // CPP program to illustrate// Implementation of swap() function#include <deque>#include <iostream>using namespace std; int main(){ // deque container declaration deque<int> mydeque1{ 1, 2, 3, 4 }; deque<int> mydeque2{ 3, 5, 7, 9 }; // using swap() function to swap elements of deques mydeque1.swap(mydeque2); // printing the first deque cout << "mydeque1 = "; for (auto it = mydeque1.begin(); it < mydeque1.end(); ++it) cout << *it << " "; // printing the second deque cout << endl << "mydeque2 = "; for (auto it = mydeque2.begin(); it < mydeque2.end(); ++it) cout << *it << " "; return 0;} Output: mydeque1 = 3 5 7 9 mydeque2 = 1 2 3 4 cpp-deque deque STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects Socket Programming in C/C++ Operator Overloading in C++ Multidimensional Arrays in C / C++ Bitwise Operators in C/C++ Virtual Function in C++ Constructors in C++ Object Oriented Programming in C++
[ { "code": null, "e": 25193, "s": 25165, "text": "\n13 Jan, 2018" }, { "code": null, "e": 25513, "s": 25193, "text": "Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed." }, { "code": null, "e": 25629, "s": 25513, "text": "at() function is used reference the element present at the position given as the parameter to the function.Syntax :" }, { "code": null, "e": 25770, "s": 25629, "text": "dequename.at(position)\nParameters :\nPosition of the element to be fetched.\nReturns :\nDirect reference to the element at the given position.\n" }, { "code": null, "e": 25780, "s": 25770, "text": "Examples:" }, { "code": null, "e": 25918, "s": 25780, "text": "Input : mydeque = 1, 2, 3\n mydeque.at(2);\nOutput : 3\n\nInput : mydeque = 3, 4, 1, 7, 3\n mydeque.at(3);\nOutput : 7\n" }, { "code": null, "e": 25940, "s": 25918, "text": "Errors and Exceptions" }, { "code": null, "e": 26070, "s": 25940, "text": "1. If the position is not present in the deque, it throws out_of_range.2. It has a strong no exception throw guarantee otherwise." }, { "code": "// CPP program to illustrate// Implementation of at() function#include <deque>#include <iostream>using namespace std; int main(){ deque<int> mydeque; mydeque.push_back(3); mydeque.push_back(4); mydeque.push_back(1); mydeque.push_back(7); mydeque.push_back(3); cout << mydeque.at(3); return 0;}", "e": 26389, "s": 26070, "text": null }, { "code": null, "e": 26397, "s": 26389, "text": "Output:" }, { "code": null, "e": 26400, "s": 26397, "text": "7\n" }, { "code": null, "e": 26488, "s": 26400, "text": "ApplicationGiven a deque of integers, print all the integers present at even positions." }, { "code": null, "e": 26620, "s": 26488, "text": "Input :1, 2, 3, 4, 5, 6, 7, 8, 9\nOutput :1 3 5 7 9\nExplanation - 1, 3, 5, 7 and 9 are at position 0, 2, 4, 6 and 8 which are even\n" }, { "code": null, "e": 26758, "s": 26620, "text": "Algorithm1. Run a loop till the size of the array.2. Check if the position is divisible by 2, if yes, print the element at that position." }, { "code": "// CPP program to illustrate// Application of at() function#include <deque>#include <iostream>using namespace std; int main(){ deque<int> mydeque; mydeque.push_back(1); mydeque.push_back(2); mydeque.push_back(3); mydeque.push_back(4); mydeque.push_back(5); mydeque.push_back(6); mydeque.push_back(7); mydeque.push_back(8); mydeque.push_back(9); // Deque becomes 1, 2, 3, 4, 5, 6, 7, 8, 9 for (int i = 0; i < mydeque.size(); ++i) { if (i % 2 == 0) { cout << mydeque.at(i); cout << \" \"; } } return 0;}", "e": 27339, "s": 26758, "text": null }, { "code": null, "e": 27347, "s": 27339, "text": "Output:" }, { "code": null, "e": 27358, "s": 27347, "text": "1 3 5 7 9\n" }, { "code": null, "e": 27456, "s": 27358, "text": "This function is used to swap the contents of one deque with another deque of same type and size." }, { "code": null, "e": 27465, "s": 27456, "text": "Syntax :" }, { "code": null, "e": 27627, "s": 27465, "text": "dequename1.swap(dequename2)\nParameters :\nThe name of the deque with which\nthe contents have to be swapped.\nResult :\nAll the elements of the 2 deque are swapped.\n" }, { "code": null, "e": 27637, "s": 27627, "text": "Examples:" }, { "code": null, "e": 27971, "s": 27637, "text": "Input : mydeque1 = {1, 2, 3, 4}\n mydeque2 = {3, 5, 7, 9}\n mydeque1.swap(mydeque2);\nOutput : mydeque1 = {3, 5, 7, 9}\n mydeque2 = {1, 2, 3, 4}\n\nInput : mydeque1 = {1, 3, 5, 7}\n mydeque2 = {2, 4, 6, 8}\n mydeque1.swap(mydeque2);\nOutput : mydeque1 = {2, 4, 6, 8}\n mydeque2 = {1, 3, 5, 7}\n" }, { "code": null, "e": 27993, "s": 27971, "text": "Errors and Exceptions" }, { "code": null, "e": 28168, "s": 27993, "text": "1. It throws an error if the deque are not of the same type.2. It throws error if the deque are not of the same size.2. It has a basic no exception throw guarantee otherwise." }, { "code": "// CPP program to illustrate// Implementation of swap() function#include <deque>#include <iostream>using namespace std; int main(){ // deque container declaration deque<int> mydeque1{ 1, 2, 3, 4 }; deque<int> mydeque2{ 3, 5, 7, 9 }; // using swap() function to swap elements of deques mydeque1.swap(mydeque2); // printing the first deque cout << \"mydeque1 = \"; for (auto it = mydeque1.begin(); it < mydeque1.end(); ++it) cout << *it << \" \"; // printing the second deque cout << endl << \"mydeque2 = \"; for (auto it = mydeque2.begin(); it < mydeque2.end(); ++it) cout << *it << \" \"; return 0;}", "e": 28825, "s": 28168, "text": null }, { "code": null, "e": 28833, "s": 28825, "text": "Output:" }, { "code": null, "e": 28874, "s": 28833, "text": "mydeque1 = 3 5 7 9 \nmydeque2 = 1 2 3 4 \n" }, { "code": null, "e": 28884, "s": 28874, "text": "cpp-deque" }, { "code": null, "e": 28890, "s": 28884, "text": "deque" }, { "code": null, "e": 28894, "s": 28890, "text": "STL" }, { "code": null, "e": 28898, "s": 28894, "text": "C++" }, { "code": null, "e": 28902, "s": 28898, "text": "STL" }, { "code": null, "e": 28906, "s": 28902, "text": "CPP" }, { "code": null, "e": 29004, "s": 28906, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29013, "s": 29004, "text": "Comments" }, { "code": null, "e": 29026, "s": 29013, "text": "Old Comments" }, { "code": null, "e": 29045, "s": 29026, "text": "Inheritance in C++" }, { "code": null, "e": 29088, "s": 29045, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 29112, "s": 29088, "text": "C++ Classes and Objects" }, { "code": null, "e": 29140, "s": 29112, "text": "Socket Programming in C/C++" }, { "code": null, "e": 29168, "s": 29140, "text": "Operator Overloading in C++" }, { "code": null, "e": 29203, "s": 29168, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 29230, "s": 29203, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 29254, "s": 29230, "text": "Virtual Function in C++" }, { "code": null, "e": 29274, "s": 29254, "text": "Constructors in C++" } ]
How to get MySQL random integer range?
To get the random integer range, use the rand() function. The query to create a table βˆ’ mysql> create table RandomIntegerDemo βˆ’> ( βˆ’> Number int βˆ’> ); Query OK, 0 rows affected (0.61 sec) Inserting records into table. The query is as follows βˆ’ mysql> insert into RandomIntegerDemo values(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13),(14); Query OK, 14 rows affected (0.14 sec) Records: 14 Duplicates: 0 Warnings: 0 Now you can display all records with the help of select statement. The query is as follows βˆ’ mysql> select *from RandomIntegerDemo; The following is the output displaying integers βˆ’ +--------+ | Number | +--------+ | 1 | | 2 | | 3 | | 4 | | 5 | | 6 | | 7 | | 8 | | 9 | | 10 | | 11 | | 12 | | 13 | | 14 | +--------+ 14 rows in set (0.00 sec) The query to generate the random integer range is as follows βˆ’ mysql> select Number, (FLOOR( 1 + RAND( ) *14 )) AS RandomValue βˆ’> from RandomIntegerDemo βˆ’> limit 0,14; The output displays random integer range in the same table βˆ’ +--------+-------------+ | Number | RandomValue | +--------+-------------+ | 1 | 9 | | 2 | 8 | | 3 | 13 | | 4 | 13 | | 5 | 10 | | 6 | 10 | | 7 | 7 | | 8 | 3 | | 9 | 8 | | 10 | 2 | | 11 | 14 | | 12 | 6 | | 13 | 3 | | 14 | 9 | +--------+-------------+ 14 rows in set (0.00 sec)
[ { "code": null, "e": 1150, "s": 1062, "text": "To get the random integer range, use the rand() function. The query to create a table βˆ’" }, { "code": null, "e": 1253, "s": 1150, "text": "mysql> create table RandomIntegerDemo\nβˆ’> (\n βˆ’> Number int\nβˆ’> );\nQuery OK, 0 rows affected (0.61 sec)" }, { "code": null, "e": 1309, "s": 1253, "text": "Inserting records into table. The query is as follows βˆ’" }, { "code": null, "e": 1490, "s": 1309, "text": "mysql> insert into RandomIntegerDemo values(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13),(14);\nQuery OK, 14 rows affected (0.14 sec)\nRecords: 14 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 1583, "s": 1490, "text": "Now you can display all records with the help of select statement. The query is as follows βˆ’" }, { "code": null, "e": 1622, "s": 1583, "text": "mysql> select *from RandomIntegerDemo;" }, { "code": null, "e": 1672, "s": 1622, "text": "The following is the output displaying integers βˆ’" }, { "code": null, "e": 1896, "s": 1672, "text": "+--------+\n| Number |\n+--------+\n| 1 |\n| 2 |\n| 3 |\n| 4 |\n| 5 |\n| 6 |\n| 7 |\n| 8 |\n| 9 |\n| 10 |\n| 11 |\n| 12 |\n| 13 |\n| 14 |\n+--------+\n14 rows in set (0.00 sec)" }, { "code": null, "e": 1959, "s": 1896, "text": "The query to generate the random integer range is as follows βˆ’" }, { "code": null, "e": 2064, "s": 1959, "text": "mysql> select Number, (FLOOR( 1 + RAND( ) *14 )) AS RandomValue\nβˆ’> from RandomIntegerDemo\nβˆ’> limit 0,14;" }, { "code": null, "e": 2125, "s": 2064, "text": "The output displays random integer range in the same table βˆ’" }, { "code": null, "e": 2601, "s": 2125, "text": "+--------+-------------+\n| Number | RandomValue |\n+--------+-------------+\n| 1 | 9 |\n| 2 | 8 |\n| 3 | 13 |\n| 4 | 13 |\n| 5 | 10 |\n| 6 | 10 |\n| 7 | 7 |\n| 8 | 3 |\n| 9 | 8 |\n| 10 | 2 |\n| 11 | 14 |\n| 12 | 6 |\n| 13 | 3 |\n| 14 | 9 |\n+--------+-------------+\n14 rows in set (0.00 sec)" } ]
Why FAISS Works | Towards Data Science
Accurate, fast, and memory-efficient similarity search is a hard thing to do β€” but something that, if done well, lends itself very well to our huge repositories of endless (and exponentially growing) data. The reason that similarity search is so good is that it enables us to search for images, text, videos, or any other form of data β€” without getting too specific in our search queries β€” which is something that we humans are not so great at. I will use the example of image similarity search. We can take a picture, and search for similar images. This works by first converting every image into a set of automatically generated features β€” which are represented as a numerical vector. When we then compare the vectors of two similar images β€” we will find that they are very similar. Now, if we took our picture, and searched for other similar images β€” we don’t really want to compare our query vector to every single vector in the database. Imagine trying to do that with a Google Image search β€” you could be waiting some time. Instead, we want to find a more efficient approach β€” and that is exactly what Facebook AI Similarity Search (FAISS) offers. Our story of efficient similarity search begins with vectors β€” many of them in fact. If we were to take three vectors: We can say quite confidently that vectors a and b are closer to each other than c. And this can be visualized with a simple 3-dimensional chart: In our case, our vectors have many more dimensions β€” too many to visualize. But we can still use the same distance metrics to calculate the proximity and/or similarity between two highly-dimensional vectors. A few of those are: Euclidean distance (measures magnitude) Dot product (measures direction and magnitude) Cosine similarity (measure direction) FAISS makes use of both Euclidean distance and dot product for comparing vectors. Given our vectors a, and b. We calculate the Euclidean distance as: Given our Euclidean distance metric, we can move onto creating the nearest neighbors (NN) graph using a set of vectors. NN is an essential component of FAISS, it is how we build the core β€˜distance’ property in our index. However, NN-search is computationally heavy due to the curse of dimensionality. The process consists of calculating the Euclidean distance between two vectors, and then another two, and so on β€” the nearest neighbors are those with the shortest distance between them. The most basic approach to NN-search is the brute-force, exhaustive search β€” where we calculate the distance between all elements. Now, if we have a few million vectors indexed β€” or a billion (as is the number that FAISS is built for) β€” this can become a heavy operation where we sacrifice speed and memory efficiency, for accuracy: Brute ForceGood AccuracyBad SpeedBad Memory (eg a lot of memory is required) So, we can instead perform a non-exhaustive search that does not search all elements in our index and/or transforms the vectors to make them smaller (and therefore faster to compare against). Because this non-exhaustive (approximate) NN-search uses slightly modified vectors or a restricted search area β€” it returns an approximate best result, which is not necessarily the absolute best result. Approximate NNReasonable AccuracyGood SpeedGood Memory This degradation in accuracy however is very slight and viewed as a fair trade-off for the performance benefits. First, FAISS uses all of the intelligent ANN graph-building logic that we’ve already learned about. But there’s more to FAISS. The first of those efficiency savings comes from efficient usage of the GPU, so the search can process calculations in parallel rather than in series β€” offering a big speed-up. Additionally, FAISS implements three additional steps in the indexing process. A preprocessing step, followed by two quantization operations β€” the coarse quantizer for inverted file indexing (IVF), and the fine quantizer for vector encoding. For many of us, that last paragraph is nonsensical gibberish β€” so let’s break each step down and understand what each means. We enter this process with the vectors that we would like FAISS to index. The very first step is to transform these vectors into a more friendly/efficient format. FAISS offers several options here. PCA β€” use principal component analysis to reduce the number of dimensions in our vectors. L2norm β€” L2-normalize our vectors. OPQ β€” rotates our vectors so they can be encoded more efficiently by the fine quantizer β€” if using product quantization (PQ). Pad β€” pads input vectors with zeros up to a given target dimension. This operation means that when we do get around to comparing our query vector against already embedded vectors, each comparison will require less computation β€” making things faster. The next step is our inverted file (IVF) indexing process. Again, there are multiple options β€” but each one is aiming to partition data into similar clusters. This means that when we query FAISS, and our query is converted into a vector β€” it will be compared against these partition/cluster centroids. We compare similarity metrics against our query vector and each of these centroids β€” and once we find the nearest centroid, we then access all of the full vectors within that centroid (and ignore all others). Immediately, we have significantly reduced the required search area β€” reducing complexity and speeding up the search. This is also called the β€˜non-exhaustive’ search component β€” eg the component that allows us to avoid an β€˜exhaustive’ (compare everything) search. The final step is a final encoding step for each vector before it is indexed. This encoding process is carried out by our fine quantizer. The goal here is to reduce index memory size and increase search speed. There are several options: Flat β€” Vectors are stored as is, without any encoding. PQ β€” Applies product quantization. SQ β€” Applies scalar quantization. It’s worth noting that even with the Flat encoding, FAISS is still going to be very fast. All of these steps and improvements combine to create an incredibly fast similarity search engine β€” which on GPU is still unbeaten. That’s all for this article on FAISS! FAISS is an incredibly cool tool, and you can read more about it here, and the FAISS repo here. You can find Python implementations of FAISS in this notebook. I hope you’ve enjoyed the article. Let me know if you have any questions or suggestions via Twitter or in the comments below. If you’re interested in more content like this, I post on YouTube too. Thanks for reading! πŸ€– NLP With Transformers Course *All images are by the author except where stated otherwise
[ { "code": null, "e": 377, "s": 171, "text": "Accurate, fast, and memory-efficient similarity search is a hard thing to do β€” but something that, if done well, lends itself very well to our huge repositories of endless (and exponentially growing) data." }, { "code": null, "e": 616, "s": 377, "text": "The reason that similarity search is so good is that it enables us to search for images, text, videos, or any other form of data β€” without getting too specific in our search queries β€” which is something that we humans are not so great at." }, { "code": null, "e": 858, "s": 616, "text": "I will use the example of image similarity search. We can take a picture, and search for similar images. This works by first converting every image into a set of automatically generated features β€” which are represented as a numerical vector." }, { "code": null, "e": 956, "s": 858, "text": "When we then compare the vectors of two similar images β€” we will find that they are very similar." }, { "code": null, "e": 1201, "s": 956, "text": "Now, if we took our picture, and searched for other similar images β€” we don’t really want to compare our query vector to every single vector in the database. Imagine trying to do that with a Google Image search β€” you could be waiting some time." }, { "code": null, "e": 1325, "s": 1201, "text": "Instead, we want to find a more efficient approach β€” and that is exactly what Facebook AI Similarity Search (FAISS) offers." }, { "code": null, "e": 1410, "s": 1325, "text": "Our story of efficient similarity search begins with vectors β€” many of them in fact." }, { "code": null, "e": 1444, "s": 1410, "text": "If we were to take three vectors:" }, { "code": null, "e": 1589, "s": 1444, "text": "We can say quite confidently that vectors a and b are closer to each other than c. And this can be visualized with a simple 3-dimensional chart:" }, { "code": null, "e": 1817, "s": 1589, "text": "In our case, our vectors have many more dimensions β€” too many to visualize. But we can still use the same distance metrics to calculate the proximity and/or similarity between two highly-dimensional vectors. A few of those are:" }, { "code": null, "e": 1857, "s": 1817, "text": "Euclidean distance (measures magnitude)" }, { "code": null, "e": 1904, "s": 1857, "text": "Dot product (measures direction and magnitude)" }, { "code": null, "e": 1942, "s": 1904, "text": "Cosine similarity (measure direction)" }, { "code": null, "e": 2024, "s": 1942, "text": "FAISS makes use of both Euclidean distance and dot product for comparing vectors." }, { "code": null, "e": 2092, "s": 2024, "text": "Given our vectors a, and b. We calculate the Euclidean distance as:" }, { "code": null, "e": 2212, "s": 2092, "text": "Given our Euclidean distance metric, we can move onto creating the nearest neighbors (NN) graph using a set of vectors." }, { "code": null, "e": 2393, "s": 2212, "text": "NN is an essential component of FAISS, it is how we build the core β€˜distance’ property in our index. However, NN-search is computationally heavy due to the curse of dimensionality." }, { "code": null, "e": 2580, "s": 2393, "text": "The process consists of calculating the Euclidean distance between two vectors, and then another two, and so on β€” the nearest neighbors are those with the shortest distance between them." }, { "code": null, "e": 2711, "s": 2580, "text": "The most basic approach to NN-search is the brute-force, exhaustive search β€” where we calculate the distance between all elements." }, { "code": null, "e": 2913, "s": 2711, "text": "Now, if we have a few million vectors indexed β€” or a billion (as is the number that FAISS is built for) β€” this can become a heavy operation where we sacrifice speed and memory efficiency, for accuracy:" }, { "code": null, "e": 2990, "s": 2913, "text": "Brute ForceGood AccuracyBad SpeedBad Memory (eg a lot of memory is required)" }, { "code": null, "e": 3182, "s": 2990, "text": "So, we can instead perform a non-exhaustive search that does not search all elements in our index and/or transforms the vectors to make them smaller (and therefore faster to compare against)." }, { "code": null, "e": 3385, "s": 3182, "text": "Because this non-exhaustive (approximate) NN-search uses slightly modified vectors or a restricted search area β€” it returns an approximate best result, which is not necessarily the absolute best result." }, { "code": null, "e": 3440, "s": 3385, "text": "Approximate NNReasonable AccuracyGood SpeedGood Memory" }, { "code": null, "e": 3553, "s": 3440, "text": "This degradation in accuracy however is very slight and viewed as a fair trade-off for the performance benefits." }, { "code": null, "e": 3680, "s": 3553, "text": "First, FAISS uses all of the intelligent ANN graph-building logic that we’ve already learned about. But there’s more to FAISS." }, { "code": null, "e": 3857, "s": 3680, "text": "The first of those efficiency savings comes from efficient usage of the GPU, so the search can process calculations in parallel rather than in series β€” offering a big speed-up." }, { "code": null, "e": 4099, "s": 3857, "text": "Additionally, FAISS implements three additional steps in the indexing process. A preprocessing step, followed by two quantization operations β€” the coarse quantizer for inverted file indexing (IVF), and the fine quantizer for vector encoding." }, { "code": null, "e": 4224, "s": 4099, "text": "For many of us, that last paragraph is nonsensical gibberish β€” so let’s break each step down and understand what each means." }, { "code": null, "e": 4422, "s": 4224, "text": "We enter this process with the vectors that we would like FAISS to index. The very first step is to transform these vectors into a more friendly/efficient format. FAISS offers several options here." }, { "code": null, "e": 4512, "s": 4422, "text": "PCA β€” use principal component analysis to reduce the number of dimensions in our vectors." }, { "code": null, "e": 4547, "s": 4512, "text": "L2norm β€” L2-normalize our vectors." }, { "code": null, "e": 4673, "s": 4547, "text": "OPQ β€” rotates our vectors so they can be encoded more efficiently by the fine quantizer β€” if using product quantization (PQ)." }, { "code": null, "e": 4741, "s": 4673, "text": "Pad β€” pads input vectors with zeros up to a given target dimension." }, { "code": null, "e": 4923, "s": 4741, "text": "This operation means that when we do get around to comparing our query vector against already embedded vectors, each comparison will require less computation β€” making things faster." }, { "code": null, "e": 5082, "s": 4923, "text": "The next step is our inverted file (IVF) indexing process. Again, there are multiple options β€” but each one is aiming to partition data into similar clusters." }, { "code": null, "e": 5225, "s": 5082, "text": "This means that when we query FAISS, and our query is converted into a vector β€” it will be compared against these partition/cluster centroids." }, { "code": null, "e": 5434, "s": 5225, "text": "We compare similarity metrics against our query vector and each of these centroids β€” and once we find the nearest centroid, we then access all of the full vectors within that centroid (and ignore all others)." }, { "code": null, "e": 5552, "s": 5434, "text": "Immediately, we have significantly reduced the required search area β€” reducing complexity and speeding up the search." }, { "code": null, "e": 5698, "s": 5552, "text": "This is also called the β€˜non-exhaustive’ search component β€” eg the component that allows us to avoid an β€˜exhaustive’ (compare everything) search." }, { "code": null, "e": 5908, "s": 5698, "text": "The final step is a final encoding step for each vector before it is indexed. This encoding process is carried out by our fine quantizer. The goal here is to reduce index memory size and increase search speed." }, { "code": null, "e": 5935, "s": 5908, "text": "There are several options:" }, { "code": null, "e": 5990, "s": 5935, "text": "Flat β€” Vectors are stored as is, without any encoding." }, { "code": null, "e": 6025, "s": 5990, "text": "PQ β€” Applies product quantization." }, { "code": null, "e": 6059, "s": 6025, "text": "SQ β€” Applies scalar quantization." }, { "code": null, "e": 6149, "s": 6059, "text": "It’s worth noting that even with the Flat encoding, FAISS is still going to be very fast." }, { "code": null, "e": 6281, "s": 6149, "text": "All of these steps and improvements combine to create an incredibly fast similarity search engine β€” which on GPU is still unbeaten." }, { "code": null, "e": 6415, "s": 6281, "text": "That’s all for this article on FAISS! FAISS is an incredibly cool tool, and you can read more about it here, and the FAISS repo here." }, { "code": null, "e": 6478, "s": 6415, "text": "You can find Python implementations of FAISS in this notebook." }, { "code": null, "e": 6675, "s": 6478, "text": "I hope you’ve enjoyed the article. Let me know if you have any questions or suggestions via Twitter or in the comments below. If you’re interested in more content like this, I post on YouTube too." }, { "code": null, "e": 6695, "s": 6675, "text": "Thanks for reading!" }, { "code": null, "e": 6726, "s": 6695, "text": "πŸ€– NLP With Transformers Course" } ]
mtools - Unix, Linux Command
Mtools is sufficient to give access to MS-DOS filesystems. For instance, commands such as mdir a: work on the a: floppy without any preliminary mounting or initialization (assuming the default oo/etc/mtools.confI works on your machine). With mtools, one can change floppies too without unmounting and mounting. Mtools can be found at the following places (and their mirrors): http://mtools.linux.lu/mtools-3.9.10.tar.gz ftp://www.tux.org/pub/knaff/mtools/mtools-3.9.10.tar.gz ftp://ibiblio.unc.edu/pub/Linux/utils/disk-management/mtools-3.9.10.tar.gz Before reporting a bug, make sure that it has not yet been fixed in the Alpha patches which can be found at: http://mtools.linux.lu/ ftp://www.tux.org/pub/knaff/mtools These patches are named mtools-version-ddmm.taz, where version stands for the base version, dd for the day and mm for the month. Due to a lack of space, I usually leave only the most recent patch. There is an mtools mailing list at mtools @ tux.org . Please send all bug reports to this list. You may subscribe to the list by sending a message with ’subscribe mtools @ tux.org’ in its body to majordomo @ tux.org . (N.B. Please remove the spaces around the "@" both times. I left them there in order to fool spambots.) Announcements of new mtools versions will also be sent to the list, in addition to the linux announce newsgroups. The mailing list is archived at http://www.tux.org/hypermail/mtools/latest The regular expression "pattern matching" routines follow the Unix-style rules. For example, β€˜*’ matches all MS-DOS files in lieu of β€˜*.*’. The archive, hidden, read-only and system attribute bits are ignored during pattern matching. All options use the - (minus) as their first character, not / as you’d expect in MS-DOS. Most mtools commands allow multiple filename parameters, which doesn’t follow MS-DOS conventions, but which is more user-friendly. Most mtools commands allow options that instruct them how to handle file name clashes. See section name clashes, for more details on these. All commands accept the -V flags which prints the version, and most accept the -v flag, which switches on verbose mode. In verbose mode, these commands print out the name of the MS-DOS files upon which they act, unless stated otherwise. See section Commands, for a description of the options which are specific to each command. The meaning of the drive letters depends on the target architectures. However, on most target architectures, drive A is the first floppy drive, drive B is the second floppy drive (if available), drive J is a Jaz drive (if available), and drive Z is a Zip drive (if available). On those systems where the device name is derived from the SCSI id, the Jaz drive is assumed to be at Scsi target 4, and the Zip at Scsi target 5 (factory default settings). On Linux, both drives are assumed to be the second drive on the Scsi bus (/dev/sdb). The default settings can be changes using a configuration file (see section Configuration). The drive letter : (colon) has a special meaning. It is used to access image files which are directly specified on the command line using the -i options. Example: mcopy -i my-image-file.bin ::file1 ::file2 . This copies file1 and file2 from the image file (my-image-file.bin) to the /tmp directory. The mcd command (oomcdI) is used to establish the device and the current working directory (relative to the MS-DOS filesystem), otherwise the default is assumed to be A:/. However, unlike MS-DOS, there is only one working directory for all drives, and not one per drive. This version of mtools supports VFAT style long filenames. If a Unix filename is too long to fit in a short DOS name, it is stored as a VFAT long name, and a companion short name is generated. This short name is what you see when you examine the disk with a pre-7.0 version of DOS. The following table shows some examples of short names: Long name MS-DOS name Reason for the change --------- ---------- --------------------- thisisatest THISIS~1 filename too long alain.knaff ALAIN~1.KNA extension too long prn.txt PRN~1.TXT PRN is a device name .abc ABC~1 null filename hot+cold HOT_CO~1 illegal character As you see, the following transformations happen to derive a short name: mcopy /etc/motd a:Reallylongname Mtools creates a VFAT entry for Reallylongname, and uses REALLYLO as a short name. Reallylongname is the primary name, and REALLYLO is the secondary name. mcopy /etc/motd a:motd Motd fits into the DOS filename limits. Mtools doesn’t need to derivate another name. Motd is the primary name, and there is no secondary name. Unix name Long name Reason for the change --------- ---------- --------------------- prn prn-1 PRN is a device name ab:c ab_c-1 illegal character When writing a file to disk, its long name or short name may collide with an already existing file or directory. This may happen for all commands which create new directory entries, such as mcopy, mmd, mren, mmove. When a name clash happens, mtools asks you what it should do. It offers several choices: The primary name is the name as displayed in Windows 95 or Windows NT: i.e. the long name if it exists, and the short name otherwise. The secondary name is the "hidden" name, i.e. the short name if a long name exists. By default, the user is prompted if the primary name clashes, and the secondary name is autorenamed. If a name clash occurs in a Unix directory, mtools only asks whether to overwrite the file, or to skip it. The VFAT filesystem is able to remember the case of the filenames. However, filenames which differ only in case are not allowed to coexist in the same directory. For example if you store a file called LongFileName on a VFAT filesystem, mdir shows this file as LongFileName, and not as Longfilename. However, if you then try to add LongFilename to the same directory, it is refused, because case is ignored for clash checks. The VFAT filesystem allows to store the case of a filename in the attribute byte, if all letters of the filename are the same case, and if all letters of the extension are the same case too. Mtools uses this information when displaying the files, and also to generate the Unix filename when mcopying to a Unix directory. This may have unexpected results when applied to files written using an pre-7.0 version of DOS: Indeed, the old style filenames map to all upper case. This is different from the behavior of the old version of mtools which used to generate lower case Unix filenames. Mtools supports a number of formats which allow to store more data on disk as usual. Due to different operating system abilities, these formats are not supported on all OS’es. Mtools recognizes these formats transparently where supported. In order to format these disks, you need to use an operating system specific tool. For Linux, suitable floppy tools can be found in the fdutils package at the following locations~: ftp://www.tux.org/pub/knaff/fdutils/. ftp://ibiblio.unc.edu/pub/Linux/utils/disk-management/fdutils-* See the manpages included in that package for further detail: Use superformat to format all formats except XDF, and use xdfcopy to format XDF. The oldest method of fitting more data on a disk is to use more sectors and more cylinders. Although the standard format uses 80 cylinders and 18 sectors (on a 3 1/2 high density disk), it is possible to use up to 83 cylinders (on most drives) and up to 21 sectors. This method allows to store up to 1743K on a 3 1/2 HD disk. However, 21 sector disks are twice as slow as the standard 18 sector disks because the sectors are packed so close together that we need to interleave them. This problem doesn’t exist for 20 sector formats. These formats are supported by numerous DOS shareware utilities such as fdformat and vgacopy. In his infinite hybris, Bill Gate$ believed that he invented this, and called it ooDMF disksI, or ooWindows formatted disksI. But in reality, it has already existed years before! Mtools supports these formats on Linux, on SunOs and on the DELL Unix PC. This method allows to store up to 1992K on a 3 1/2 HD disk. Mtools supports these formats only on Linux. The 2m format was originally invented by Ciriaco Garcia de Celis. It also uses bigger sectors than usual in order to fit more data on the disk. However, it uses the standard format (18 sectors of 512 bytes each) on the first cylinder, in order to make these disks easyer to handle by DOS. Indeed this method allows to have a standard sized bootsector, which contains a description of how the rest of the disk should be read. However, the drawback of this is that the first cylinder can hold less data than the others. Unfortunately, DOS can only handle disks where each track contains the same amount of data. Thus 2m hides the fact that the first track contains less data by using a shadow FAT. (Usually, DOS stores the FAT in two identical copies, for additional safety. XDF stores only one copy, and it tells DOS that it stores two. Thus the same that would be taken up by the second FAT copy is saved.) This also means that your should never use a 2m disk to store anything else than a DOS fs. Mtools supports these format only on Linux. XDF is a high capacity format used by OS/2. It can hold 1840 K per disk. That’s lower than the best 2m formats, but its main advantage is that it is fast: 600 milliseconds per track. That’s faster than the 21 sector format, and almost as fast as the standard 18 sector format. In order to access these disks, make sure mtools has been compiled with XDF support, and set the use_xdf variable for the drive in the configuration file. See section Compiling mtools, and oomisc variablesI, for details on how to do this. Fast XDF access is only available for Linux kernels which are more recent than 1.1.34. Mtools supports this format only on Linux. Caution / Attention distributors: If mtools is compiled on a Linux kernel more recent than 1.3.34, it won’t run on an older kernel. However, if it has been compiled on an older kernel, it still runs on a newer kernel, except that XDF access is slower. It is recommended that distribution authors only include mtools binaries compiled on kernels older than 1.3.34 until 2.0 comes out. When 2.0 will be out, mtools binaries compiled on newer kernels may (and should) be distributed. Mtools binaries compiled on kernels older than 1.3.34 won’t run on any 2.1 kernel or later. The fat checking code chokes on 1.72 Mb disks mformatted with pre-2.0.7 mtools. Set the environmental variable MTOOLS_FAT_COMPATIBILITY (or the corresponding configuration file variable, ooglobal variablesI) to bypass the fat checking. Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10901, "s": 10586, "text": "\nMtools is sufficient to give access to MS-DOS filesystems. For\ninstance, commands such as mdir a: work on the a: floppy\nwithout any preliminary mounting or initialization (assuming the default\noo/etc/mtools.confI works on your machine). With mtools, one can\nchange floppies too without unmounting and mounting.\n" }, { "code": null, "e": 10970, "s": 10903, "text": "\nMtools can be found at the following places (and their mirrors):\n" }, { "code": null, "e": 11149, "s": 10972, "text": "\nhttp://mtools.linux.lu/mtools-3.9.10.tar.gz\nftp://www.tux.org/pub/knaff/mtools/mtools-3.9.10.tar.gz\nftp://ibiblio.unc.edu/pub/Linux/utils/disk-management/mtools-3.9.10.tar.gz\n" }, { "code": null, "e": 11262, "s": 11151, "text": "\nBefore reporting a bug, make sure that it has not yet been fixed in the\nAlpha patches which can be found at:\n" }, { "code": null, "e": 11325, "s": 11264, "text": "\nhttp://mtools.linux.lu/\nftp://www.tux.org/pub/knaff/mtools\n" }, { "code": null, "e": 11526, "s": 11327, "text": "\nThese patches are named\nmtools-version-ddmm.taz, where version\nstands for the base version, dd for the day and mm for the\nmonth. Due to a lack of space, I usually leave only the most recent\npatch.\n" }, { "code": null, "e": 12043, "s": 11526, "text": "\nThere is an mtools mailing list at mtools @ tux.org . Please\nsend all bug reports to this list. You may subscribe to the list by\nsending a message with ’subscribe mtools @ tux.org’ in its\nbody to majordomo @ tux.org . (N.B. Please remove the spaces\naround the \"@\" both times. I left them there in order to fool\nspambots.) Announcements of new mtools versions will also be sent to\nthe list, in addition to the linux announce newsgroups. The mailing\nlist is archived at http://www.tux.org/hypermail/mtools/latest\n" }, { "code": null, "e": 12285, "s": 12047, "text": "\nThe regular expression \"pattern matching\" routines follow the Unix-style\nrules. For example, β€˜*’ matches all MS-DOS files in lieu of\nβ€˜*.*’. The archive, hidden, read-only and system attribute bits\nare ignored during pattern matching.\n" }, { "code": null, "e": 12376, "s": 12285, "text": "\nAll options use the - (minus) as their first character, not\n/ as you’d expect in MS-DOS.\n" }, { "code": null, "e": 12509, "s": 12376, "text": "\nMost mtools commands allow multiple filename parameters, which\ndoesn’t follow MS-DOS conventions, but which is more user-friendly.\n" }, { "code": null, "e": 12979, "s": 12509, "text": "\nMost mtools commands allow options that instruct them how to handle file\nname clashes. See section name clashes, for more details on these. All\ncommands accept the -V flags which prints the version, and most\naccept the -v flag, which switches on verbose mode. In verbose\nmode, these commands print out the name of the MS-DOS files upon which\nthey act, unless stated otherwise. See section Commands, for a description of\nthe options which are specific to each command.\n" }, { "code": null, "e": 13614, "s": 12981, "text": "\nThe meaning of the drive letters depends on the target architectures.\nHowever, on most target architectures, drive A is the first floppy\ndrive, drive B is the second floppy drive (if available), drive J is a\nJaz drive (if available), and drive Z is a Zip drive (if available). On\nthose systems where the device name is derived from the SCSI id, the Jaz\ndrive is assumed to be at Scsi target 4, and the Zip at Scsi target 5\n(factory default settings). On Linux, both drives are assumed to be the\nsecond drive on the Scsi bus (/dev/sdb). The default settings can be\nchanges using a configuration file (see section Configuration).\n" }, { "code": null, "e": 13770, "s": 13614, "text": "\nThe drive letter : (colon) has a special meaning. It is used to access\nimage files which are directly specified on the command line using the\n-i options.\n" }, { "code": null, "e": 13781, "s": 13770, "text": "\nExample:\n" }, { "code": null, "e": 13831, "s": 13783, "text": "\n mcopy -i my-image-file.bin ::file1 ::file2 .\n" }, { "code": null, "e": 13926, "s": 13833, "text": "\nThis copies file1 and file2 from the image file\n(my-image-file.bin) to the /tmp directory.\n" }, { "code": null, "e": 14201, "s": 13928, "text": "\nThe mcd command (oomcdI) is used to establish the device and\nthe current working directory (relative to the MS-DOS filesystem),\notherwise the default is assumed to be A:/. However, unlike\nMS-DOS, there is only one working directory for all drives, and not one\nper drive.\n" }, { "code": null, "e": 14545, "s": 14203, "text": "\nThis version of mtools supports VFAT style long filenames. If a Unix\nfilename is too long to fit in a short DOS name, it is stored as a\nVFAT long name, and a companion short name is generated. This short\nname is what you see when you examine the disk with a pre-7.0 version\nof DOS.\n\n The following table shows some examples of short names:\n" }, { "code": null, "e": 14909, "s": 14549, "text": "\nLong name MS-DOS name Reason for the change\n--------- ---------- ---------------------\nthisisatest THISIS~1 filename too long\nalain.knaff ALAIN~1.KNA extension too long\nprn.txt PRN~1.TXT PRN is a device name\n.abc ABC~1 null filename\nhot+cold HOT_CO~1 illegal character\n" }, { "code": null, "e": 14987, "s": 14911, "text": "\n As you see, the following transformations happen to derive a short\nname:\n" }, { "code": null, "e": 15025, "s": 14989, "text": "\n mcopy /etc/motd a:Reallylongname\n" }, { "code": null, "e": 15183, "s": 15025, "text": "\n Mtools creates a VFAT entry for Reallylongname, and uses REALLYLO as\na short name. Reallylongname is the primary name, and REALLYLO is the\nsecondary name.\n" }, { "code": null, "e": 15211, "s": 15185, "text": "\n mcopy /etc/motd a:motd\n" }, { "code": null, "e": 15358, "s": 15211, "text": "\n Motd fits into the DOS filename limits. Mtools doesn’t need to\nderivate another name. Motd is the primary name, and there is no\nsecondary name.\n" }, { "code": null, "e": 15573, "s": 15360, "text": "\nUnix name Long name Reason for the change\n--------- ---------- ---------------------\nprn prn-1 PRN is a device name\nab:c ab_c-1 illegal character\n" }, { "code": null, "e": 15881, "s": 15575, "text": "\nWhen writing a file to disk, its long name or short name may collide\nwith an already existing file or directory. This may happen for all\ncommands which create new directory entries, such as mcopy,\nmmd, mren, mmove. When a name clash happens, mtools\nasks you what it should do. It offers several choices:\n" }, { "code": null, "e": 16102, "s": 15881, "text": "\nThe primary name is the name as displayed in Windows 95 or Windows NT:\ni.e. the long name if it exists, and the short name otherwise. The\nsecondary name is the \"hidden\" name, i.e. the short name if a long name\nexists.\n" }, { "code": null, "e": 16205, "s": 16102, "text": "\nBy default, the user is prompted if the primary name clashes, and the\nsecondary name is autorenamed.\n" }, { "code": null, "e": 16314, "s": 16205, "text": "\nIf a name clash occurs in a Unix directory, mtools only asks whether\nto overwrite the file, or to skip it.\n" }, { "code": null, "e": 16742, "s": 16316, "text": "\nThe VFAT filesystem is able to remember the case of the\nfilenames. However, filenames which differ only in case are not allowed\nto coexist in the same directory. For example if you store a file called\nLongFileName on a VFAT filesystem, mdir shows this file as LongFileName,\nand not as Longfilename. However, if you then try to add LongFilename to\nthe same directory, it is refused, because case is ignored for clash\nchecks.\n" }, { "code": null, "e": 17331, "s": 16742, "text": "\nThe VFAT filesystem allows to store the case of a filename in the\nattribute byte, if all letters of the filename are the same case, and if\nall letters of the extension are the same case too. Mtools uses this\ninformation when displaying the files, and also to generate the Unix\nfilename when mcopying to a Unix directory. This may have unexpected\nresults when applied to files written using an pre-7.0 version of DOS:\nIndeed, the old style filenames map to all upper case. This is different\nfrom the behavior of the old version of mtools which used to generate\nlower case Unix filenames.\n" }, { "code": null, "e": 17574, "s": 17333, "text": "\nMtools supports a number of formats which allow to store more data on\ndisk as usual. Due to different operating system abilities, these\nformats are not supported on all OS’es. Mtools recognizes these formats\ntransparently where supported.\n" }, { "code": null, "e": 17757, "s": 17574, "text": "\nIn order to format these disks, you need to use an operating system\nspecific tool. For Linux, suitable floppy tools can be found in the\nfdutils package at the following locations~:\n" }, { "code": null, "e": 17863, "s": 17759, "text": "\nftp://www.tux.org/pub/knaff/fdutils/.\nftp://ibiblio.unc.edu/pub/Linux/utils/disk-management/fdutils-*\n" }, { "code": null, "e": 18010, "s": 17865, "text": "\nSee the manpages included in that package for further detail: Use\nsuperformat to format all formats except XDF, and use\nxdfcopy to format XDF.\n" }, { "code": null, "e": 18547, "s": 18012, "text": "\nThe oldest method of fitting more data on a disk is to use more sectors\nand more cylinders. Although the standard format uses 80 cylinders and\n18 sectors (on a 3 1/2 high density disk), it is possible to use up to\n83 cylinders (on most drives) and up to 21 sectors. This method allows\nto store up to 1743K on a 3 1/2 HD disk. However, 21 sector disks are\ntwice as slow as the standard 18 sector disks because the sectors are\npacked so close together that we need to interleave them. This problem\ndoesn’t exist for 20 sector formats.\n" }, { "code": null, "e": 18896, "s": 18547, "text": "\nThese formats are supported by numerous DOS shareware utilities such as\nfdformat and vgacopy. In his infinite hybris, Bill Gate$\nbelieved that he invented this, and called it ooDMF disksI, or\nooWindows formatted disksI. But in reality, it has already existed\nyears before! Mtools supports these formats on Linux, on SunOs and on\nthe DELL Unix PC.\n" }, { "code": null, "e": 18960, "s": 18898, "text": "\nThis method allows to store up to 1992K on a 3 1/2 HD disk.\n" }, { "code": null, "e": 19007, "s": 18960, "text": "\nMtools supports these formats only on Linux.\n" }, { "code": null, "e": 19437, "s": 19009, "text": "\nThe 2m format was originally invented by Ciriaco Garcia de Celis. It\nalso uses bigger sectors than usual in order to fit more data on the\ndisk. However, it uses the standard format (18 sectors of 512 bytes\neach) on the first cylinder, in order to make these disks easyer to\nhandle by DOS. Indeed this method allows to have a standard sized\nbootsector, which contains a description of how the rest of the disk\nshould be read.\n" }, { "code": null, "e": 20013, "s": 19437, "text": "\nHowever, the drawback of this is that the first cylinder can hold less\ndata than the others. Unfortunately, DOS can only handle disks where\neach track contains the same amount of data. Thus 2m hides the fact that\nthe first track contains less data by using a shadow\nFAT. (Usually, DOS stores the FAT in two identical copies, for\nadditional safety. XDF stores only one copy, and it tells DOS that it\nstores two. Thus the same that would be taken up by the second FAT copy\nis saved.) This also means that your should never use a 2m disk\nto store anything else than a DOS fs.\n" }, { "code": null, "e": 20059, "s": 20013, "text": "\nMtools supports these format only on Linux.\n" }, { "code": null, "e": 20666, "s": 20061, "text": "\nXDF is a high capacity format used by OS/2. It can hold 1840 K per\ndisk. That’s lower than the best 2m formats, but its main advantage is\nthat it is fast: 600 milliseconds per track. That’s faster than the 21\nsector format, and almost as fast as the standard 18 sector format. In\norder to access these disks, make sure mtools has been compiled with XDF\nsupport, and set the use_xdf variable for the drive in the\nconfiguration file. See section Compiling mtools, and oomisc variablesI,\nfor details on how to do this. Fast XDF access is only available for\nLinux kernels which are more recent than 1.1.34.\n" }, { "code": null, "e": 20711, "s": 20666, "text": "\nMtools supports this format only on Linux.\n" }, { "code": null, "e": 21286, "s": 20711, "text": "\nCaution / Attention distributors: If mtools is compiled on a\nLinux kernel more recent than 1.3.34, it won’t run on an older\nkernel. However, if it has been compiled on an older kernel, it still\nruns on a newer kernel, except that XDF access is slower. It is\nrecommended that distribution authors only include mtools binaries\ncompiled on kernels older than 1.3.34 until 2.0 comes out. When 2.0 will\nbe out, mtools binaries compiled on newer kernels may (and should) be\ndistributed. Mtools binaries compiled on kernels older than 1.3.34 won’t\nrun on any 2.1 kernel or later.\n" }, { "code": null, "e": 21526, "s": 21288, "text": "\nThe fat checking code chokes on 1.72 Mb disks mformatted with pre-2.0.7\nmtools. Set the environmental variable MTOOLS_FAT_COMPATIBILITY (or the\ncorresponding configuration file variable, ooglobal variablesI) to\nbypass the fat checking.\n" }, { "code": null, "e": 21545, "s": 21528, "text": "\nAdvertisements\n" }, { "code": null, "e": 21580, "s": 21545, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 21608, "s": 21580, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 21642, "s": 21608, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 21659, "s": 21642, "text": " Frahaan Hussain" }, { "code": null, "e": 21692, "s": 21659, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 21703, "s": 21692, "text": " Pradeep D" }, { "code": null, "e": 21738, "s": 21703, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 21754, "s": 21738, "text": " Musab Zayadneh" }, { "code": null, "e": 21787, "s": 21754, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 21799, "s": 21787, "text": " GUHARAJANM" }, { "code": null, "e": 21831, "s": 21799, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 21839, "s": 21831, "text": " Uplatz" }, { "code": null, "e": 21846, "s": 21839, "text": " Print" }, { "code": null, "e": 21857, "s": 21846, "text": " Add Notes" } ]
How to create data-driven presentations with jupyter notebooks, reveal.js, host on github, and show it to the world: Part I β€” make a basic slide deck | by Arindam Basu | Towards Data Science
... in which I discuss a workflow where you can start writing your contents on a jupyter notebook, create a reveal.js slide deck, and host it on github for presentations. This is for a very simple presentation that you can fully control yourself Part I: Basic slide deckPart II: Basic slide deck using remarkjsPart III: Advanced techniques Set up a github repo and add a submodule Step 1. Start with creating a github repository for hosting your slide deck. To do this, visit https://www.github.com and start a repository and you will also need to install git. I have used a hosted instance on Vultr and it came with a preinstalled git. If you use Windows, Mac, or Linux, you may want to install git or check in your terminal that you have git installed by issuing something like: git --version Step 2. Add a repository. For example, I have created a repository named myJupyterSlides, see the screenshot below: Step 3. (While still using the web interface) It’s a good idea to create an index.md file in the master branch and write that you will keep your slides here in this repository. You can also use a β€œREADME.md” for that purpose. Let’s create a file now. Below you can see the file was created: Step 4. (While still using the web interface), using the web interface, create a new β€˜branch’ named gh-pages (see the screenshot below as to how to create the gh-pages branch) Once you create the gh-pages branch, github automatically creates a website for you. If you click β€œSettings” on your github repository (β€œgithub repo”), it will show that your site is published. For example, if here is the screenshot that shows where my site is published from my github repo: If I were to click on the link, it would show a simple webpage. You have now set up a site where your slides will be published. In the next steps, we will make available to our computer (it could be local computer machine or an instance or a virtual machine) a folder using this git repo where we will build the files for our slide deck. Here are the steps: Step 5. Now on your terminal, β€˜clone’ the git repo. First, make a directory (or folder). For example, I made a directory named β€œjupyterslides”. I changed from my current directory to this directory (1). Then initialise a git folder (2). After this add your github repo to this folder as a subfolder (3). You will see that a folder is added whose name is same as your github repo name. ~$ cd jupyterslides (1)~$ git init (2)~$ git submodule add <your github https repo address> (3) Step 6. Now that you have set up a github repo and you have added that repo as a submodule to your computer or instance, let’s start building the contents of the slide deck. By the time you will complete this tutorial, you will build a simple presentation from the Jupyter notebook that will be displayed over the web. Later, you will see you can build interactivity to this presentation and more advanced features. Unlike Keynote, Powerpoint, or OpenOffice/LibreOffice Impress, you will not use any point and click based system to build such content; you will, instead use plain text tools to build your presentation. Therefore, the first step is develop the content in Jupyter notebook. The second step is convert this notebook programmatically to a markdown document The third step is to use β€˜pandoc’ (a universal document converter, a.k.a. Swiss Army Knife of document conversion) to convert the document to a set of slide decks The fourth step is to β€˜push’ the contents to the github repo for display over the Internet Step 7: create content in Jupyter notebook. β€” For this tutorial, let’s create a five slide-deck presentation (this is for illustration) containing: A title slide (we will add the title slide later) A slide that contains bullet points A slide that contains an image A slide that contains a link A slide that contains a table I will later show you that you can use these four elements (bullet points, image, link, and table) are basic constituents to create different types of presentations. I will also show you how you can add interactivity to these elements. You can create images, and tables in Jupyter notebooks using markdown or codes written in R or Python or Julia (and indeed in many other languages). So this is a good time to launch into four related issues: how to author contents in markdown, what is reveal.js and why we use it (and there are others as well), and guidance on slide making. Markdown is a content authoring system designed to write structured documents on the web. The following elements of a document make up markdown syntax: The following is an example of a table written in Markdown and will be rendered as a table in github flavoured markdown| Element of text | Equivalent Markdown syntax ||--------------------|-----------------------------------|| Heading levels | Usually with ## || First level header | # Example of a first level header || Second level header| ## Second level header || Paragraphs | Text separated by two line spaces || Unnumbered list | * this is an element || Numbered list | 1. This is the first element || Tables | This is a markdown table || Formula | $\formula$ || Images | ![image alt](image URL) || Hyperlinks | [Link text](URL to be linked) || References | [@bibtex_entry_ID] || Codes | backticks (`code goes here`) || Italic | *text to be italicised* || Bold | **text to be in bold font** || Underline | _text to be underlined_ || Blockquote | > Text to be blockquoted | In the code block above, I have provided you with a list of commonly used markdown conventions. For a longer list and cheatsheet of github flavoured markdown, see the following link github.com In a Jupyter notebook, you can author documents in markdown. Jupyter notebooks use github flavoured markdown and this is what we will use as well. Besides, if you want to use references and citations and if you would like to transfer the documents to other formats that include citations and list of references in it, I recommend you use pandoc to transfer the document from a markdown format to the desired format. You can learn more about pandoc and how to transfer documents using pandoc here. The following youtube video provides you more information about pandoc: We will cover how to use pandoc to create slide decks in a separate section of this document. For now, we will use markdown to write our slides. We will use next reveal.js to style our slides. Think of reveal.js as a tool that you will use to render the slides you have created. Revealjs consists of three elements: A CSS (cascading style sheet that renders the appearance of the document) A javascript engine (that renders the slide decks), and An HTML5 document that you will create that will be shown as slides Think of each β€˜slide’ that you will show to be included within the <section> and \<section> elements. So, it goes like as follows: <html>CSS statements<section>Your slide data will go here ...</section><javacript file></html> This is the basic structure. There are other tools and frameworks as well, please check them out. In this tutorial we will cover revealjs, and in subsequent tutorials, I will cover several of them. Some common and popular frameworks are: Impress.js Shower.js Deck.js Remarkjs (we will cover this in the next tutorial) I will cover these in subsequent posts, so this is the one where we are going to focus on revealjs. Step 8. Obtain a copy of reveal.js from their github repo and use wget command in your terminal in Jupyter notebook like so: ~$ cd myjupyterslides (1)~$ wget https://github.com/hakimel/reveal.js/archive/master.zip (2)~$ unzip master.zip (3)# this will create a folder named 'reveal.js-master'# rename the folder to 'revealjs' with:~$ mv reveal.js-master revealjs (4) Explanation of the above code block: cd myjupyterslides (1) . β€” You will change directory to get into myjupyterslides where myjupyterslides is the github repository you created earlier and therefore when you added the git submodule, this was added as a folder to your present directorywget <URL> (2) wget is a utility which helps you to download web contents, in this case the master branch of the revealjs repositoryunzip master.zip (3) is self-explanatory, it will unzip the file and add a folder β€˜reveal.js-master’ to the current directorymv reveal.js-master revealjs is a way to β€˜rename’ a folder so now your folder is renamed revaljs. cd myjupyterslides (1) . β€” You will change directory to get into myjupyterslides where myjupyterslides is the github repository you created earlier and therefore when you added the git submodule, this was added as a folder to your present directory wget <URL> (2) wget is a utility which helps you to download web contents, in this case the master branch of the revealjs repository unzip master.zip (3) is self-explanatory, it will unzip the file and add a folder β€˜reveal.js-master’ to the current directory mv reveal.js-master revealjs is a way to β€˜rename’ a folder so now your folder is renamed revaljs. At the end of this step, you are set to use revealjs to create a local copy of your slide decks. But before we start putting together contents, let’s learn a few points about good practices on creating slide decks and data visualisation. This is a HIGHLY condensed version of what I will discuss in subsequent articles in this series, but will serve our purpose for this tutorial. A few things about creating slide decks and data visualisations is in order. First, keep in mind the five laws of data ink from Edward Tufte, Above all else, show the dataMaximise the data ink ratio (more data per ink flow)Erase non-data inkErase redundant data inkRevise and edit Above all else, show the data Maximise the data ink ratio (more data per ink flow) Erase non-data ink Erase redundant data ink Revise and edit For a more detailed explanation of the above concepts, please review the following source: medium.com Some other tips include: Craft a story with a beginning, a middle and an end Use storyboards to develop your ideas (see work by Garr Reynolds and Cliff Atkinson) Let’s create a simple five slide presentation in jupyter notebook. The syntax is simple and we will create something like as follows (you can see how it looks as a jupyter notebook like by visiting this link ) ## This is the first slide (1)- We will create simple set of slides- Let's analyse some data- Create a figure from the data- Create a tablelibrary(tidyverse) (2)mtcars1 <- mtcars %>% (3) head() mtcars1 # produces the first five rows in the form of a tablemtcars %>% (4) ggplot(aes(x = disp, y = mpg)) + geom_point() + geom_smooth(method = "loess", colour = "blue", se = FALSE) + geom_smooth(method = "lm", colour = "red", se = FALSE) + labs(x = "Engine size", y = "Miles per gallon", title = "Relationship between engine size and milage for cars") + theme_bw() + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + ggsave("test5.png") Explanation of the above code: (1) This is the first slide written in a markdown block. You can move around the blocks so you can in essence have a storyboard built in Jupyter(2) This is written in a code window and calls the tidyverse library in R(3) mtcars1 is a data subset created from mtcars, a large data set on cars; we will use this to demonstrate creation of tables programmatically(4) We use this code to generate a plot programmatically Step 9. After we generate these figures and tables using jupyter notebook and using R within Jupyter notebook, we then export this jupyter notebook to a markdown document. We could use jupyter notebook itself to create a reveal.js set of slide decks, but exporting first to markdown provides you more control on some aspects of the elements o slide creation. You use the following code to convert a jupyter notebook to a markdown document: ~$ jupyter nbconvert -t markdown mynotebook.ipynb (1)# generates mynotebook.md (2) Explanation: (1) mynotebook.ipynb is the name of the jupyter notebook I want to convert(2) This will generate mynotebook.md markdown document Now our markdown document looks like as follows: ## This is the first slide- We will create simple set of slides- Let's analyse some data- Create a figure from the data- Create a table```Rlibrary(tidyverse)```── u001b[1mAttaching packagesu001b[22m ─────────────────────────────────────── tidyverse 1.2.1 ── u001b[32mβœ”u001b[39m u001b[34mggplot2u001b[39m 3.1.1 u001b[32mβœ”u001b[39m u001b[34mpurrr u001b[39m 0.3.2 u001b[32mβœ”u001b[39m u001b[34mtibble u001b[39m 2.1.3 u001b[32mβœ”u001b[39m u001b[34mdplyr u001b[39m 0.8.1 u001b[32mβœ”u001b[39m u001b[34mtidyr u001b[39m 0.8.3 u001b[32mβœ”u001b[39m u001b[34mstringru001b[39m 1.4.0 u001b[32mβœ”u001b[39m u001b[34mreadr u001b[39m 1.3.1 u001b[32mβœ”u001b[39m u001b[34mforcatsu001b[39m 0.4.0 ── u001b[1mConflictsu001b[22m ────────────────────────────────────────── tidyverse_conflicts() ── u001b[31mβœ–u001b[39m u001b[34mdplyru001b[39m::u001b[32mfilter()u001b[39m masks u001b[34mstatsu001b[39m::filter() u001b[31mβœ–u001b[39m u001b[34mdplyru001b[39m::u001b[32mlag()u001b[39m masks u001b[34mstatsu001b[39m::lag()```Rmtcars1 <- mtcars %>% head() mtcars1 # produces the first five rows in the form of a table```<table><caption>A data.frame: 6 Γ— 11</caption><thead> <tr><th></th><th scope=col>mpg</th><th scope=col>cyl</th><th scope=col>disp</th><th scope=col>hp</th><th scope=col>drat</th><th scope=col>wt</th><th scope=col>qsec</th><th scope=col>vs</th><th scope=col>am</th><th scope=col>gear</th><th scope=col>carb</th></tr> <tr><th></th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th></tr></thead><tbody> <tr><th scope=row>Mazda RX4</th><td>21.0</td><td>6</td><td>160</td><td>110</td><td>3.90</td><td>2.620</td><td>16.46</td><td>0</td><td>1</td><td>4</td><td>4</td></tr> <tr><th scope=row>Mazda RX4 Wag</th><td>21.0</td><td>6</td><td>160</td><td>110</td><td>3.90</td><td>2.875</td><td>17.02</td><td>0</td><td>1</td><td>4</td><td>4</td></tr> <tr><th scope=row>Datsun 710</th><td>22.8</td><td>4</td><td>108</td><td> 93</td><td>3.85</td><td>2.320</td><td>18.61</td><td>1</td><td>1</td><td>4</td><td>1</td></tr> <tr><th scope=row>Hornet 4 Drive</th><td>21.4</td><td>6</td><td>258</td><td>110</td><td>3.08</td><td>3.215</td><td>19.44</td><td>1</td><td>0</td><td>3</td><td>1</td></tr> <tr><th scope=row>Hornet Sportabout</th><td>18.7</td><td>8</td><td>360</td><td>175</td><td>3.15</td><td>3.440</td><td>17.02</td><td>0</td><td>0</td><td>3</td><td>2</td></tr> <tr><th scope=row>Valiant</th><td>18.1</td><td>6</td><td>225</td><td>105</td><td>2.76</td><td>3.460</td><td>20.22</td><td>1</td><td>0</td><td>3</td><td>1</td></tr></tbody></table>```Rmtcars %>% ggplot(aes(x = disp, y = mpg)) + geom_point() + geom_smooth(method = "loess", colour = "blue", se = FALSE) + geom_smooth(method = "lm", colour = "red", se = FALSE) + labs(x = "Engine size", y = "Miles per gallon", title = "Relationship between engine size and milage for cars") + theme_bw() + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + ggsave("test5.png")```Saving 6.67 x 6.67 in image![png](test5_files/test5_3_1.png)```R``` Step 10. We will work on this document and make it β€˜slide worthy’ using the tips and principles from the following two documents: Reveal.js documentation (see https://github.com/hakimel/reveal.js#markdown): from this documentation, these lines are useful for us: It's possible to write your slides using Markdown. To enable Markdown, add the data-markdown attribute to your <section>elements and wrap the contents in a <textarea data-template> like the example below. You'll also need to add the plugin/markdown/marked.js and plugin/markdown/markdown.js scripts (in that order) to your HTML file.<section data-markdown> <textarea data-template> ## Page title A paragraph with some text and a [link](http://hakim.se). </textarea></section> We will see that Pandoc will do that for us. But the documentation goes on, Special syntax (through HTML comments) is available for adding attributes to Markdown elements. This is useful for fragments, amongst other things.<section data-markdown> <script type="text/template"> - Item 1 <!-- .element: class="fragment" data-fragment-index="2" --> - Item 2 <!-- .element: class="fragment" data-fragment-index="1" --> </script></section> This part needs a bit of explanation. Here, revealjs developers are directing your attention to the β€˜markdown elements’ you decide to include within the slide deck, and gives an example of a list element. There are other elements as well (note the list above). You can control each of those elements with these sort of class definitions. But then there are issues around behaviours of entire slides in the deck. This is where they talk about controlling elements like changing background colours, adding a background image as opposed to an image with a title, and so on. Here is the relevant documentation: Slide AttributesSpecial syntax (through HTML comments) is available for adding attributes to the slide <section> elements generated by your Markdown.<section data-markdown> <script type="text/template"> <!-- .slide: data-background="#ff0000" --> Markdown content </script></section> We will make use of this information later in the series to generate pretty slides with interactivity. For now, we will let Pandoc generate what it can. Here is more information from pandoc documentation: Pandoc documentation on creating slide decks (see https://pandoc.org/MANUAL.html#producing-slide-shows-with-pandoc) From pandoc documentation, note: By default, the slide level is the highest heading level in the hierarchy that is followed immediately by content, and not another heading, somewhere in the document. In the example above, level-1 headings are always followed by level-2 headings, which are followed by content, so the slide level is 2. This default can be overridden using the --slide-level option.The document is carved up into slides according to the following rules:* A horizontal rule always starts a new slide.* A heading at the slide level always starts a new slide.* Headings below the slide level in the hierarchy create headings within a slide.* Headings above the slide level in the hierarchy create β€œtitle slides,” which just contain the section title and help to break the slide show into sections. Non-slide content under these headings will be included on the title slide (for HTML slide shows) or in a subsequent slide with the same title (for beamer).* Headings above the slide level in the hierarchy create β€œtitle slides,” which just contain the section title and help to break the slide show into sections. Non-slide content under these headings will be included on the title slide (for HTML slide shows) or in a subsequent slide with the same title (for beamer).* A title page is constructed automatically from the document’s title block, if present. (In the case of beamer, this can be disabled by commenting out some lines in the default template.) Following these rules, it is possible to construct a series of slides that can be modified to suit most of our needs. In this tutorial we will create a simple set of slide deck so we will not into depth of the different options. In subsequent articles, we will explore many ways to β€˜tweak’ the appearance of the slide deck and add interactivity to the slides. Here, in brief, at the least: We willl add a title page We will insert some slide dividers We will remove the code blocks After these changes were put into place, the resulting markdown document looked like this: --- (1)title: A first simple slide deckauthor: Me Myselfdate: 9th August, 2019---## This is the first slide (2)- We will create simple set of slides- Let's analyse some data- Create a figure from the data- Create a table---------- (3)<table><caption>A data.frame: 6 Γ— 11</caption><thead> <tr><th></th><th scope=col>mpg</th><th scope=col>cyl</th><th scope=col>disp</th><th scope=col>hp</th><th scope=col>drat</th><th scope=col>wt</th><th scope=col>qsec</th><th scope=col>vs</th><th scope=col>am</th><th scope=col>gear</th><th scope=col>carb</th></tr> <tr><th></th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th></tr></thead><tbody> <tr><th scope=row>Mazda RX4</th><td>21.0</td><td>6</td><td>160</td><td>110</td><td>3.90</td><td>2.620</td><td>16.46</td><td>0</td><td>1</td><td>4</td><td>4</td></tr> <tr><th scope=row>Mazda RX4 Wag</th><td>21.0</td><td>6</td><td>160</td><td>110</td><td>3.90</td><td>2.875</td><td>17.02</td><td>0</td><td>1</td><td>4</td><td>4</td></tr> <tr><th scope=row>Datsun 710</th><td>22.8</td><td>4</td><td>108</td><td> 93</td><td>3.85</td><td>2.320</td><td>18.61</td><td>1</td><td>1</td><td>4</td><td>1</td></tr> <tr><th scope=row>Hornet 4 Drive</th><td>21.4</td><td>6</td><td>258</td><td>110</td><td>3.08</td><td>3.215</td><td>19.44</td><td>1</td><td>0</td><td>3</td><td>1</td></tr> <tr><th scope=row>Hornet Sportabout</th><td>18.7</td><td>8</td><td>360</td><td>175</td><td>3.15</td><td>3.440</td><td>17.02</td><td>0</td><td>0</td><td>3</td><td>2</td></tr> <tr><th scope=row>Valiant</th><td>18.1</td><td>6</td><td>225</td><td>105</td><td>2.76</td><td>3.460</td><td>20.22</td><td>1</td><td>0</td><td>3</td><td>1</td></tr></tbody></table>------ (4)![Relationship between milage and engine](test5_files/test5_3_1.png) Explanation for this code block: (1) This is the preamble. Pandoc will look for this block first of all and if it cannot find, it will raise a warning. Include at least a title, and a date information, and an author’s name(2) This is the first slide deck with two hashes, states that it is a second level header and as this is followed by content, therefore this is deemed that the base level is 2(3) A separator that will post a table in the next slide(4) A separator that will post a figure in the next slide Step 11. This document is saved as β€˜test5.md’. We will now convert this markdown document to an html using pandoc. For this, we type the following code (assuming that you are in the correct folder): ~$ pandoc -t revealjs -s -o {output filename.html} {input markdown file name} -V revealjs-url={file or absolute URL} So, in our case: pandoc is the programme revealjs = revealjs output file name.html = test5.html input file name = test5.md revealjs-url = ./revealjs (that is the folder where revealjs resides) Hence, we have: ~$ pandoc -t revealjs -s -o test5.html test5.md -V revealjs-url=./revealjs If everything goes OK, this will produce the test5.html file. Step 12. Now we connect our folder to git and commit the folder to our github repository. For this we do: ~$ git checkout -b gh-pages (1)~$ git add . (2)~$ git commit -m "added the slide deck files" (3)~$ git push origin gh-pages (4) Explanation:(1) git checkout is the command you use to switch to the gh-pages branch you created earlier that allowed you to host your slides(2) git add . is the command you use to add EVERYTHING in the git folder(3) git commit -m signals that you add a text to indicate what did you do at that point: this is your version control(4) git push origin gh-pages signifies that you added the files to your gh-pages branch from where they will be published If everything goes OK, your site will now be live after a lag of about a minute (sometimes, it takes longer and patient is a virtue). Assuming that your username is β€˜someusername’ and you created a github repository named β€˜jupyterslidedeck’, your site will be live at: https://someusername.github.io/jupyterslidedeck/test5.html It will look like as follows: So now you have created a slide deck. It is still far from complete as you will see that the table does not look alright, the figure shows the image but it can be better aligned, and so on. You may also want to add additional slides to it, and more interactions. We will address these in the next article in the series. So at least to summarise what we have done: Start a github repository that will contain your slides, say β€˜myslides’Add a submodule to this github repository to your β€˜instance’ or your machine (Mac/Linux/Windows) using the terminal; this will create a folder named β€˜myslides’Change directory (cd) into myslidesGet a copy of revealjs git repo zipped (master.zip) in this folder using wget command and then unzip everything with unzip command and then, rename the reveal.js folder to revealjs (optional)In the myslides folder start a jupyter notebook file and write the slide document with graphs and tables and lists and textConvert the ipynb file to markdown file format using jupyter nbconvert --to markdownOpen the resulting markdown file in Jupyter itself and add a title block, add separators, remove (or you can retain) code blocks and so onUse pandoc to convert the markdown file to html using pandoc -t revealjs -s -o whatever.html whatever.md -V revealjs-url=./revealjsOf course step 8 assumes that whatever.md was your markdown file name, and revealjs was the folder where you downloaded and unzipped the master.zip file from revealjs git repoNow switch to the gh-pages branch, add the files to git repo, commit the changes, and push to your git repo. Your slide decks will be live Start a github repository that will contain your slides, say β€˜myslides’ Add a submodule to this github repository to your β€˜instance’ or your machine (Mac/Linux/Windows) using the terminal; this will create a folder named β€˜myslides’ Change directory (cd) into myslides Get a copy of revealjs git repo zipped (master.zip) in this folder using wget command and then unzip everything with unzip command and then, rename the reveal.js folder to revealjs (optional) In the myslides folder start a jupyter notebook file and write the slide document with graphs and tables and lists and text Convert the ipynb file to markdown file format using jupyter nbconvert --to markdown Open the resulting markdown file in Jupyter itself and add a title block, add separators, remove (or you can retain) code blocks and so on Use pandoc to convert the markdown file to html using pandoc -t revealjs -s -o whatever.html whatever.md -V revealjs-url=./revealjs Of course step 8 assumes that whatever.md was your markdown file name, and revealjs was the folder where you downloaded and unzipped the master.zip file from revealjs git repo Now switch to the gh-pages branch, add the files to git repo, commit the changes, and push to your git repo. Your slide decks will be live From now on, for any changes that you will make to the slides, you can either make them directly to the markdown file and work from there, OR you can make them in the jupyter notebook and re-run steps 6 through 10 in the above list.
[ { "code": null, "e": 417, "s": 171, "text": "... in which I discuss a workflow where you can start writing your contents on a jupyter notebook, create a reveal.js slide deck, and host it on github for presentations. This is for a very simple presentation that you can fully control yourself" }, { "code": null, "e": 511, "s": 417, "text": "Part I: Basic slide deckPart II: Basic slide deck using remarkjsPart III: Advanced techniques" }, { "code": null, "e": 552, "s": 511, "text": "Set up a github repo and add a submodule" }, { "code": null, "e": 952, "s": 552, "text": "Step 1. Start with creating a github repository for hosting your slide deck. To do this, visit https://www.github.com and start a repository and you will also need to install git. I have used a hosted instance on Vultr and it came with a preinstalled git. If you use Windows, Mac, or Linux, you may want to install git or check in your terminal that you have git installed by issuing something like:" }, { "code": null, "e": 966, "s": 952, "text": "git --version" }, { "code": null, "e": 1082, "s": 966, "text": "Step 2. Add a repository. For example, I have created a repository named myJupyterSlides, see the screenshot below:" }, { "code": null, "e": 1373, "s": 1082, "text": "Step 3. (While still using the web interface) It’s a good idea to create an index.md file in the master branch and write that you will keep your slides here in this repository. You can also use a β€œREADME.md” for that purpose. Let’s create a file now. Below you can see the file was created:" }, { "code": null, "e": 1549, "s": 1373, "text": "Step 4. (While still using the web interface), using the web interface, create a new β€˜branch’ named gh-pages (see the screenshot below as to how to create the gh-pages branch)" }, { "code": null, "e": 1841, "s": 1549, "text": "Once you create the gh-pages branch, github automatically creates a website for you. If you click β€œSettings” on your github repository (β€œgithub repo”), it will show that your site is published. For example, if here is the screenshot that shows where my site is published from my github repo:" }, { "code": null, "e": 1905, "s": 1841, "text": "If I were to click on the link, it would show a simple webpage." }, { "code": null, "e": 2199, "s": 1905, "text": "You have now set up a site where your slides will be published. In the next steps, we will make available to our computer (it could be local computer machine or an instance or a virtual machine) a folder using this git repo where we will build the files for our slide deck. Here are the steps:" }, { "code": null, "e": 2584, "s": 2199, "text": "Step 5. Now on your terminal, β€˜clone’ the git repo. First, make a directory (or folder). For example, I made a directory named β€œjupyterslides”. I changed from my current directory to this directory (1). Then initialise a git folder (2). After this add your github repo to this folder as a subfolder (3). You will see that a folder is added whose name is same as your github repo name." }, { "code": null, "e": 2680, "s": 2584, "text": "~$ cd jupyterslides (1)~$ git init (2)~$ git submodule add <your github https repo address> (3)" }, { "code": null, "e": 3310, "s": 2680, "text": "Step 6. Now that you have set up a github repo and you have added that repo as a submodule to your computer or instance, let’s start building the contents of the slide deck. By the time you will complete this tutorial, you will build a simple presentation from the Jupyter notebook that will be displayed over the web. Later, you will see you can build interactivity to this presentation and more advanced features. Unlike Keynote, Powerpoint, or OpenOffice/LibreOffice Impress, you will not use any point and click based system to build such content; you will, instead use plain text tools to build your presentation. Therefore," }, { "code": null, "e": 3369, "s": 3310, "text": "the first step is develop the content in Jupyter notebook." }, { "code": null, "e": 3450, "s": 3369, "text": "The second step is convert this notebook programmatically to a markdown document" }, { "code": null, "e": 3613, "s": 3450, "text": "The third step is to use β€˜pandoc’ (a universal document converter, a.k.a. Swiss Army Knife of document conversion) to convert the document to a set of slide decks" }, { "code": null, "e": 3704, "s": 3613, "text": "The fourth step is to β€˜push’ the contents to the github repo for display over the Internet" }, { "code": null, "e": 3852, "s": 3704, "text": "Step 7: create content in Jupyter notebook. β€” For this tutorial, let’s create a five slide-deck presentation (this is for illustration) containing:" }, { "code": null, "e": 3902, "s": 3852, "text": "A title slide (we will add the title slide later)" }, { "code": null, "e": 3938, "s": 3902, "text": "A slide that contains bullet points" }, { "code": null, "e": 3969, "s": 3938, "text": "A slide that contains an image" }, { "code": null, "e": 3998, "s": 3969, "text": "A slide that contains a link" }, { "code": null, "e": 4028, "s": 3998, "text": "A slide that contains a table" }, { "code": null, "e": 4606, "s": 4028, "text": "I will later show you that you can use these four elements (bullet points, image, link, and table) are basic constituents to create different types of presentations. I will also show you how you can add interactivity to these elements. You can create images, and tables in Jupyter notebooks using markdown or codes written in R or Python or Julia (and indeed in many other languages). So this is a good time to launch into four related issues: how to author contents in markdown, what is reveal.js and why we use it (and there are others as well), and guidance on slide making." }, { "code": null, "e": 4758, "s": 4606, "text": "Markdown is a content authoring system designed to write structured documents on the web. The following elements of a document make up markdown syntax:" }, { "code": null, "e": 5922, "s": 4758, "text": "The following is an example of a table written in Markdown and will be rendered as a table in github flavoured markdown| Element of text | Equivalent Markdown syntax ||--------------------|-----------------------------------|| Heading levels | Usually with ## || First level header | # Example of a first level header || Second level header| ## Second level header || Paragraphs | Text separated by two line spaces || Unnumbered list | * this is an element || Numbered list | 1. This is the first element || Tables | This is a markdown table || Formula | $\\formula$ || Images | ![image alt](image URL) || Hyperlinks | [Link text](URL to be linked) || References | [@bibtex_entry_ID] || Codes | backticks (`code goes here`) || Italic | *text to be italicised* || Bold | **text to be in bold font** || Underline | _text to be underlined_ || Blockquote | > Text to be blockquoted |" }, { "code": null, "e": 6104, "s": 5922, "text": "In the code block above, I have provided you with a list of commonly used markdown conventions. For a longer list and cheatsheet of github flavoured markdown, see the following link" }, { "code": null, "e": 6115, "s": 6104, "text": "github.com" }, { "code": null, "e": 6684, "s": 6115, "text": "In a Jupyter notebook, you can author documents in markdown. Jupyter notebooks use github flavoured markdown and this is what we will use as well. Besides, if you want to use references and citations and if you would like to transfer the documents to other formats that include citations and list of references in it, I recommend you use pandoc to transfer the document from a markdown format to the desired format. You can learn more about pandoc and how to transfer documents using pandoc here. The following youtube video provides you more information about pandoc:" }, { "code": null, "e": 6877, "s": 6684, "text": "We will cover how to use pandoc to create slide decks in a separate section of this document. For now, we will use markdown to write our slides. We will use next reveal.js to style our slides." }, { "code": null, "e": 7000, "s": 6877, "text": "Think of reveal.js as a tool that you will use to render the slides you have created. Revealjs consists of three elements:" }, { "code": null, "e": 7074, "s": 7000, "text": "A CSS (cascading style sheet that renders the appearance of the document)" }, { "code": null, "e": 7130, "s": 7074, "text": "A javascript engine (that renders the slide decks), and" }, { "code": null, "e": 7198, "s": 7130, "text": "An HTML5 document that you will create that will be shown as slides" }, { "code": null, "e": 7329, "s": 7198, "text": "Think of each β€˜slide’ that you will show to be included within the <section> and \\<section> elements. So, it goes like as follows:" }, { "code": null, "e": 7424, "s": 7329, "text": "<html>CSS statements<section>Your slide data will go here ...</section><javacript file></html>" }, { "code": null, "e": 7662, "s": 7424, "text": "This is the basic structure. There are other tools and frameworks as well, please check them out. In this tutorial we will cover revealjs, and in subsequent tutorials, I will cover several of them. Some common and popular frameworks are:" }, { "code": null, "e": 7673, "s": 7662, "text": "Impress.js" }, { "code": null, "e": 7683, "s": 7673, "text": "Shower.js" }, { "code": null, "e": 7691, "s": 7683, "text": "Deck.js" }, { "code": null, "e": 7742, "s": 7691, "text": "Remarkjs (we will cover this in the next tutorial)" }, { "code": null, "e": 7842, "s": 7742, "text": "I will cover these in subsequent posts, so this is the one where we are going to focus on revealjs." }, { "code": null, "e": 7967, "s": 7842, "text": "Step 8. Obtain a copy of reveal.js from their github repo and use wget command in your terminal in Jupyter notebook like so:" }, { "code": null, "e": 8209, "s": 7967, "text": "~$ cd myjupyterslides (1)~$ wget https://github.com/hakimel/reveal.js/archive/master.zip (2)~$ unzip master.zip (3)# this will create a folder named 'reveal.js-master'# rename the folder to 'revealjs' with:~$ mv reveal.js-master revealjs (4)" }, { "code": null, "e": 8246, "s": 8209, "text": "Explanation of the above code block:" }, { "code": null, "e": 8849, "s": 8246, "text": "cd myjupyterslides (1) . β€” You will change directory to get into myjupyterslides where myjupyterslides is the github repository you created earlier and therefore when you added the git submodule, this was added as a folder to your present directorywget <URL> (2) wget is a utility which helps you to download web contents, in this case the master branch of the revealjs repositoryunzip master.zip (3) is self-explanatory, it will unzip the file and add a folder β€˜reveal.js-master’ to the current directorymv reveal.js-master revealjs is a way to β€˜rename’ a folder so now your folder is renamed revaljs." }, { "code": null, "e": 9098, "s": 8849, "text": "cd myjupyterslides (1) . β€” You will change directory to get into myjupyterslides where myjupyterslides is the github repository you created earlier and therefore when you added the git submodule, this was added as a folder to your present directory" }, { "code": null, "e": 9231, "s": 9098, "text": "wget <URL> (2) wget is a utility which helps you to download web contents, in this case the master branch of the revealjs repository" }, { "code": null, "e": 9357, "s": 9231, "text": "unzip master.zip (3) is self-explanatory, it will unzip the file and add a folder β€˜reveal.js-master’ to the current directory" }, { "code": null, "e": 9455, "s": 9357, "text": "mv reveal.js-master revealjs is a way to β€˜rename’ a folder so now your folder is renamed revaljs." }, { "code": null, "e": 9836, "s": 9455, "text": "At the end of this step, you are set to use revealjs to create a local copy of your slide decks. But before we start putting together contents, let’s learn a few points about good practices on creating slide decks and data visualisation. This is a HIGHLY condensed version of what I will discuss in subsequent articles in this series, but will serve our purpose for this tutorial." }, { "code": null, "e": 9913, "s": 9836, "text": "A few things about creating slide decks and data visualisations is in order." }, { "code": null, "e": 9978, "s": 9913, "text": "First, keep in mind the five laws of data ink from Edward Tufte," }, { "code": null, "e": 10117, "s": 9978, "text": "Above all else, show the dataMaximise the data ink ratio (more data per ink flow)Erase non-data inkErase redundant data inkRevise and edit" }, { "code": null, "e": 10147, "s": 10117, "text": "Above all else, show the data" }, { "code": null, "e": 10200, "s": 10147, "text": "Maximise the data ink ratio (more data per ink flow)" }, { "code": null, "e": 10219, "s": 10200, "text": "Erase non-data ink" }, { "code": null, "e": 10244, "s": 10219, "text": "Erase redundant data ink" }, { "code": null, "e": 10260, "s": 10244, "text": "Revise and edit" }, { "code": null, "e": 10351, "s": 10260, "text": "For a more detailed explanation of the above concepts, please review the following source:" }, { "code": null, "e": 10362, "s": 10351, "text": "medium.com" }, { "code": null, "e": 10387, "s": 10362, "text": "Some other tips include:" }, { "code": null, "e": 10439, "s": 10387, "text": "Craft a story with a beginning, a middle and an end" }, { "code": null, "e": 10524, "s": 10439, "text": "Use storyboards to develop your ideas (see work by Garr Reynolds and Cliff Atkinson)" }, { "code": null, "e": 10734, "s": 10524, "text": "Let’s create a simple five slide presentation in jupyter notebook. The syntax is simple and we will create something like as follows (you can see how it looks as a jupyter notebook like by visiting this link )" }, { "code": null, "e": 11436, "s": 10734, "text": "## This is the first slide (1)- We will create simple set of slides- Let's analyse some data- Create a figure from the data- Create a tablelibrary(tidyverse) (2)mtcars1 <- mtcars %>% (3) head() mtcars1 # produces the first five rows in the form of a tablemtcars %>% (4) ggplot(aes(x = disp, y = mpg)) + geom_point() + geom_smooth(method = \"loess\", colour = \"blue\", se = FALSE) + geom_smooth(method = \"lm\", colour = \"red\", se = FALSE) + labs(x = \"Engine size\", y = \"Miles per gallon\", title = \"Relationship between engine size and milage for cars\") + theme_bw() + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + ggsave(\"test5.png\")" }, { "code": null, "e": 11467, "s": 11436, "text": "Explanation of the above code:" }, { "code": null, "e": 11884, "s": 11467, "text": "(1) This is the first slide written in a markdown block. You can move around the blocks so you can in essence have a storyboard built in Jupyter(2) This is written in a code window and calls the tidyverse library in R(3) mtcars1 is a data subset created from mtcars, a large data set on cars; we will use this to demonstrate creation of tables programmatically(4) We use this code to generate a plot programmatically" }, { "code": null, "e": 12324, "s": 11884, "text": "Step 9. After we generate these figures and tables using jupyter notebook and using R within Jupyter notebook, we then export this jupyter notebook to a markdown document. We could use jupyter notebook itself to create a reveal.js set of slide decks, but exporting first to markdown provides you more control on some aspects of the elements o slide creation. You use the following code to convert a jupyter notebook to a markdown document:" }, { "code": null, "e": 12407, "s": 12324, "text": "~$ jupyter nbconvert -t markdown mynotebook.ipynb (1)# generates mynotebook.md (2)" }, { "code": null, "e": 12420, "s": 12407, "text": "Explanation:" }, { "code": null, "e": 12549, "s": 12420, "text": "(1) mynotebook.ipynb is the name of the jupyter notebook I want to convert(2) This will generate mynotebook.md markdown document" }, { "code": null, "e": 12598, "s": 12549, "text": "Now our markdown document looks like as follows:" }, { "code": null, "e": 15948, "s": 12598, "text": "## This is the first slide- We will create simple set of slides- Let's analyse some data- Create a figure from the data- Create a table```Rlibrary(tidyverse)```── u001b[1mAttaching packagesu001b[22m ─────────────────────────────────────── tidyverse 1.2.1 ── u001b[32mβœ”u001b[39m u001b[34mggplot2u001b[39m 3.1.1 u001b[32mβœ”u001b[39m u001b[34mpurrr u001b[39m 0.3.2 u001b[32mβœ”u001b[39m u001b[34mtibble u001b[39m 2.1.3 u001b[32mβœ”u001b[39m u001b[34mdplyr u001b[39m 0.8.1 u001b[32mβœ”u001b[39m u001b[34mtidyr u001b[39m 0.8.3 u001b[32mβœ”u001b[39m u001b[34mstringru001b[39m 1.4.0 u001b[32mβœ”u001b[39m u001b[34mreadr u001b[39m 1.3.1 u001b[32mβœ”u001b[39m u001b[34mforcatsu001b[39m 0.4.0 ── u001b[1mConflictsu001b[22m ────────────────────────────────────────── tidyverse_conflicts() ── u001b[31mβœ–u001b[39m u001b[34mdplyru001b[39m::u001b[32mfilter()u001b[39m masks u001b[34mstatsu001b[39m::filter() u001b[31mβœ–u001b[39m u001b[34mdplyru001b[39m::u001b[32mlag()u001b[39m masks u001b[34mstatsu001b[39m::lag()```Rmtcars1 <- mtcars %>% head() mtcars1 # produces the first five rows in the form of a table```<table><caption>A data.frame: 6 Γ— 11</caption><thead> <tr><th></th><th scope=col>mpg</th><th scope=col>cyl</th><th scope=col>disp</th><th scope=col>hp</th><th scope=col>drat</th><th scope=col>wt</th><th scope=col>qsec</th><th scope=col>vs</th><th scope=col>am</th><th scope=col>gear</th><th scope=col>carb</th></tr> <tr><th></th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th></tr></thead><tbody> <tr><th scope=row>Mazda RX4</th><td>21.0</td><td>6</td><td>160</td><td>110</td><td>3.90</td><td>2.620</td><td>16.46</td><td>0</td><td>1</td><td>4</td><td>4</td></tr> <tr><th scope=row>Mazda RX4 Wag</th><td>21.0</td><td>6</td><td>160</td><td>110</td><td>3.90</td><td>2.875</td><td>17.02</td><td>0</td><td>1</td><td>4</td><td>4</td></tr> <tr><th scope=row>Datsun 710</th><td>22.8</td><td>4</td><td>108</td><td> 93</td><td>3.85</td><td>2.320</td><td>18.61</td><td>1</td><td>1</td><td>4</td><td>1</td></tr> <tr><th scope=row>Hornet 4 Drive</th><td>21.4</td><td>6</td><td>258</td><td>110</td><td>3.08</td><td>3.215</td><td>19.44</td><td>1</td><td>0</td><td>3</td><td>1</td></tr> <tr><th scope=row>Hornet Sportabout</th><td>18.7</td><td>8</td><td>360</td><td>175</td><td>3.15</td><td>3.440</td><td>17.02</td><td>0</td><td>0</td><td>3</td><td>2</td></tr> <tr><th scope=row>Valiant</th><td>18.1</td><td>6</td><td>225</td><td>105</td><td>2.76</td><td>3.460</td><td>20.22</td><td>1</td><td>0</td><td>3</td><td>1</td></tr></tbody></table>```Rmtcars %>% ggplot(aes(x = disp, y = mpg)) + geom_point() + geom_smooth(method = \"loess\", colour = \"blue\", se = FALSE) + geom_smooth(method = \"lm\", colour = \"red\", se = FALSE) + labs(x = \"Engine size\", y = \"Miles per gallon\", title = \"Relationship between engine size and milage for cars\") + theme_bw() + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + ggsave(\"test5.png\")```Saving 6.67 x 6.67 in image![png](test5_files/test5_3_1.png)```R```" }, { "code": null, "e": 16078, "s": 15948, "text": "Step 10. We will work on this document and make it β€˜slide worthy’ using the tips and principles from the following two documents:" }, { "code": null, "e": 16211, "s": 16078, "text": "Reveal.js documentation (see https://github.com/hakimel/reveal.js#markdown): from this documentation, these lines are useful for us:" }, { "code": null, "e": 16689, "s": 16211, "text": "It's possible to write your slides using Markdown. To enable Markdown, add the data-markdown attribute to your <section>elements and wrap the contents in a <textarea data-template> like the example below. You'll also need to add the plugin/markdown/marked.js and plugin/markdown/markdown.js scripts (in that order) to your HTML file.<section data-markdown>\t<textarea data-template>\t\t## Page title\t\tA paragraph with some text and a [link](http://hakim.se).\t</textarea></section>" }, { "code": null, "e": 16765, "s": 16689, "text": "We will see that Pandoc will do that for us. But the documentation goes on," }, { "code": null, "e": 17126, "s": 16765, "text": "Special syntax (through HTML comments) is available for adding attributes to Markdown elements. This is useful for fragments, amongst other things.<section data-markdown>\t<script type=\"text/template\">\t\t- Item 1 <!-- .element: class=\"fragment\" data-fragment-index=\"2\" -->\t\t- Item 2 <!-- .element: class=\"fragment\" data-fragment-index=\"1\" -->\t</script></section>" }, { "code": null, "e": 17733, "s": 17126, "text": "This part needs a bit of explanation. Here, revealjs developers are directing your attention to the β€˜markdown elements’ you decide to include within the slide deck, and gives an example of a list element. There are other elements as well (note the list above). You can control each of those elements with these sort of class definitions. But then there are issues around behaviours of entire slides in the deck. This is where they talk about controlling elements like changing background colours, adding a background image as opposed to an image with a title, and so on. Here is the relevant documentation:" }, { "code": null, "e": 18017, "s": 17733, "text": "Slide AttributesSpecial syntax (through HTML comments) is available for adding attributes to the slide <section> elements generated by your Markdown.<section data-markdown>\t<script type=\"text/template\">\t<!-- .slide: data-background=\"#ff0000\" -->\t\tMarkdown content\t</script></section>" }, { "code": null, "e": 18222, "s": 18017, "text": "We will make use of this information later in the series to generate pretty slides with interactivity. For now, we will let Pandoc generate what it can. Here is more information from pandoc documentation:" }, { "code": null, "e": 18338, "s": 18222, "text": "Pandoc documentation on creating slide decks (see https://pandoc.org/MANUAL.html#producing-slide-shows-with-pandoc)" }, { "code": null, "e": 18371, "s": 18338, "text": "From pandoc documentation, note:" }, { "code": null, "e": 19808, "s": 18371, "text": "By default, the slide level is the highest heading level in the hierarchy that is followed immediately by content, and not another heading, somewhere in the document. In the example above, level-1 headings are always followed by level-2 headings, which are followed by content, so the slide level is 2. This default can be overridden using the --slide-level option.The document is carved up into slides according to the following rules:* A horizontal rule always starts a new slide.* A heading at the slide level always starts a new slide.* Headings below the slide level in the hierarchy create headings within a slide.* Headings above the slide level in the hierarchy create β€œtitle slides,” which just contain the section title and help to break the slide show into sections. Non-slide content under these headings will be included on the title slide (for HTML slide shows) or in a subsequent slide with the same title (for beamer).* Headings above the slide level in the hierarchy create β€œtitle slides,” which just contain the section title and help to break the slide show into sections. Non-slide content under these headings will be included on the title slide (for HTML slide shows) or in a subsequent slide with the same title (for beamer).* A title page is constructed automatically from the document’s title block, if present. (In the case of beamer, this can be disabled by commenting out some lines in the default template.)" }, { "code": null, "e": 20168, "s": 19808, "text": "Following these rules, it is possible to construct a series of slides that can be modified to suit most of our needs. In this tutorial we will create a simple set of slide deck so we will not into depth of the different options. In subsequent articles, we will explore many ways to β€˜tweak’ the appearance of the slide deck and add interactivity to the slides." }, { "code": null, "e": 20198, "s": 20168, "text": "Here, in brief, at the least:" }, { "code": null, "e": 20224, "s": 20198, "text": "We willl add a title page" }, { "code": null, "e": 20259, "s": 20224, "text": "We will insert some slide dividers" }, { "code": null, "e": 20290, "s": 20259, "text": "We will remove the code blocks" }, { "code": null, "e": 20381, "s": 20290, "text": "After these changes were put into place, the resulting markdown document looked like this:" }, { "code": null, "e": 22401, "s": 20381, "text": "--- (1)title: A first simple slide deckauthor: Me Myselfdate: 9th August, 2019---## This is the first slide (2)- We will create simple set of slides- Let's analyse some data- Create a figure from the data- Create a table---------- (3)<table><caption>A data.frame: 6 Γ— 11</caption><thead> <tr><th></th><th scope=col>mpg</th><th scope=col>cyl</th><th scope=col>disp</th><th scope=col>hp</th><th scope=col>drat</th><th scope=col>wt</th><th scope=col>qsec</th><th scope=col>vs</th><th scope=col>am</th><th scope=col>gear</th><th scope=col>carb</th></tr> <tr><th></th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th><th scope=col>&lt;dbl&gt;</th></tr></thead><tbody> <tr><th scope=row>Mazda RX4</th><td>21.0</td><td>6</td><td>160</td><td>110</td><td>3.90</td><td>2.620</td><td>16.46</td><td>0</td><td>1</td><td>4</td><td>4</td></tr> <tr><th scope=row>Mazda RX4 Wag</th><td>21.0</td><td>6</td><td>160</td><td>110</td><td>3.90</td><td>2.875</td><td>17.02</td><td>0</td><td>1</td><td>4</td><td>4</td></tr> <tr><th scope=row>Datsun 710</th><td>22.8</td><td>4</td><td>108</td><td> 93</td><td>3.85</td><td>2.320</td><td>18.61</td><td>1</td><td>1</td><td>4</td><td>1</td></tr> <tr><th scope=row>Hornet 4 Drive</th><td>21.4</td><td>6</td><td>258</td><td>110</td><td>3.08</td><td>3.215</td><td>19.44</td><td>1</td><td>0</td><td>3</td><td>1</td></tr> <tr><th scope=row>Hornet Sportabout</th><td>18.7</td><td>8</td><td>360</td><td>175</td><td>3.15</td><td>3.440</td><td>17.02</td><td>0</td><td>0</td><td>3</td><td>2</td></tr> <tr><th scope=row>Valiant</th><td>18.1</td><td>6</td><td>225</td><td>105</td><td>2.76</td><td>3.460</td><td>20.22</td><td>1</td><td>0</td><td>3</td><td>1</td></tr></tbody></table>------ (4)![Relationship between milage and engine](test5_files/test5_3_1.png)" }, { "code": null, "e": 22434, "s": 22401, "text": "Explanation for this code block:" }, { "code": null, "e": 22912, "s": 22434, "text": "(1) This is the preamble. Pandoc will look for this block first of all and if it cannot find, it will raise a warning. Include at least a title, and a date information, and an author’s name(2) This is the first slide deck with two hashes, states that it is a second level header and as this is followed by content, therefore this is deemed that the base level is 2(3) A separator that will post a table in the next slide(4) A separator that will post a figure in the next slide" }, { "code": null, "e": 23111, "s": 22912, "text": "Step 11. This document is saved as β€˜test5.md’. We will now convert this markdown document to an html using pandoc. For this, we type the following code (assuming that you are in the correct folder):" }, { "code": null, "e": 23228, "s": 23111, "text": "~$ pandoc -t revealjs -s -o {output filename.html} {input markdown file name} -V revealjs-url={file or absolute URL}" }, { "code": null, "e": 23245, "s": 23228, "text": "So, in our case:" }, { "code": null, "e": 23269, "s": 23245, "text": "pandoc is the programme" }, { "code": null, "e": 23289, "s": 23269, "text": "revealjs = revealjs" }, { "code": null, "e": 23324, "s": 23289, "text": "output file name.html = test5.html" }, { "code": null, "e": 23351, "s": 23324, "text": "input file name = test5.md" }, { "code": null, "e": 23421, "s": 23351, "text": "revealjs-url = ./revealjs (that is the folder where revealjs resides)" }, { "code": null, "e": 23437, "s": 23421, "text": "Hence, we have:" }, { "code": null, "e": 23512, "s": 23437, "text": "~$ pandoc -t revealjs -s -o test5.html test5.md -V revealjs-url=./revealjs" }, { "code": null, "e": 23574, "s": 23512, "text": "If everything goes OK, this will produce the test5.html file." }, { "code": null, "e": 23680, "s": 23574, "text": "Step 12. Now we connect our folder to git and commit the folder to our github repository. For this we do:" }, { "code": null, "e": 23808, "s": 23680, "text": "~$ git checkout -b gh-pages (1)~$ git add . (2)~$ git commit -m \"added the slide deck files\" (3)~$ git push origin gh-pages (4)" }, { "code": null, "e": 24260, "s": 23808, "text": "Explanation:(1) git checkout is the command you use to switch to the gh-pages branch you created earlier that allowed you to host your slides(2) git add . is the command you use to add EVERYTHING in the git folder(3) git commit -m signals that you add a text to indicate what did you do at that point: this is your version control(4) git push origin gh-pages signifies that you added the files to your gh-pages branch from where they will be published" }, { "code": null, "e": 24529, "s": 24260, "text": "If everything goes OK, your site will now be live after a lag of about a minute (sometimes, it takes longer and patient is a virtue). Assuming that your username is β€˜someusername’ and you created a github repository named β€˜jupyterslidedeck’, your site will be live at:" }, { "code": null, "e": 24588, "s": 24529, "text": "https://someusername.github.io/jupyterslidedeck/test5.html" }, { "code": null, "e": 24618, "s": 24588, "text": "It will look like as follows:" }, { "code": null, "e": 24982, "s": 24618, "text": "So now you have created a slide deck. It is still far from complete as you will see that the table does not look alright, the figure shows the image but it can be better aligned, and so on. You may also want to add additional slides to it, and more interactions. We will address these in the next article in the series. So at least to summarise what we have done:" }, { "code": null, "e": 26228, "s": 24982, "text": "Start a github repository that will contain your slides, say β€˜myslides’Add a submodule to this github repository to your β€˜instance’ or your machine (Mac/Linux/Windows) using the terminal; this will create a folder named β€˜myslides’Change directory (cd) into myslidesGet a copy of revealjs git repo zipped (master.zip) in this folder using wget command and then unzip everything with unzip command and then, rename the reveal.js folder to revealjs (optional)In the myslides folder start a jupyter notebook file and write the slide document with graphs and tables and lists and textConvert the ipynb file to markdown file format using jupyter nbconvert --to markdownOpen the resulting markdown file in Jupyter itself and add a title block, add separators, remove (or you can retain) code blocks and so onUse pandoc to convert the markdown file to html using pandoc -t revealjs -s -o whatever.html whatever.md -V revealjs-url=./revealjsOf course step 8 assumes that whatever.md was your markdown file name, and revealjs was the folder where you downloaded and unzipped the master.zip file from revealjs git repoNow switch to the gh-pages branch, add the files to git repo, commit the changes, and push to your git repo. Your slide decks will be live" }, { "code": null, "e": 26300, "s": 26228, "text": "Start a github repository that will contain your slides, say β€˜myslides’" }, { "code": null, "e": 26460, "s": 26300, "text": "Add a submodule to this github repository to your β€˜instance’ or your machine (Mac/Linux/Windows) using the terminal; this will create a folder named β€˜myslides’" }, { "code": null, "e": 26496, "s": 26460, "text": "Change directory (cd) into myslides" }, { "code": null, "e": 26688, "s": 26496, "text": "Get a copy of revealjs git repo zipped (master.zip) in this folder using wget command and then unzip everything with unzip command and then, rename the reveal.js folder to revealjs (optional)" }, { "code": null, "e": 26812, "s": 26688, "text": "In the myslides folder start a jupyter notebook file and write the slide document with graphs and tables and lists and text" }, { "code": null, "e": 26897, "s": 26812, "text": "Convert the ipynb file to markdown file format using jupyter nbconvert --to markdown" }, { "code": null, "e": 27036, "s": 26897, "text": "Open the resulting markdown file in Jupyter itself and add a title block, add separators, remove (or you can retain) code blocks and so on" }, { "code": null, "e": 27168, "s": 27036, "text": "Use pandoc to convert the markdown file to html using pandoc -t revealjs -s -o whatever.html whatever.md -V revealjs-url=./revealjs" }, { "code": null, "e": 27344, "s": 27168, "text": "Of course step 8 assumes that whatever.md was your markdown file name, and revealjs was the folder where you downloaded and unzipped the master.zip file from revealjs git repo" }, { "code": null, "e": 27483, "s": 27344, "text": "Now switch to the gh-pages branch, add the files to git repo, commit the changes, and push to your git repo. Your slide decks will be live" } ]
Building a Data Lake on GCP with CDAP | by Deepesh Nair | Towards Data Science
It is no secret that traditional platforms for data analysis, like data warehouses, are difficult and expensive to scale, to meet the current data demands for storage and compute. And purpose-built platforms designed to process big data often require significant up-front and on-going investment if deployed on-premise. Alternatively, cloud computing is the perfect vehicle to scale and accommodate such large volumes of data in an economical way. While the economics are right, enterprises migrating their on-premises data warehouses or building a new warehouse or data lake in the cloud face many challenges along the way. These range from architecting network, securing critical data, having the right skill sets to work with the chosen cloud technologies, to figuring out the right set of tools and technologies to create operational workflows to load, transform and blend data. Technology is nothing. What’s important is that you have a faith in people, that they’re basically good and smart, and if you give them right tools, they’ll do wonderful things with them. β€” Steve Jobs Businesses are more dependent on data than ever before. Having the right toolsets empowering the right people makes data readily available for better and faster decision-making. Choosing the right toolsets that make integration simple and allow them to focus on solving their business challenges rather than focusing on infrastructure and technology is one of the most important steps in migrating a data warehouse to the cloud or building one in the cloud. In this blog post, we will talk about how CDAP (Cask Data Application Platform) seamlessly integrates with Google Cloud Platform (GCP) technologies to build a data lake in the cloud. We will look at how CDAP helps data management professionals to maximise the value of their investments in GCP by integrating more data using CDAP to achieve their business objective of migrating or building data lake on GCP. The CDAP Pipeline (Workflows) is a data orchestration capability that moves, transforms, blends and enriches data. CDAP Pipelines manage the scheduling, orchestration, and monitoring of all pipeline activities, as well as handle failure scenarios. CDAP Pipelines offer a collection of hundreds of pre-built connectors, simplified stream processing on top of open-source streaming engines, as well as new out-of-the-box connectivity to BigTable, BigQuery, Google Cloud Storage, Google PubSub and other GCP technologies. Thus, they enable users to integrate nearly any data, anywhere in a Google Cloud environment. Governance is an important requirement of any data lake or data warehouse, whether it is deployed on-premises or in the cloud. The ability to automatically capture and index technical, business and operational metadata for any pipelines built within CDAP makes it easy to discover datasets, perform impact analysis, trace the lineage of a dataset, and create audit trails. So, let’s look at some of the capabilities recently added in CDAP to integrate with Google Cloud Platform technologies. With Cask, having seamless workflows that optimise macro user-flows provide a complete and fun experience whilst working with complex technologies. It was observed first hand with customers that in doing so they achieve higher efficiencies, reduced operating cost, less user frustration and ultimately the democratisation of access to data, which leads to greater value from the data faster. In the spirit of achieving higher efficiency, lets first integrate CDAP’s Data Prep capability with Google Cloud Storage. Google Cloud Storage (GCS) is unified object storage that supports a wide variety of unstructured data in the areas of content distribution, backup and archiving, disaster recovery, and big data analytics, among others. You can use CDAP Pipelines to move and synchronise data into and out of GCS for analytics, applications, and a broad range of use cases. With CDAP, you can quickly and reliably streamline workflows and operations or use the same flow to move your customer or vendor data from Amazon S3, Azure ADLS or WASB into Google Cloud Storage. CDAP Pipelines provide plugins for integrating with GCS natively, irrespective of whether you are working with structured or unstructured data. They also provide seamless integration with CDAP Data Prep capabilities and make it easy to create a GCS connection to your project, browse GCS, and immediately wrangle your data without having to use code or move to another console. Watch the screencast below to understand the flow of integration with respect to CDAP Data Prep and CDAP Pipelines and GCS. In addition to integration with CDAP Data Prep, the following CDAP plugins are available to work with GCS: GCS Text File Source β€” A source plugin that allows users to read plain text files stored on GCS. Files can be CSV, tab delimited, line separated JSON, fixed length, etc. GCS Binary File Source β€” A source plugin that allows users to read files as blobs stored on GCS. Files like XML, AVRO, Protobuf, Image, and Audio files can be read. CDAP Data Prep automatically determines the file type and uses the right source depending on the file extension and the content type of the file. Below is a simple pipeline and configuration associated with GCS Text File Source for your reference. Another important component of the Google Cloud Platform is Google BigQuery. Google BigQuery is a serverless, fully-managed petabyte-scale data warehouse which empowers enterprises to execute all their data warehousing operations in a highly concurrent manner. With CDAP’s native Google BigQuery connector, Spark, Spark Streaming, and MapReduce jobs can be used to load massive amounts of data into BigQuery rapidly. CDAP’s support for nested schemas and complex schemas allows diverse data types to be analyzed in BigQuery efficiently. The schemas of the dataset tables are seamlessly made available to users while configuring the plugins. New tables within datasets can be created without additional effort. The above pipeline reads the New York Trips Dataset (available as a public dataset on Google BigQuery), performs some transformations and calculations on the cluster, and writes the results back into Google BigQuery. This example might not be highly relevant to a real use case since you could use BigQuery SQL to do what is being done here, but this pipeline is for demonstration purposes only, to show that sources and sinks for Google BigQuery are available to read from and write to. These BigQuery plugins provide simplicity in terms of importing metadata from BigQuery and automatically creating tables along with right schema based on pipeline schema. Google PubSub is a fully-managed real-time messaging service that lets you ingest data from sensors, logs, and clickstreams into your data lake. CDAP’s support for Spark Streaming, Kafka, MQTT, and native connectivity to Google PubSub makes it easy to combine historical data with real-time data, for a complete 360-degree view of your customers. It also makes it easy to move the data between on-premises and the cloud. Following is a simple real-time CDAP Data Pipeline used for pushing data up to Google Cloud Platform PubSub from on-premises Kafka in real time. The data published is readily and immediately available to be consumed for further transformation and processing. Over the past decades, enterprises have installed appliances and other pre-configured hardware for data warehousing. The goal for these solutions, which often required heavy investments in proprietary technology, was to make it easier to manage and analyse data. However, recent advancements in open source technology that provide less expensive ways for storing and processing massive amounts of data have broken down the enterprise walls, allowing enterprises to question the cost of expensive hardware.This time, instead of replacing legacy systems with new hardware, enterprises are looking to move to the cloud to build their data lakes when it makes sense for them. But, the right tooling is needed to support the many possible use cases of a data warehouse in the cloud. Four things are needed to efficiently and reliably offload data from an on-premises data warehouse to the cloud: Ease of loading data and of keeping it updated Query tools that support faster queries on Small & Large Dataset Support for High Concurrency without degradation in performance A custom reporting and dashboard tool. Google BigTable in combination with Google BigQuery provides the ability to support bulk loads, and upserts along with the ability to query the data loaded at scale. For reporting and dashboards, Google Data Studio or any other popular BI tools can be used in combination with Google Query to satisfy many of the reporting needs. Now, the main problem is how an enterprise can efficiently offload data from their on-premise warehouses into BigTable and keep the data in BigTable in sync. To support the EDW Offload to BigTable use case, CDAP provides capabilities to perform Change Data Capture (CDC) on relational databases and data pipelines, and plugins for consuming the change data events and updating the corresponding Google BigTable instance to keep the data in sync. The change data capture solutions can use one of three approaches for capturing changes in the source databases: Transactional Log in the source table via Oracle Golden GateQuerying REDO logs via Oracle Log Miner orUsing change tracking to track the changes for SQL Server Transactional Log in the source table via Oracle Golden Gate Querying REDO logs via Oracle Log Miner or Using change tracking to track the changes for SQL Server The first solution reads the database transactional logs and publishes all the DDL and DML operations into Kafka or Google PubSub. The real-time CDAP Data Pipeline consumes these changesets from Kafka or Google PubSub, normalises and performs the corresponding operations for inserts, updates, and deletes to BigTable using the CDC BigTable Sink plugin. Following is a pipeline that reads the changesets from a streaming source and writes them to BigTable recreating all the table updates and keep them in sync. To query from BigQuery, add the tables as an external table. More information on how-to is available here. There are multiple reasons why an enterprise might decide to migrate from one public cloud platform to another or to choose more than one cloud provider. One reason might be that a different public cloud provider offers better pricing than the current provider or a better match in terms of services offered. Another common case is an enterprise recently went through a merger, and the acquirer already has a preference for their public cloud provider. Regardless of the reasons, one way to ease migration or support more than one cloud is to start with a multi-cloud data management platform that integrates with cloud environments. By using a multi-cloud data management solution, such as CDAP, you can seamlessly create an abstraction that hides the underlying cloud differences and allows simple migration of workflows and data. Adopting such a platform from the get-go is extremely valuable in a hybrid cloud environment, where you may be managing on-premises, (hosted) private as well as public clouds. Building workflows that can efficiently and reliably migrate data from one public cloud store to another are simple with CDAP Pipelines. Following is an example that shows how data from Amazon S3 can be migrated into GCS and, during the process, can be transformed and stored in Google BigQuery. After the pipeline is executed the results of execution of the pipeline are available on GCS and as well as within BigQuery. Transcription is the best way to convert your recorded audio into highly accurate, searchable and readable text; being able to index and search through audio content is useful because it helps your users find relevant content. It can be used to boost organic traffic, improve accessibility, and also enhance your AI by transcribing audio files to provide better service to your customers. Let’s say you have a company that offers customer support services and you are recording random customer conversations to improve the quality of service in order to get better insights into how representatives handle calls. The first step as part of improving the service is to transcribe the recorded audio files into digitised readable text. Further, the text can go through various AI / ML workflows to determine the mood of the call, customer sentiment, resolution latency, and more. Google Cloud Speech API uses powerful neural network models to convert audio to text. It recognises over 110 languages and variants, to support your global user base. Simplifying the transcribing of massive amounts of recorded audio files, Google Cloud Platform technologies and CDAP together provide users with an integrated, scalable and code-free way to transcribe audio files. This integration allows users to build pipelines that can be scheduled and monitored with ease, for any production deployment, in minutes to hours, rather than weeks or months. Below is a simple CDAP Pipeline that takes the raw audio files stored on Google Cloud Storage, passes it through Google Speech Translator plugin, and writes the transcribed text to another location on Google Cloud Storage. The Google Speech Translator CDAP plugin is ready to go with a minor configuration of settings depending on the types of the files being recorded. The translation applied to the raw audio file in the above example generates a JSON output that describes the file that was transcribed, with the computed confidence for the transcription. { "path": "/audio/raw/audio.raw", "speeches": [ { "confidence": 0.9876289963722229, "transcript": "how old is the Brooklyn Bridge" } ]} Case Study: Data Lake, XML Transform, Data Discovery , Security Analytics Guide : Kafka consumption, Twitter data, Data Processing with Flow & Flume Code examples : TwitterSentiment , MovieRecommender , Netlens, Wise Tutorial : Fraud ML Classification, Migrate S3 to ADLS, EDW Optimization API : CDAP API and Dependent Packages If you are using or evaluating GCP and are looking for ways to improve your integration on GCP, you may want to try out CDAP and install GCP connectors from Cask Market today. Also, If you’re Developer or Data Engineer/Scientist , you can proceed by downloading the CDAP Local Sandbox Originally published at blog.cdap.io.
[ { "code": null, "e": 1054, "s": 171, "text": "It is no secret that traditional platforms for data analysis, like data warehouses, are difficult and expensive to scale, to meet the current data demands for storage and compute. And purpose-built platforms designed to process big data often require significant up-front and on-going investment if deployed on-premise. Alternatively, cloud computing is the perfect vehicle to scale and accommodate such large volumes of data in an economical way. While the economics are right, enterprises migrating their on-premises data warehouses or building a new warehouse or data lake in the cloud face many challenges along the way. These range from architecting network, securing critical data, having the right skill sets to work with the chosen cloud technologies, to figuring out the right set of tools and technologies to create operational workflows to load, transform and blend data." }, { "code": null, "e": 1255, "s": 1054, "text": "Technology is nothing. What’s important is that you have a faith in people, that they’re basically good and smart, and if you give them right tools, they’ll do wonderful things with them. β€” Steve Jobs" }, { "code": null, "e": 1713, "s": 1255, "text": "Businesses are more dependent on data than ever before. Having the right toolsets empowering the right people makes data readily available for better and faster decision-making. Choosing the right toolsets that make integration simple and allow them to focus on solving their business challenges rather than focusing on infrastructure and technology is one of the most important steps in migrating a data warehouse to the cloud or building one in the cloud." }, { "code": null, "e": 2122, "s": 1713, "text": "In this blog post, we will talk about how CDAP (Cask Data Application Platform) seamlessly integrates with Google Cloud Platform (GCP) technologies to build a data lake in the cloud. We will look at how CDAP helps data management professionals to maximise the value of their investments in GCP by integrating more data using CDAP to achieve their business objective of migrating or building data lake on GCP." }, { "code": null, "e": 2735, "s": 2122, "text": "The CDAP Pipeline (Workflows) is a data orchestration capability that moves, transforms, blends and enriches data. CDAP Pipelines manage the scheduling, orchestration, and monitoring of all pipeline activities, as well as handle failure scenarios. CDAP Pipelines offer a collection of hundreds of pre-built connectors, simplified stream processing on top of open-source streaming engines, as well as new out-of-the-box connectivity to BigTable, BigQuery, Google Cloud Storage, Google PubSub and other GCP technologies. Thus, they enable users to integrate nearly any data, anywhere in a Google Cloud environment." }, { "code": null, "e": 3108, "s": 2735, "text": "Governance is an important requirement of any data lake or data warehouse, whether it is deployed on-premises or in the cloud. The ability to automatically capture and index technical, business and operational metadata for any pipelines built within CDAP makes it easy to discover datasets, perform impact analysis, trace the lineage of a dataset, and create audit trails." }, { "code": null, "e": 3228, "s": 3108, "text": "So, let’s look at some of the capabilities recently added in CDAP to integrate with Google Cloud Platform technologies." }, { "code": null, "e": 3742, "s": 3228, "text": "With Cask, having seamless workflows that optimise macro user-flows provide a complete and fun experience whilst working with complex technologies. It was observed first hand with customers that in doing so they achieve higher efficiencies, reduced operating cost, less user frustration and ultimately the democratisation of access to data, which leads to greater value from the data faster. In the spirit of achieving higher efficiency, lets first integrate CDAP’s Data Prep capability with Google Cloud Storage." }, { "code": null, "e": 4295, "s": 3742, "text": "Google Cloud Storage (GCS) is unified object storage that supports a wide variety of unstructured data in the areas of content distribution, backup and archiving, disaster recovery, and big data analytics, among others. You can use CDAP Pipelines to move and synchronise data into and out of GCS for analytics, applications, and a broad range of use cases. With CDAP, you can quickly and reliably streamline workflows and operations or use the same flow to move your customer or vendor data from Amazon S3, Azure ADLS or WASB into Google Cloud Storage." }, { "code": null, "e": 4673, "s": 4295, "text": "CDAP Pipelines provide plugins for integrating with GCS natively, irrespective of whether you are working with structured or unstructured data. They also provide seamless integration with CDAP Data Prep capabilities and make it easy to create a GCS connection to your project, browse GCS, and immediately wrangle your data without having to use code or move to another console." }, { "code": null, "e": 4797, "s": 4673, "text": "Watch the screencast below to understand the flow of integration with respect to CDAP Data Prep and CDAP Pipelines and GCS." }, { "code": null, "e": 4904, "s": 4797, "text": "In addition to integration with CDAP Data Prep, the following CDAP plugins are available to work with GCS:" }, { "code": null, "e": 5074, "s": 4904, "text": "GCS Text File Source β€” A source plugin that allows users to read plain text files stored on GCS. Files can be CSV, tab delimited, line separated JSON, fixed length, etc." }, { "code": null, "e": 5239, "s": 5074, "text": "GCS Binary File Source β€” A source plugin that allows users to read files as blobs stored on GCS. Files like XML, AVRO, Protobuf, Image, and Audio files can be read." }, { "code": null, "e": 5487, "s": 5239, "text": "CDAP Data Prep automatically determines the file type and uses the right source depending on the file extension and the content type of the file. Below is a simple pipeline and configuration associated with GCS Text File Source for your reference." }, { "code": null, "e": 6197, "s": 5487, "text": "Another important component of the Google Cloud Platform is Google BigQuery. Google BigQuery is a serverless, fully-managed petabyte-scale data warehouse which empowers enterprises to execute all their data warehousing operations in a highly concurrent manner. With CDAP’s native Google BigQuery connector, Spark, Spark Streaming, and MapReduce jobs can be used to load massive amounts of data into BigQuery rapidly. CDAP’s support for nested schemas and complex schemas allows diverse data types to be analyzed in BigQuery efficiently. The schemas of the dataset tables are seamlessly made available to users while configuring the plugins. New tables within datasets can be created without additional effort." }, { "code": null, "e": 6685, "s": 6197, "text": "The above pipeline reads the New York Trips Dataset (available as a public dataset on Google BigQuery), performs some transformations and calculations on the cluster, and writes the results back into Google BigQuery. This example might not be highly relevant to a real use case since you could use BigQuery SQL to do what is being done here, but this pipeline is for demonstration purposes only, to show that sources and sinks for Google BigQuery are available to read from and write to." }, { "code": null, "e": 6856, "s": 6685, "text": "These BigQuery plugins provide simplicity in terms of importing metadata from BigQuery and automatically creating tables along with right schema based on pipeline schema." }, { "code": null, "e": 7277, "s": 6856, "text": "Google PubSub is a fully-managed real-time messaging service that lets you ingest data from sensors, logs, and clickstreams into your data lake. CDAP’s support for Spark Streaming, Kafka, MQTT, and native connectivity to Google PubSub makes it easy to combine historical data with real-time data, for a complete 360-degree view of your customers. It also makes it easy to move the data between on-premises and the cloud." }, { "code": null, "e": 7536, "s": 7277, "text": "Following is a simple real-time CDAP Data Pipeline used for pushing data up to Google Cloud Platform PubSub from on-premises Kafka in real time. The data published is readily and immediately available to be consumed for further transformation and processing." }, { "code": null, "e": 8427, "s": 7536, "text": "Over the past decades, enterprises have installed appliances and other pre-configured hardware for data warehousing. The goal for these solutions, which often required heavy investments in proprietary technology, was to make it easier to manage and analyse data. However, recent advancements in open source technology that provide less expensive ways for storing and processing massive amounts of data have broken down the enterprise walls, allowing enterprises to question the cost of expensive hardware.This time, instead of replacing legacy systems with new hardware, enterprises are looking to move to the cloud to build their data lakes when it makes sense for them. But, the right tooling is needed to support the many possible use cases of a data warehouse in the cloud. Four things are needed to efficiently and reliably offload data from an on-premises data warehouse to the cloud:" }, { "code": null, "e": 8474, "s": 8427, "text": "Ease of loading data and of keeping it updated" }, { "code": null, "e": 8539, "s": 8474, "text": "Query tools that support faster queries on Small & Large Dataset" }, { "code": null, "e": 8603, "s": 8539, "text": "Support for High Concurrency without degradation in performance" }, { "code": null, "e": 8642, "s": 8603, "text": "A custom reporting and dashboard tool." }, { "code": null, "e": 8972, "s": 8642, "text": "Google BigTable in combination with Google BigQuery provides the ability to support bulk loads, and upserts along with the ability to query the data loaded at scale. For reporting and dashboards, Google Data Studio or any other popular BI tools can be used in combination with Google Query to satisfy many of the reporting needs." }, { "code": null, "e": 9531, "s": 8972, "text": "Now, the main problem is how an enterprise can efficiently offload data from their on-premise warehouses into BigTable and keep the data in BigTable in sync. To support the EDW Offload to BigTable use case, CDAP provides capabilities to perform Change Data Capture (CDC) on relational databases and data pipelines, and plugins for consuming the change data events and updating the corresponding Google BigTable instance to keep the data in sync. The change data capture solutions can use one of three approaches for capturing changes in the source databases:" }, { "code": null, "e": 9691, "s": 9531, "text": "Transactional Log in the source table via Oracle Golden GateQuerying REDO logs via Oracle Log Miner orUsing change tracking to track the changes for SQL Server" }, { "code": null, "e": 9752, "s": 9691, "text": "Transactional Log in the source table via Oracle Golden Gate" }, { "code": null, "e": 9795, "s": 9752, "text": "Querying REDO logs via Oracle Log Miner or" }, { "code": null, "e": 9853, "s": 9795, "text": "Using change tracking to track the changes for SQL Server" }, { "code": null, "e": 10207, "s": 9853, "text": "The first solution reads the database transactional logs and publishes all the DDL and DML operations into Kafka or Google PubSub. The real-time CDAP Data Pipeline consumes these changesets from Kafka or Google PubSub, normalises and performs the corresponding operations for inserts, updates, and deletes to BigTable using the CDC BigTable Sink plugin." }, { "code": null, "e": 10365, "s": 10207, "text": "Following is a pipeline that reads the changesets from a streaming source and writes them to BigTable recreating all the table updates and keep them in sync." }, { "code": null, "e": 10472, "s": 10365, "text": "To query from BigQuery, add the tables as an external table. More information on how-to is available here." }, { "code": null, "e": 11481, "s": 10472, "text": "There are multiple reasons why an enterprise might decide to migrate from one public cloud platform to another or to choose more than one cloud provider. One reason might be that a different public cloud provider offers better pricing than the current provider or a better match in terms of services offered. Another common case is an enterprise recently went through a merger, and the acquirer already has a preference for their public cloud provider. Regardless of the reasons, one way to ease migration or support more than one cloud is to start with a multi-cloud data management platform that integrates with cloud environments. By using a multi-cloud data management solution, such as CDAP, you can seamlessly create an abstraction that hides the underlying cloud differences and allows simple migration of workflows and data. Adopting such a platform from the get-go is extremely valuable in a hybrid cloud environment, where you may be managing on-premises, (hosted) private as well as public clouds." }, { "code": null, "e": 11777, "s": 11481, "text": "Building workflows that can efficiently and reliably migrate data from one public cloud store to another are simple with CDAP Pipelines. Following is an example that shows how data from Amazon S3 can be migrated into GCS and, during the process, can be transformed and stored in Google BigQuery." }, { "code": null, "e": 11902, "s": 11777, "text": "After the pipeline is executed the results of execution of the pipeline are available on GCS and as well as within BigQuery." }, { "code": null, "e": 12291, "s": 11902, "text": "Transcription is the best way to convert your recorded audio into highly accurate, searchable and readable text; being able to index and search through audio content is useful because it helps your users find relevant content. It can be used to boost organic traffic, improve accessibility, and also enhance your AI by transcribing audio files to provide better service to your customers." }, { "code": null, "e": 12779, "s": 12291, "text": "Let’s say you have a company that offers customer support services and you are recording random customer conversations to improve the quality of service in order to get better insights into how representatives handle calls. The first step as part of improving the service is to transcribe the recorded audio files into digitised readable text. Further, the text can go through various AI / ML workflows to determine the mood of the call, customer sentiment, resolution latency, and more." }, { "code": null, "e": 12946, "s": 12779, "text": "Google Cloud Speech API uses powerful neural network models to convert audio to text. It recognises over 110 languages and variants, to support your global user base." }, { "code": null, "e": 13337, "s": 12946, "text": "Simplifying the transcribing of massive amounts of recorded audio files, Google Cloud Platform technologies and CDAP together provide users with an integrated, scalable and code-free way to transcribe audio files. This integration allows users to build pipelines that can be scheduled and monitored with ease, for any production deployment, in minutes to hours, rather than weeks or months." }, { "code": null, "e": 13560, "s": 13337, "text": "Below is a simple CDAP Pipeline that takes the raw audio files stored on Google Cloud Storage, passes it through Google Speech Translator plugin, and writes the transcribed text to another location on Google Cloud Storage." }, { "code": null, "e": 13896, "s": 13560, "text": "The Google Speech Translator CDAP plugin is ready to go with a minor configuration of settings depending on the types of the files being recorded. The translation applied to the raw audio file in the above example generates a JSON output that describes the file that was transcribed, with the computed confidence for the transcription." }, { "code": null, "e": 14053, "s": 13896, "text": "{ \"path\": \"/audio/raw/audio.raw\", \"speeches\": [ { \"confidence\": 0.9876289963722229, \"transcript\": \"how old is the Brooklyn Bridge\" } ]}" }, { "code": null, "e": 14127, "s": 14053, "text": "Case Study: Data Lake, XML Transform, Data Discovery , Security Analytics" }, { "code": null, "e": 14202, "s": 14127, "text": "Guide : Kafka consumption, Twitter data, Data Processing with Flow & Flume" }, { "code": null, "e": 14270, "s": 14202, "text": "Code examples : TwitterSentiment , MovieRecommender , Netlens, Wise" }, { "code": null, "e": 14343, "s": 14270, "text": "Tutorial : Fraud ML Classification, Migrate S3 to ADLS, EDW Optimization" }, { "code": null, "e": 14381, "s": 14343, "text": "API : CDAP API and Dependent Packages" }, { "code": null, "e": 14666, "s": 14381, "text": "If you are using or evaluating GCP and are looking for ways to improve your integration on GCP, you may want to try out CDAP and install GCP connectors from Cask Market today. Also, If you’re Developer or Data Engineer/Scientist , you can proceed by downloading the CDAP Local Sandbox" } ]
Wrapper Class in Python - GeeksforGeeks
21 Apr, 2020 Decoration is a way to specify management code for functions and classes. Decorators themselves take the form of callable objects that process other callable objects. A Class Decorator is similar to function decorators, but they are run at the end of a class statement to rebind a class name to a callable (e.g functions). As such, they can be used to either manage classes just after they are created or insert a layer of wrapper logic to manage instances when they are later created. Class decorator can be used to manage class object directly, instead of instance calls – to increase/modify a class with new methods. Class decorators are strongly related to function decorators, in fact, they use nearly the same syntax and very similar coding pattern but somewhere logic differs. Note: For more information, refer to Decorators in Python Syntax:Syntactically, class decorators appear just before class statements. @decorator class Class_Name: ... inst = Class_Name(50) This piece of code is equivalent to class Class_Name: ... Class_Name = decorator(Class_Name) inst = Class_Name(50); Let’s understand the syntax, and how its works with an example: Example: # decorator accepts a class as # a parameterdef decorator(cls): class Wrapper: def __init__(self, x): self.wrap = cls(x) def get_name(self): # fetches the name attribute return self.wrap.name return Wrapper @decoratorclass C: def __init__(self, y): self.name = y # its equivalent to saying# C = decorator(C)x = C("Geeks")print(x.get_name()) OUTPUT: Geeks In this example, the decorator rebinds the class C to another class Wrapper, which retains the original class in an enclosing scope and creates and embeds an instance (wrap) of the original class when it’s called. In more easy language, @decorator is equivalent to C = decorator(C) which is executed at the end of the definition of class C. In the decorator body, wrapper class modifies the class C maintaining the originality or without changing C. cls(x) return an object of class C (with its name attribute initialized with the value of x). The method get_name return the name attribute for the wrap object. And finally in the output β€œGeeks” gets printed. So, this was an overview of the decorator or wrapper for the class. The class decorators are used to add additional functionality to the class without changing the original class to use as required in any situation. Python Decorators Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Reading and Writing to text files in Python *args and **kwargs in Python How to drop one or multiple columns in Pandas Dataframe Selecting rows in pandas DataFrame based on conditions
[ { "code": null, "e": 24418, "s": 24390, "text": "\n21 Apr, 2020" }, { "code": null, "e": 25202, "s": 24418, "text": "Decoration is a way to specify management code for functions and classes. Decorators themselves take the form of callable objects that process other callable objects. A Class Decorator is similar to function decorators, but they are run at the end of a class statement to rebind a class name to a callable (e.g functions). As such, they can be used to either manage classes just after they are created or insert a layer of wrapper logic to manage instances when they are later created. Class decorator can be used to manage class object directly, instead of instance calls – to increase/modify a class with new methods. Class decorators are strongly related to function decorators, in fact, they use nearly the same syntax and very similar coding pattern but somewhere logic differs." }, { "code": null, "e": 25260, "s": 25202, "text": "Note: For more information, refer to Decorators in Python" }, { "code": null, "e": 25336, "s": 25260, "text": "Syntax:Syntactically, class decorators appear just before class statements." }, { "code": null, "e": 25531, "s": 25336, "text": "@decorator\nclass Class_Name: \n ...\n\ninst = Class_Name(50)\n\nThis piece of code is equivalent to\n\nclass Class_Name:\n ...\n\nClass_Name = decorator(Class_Name)\ninst = Class_Name(50);\n" }, { "code": null, "e": 25595, "s": 25531, "text": "Let’s understand the syntax, and how its works with an example:" }, { "code": null, "e": 25604, "s": 25595, "text": "Example:" }, { "code": "# decorator accepts a class as # a parameterdef decorator(cls): class Wrapper: def __init__(self, x): self.wrap = cls(x) def get_name(self): # fetches the name attribute return self.wrap.name return Wrapper @decoratorclass C: def __init__(self, y): self.name = y # its equivalent to saying# C = decorator(C)x = C(\"Geeks\")print(x.get_name()) ", "e": 26081, "s": 25604, "text": null }, { "code": null, "e": 26089, "s": 26081, "text": "OUTPUT:" }, { "code": null, "e": 26096, "s": 26089, "text": "Geeks\n" }, { "code": null, "e": 26755, "s": 26096, "text": "In this example, the decorator rebinds the class C to another class Wrapper, which retains the original class in an enclosing scope and creates and embeds an instance (wrap) of the original class when it’s called. In more easy language, @decorator is equivalent to C = decorator(C) which is executed at the end of the definition of class C. In the decorator body, wrapper class modifies the class C maintaining the originality or without changing C. cls(x) return an object of class C (with its name attribute initialized with the value of x). The method get_name return the name attribute for the wrap object. And finally in the output β€œGeeks” gets printed." }, { "code": null, "e": 26971, "s": 26755, "text": "So, this was an overview of the decorator or wrapper for the class. The class decorators are used to add additional functionality to the class without changing the original class to use as required in any situation." }, { "code": null, "e": 26989, "s": 26971, "text": "Python Decorators" }, { "code": null, "e": 26996, "s": 26989, "text": "Python" }, { "code": null, "e": 27094, "s": 26996, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27103, "s": 27094, "text": "Comments" }, { "code": null, "e": 27116, "s": 27103, "text": "Old Comments" }, { "code": null, "e": 27134, "s": 27116, "text": "Python Dictionary" }, { "code": null, "e": 27166, "s": 27134, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27188, "s": 27166, "text": "Enumerate() in Python" }, { "code": null, "e": 27230, "s": 27188, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27256, "s": 27230, "text": "Python String | replace()" }, { "code": null, "e": 27293, "s": 27256, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27337, "s": 27293, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27366, "s": 27337, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27422, "s": 27366, "text": "How to drop one or multiple columns in Pandas Dataframe" } ]
Difference between the list() and listFiles() methods in Java
The class named File of the java.io package represents a file or directory (path names) in the system. To get the list of all the existing files in a directory this class provides the list() and ListFiles() methods. The main difference between them is that The list() method returns the names of all files in the given directory in the form of a String array. The list() method returns the names of all files in the given directory in the form of a String array. The ListFiles() method returns the objects (File) of the files in the given directory, in the form of an array of type File. The ListFiles() method returns the objects (File) of the files in the given directory, in the form of an array of type File. i.e. If you just need the names of the files within a particular directory you can use the list() method and, if you need the details of the files in a directory such as name, path etc. you need to use the ListFiles() method, retrieve the objects of all the files and get the required details by invoking the respective methods. import java.io.File; import java.io.IOException; public class ListOfFiles { public static void main(String args[]) throws IOException { //Creating a File object for directory File path = new File("D:\\ExampleDirectory"); //List of all files and directories String contents[] = path.list(); System.out.println("List of files and directories in the specified directory:"); for(int i=0; i < contents.length; i++) { System.out.println(contents[i]); } } } List of files and directories in the specified directory: SampleDirectory1 SampleDirectory2 SampleFile1.txt SampleFile2.txt SapmleFile3.txt import java.io.File; import java.io.IOException; public class ListOfFiles { public static void main(String args[]) throws IOException { //Creating a File object for directory File path = new File("D:\\ExampleDirectory"); //List of all files and directories File files [] = path.listFiles(); System.out.println("List of files and directories in the specified directory:"); for(File file : files) { System.out.println("File name: "+file.getName()); System.out.println("File path: "+file.getAbsolutePath()); System.out.println(" "); } } } List of files and directories in the specified directory: File name: SampleDirectory1 File path: D:\ExampleDirectory\SampleDirectory1 File name: SampleDirectory2 File path: D:\ExampleDirectory\SampleDirectory2 File name: SampleFile1.txt File path: D:\ExampleDirectory\SampleFile1.txt File name: SampleFile2.txt File path: D:\ExampleDirectory\SampleFile2.txt File name: SapmleFile3.txt File path: D:\ExampleDirectory\SapmleFile3.txt
[ { "code": null, "e": 1278, "s": 1062, "text": "The class named File of the java.io package represents a file or directory (path names) in the system. To get the list of all the existing files in a directory this class provides the list() and ListFiles() methods." }, { "code": null, "e": 1319, "s": 1278, "text": "The main difference between them is that" }, { "code": null, "e": 1422, "s": 1319, "text": "The list() method returns the names of all files in the given directory in the form of a String array." }, { "code": null, "e": 1525, "s": 1422, "text": "The list() method returns the names of all files in the given directory in the form of a String array." }, { "code": null, "e": 1650, "s": 1525, "text": "The ListFiles() method returns the objects (File) of the files in the given directory, in the form of an array of type File." }, { "code": null, "e": 1775, "s": 1650, "text": "The ListFiles() method returns the objects (File) of the files in the given directory, in the form of an array of type File." }, { "code": null, "e": 2104, "s": 1775, "text": "i.e. If you just need the names of the files within a particular directory you can use the list() method and, if you need the details of the files in a directory such as name, path etc. you need to use the ListFiles() method, retrieve the objects of all the files and get the required details by invoking the respective methods." }, { "code": null, "e": 2612, "s": 2104, "text": "import java.io.File;\nimport java.io.IOException;\npublic class ListOfFiles {\n public static void main(String args[]) throws IOException {\n //Creating a File object for directory\n File path = new File(\"D:\\\\ExampleDirectory\");\n //List of all files and directories\n String contents[] = path.list();\n System.out.println(\"List of files and directories in the specified directory:\");\n for(int i=0; i < contents.length; i++) {\n System.out.println(contents[i]);\n }\n }\n}" }, { "code": null, "e": 2752, "s": 2612, "text": "List of files and directories in the specified directory:\nSampleDirectory1\nSampleDirectory2\nSampleFile1.txt\nSampleFile2.txt\nSapmleFile3.txt" }, { "code": null, "e": 3363, "s": 2752, "text": "import java.io.File;\nimport java.io.IOException;\npublic class ListOfFiles {\n public static void main(String args[]) throws IOException {\n //Creating a File object for directory\n File path = new File(\"D:\\\\ExampleDirectory\");\n //List of all files and directories\n File files [] = path.listFiles();\n System.out.println(\"List of files and directories in the specified directory:\");\n for(File file : files) {\n System.out.println(\"File name: \"+file.getName());\n System.out.println(\"File path: \"+file.getAbsolutePath());\n System.out.println(\" \");\n }\n }\n}" }, { "code": null, "e": 3799, "s": 3363, "text": "List of files and directories in the specified directory:\nFile name: SampleDirectory1\nFile path: D:\\ExampleDirectory\\SampleDirectory1\n\nFile name: SampleDirectory2\nFile path: D:\\ExampleDirectory\\SampleDirectory2\n\nFile name: SampleFile1.txt\nFile path: D:\\ExampleDirectory\\SampleFile1.txt\n\nFile name: SampleFile2.txt\nFile path: D:\\ExampleDirectory\\SampleFile2.txt\n\nFile name: SapmleFile3.txt\nFile path: D:\\ExampleDirectory\\SapmleFile3.txt" } ]
How to get the smallest integer greater than or equal to a number in JavaScript?
To get the smallest integer greater than or equal to a number, use the JavaScript Math.ceil() method. This method returns the smallest integer greater than or equal to a number. You can try to run the following code to get the smallest integer greater than or equal to a number βˆ’ <html> <head> <title>JavaScript Math ceil() Method</title> </head> <body> <script> var value = Math.ceil(80.55); document.write("First Value : " + value ); value = Math.ceil(42.45); document.write("<br />Second Value : " + value ); value = Math.ceil(-70.70); document.write("<br />Third Value : " + value ); value = Math.ceil(-20.30); document.write("<br />Fourth Value : " + value ); </script> </body> </html>
[ { "code": null, "e": 1240, "s": 1062, "text": "To get the smallest integer greater than or equal to a number, use the JavaScript Math.ceil() method. This method returns the smallest integer greater than or equal to a number." }, { "code": null, "e": 1342, "s": 1240, "text": "You can try to run the following code to get the smallest integer greater than or equal to a number βˆ’" }, { "code": null, "e": 1885, "s": 1342, "text": "<html>\n <head>\n <title>JavaScript Math ceil() Method</title>\n </head>\n <body>\n <script>\n var value = Math.ceil(80.55);\n document.write(\"First Value : \" + value );\n \n value = Math.ceil(42.45);\n document.write(\"<br />Second Value : \" + value );\n \n value = Math.ceil(-70.70);\n document.write(\"<br />Third Value : \" + value );\n \n value = Math.ceil(-20.30);\n document.write(\"<br />Fourth Value : \" + value );\n </script>\n </body>\n</html>" } ]
Iterator Functions in Python
In this article, we will learn about the four iterator functions available in Python 3.x. Or earlier namely accumulate() , chain(), filter false() , dropwhile() methods. Now let’s look on each of them in detail βˆ’ Accumulate() method takes two arguments, one being iterable to operate on and another the function/operation to be performed. By default, the second argument performs the addition operation. Chain() method prints all the iterable targets after concatenating all of the iterables. The below example explains the implementation βˆ’ Live Demo import itertools import operator as op # initializing list 1 li1 = ['t','u','t','o','r'] # initializing list 2 li2 = [1,1,1,1,1] # initializing list 3 li3 = ['i','a','l','s','p','o','i','n','t'] # using accumulate() add method print ("The sum after each iteration is : ",end="") print (list(itertools.accumulate(li1,op.add))) # using accumulate() multiply method print ("The product after each iteration is : ",end="") print (list(itertools.accumulate(li2,op.mul))) # using chain() method print ("All values in mentioned chain are : ",end="") print (list(itertools.chain(li1,li3))) The sum after each iteration is : ['t', 'tu', 'tut', 'tuto', 'tutor'] The product after each iteration is : [1, 1, 1, 1, 1] All values in mentioned chain are : ['t', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', 'p', 'o', 'i', 'n', 't'] Drop while() method accepts a function to check the condition and an input iterable to operate on. It returns all values of the iterable after the condition becomes false. Filterfalse() method accepts a function to check the condition and an input iterable to operate on. It returns the value when the given condition becomes false. Live Demo import itertools # list l = ['t','u','t','o','r'] # using dropwhile() method print ("The values after condition fails : ",end="") print (list(itertools.dropwhile(lambda x : x!='o',l))) # using filterfalse() method print ("The values when condition fails : ",end="") print (list(itertools.filterfalse(lambda x : x!='o',l))) The values after condition fails : ['o', 'r'] The values when condition fails : ['o'] In this article, we learned about the different types of iterator functions available in Python 3.x. Or earlier.
[ { "code": null, "e": 1232, "s": 1062, "text": "In this article, we will learn about the four iterator functions available in Python 3.x. Or earlier namely accumulate() , chain(), filter false() , dropwhile() methods." }, { "code": null, "e": 1275, "s": 1232, "text": "Now let’s look on each of them in detail βˆ’" }, { "code": null, "e": 1466, "s": 1275, "text": "Accumulate() method takes two arguments, one being iterable to operate on and another the function/operation to be performed. By default, the second argument performs the addition operation." }, { "code": null, "e": 1555, "s": 1466, "text": "Chain() method prints all the iterable targets after concatenating all of the iterables." }, { "code": null, "e": 1603, "s": 1555, "text": "The below example explains the implementation βˆ’" }, { "code": null, "e": 1614, "s": 1603, "text": " Live Demo" }, { "code": null, "e": 2196, "s": 1614, "text": "import itertools\nimport operator as op\n# initializing list 1\nli1 = ['t','u','t','o','r']\n# initializing list 2\nli2 = [1,1,1,1,1]\n# initializing list 3\nli3 = ['i','a','l','s','p','o','i','n','t']\n# using accumulate() add method\nprint (\"The sum after each iteration is : \",end=\"\")\nprint (list(itertools.accumulate(li1,op.add)))\n# using accumulate() multiply method\nprint (\"The product after each iteration is : \",end=\"\")\nprint (list(itertools.accumulate(li2,op.mul)))\n# using chain() method\nprint (\"All values in mentioned chain are : \",end=\"\")\nprint (list(itertools.chain(li1,li3)))" }, { "code": null, "e": 2427, "s": 2196, "text": "The sum after each iteration is : ['t', 'tu', 'tut', 'tuto', 'tutor']\nThe product after each iteration is : [1, 1, 1, 1, 1]\nAll values in mentioned chain are : ['t', 'u', 't', 'o', 'r', 'i',\n'a', 'l', 's', 'p', 'o', 'i', 'n', 't']" }, { "code": null, "e": 2599, "s": 2427, "text": "Drop while() method accepts a function to check the condition and an input iterable to operate on. It returns all values of the iterable after the condition becomes false." }, { "code": null, "e": 2760, "s": 2599, "text": "Filterfalse() method accepts a function to check the condition and an input iterable to operate on. It returns the value when the given condition becomes false." }, { "code": null, "e": 2771, "s": 2760, "text": " Live Demo" }, { "code": null, "e": 3094, "s": 2771, "text": "import itertools\n# list\nl = ['t','u','t','o','r']\n# using dropwhile() method\nprint (\"The values after condition fails : \",end=\"\")\nprint (list(itertools.dropwhile(lambda x : x!='o',l)))\n# using filterfalse() method\nprint (\"The values when condition fails : \",end=\"\")\nprint (list(itertools.filterfalse(lambda x : x!='o',l)))" }, { "code": null, "e": 3180, "s": 3094, "text": "The values after condition fails : ['o', 'r']\nThe values when condition fails : ['o']" }, { "code": null, "e": 3293, "s": 3180, "text": "In this article, we learned about the different types of iterator functions available in Python 3.x. Or earlier." } ]
DataFrame.to_pickle() in function Pandas - GeeksforGeeks
05 Jun, 2020 The to_pickle() method is used to pickle (serialize) the given object into the file. This method uses the syntax as given below : Syntax: DataFrame.to_pickle(self, path, compression='infer', protocol=4) Example 1: Python3 # importing packagesimport pandas as pd # dictionary of datadct = {'ID': {0: 23, 1: 43, 2: 12, 3: 13, 4: 67, 5: 89, 6: 90, 7: 56, 8: 34}, 'Name': {0: 'Ram', 1: 'Deep', 2: 'Yash', 3: 'Aman', 4: 'Arjun', 5: 'Aditya', 6: 'Divya', 7: 'Chalsea', 8: 'Akash' }, 'Marks': {0: 89, 1: 97, 2: 45, 3: 78, 4: 56, 5: 76, 6: 100, 7: 87, 8: 81}, 'Grade': {0: 'B', 1: 'A', 2: 'F', 3: 'C', 4: 'E', 5: 'C', 6: 'A', 7: 'B', 8: 'B'} } # forming dataframe and printingdata = pd.DataFrame(dct)print(data) # using to_pickle function to form file # with name 'pickle_file'data.to_pickle('pickle_file') Output : ID Name Marks Grade 0 23 Ram 89 B 1 43 Deep 97 A 2 12 Yash 45 F 3 13 Aman 78 C 4 67 Arjun 56 E 5 89 Aditya 76 C 6 90 Divya 100 A 7 56 Chalsea 87 B 8 34 Akash 81 B Example 2: Python3 # importing packagesimport pandas as pd # dictionary of datadct = {"f1": range(6), "b1": range(6, 12)} # forming dataframe and printingdata = pd.DataFrame(dct)print(data) # using to_pickle function to form # file with name 'pickle_file'data.to_pickle('pickle_file') Output: f1 b1 0 0 6 1 1 7 2 2 8 3 3 9 4 4 10 5 5 11 Python pandas-dataFrame Python pandas-dataFrame-methods 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": "\n05 Jun, 2020" }, { "code": null, "e": 24031, "s": 23901, "text": "The to_pickle() method is used to pickle (serialize) the given object into the file. This method uses the syntax as given below :" }, { "code": null, "e": 24039, "s": 24031, "text": "Syntax:" }, { "code": null, "e": 24145, "s": 24039, "text": "DataFrame.to_pickle(self, path,\n compression='infer',\n protocol=4)\n" }, { "code": null, "e": 24156, "s": 24145, "text": "Example 1:" }, { "code": null, "e": 24164, "s": 24156, "text": "Python3" }, { "code": "# importing packagesimport pandas as pd # dictionary of datadct = {'ID': {0: 23, 1: 43, 2: 12, 3: 13, 4: 67, 5: 89, 6: 90, 7: 56, 8: 34}, 'Name': {0: 'Ram', 1: 'Deep', 2: 'Yash', 3: 'Aman', 4: 'Arjun', 5: 'Aditya', 6: 'Divya', 7: 'Chalsea', 8: 'Akash' }, 'Marks': {0: 89, 1: 97, 2: 45, 3: 78, 4: 56, 5: 76, 6: 100, 7: 87, 8: 81}, 'Grade': {0: 'B', 1: 'A', 2: 'F', 3: 'C', 4: 'E', 5: 'C', 6: 'A', 7: 'B', 8: 'B'} } # forming dataframe and printingdata = pd.DataFrame(dct)print(data) # using to_pickle function to form file # with name 'pickle_file'data.to_pickle('pickle_file')", "e": 24921, "s": 24164, "text": null }, { "code": null, "e": 24930, "s": 24921, "text": "Output :" }, { "code": null, "e": 25211, "s": 24930, "text": " ID Name Marks Grade\n0 23 Ram 89 B\n1 43 Deep 97 A\n2 12 Yash 45 F\n3 13 Aman 78 C\n4 67 Arjun 56 E\n5 89 Aditya 76 C\n6 90 Divya 100 A\n7 56 Chalsea 87 B\n8 34 Akash 81 B\n" }, { "code": null, "e": 25222, "s": 25211, "text": "Example 2:" }, { "code": null, "e": 25230, "s": 25222, "text": "Python3" }, { "code": "# importing packagesimport pandas as pd # dictionary of datadct = {\"f1\": range(6), \"b1\": range(6, 12)} # forming dataframe and printingdata = pd.DataFrame(dct)print(data) # using to_pickle function to form # file with name 'pickle_file'data.to_pickle('pickle_file')", "e": 25502, "s": 25230, "text": null }, { "code": null, "e": 25510, "s": 25502, "text": "Output:" }, { "code": null, "e": 25580, "s": 25510, "text": " f1 b1\n0 0 6\n1 1 7\n2 2 8\n3 3 9\n4 4 10\n5 5 11" }, { "code": null, "e": 25604, "s": 25580, "text": "Python pandas-dataFrame" }, { "code": null, "e": 25636, "s": 25604, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 25650, "s": 25636, "text": "Python-pandas" }, { "code": null, "e": 25657, "s": 25650, "text": "Python" }, { "code": null, "e": 25755, "s": 25657, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25764, "s": 25755, "text": "Comments" }, { "code": null, "e": 25777, "s": 25764, "text": "Old Comments" }, { "code": null, "e": 25813, "s": 25777, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 25836, "s": 25813, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 25875, "s": 25836, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 25908, "s": 25875, "text": "Python | Convert set into a list" }, { "code": null, "e": 25957, "s": 25908, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 25998, "s": 25957, "text": "Python - Call function from another file" }, { "code": null, "e": 26014, "s": 25998, "text": "loops in python" }, { "code": null, "e": 26065, "s": 26014, "text": "Multithreading in Python | Set 2 (Synchronization)" }, { "code": null, "e": 26097, "s": 26065, "text": "Python Dictionary keys() method" } ]
How to Delete files in Python using send2trash module? - GeeksforGeeks
16 Jul, 2020 In this article, we will see how to safely delete files and folders using the send2trash module in Python. Using send2trash, we can send files to the Trash or Recycle Bin instead of permanently deleting them. The OS module’s unlink(), remove() and rmdir() functions can be used to delete files or folders. But, these functions delete the files permanently. The operations cannot be undone if there were any accidental deletions performed. This can be prevented using send2trash. OS : The OS module in Python provides functions for interacting with the operating system. OS module comes with Python’s Standard Library. send2trash : Send2Trash is a small package that sends files to the Trash (or Recycle Bin) natively and on all platforms. To install it type the below command in the terminal. pip install send2trash The send2trash() function accepts the location of the file or folder to be deleted. Python3 import send2trash send2trash.send2trash("/location/to/file") The process of deleting a directory is same as above. If the directory contains files or other folders, those are also deleted. A TrashPermissionError exception is raised, in case a file could not be deleted due to permission error or any other unexpected reason. We can use the os.walk() function to walk through a directory and delete specific files. In the example below, we will delete all β€˜.txt’ files in the given directory. Python3 import osimport send2trash # walking through the directoryfor folder, subfolders, files in os.walk('/Users/tithighosh/Documents'): for file in files: # checking if file is # of .txt type if file.endswith('.txt'): path = os.path.join(folder, file) # printing the path of the file # to be deleted print('deleted : ', path ) # deleting the file send2trash.send2trash(path) Output : deleted : /Users/tithighosh/Documents/cfile.txt deleted : /Users/tithighosh/Documents/e_also_big_output.txt deleted : /Users/tithighosh/Documents/res.txt deleted : /Users/tithighosh/Documents/tk.txt python-modules Python-projects python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python OOPs Concepts How to Install PIP on Windows ? Bar Plot in Matplotlib Defaultdict in Python Python Classes and Objects Deque in Python Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python - Ways to remove duplicates from list Class method vs Static method in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n16 Jul, 2020" }, { "code": null, "e": 24380, "s": 23901, "text": "In this article, we will see how to safely delete files and folders using the send2trash module in Python. Using send2trash, we can send files to the Trash or Recycle Bin instead of permanently deleting them. The OS module’s unlink(), remove() and rmdir() functions can be used to delete files or folders. But, these functions delete the files permanently. The operations cannot be undone if there were any accidental deletions performed. This can be prevented using send2trash." }, { "code": null, "e": 24519, "s": 24380, "text": "OS : The OS module in Python provides functions for interacting with the operating system. OS module comes with Python’s Standard Library." }, { "code": null, "e": 24694, "s": 24519, "text": "send2trash : Send2Trash is a small package that sends files to the Trash (or Recycle Bin) natively and on all platforms. To install it type the below command in the terminal." }, { "code": null, "e": 24718, "s": 24694, "text": "pip install send2trash\n" }, { "code": null, "e": 24802, "s": 24718, "text": "The send2trash() function accepts the location of the file or folder to be deleted." }, { "code": null, "e": 24810, "s": 24802, "text": "Python3" }, { "code": "import send2trash send2trash.send2trash(\"/location/to/file\")", "e": 24872, "s": 24810, "text": null }, { "code": null, "e": 25136, "s": 24872, "text": "The process of deleting a directory is same as above. If the directory contains files or other folders, those are also deleted. A TrashPermissionError exception is raised, in case a file could not be deleted due to permission error or any other unexpected reason." }, { "code": null, "e": 25303, "s": 25136, "text": "We can use the os.walk() function to walk through a directory and delete specific files. In the example below, we will delete all β€˜.txt’ files in the given directory." }, { "code": null, "e": 25311, "s": 25303, "text": "Python3" }, { "code": "import osimport send2trash # walking through the directoryfor folder, subfolders, files in os.walk('/Users/tithighosh/Documents'): for file in files: # checking if file is # of .txt type if file.endswith('.txt'): path = os.path.join(folder, file) # printing the path of the file # to be deleted print('deleted : ', path ) # deleting the file send2trash.send2trash(path)", "e": 25814, "s": 25311, "text": null }, { "code": null, "e": 25823, "s": 25814, "text": "Output :" }, { "code": null, "e": 26027, "s": 25823, "text": "deleted : /Users/tithighosh/Documents/cfile.txt\ndeleted : /Users/tithighosh/Documents/e_also_big_output.txt\ndeleted : /Users/tithighosh/Documents/res.txt\ndeleted : /Users/tithighosh/Documents/tk.txt\n" }, { "code": null, "e": 26042, "s": 26027, "text": "python-modules" }, { "code": null, "e": 26058, "s": 26042, "text": "Python-projects" }, { "code": null, "e": 26073, "s": 26058, "text": "python-utility" }, { "code": null, "e": 26080, "s": 26073, "text": "Python" }, { "code": null, "e": 26178, "s": 26080, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26187, "s": 26178, "text": "Comments" }, { "code": null, "e": 26200, "s": 26187, "text": "Old Comments" }, { "code": null, "e": 26221, "s": 26200, "text": "Python OOPs Concepts" }, { "code": null, "e": 26253, "s": 26221, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26276, "s": 26253, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 26298, "s": 26276, "text": "Defaultdict in Python" }, { "code": null, "e": 26325, "s": 26298, "text": "Python Classes and Objects" }, { "code": null, "e": 26341, "s": 26325, "text": "Deque in Python" }, { "code": null, "e": 26383, "s": 26341, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26439, "s": 26383, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26484, "s": 26439, "text": "Python - Ways to remove duplicates from list" } ]
Java Examples - Searching last occurance ?
How to search the last position of a substring ? This example shows how to determine the last position of a substring inside a string with the help of strOrig.lastIndexOf(Stringname) method. public class SearchlastString { public static void main(String[] args) { String strOrig = "Hello world ,Hello Reader"; int lastIndex = strOrig.lastIndexOf("Hello"); if(lastIndex == - 1){ System.out.println("Hello not found"); } else { System.out.println("Last occurrence of Hello is at index "+ lastIndex); } } } The above code sample will produce the following result. Last occurrence of Hello is at index 13 This another example shows how to determine the last position of a substring inside a string with the help of strOrig.lastIndexOf(Stringname) method. public class HelloWorld{ public static void main(String []args) { String t1 = "Tutorialspoint"; int index = t1.lastIndexOf("p"); System.out.println(index); } } The above code sample will produce the following result. 9 Print Add Notes Bookmark this page
[ { "code": null, "e": 2117, "s": 2068, "text": "How to search the last position of a substring ?" }, { "code": null, "e": 2259, "s": 2117, "text": "This example shows how to determine the last position of a substring inside a string with the help of strOrig.lastIndexOf(Stringname) method." }, { "code": null, "e": 2633, "s": 2259, "text": "public class SearchlastString {\n public static void main(String[] args) {\n String strOrig = \"Hello world ,Hello Reader\";\n int lastIndex = strOrig.lastIndexOf(\"Hello\");\n \n if(lastIndex == - 1){\n System.out.println(\"Hello not found\");\n } else {\n System.out.println(\"Last occurrence of Hello is at index \"+ lastIndex);\n }\n }\n}" }, { "code": null, "e": 2690, "s": 2633, "text": "The above code sample will produce the following result." }, { "code": null, "e": 2731, "s": 2690, "text": "Last occurrence of Hello is at index 13\n" }, { "code": null, "e": 2881, "s": 2731, "text": "This another example shows how to determine the last position of a substring inside a string with the help of strOrig.lastIndexOf(Stringname) method." }, { "code": null, "e": 3065, "s": 2881, "text": "public class HelloWorld{\n public static void main(String []args) {\n String t1 = \"Tutorialspoint\";\n int index = t1.lastIndexOf(\"p\");\n System.out.println(index);\n }\n}" }, { "code": null, "e": 3122, "s": 3065, "text": "The above code sample will produce the following result." }, { "code": null, "e": 3125, "s": 3122, "text": "9\n" }, { "code": null, "e": 3132, "s": 3125, "text": " Print" }, { "code": null, "e": 3143, "s": 3132, "text": " Add Notes" } ]
What is difference between raw_input() and input() functions in Python?
The function raw_input() presents a prompt to the user (the optional arg of raw_input([arg])), gets input from the user and returns the data input by the user in a string. For example, name = raw_input("What isyour name? ") print "Hello, %s." %name This differs from input() in that the latter tries to interpret the input given by the user; it is usually best to avoid input() and to stick with raw_input() and custom parsing/conversion code. In Python 3, raw_input() was renamed to input() and can be directly used. For example, name = input("What is your name? ") print("Hello, %s." %name)
[ { "code": null, "e": 1247, "s": 1062, "text": "The function raw_input() presents a prompt to the user (the optional arg of raw_input([arg])), gets input from the user and returns the data input by the user in a string. For example," }, { "code": null, "e": 1311, "s": 1247, "text": "name = raw_input(\"What isyour name? \")\nprint \"Hello, %s.\" %name" }, { "code": null, "e": 1593, "s": 1311, "text": "This differs from input() in that the latter tries to interpret the input given by the user; it is usually best to avoid input() and to stick with raw_input() and custom parsing/conversion code. In Python 3, raw_input() was renamed to input() and can be directly used. For example," }, { "code": null, "e": 1655, "s": 1593, "text": "name = input(\"What is your name? \")\nprint(\"Hello, %s.\" %name)" } ]
Sphenic Number | Practice | GeeksforGeeks
A Sphenic Number is a positive integer N which is product of exactly three distinct primes. The first few sphenic numbers are 30, 42, 66, 70, 78, 102, 105, 110, 114, ... Given a number N, your task is to find whether it is a Sphenic Number or not. Example 1: Input: N = 30 Output: 1 Explanation: 30 = 2 * 3 * 5 so N is product of 3 distinct prime numbers. Example 2: Input: N = 60 Output: 0 Explanation: 60 = 2 * 2 * 3 * 5 so N is product of 4 prime numbers. Your Task: You don't need to read or print anyhting. Your task is to complete the function isSphenicNo() which takes N as input parameter and returns 1 if N is Sphenic Number otherwise returns 0. Expected Time Complexity: O(N* log(N)) Expected Space Complexity: O(N) Constraints: 1 <= N <= 1000 0 vivekmehla32 months ago Time Complexity: O(n) Space Complexity: O(n) Time Taken:0.00sec int isSphenicNo(int n){ // Code here vector<int> v; for(int i=2;i<n;i++) { int count=0; while(n%i==0) { n=n/i; count++; } if(count>0) { v.push_back(count); } } if(n>0) { v.push_back(1); } if(v.size()>3 || v.size()<3) { return 0; } else { for(int i=0;i<v.size();i++) { if(v[i]!=1) { return 0; } } return 1; }} 0 ayazmrz982 months ago static boolean isprime(int n) { if(n<=1) { return false; } for(int i=2;i<=Math.sqrt(n);i++) { if(n%i==0) { return false; } } return true; } public int isSphenicNo(int N) { int count=0; int mul=1; for(int i=2;i<+N;i++) { if(N%i==0) { if(isprime(i)) { count++; mul=mul*i; } } } if(count==3 && mul==N) { return 1; } else { return 0; } } 0 showpnilkumar211020013 months ago //Easy soln: class Solution{public:bool check(int n){ if(n==0||n==1) return 0; for(int i=2;i<=sqrt(n);i++) { if(n%i==0) return 0; } return true;}int isSphenicNo(int N){ int count=0; int p=1; for(int i=2;i<=N;i++) { if(N%i==0) { if(check(i)==true) { count++; p=p*i; } } } if(count==3 &&p==N) return 1; else return 0;} 0 dileep kumar10 months ago dileep kumar pythonexecution time: 0.06def ISprime(n): for i in range(2,n): if n % i == 0: return 0 return 1class Solution:def isSphenicNo(self, N):# Code herel = []for i in range(2,N): if N % i == 0 and ISprime(i): l.append(i) if len(l)<3: return 0 if len(l)>=3: for i in range(0,len(l)-2): if N % l[i] == 0: if (l[i]*l[i+1]*l[i+2]==N): return 1 else: continue else: continue return 0 0 Yash Patil2 years ago Yash Patil Best Solution Execution Time 0.29:public static void main (String[] args) { int n=10000; boolean []prime=new boolean[(n+1)]; int count[]=new int[(1000)]; for(int i=0;i<=n;i++) { prime[i]=true; } for(int i=2;i*i<=n;i++) { if(prime[i]==true) { for(int j=i*i;j<=n;j+=i) { prime[j]=false; } } } int val=0; for(int i=2;i<=n;i++) { if(val>=count.length) { break; } if(prime[i]==true) { count[val++]=i; } } Scanner sc1 =new Scanner(System.in); int test=sc1.nextInt(); while(test!=0) { int m=sc1.nextInt(); TreeMap<integer,integer> tm1 =new TreeMap<integer,integer>(); int res=0,j=0; int p=count[j]; while(p*p<=m) { res=0; if(m%p==0) { while(m%p==0) { m/=p; res++; } tm1.put(p,res); } j++; p=count[j]; } if(m!=1) { tm1.put(m,1); } if(tm1.size()>3) { System.out.println(0); } else { boolean flag=true; for(Map.Entry<integer,integer> x1:tm1.entrySet()) { if(x1.getValue()>1) { flag=false; break; } } if(flag==true&&tm1.size()==3) { System.out.println(1); } else { System.out.println(0); } } test--; } } 0 Ranadheer2 years ago Ranadheer c++ solutionhttps://ide.geeksforgeeks.o... 0 Riya kashyap2 years ago Riya kashyap solution in javahttps://ide.geeksforgeeks.o... 0 This comment was deleted. 0 prerna singh2 years ago prerna singh https://ide.geeksforgeeks.org/YPFZ4n21Cw0.01 0 Ajay Agrawal3 years ago Ajay Agrawal https://ide.geeksforgeeks.o...execution time : 0.01sec 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": 488, "s": 238, "text": "A Sphenic Number is a positive integer N which is product of exactly three distinct primes. The first few sphenic numbers are 30, 42, 66, 70, 78, 102, 105, 110, 114, ...\nGiven a number N, your task is to find whether it is a Sphenic Number or not.\n " }, { "code": null, "e": 499, "s": 488, "text": "Example 1:" }, { "code": null, "e": 598, "s": 499, "text": "Input: N = 30\nOutput: 1\nExplanation: 30 = 2 * 3 * 5 so N is \nproduct of 3 distinct prime numbers.\n" }, { "code": null, "e": 609, "s": 598, "text": "Example 2:" }, { "code": null, "e": 702, "s": 609, "text": "Input: N = 60\nOutput: 0\nExplanation: 60 = 2 * 2 * 3 * 5 so N is\nproduct of 4 prime numbers.\n" }, { "code": null, "e": 902, "s": 704, "text": "Your Task:\nYou don't need to read or print anyhting. Your task is to complete the function isSphenicNo() which takes N as input parameter and returns 1 if N is Sphenic Number otherwise returns 0.\n " }, { "code": null, "e": 975, "s": 902, "text": "Expected Time Complexity: O(N* log(N))\nExpected Space Complexity: O(N)\n " }, { "code": null, "e": 1003, "s": 975, "text": "Constraints:\n1 <= N <= 1000" }, { "code": null, "e": 1005, "s": 1003, "text": "0" }, { "code": null, "e": 1029, "s": 1005, "text": "vivekmehla32 months ago" }, { "code": null, "e": 1051, "s": 1029, "text": "Time Complexity: O(n)" }, { "code": null, "e": 1074, "s": 1051, "text": "Space Complexity: O(n)" }, { "code": null, "e": 1093, "s": 1074, "text": "Time Taken:0.00sec" }, { "code": null, "e": 1617, "s": 1093, "text": " int isSphenicNo(int n){ // Code here vector<int> v; for(int i=2;i<n;i++) { int count=0; while(n%i==0) { n=n/i; count++; } if(count>0) { v.push_back(count); } } if(n>0) { v.push_back(1); } if(v.size()>3 || v.size()<3) { return 0; } else { for(int i=0;i<v.size();i++) { if(v[i]!=1) { return 0; } } return 1; }}" }, { "code": null, "e": 1619, "s": 1617, "text": "0" }, { "code": null, "e": 1641, "s": 1619, "text": "ayazmrz982 months ago" }, { "code": null, "e": 2332, "s": 1641, "text": " static boolean isprime(int n)\n {\n if(n<=1)\n {\n return false;\n }\n for(int i=2;i<=Math.sqrt(n);i++)\n {\n if(n%i==0)\n {\n return false;\n }\n }\n return true;\n }\n public int isSphenicNo(int N)\n {\n \n int count=0;\n int mul=1;\n for(int i=2;i<+N;i++)\n {\n if(N%i==0)\n {\n if(isprime(i))\n {\n count++;\n mul=mul*i;\n }\n }\n }\n \n if(count==3 && mul==N)\n {\n return 1;\n }\n else\n {\n return 0; \n }\n }" }, { "code": null, "e": 2334, "s": 2332, "text": "0" }, { "code": null, "e": 2368, "s": 2334, "text": "showpnilkumar211020013 months ago" }, { "code": null, "e": 2381, "s": 2368, "text": "//Easy soln:" }, { "code": null, "e": 2844, "s": 2381, "text": "class Solution{public:bool check(int n){ if(n==0||n==1) return 0; for(int i=2;i<=sqrt(n);i++) { if(n%i==0) return 0; } return true;}int isSphenicNo(int N){ int count=0; int p=1; for(int i=2;i<=N;i++) { if(N%i==0) { if(check(i)==true) { count++; p=p*i; } } } if(count==3 &&p==N) return 1; else return 0;}" }, { "code": null, "e": 2846, "s": 2844, "text": "0" }, { "code": null, "e": 2872, "s": 2846, "text": "dileep kumar10 months ago" }, { "code": null, "e": 2885, "s": 2872, "text": "dileep kumar" }, { "code": null, "e": 3082, "s": 2885, "text": "pythonexecution time: 0.06def ISprime(n): for i in range(2,n): if n % i == 0: return 0 return 1class Solution:def isSphenicNo(self, N):# Code herel = []for i in range(2,N):" }, { "code": null, "e": 3473, "s": 3082, "text": " if N % i == 0 and ISprime(i): l.append(i) if len(l)<3: return 0 if len(l)>=3: for i in range(0,len(l)-2): if N % l[i] == 0: if (l[i]*l[i+1]*l[i+2]==N): return 1 else: continue else: continue return 0" }, { "code": null, "e": 3475, "s": 3473, "text": "0" }, { "code": null, "e": 3497, "s": 3475, "text": "Yash Patil2 years ago" }, { "code": null, "e": 3508, "s": 3497, "text": "Yash Patil" }, { "code": null, "e": 4307, "s": 3508, "text": "Best Solution Execution Time 0.29:public static void main (String[] args) { int n=10000; boolean []prime=new boolean[(n+1)]; int count[]=new int[(1000)]; for(int i=0;i<=n;i++) { prime[i]=true; } for(int i=2;i*i<=n;i++) { if(prime[i]==true) { for(int j=i*i;j<=n;j+=i) { prime[j]=false; } } } int val=0; for(int i=2;i<=n;i++) { if(val>=count.length) { break; } if(prime[i]==true) { count[val++]=i; } } Scanner sc1 =new Scanner(System.in); int test=sc1.nextInt(); while(test!=0) {" }, { "code": null, "e": 4823, "s": 4307, "text": " int m=sc1.nextInt(); TreeMap<integer,integer> tm1 =new TreeMap<integer,integer>(); int res=0,j=0; int p=count[j]; while(p*p<=m) { res=0; if(m%p==0) { while(m%p==0) { m/=p; res++; } tm1.put(p,res); } j++; p=count[j]; } if(m!=1) { tm1.put(m,1); }" }, { "code": null, "e": 5297, "s": 4823, "text": " if(tm1.size()>3) { System.out.println(0); } else { boolean flag=true; for(Map.Entry<integer,integer> x1:tm1.entrySet()) { if(x1.getValue()>1) { flag=false; break; } } if(flag==true&&tm1.size()==3) { System.out.println(1); } else { System.out.println(0); }" }, { "code": null, "e": 5335, "s": 5297, "text": " } test--; }" }, { "code": null, "e": 5337, "s": 5335, "text": "}" }, { "code": null, "e": 5339, "s": 5337, "text": "0" }, { "code": null, "e": 5360, "s": 5339, "text": "Ranadheer2 years ago" }, { "code": null, "e": 5370, "s": 5360, "text": "Ranadheer" }, { "code": null, "e": 5413, "s": 5370, "text": "c++ solutionhttps://ide.geeksforgeeks.o..." }, { "code": null, "e": 5415, "s": 5413, "text": "0" }, { "code": null, "e": 5439, "s": 5415, "text": "Riya kashyap2 years ago" }, { "code": null, "e": 5452, "s": 5439, "text": "Riya kashyap" }, { "code": null, "e": 5499, "s": 5452, "text": "solution in javahttps://ide.geeksforgeeks.o..." }, { "code": null, "e": 5501, "s": 5499, "text": "0" }, { "code": null, "e": 5527, "s": 5501, "text": "This comment was deleted." }, { "code": null, "e": 5529, "s": 5527, "text": "0" }, { "code": null, "e": 5553, "s": 5529, "text": "prerna singh2 years ago" }, { "code": null, "e": 5566, "s": 5553, "text": "prerna singh" }, { "code": null, "e": 5611, "s": 5566, "text": "https://ide.geeksforgeeks.org/YPFZ4n21Cw0.01" }, { "code": null, "e": 5613, "s": 5611, "text": "0" }, { "code": null, "e": 5637, "s": 5613, "text": "Ajay Agrawal3 years ago" }, { "code": null, "e": 5650, "s": 5637, "text": "Ajay Agrawal" }, { "code": null, "e": 5705, "s": 5650, "text": "https://ide.geeksforgeeks.o...execution time : 0.01sec" }, { "code": null, "e": 5851, "s": 5705, "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": 5887, "s": 5851, "text": " Login to access your submissions. " }, { "code": null, "e": 5897, "s": 5887, "text": "\nProblem\n" }, { "code": null, "e": 5907, "s": 5897, "text": "\nContest\n" }, { "code": null, "e": 5970, "s": 5907, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6118, "s": 5970, "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": 6326, "s": 6118, "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": 6432, "s": 6326, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
MySQL query to find duplicate tuples and display the count?
To find duplicate tuples, use GROUP BY HAVING clause. Let us first create a table βˆ’ mysql> create table DemoTable -> ( -> Id int, -> Name varchar(20) -> ); Query OK, 0 rows affected (0.80 sec) Insert some records in the table using insert command βˆ’ mysql> insert into DemoTable values(100,'Chris'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(101,'David'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable values(101,'Mike'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(100,'Carol'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values(100,'Chris'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(100,'Chris'); Query OK, 1 row affected (0.10 sec) Display all records from the table using select statement βˆ’ mysql> select * from DemoTable; This will produce the following output βˆ’ +------+-------+ | Id | Name | +------+-------+ | 100 | Chris | | 101 | David | | 101 | Mike | | 100 | Carol | | 100 | Chris | | 100 | Chris | +------+-------+ 6 rows in set (0.00 sec) Following is the query to find duplicate tuples βˆ’ mysql> select Id,Name,count(*) as t from DemoTable -> group by Id,Name -> having count(*) > 2; This will produce the following output βˆ’ +------+-------+---+ | Id | Name | t | +------+-------+---+ | 100 | Chris | 3 | +------+-------+---+ 1 row in set (0.03 sec)
[ { "code": null, "e": 1146, "s": 1062, "text": "To find duplicate tuples, use GROUP BY HAVING clause. Let us first create a table βˆ’" }, { "code": null, "e": 1267, "s": 1146, "text": "mysql> create table DemoTable\n -> (\n -> Id int,\n -> Name varchar(20)\n -> );\nQuery OK, 0 rows affected (0.80 sec)" }, { "code": null, "e": 1323, "s": 1267, "text": "Insert some records in the table using insert command βˆ’" }, { "code": null, "e": 1838, "s": 1323, "text": "mysql> insert into DemoTable values(100,'Chris');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable values(101,'David');\nQuery OK, 1 row affected (0.23 sec)\nmysql> insert into DemoTable values(101,'Mike');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values(100,'Carol');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable values(100,'Chris');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values(100,'Chris');\nQuery OK, 1 row affected (0.10 sec)" }, { "code": null, "e": 1898, "s": 1838, "text": "Display all records from the table using select statement βˆ’" }, { "code": null, "e": 1930, "s": 1898, "text": "mysql> select * from DemoTable;" }, { "code": null, "e": 1971, "s": 1930, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 2166, "s": 1971, "text": "+------+-------+\n| Id | Name |\n+------+-------+\n| 100 | Chris |\n| 101 | David |\n| 101 | Mike |\n| 100 | Carol |\n| 100 | Chris |\n| 100 | Chris |\n+------+-------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2216, "s": 2166, "text": "Following is the query to find duplicate tuples βˆ’" }, { "code": null, "e": 2317, "s": 2216, "text": "mysql> select Id,Name,count(*) as t from DemoTable\n -> group by Id,Name\n -> having count(*) > 2;" }, { "code": null, "e": 2358, "s": 2317, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 2487, "s": 2358, "text": "+------+-------+---+\n| Id | Name | t |\n+------+-------+---+\n| 100 | Chris | 3 |\n+------+-------+---+\n1 row in set (0.03 sec)" } ]
QlikView - Match Function
The Match() function in QlikView is used to match the value of a string on expression with data value present in a column. It is similar to the in function that we see in SQL language. It is useful to fetch rows containing specific strings and it also has an extension in form of wildmatch() function. Let us consider the following data as input file for the examples illustrated below. Product_Id,Product_Line,Product_category,Product_Subcategory 1,Sporting Goods,Outdoor Recreation,Winter Sports & Activities 2,Food, Beverages & Tobacco,Food Items,Fruits & Vegetables 3,Apparel & Accessories,Clothing,Uniforms 4,Sporting Goods,Athletics,Rugby 5,Health & Beauty,Personal Care 6,Arts & Entertainment,Hobbies & Creative Arts,Musical Instruments 7,Arts & Entertainment,Hobbies & Creative Arts,Orchestra Accessories 8,Arts & Entertainment,Hobbies & Creative Arts,Crafting Materials 9,Hardware,Tool Accessories,Power Tool Batteries 10,Home & Garden,Bathroom Accessories,Bath Caddies 11,Food, Beverages & Tobacco,Food Items,Frozen Vegetables 12,Home & Garden,Lawn & Garden,Power Equipment 13,Office Supplies,Presentation Supplies,Display 14,Hardware,Tool Accessories,Jigs 15,Baby & Toddler,Diapering,Baby Wipes The following script shows the Load script, which reads the file named product_categories.csv. We search the field Product_Line for values matching with strings 'Food' and 'Sporting Goods'. Let us create a Table Box sheet object to show the data generated by the match function. Go to the menu Layout β†’ New Sheet Object β†’ Table Box. The following window appears in which we mention the Title of the table and then select the required fields to be displayed. Clicking OK displays the data from the CSV file in the QlikView Table Box as shown below. The wildmatch() function is an extension of match() function in which we can use wildcards as part of the strings used to match the values with values in the fields being searched for. We search for the strings 'Off*','*ome*. Let us create a Table Box sheet object to show the data generated by the wildmatch function. Go to the menu item Layout β†’ New Sheet Object β†’ Table Box. The following window appears in which we mention the Title of the table and then select the required fields to be displayed. Clicking OK displays the data from the CSV file in the QlikView Table Box as shown below. 70 Lectures 5 hours Arthur Fong Print Add Notes Bookmark this page
[ { "code": null, "e": 3223, "s": 2920, "text": "The Match() function in QlikView is used to match the value of a string on expression with data value present in a column. It is similar to the in function that we see in SQL language. It is useful to fetch rows containing specific strings and it also has an extension in form of wildmatch() function." }, { "code": null, "e": 3308, "s": 3223, "text": "Let us consider the following data as input file for the examples illustrated below." }, { "code": null, "e": 4128, "s": 3308, "text": "Product_Id,Product_Line,Product_category,Product_Subcategory\n1,Sporting Goods,Outdoor Recreation,Winter Sports & Activities\n2,Food, Beverages & Tobacco,Food Items,Fruits & Vegetables\n3,Apparel & Accessories,Clothing,Uniforms\n4,Sporting Goods,Athletics,Rugby\n5,Health & Beauty,Personal Care\n6,Arts & Entertainment,Hobbies & Creative Arts,Musical Instruments\n7,Arts & Entertainment,Hobbies & Creative Arts,Orchestra Accessories\n8,Arts & Entertainment,Hobbies & Creative Arts,Crafting Materials\n9,Hardware,Tool Accessories,Power Tool Batteries\n10,Home & Garden,Bathroom Accessories,Bath Caddies\n11,Food, Beverages & Tobacco,Food Items,Frozen Vegetables\n12,Home & Garden,Lawn & Garden,Power Equipment\n13,Office Supplies,Presentation Supplies,Display\n14,Hardware,Tool Accessories,Jigs\n15,Baby & Toddler,Diapering,Baby Wipes\n" }, { "code": null, "e": 4319, "s": 4128, "text": "The following script shows the Load script, which reads the file named product_categories.csv. We search the field Product_Line for values matching with strings 'Food' and 'Sporting Goods'. " }, { "code": null, "e": 4677, "s": 4319, "text": "Let us create a Table Box sheet object to show the data generated by the match function. Go to the menu Layout β†’ New Sheet Object β†’ Table Box. The following window appears in which we mention the Title of the table and then select the required fields to be displayed. Clicking OK displays the data from the CSV file in the QlikView Table Box as shown below." }, { "code": null, "e": 4903, "s": 4677, "text": "The wildmatch() function is an extension of match() function in which we can use wildcards as part of the strings used to match the values with values in the fields being searched for. We search for the strings 'Off*','*ome*." }, { "code": null, "e": 5270, "s": 4903, "text": "Let us create a Table Box sheet object to show the data generated by the wildmatch\nfunction. Go to the menu item Layout β†’ New Sheet Object β†’ Table Box. The following window appears in which we mention the Title of the table and then select the required fields to be displayed. Clicking OK displays the data from the CSV file in the QlikView Table Box as shown below." }, { "code": null, "e": 5303, "s": 5270, "text": "\n 70 Lectures \n 5 hours \n" }, { "code": null, "e": 5316, "s": 5303, "text": " Arthur Fong" }, { "code": null, "e": 5323, "s": 5316, "text": " Print" }, { "code": null, "e": 5334, "s": 5323, "text": " Add Notes" } ]
MVVM – Hierarchies & Navigation
When building MVVM applications, you typically decompose complex screens of information into a set of parent and child views, where the child views are contained within the parent views in panels or container controls, and forms a hierarchy of use themselves. After decomposing the complex Views it doesn’t mean that each and every piece of child content that you separate into its own XAML file necessarily needs to be an MVVM view. After decomposing the complex Views it doesn’t mean that each and every piece of child content that you separate into its own XAML file necessarily needs to be an MVVM view. The chunk of content just provides the structure to render something to the screen and does not support any input or manipulation by the user for that content. The chunk of content just provides the structure to render something to the screen and does not support any input or manipulation by the user for that content. It may not need a separate ViewModel, but it could just be a chunk XAML that renders based on properties exposed by the parents ViewModel. It may not need a separate ViewModel, but it could just be a chunk XAML that renders based on properties exposed by the parents ViewModel. Finally, if you have a hierarchy of Views and ViewModels, the parent ViewModel can become a hub for communications so that each child ViewModel can remain decoupled from the other child ViewModels and from their parent as much as possible. Finally, if you have a hierarchy of Views and ViewModels, the parent ViewModel can become a hub for communications so that each child ViewModel can remain decoupled from the other child ViewModels and from their parent as much as possible. Let’s take a look at an example in which we will define a simple hierarchy between different views. Create a new WPF Application project MVVMHierarchiesDemo Step 1 βˆ’ Add the three folders (Model, ViewModel, and Views) into your project. Step 2 βˆ’ Add Customer and Order classes in Model folder, CustomerListView and OrderView in Views folder, and CustomerListViewModel and OrderViewModel in ViewModel folder as shown in the following image. Step 3 βˆ’ Add textblocks in both CustomerListView and OrderView. Here is CustomerListView.xaml file. <UserControl x:Class="MVVMHierarchiesDemo.Views.CustomerListView" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" xmlns:local = "clr-namespace:MVVMHierarchiesDemo.Views" mc:Ignorable = "d" d:DesignHeight = "300" d:DesignWidth = "300"> <Grid> <TextBlock Text = "Customer List View"/> </Grid> </UserControl> Following is the OrderView.xaml file. <UserControl x:Class = "MVVMHierarchiesDemo.Views.OrderView" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc ="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d ="http://schemas.microsoft.com/expression/blend/2008" xmlns:local = "clr-namespace:MVVMHierarchiesDemo.Views" mc:Ignorable = "d" d:DesignHeight = "300" d:DesignWidth = "300"> <Grid> <TextBlock Text = "Order View"/> </Grid> </UserControl> Now we need something to host these views, and a good place for that in our MainWindow because it is a simple application. We need a container control that we can place our views and switch them in a navigation fashion. For this purpose, we need to add ContentControl in our MainWindow.xaml file and we will be using its content property and bind that to a ViewModel reference. Now define the data templates for each view in a resource dictionary. Following is the MainWindow.xaml file. Note how each data template maps a data type (the ViewModel type) to a corresponding View. <Window x:Class = "MVVMHierarchiesDemo.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local = "clr-namespace:MVVMHierarchiesDemo" xmlns:views = "clr-namespace:MVVMHierarchiesDemo.Views" xmlns:viewModels = "clr-namespace:MVVMHierarchiesDemo.ViewModel" mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "525"> <Window.DataContext> <local:MainWindowViewModel/> </Window.DataContext> <Window.Resources> <DataTemplate DataType = "{x:Type viewModels:CustomerListViewModel}"> <views:CustomerListView/> </DataTemplate> <DataTemplate DataType = "{x:Type viewModels:OrderViewModel}"> <views:OrderView/> </DataTemplate> </Window.Resources> <Grid> <ContentControl Content = "{Binding CurrentView}"/> </Grid> </Window> Anytime the current view model is set to an instance of a CustomerListViewModel, it will render out a CustomerListView with the ViewModel is hooked up. It’s an order ViewModel, it'll render out OrderView and so on. We now need a ViewModel that has a CurrentViewModel property and some logic and commanding to be able to switch the current reference of ViewModel inside the property. Let's create a ViewModel for this MainWindow called MainWindowViewModel. We can just create an instance of our ViewModel from XAML and use that to set the DataContext property of the window. For this, we need to create a base class to encapsulate the implementation of INotifyPropertyChanged for our ViewModels. The main idea behind this class is to encapsulate the INotifyPropertyChanged implementation and provide helper methods to the derived class so that they can easily trigger the appropriate notifications. Following is the implementation of BindableBase class. using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace MVVMHierarchiesDemo { class BindableBase : INotifyPropertyChanged { protected virtual void SetProperty<T>(ref T member, T val, [CallerMemberName] string propertyName = null) { if (object.Equals(member, val)) return; member = val; PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged = delegate { }; } } Now it's time to actually start doing some view switching using our CurrentViewModel property. We just need some way to drive the setting of this property. And we're going to make it so that the end user can command going to the customer list or to the order view. First add a new class in your project which will implement the ICommand interface. Following is the implementation of ICommand interface. using System; using System.Windows.Input; namespace MVVMHierarchiesDemo { public class MyICommand<T> : ICommand { Action<T> _TargetExecuteMethod; Func<T, bool> _TargetCanExecuteMethod; public MyICommand(Action<T> executeMethod) { _TargetExecuteMethod = executeMethod; } public MyICommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod) { _TargetExecuteMethod = executeMethod; _TargetCanExecuteMethod = canExecuteMethod; } public void RaiseCanExecuteChanged() { CanExecuteChanged(this, EventArgs.Empty); } #region ICommand Members bool ICommand.CanExecute(object parameter) { if (_TargetCanExecuteMethod != null) { T tparm = (T)parameter; return _TargetCanExecuteMethod(tparm); } if (_TargetExecuteMethod != null) { return true; } return false; } // Beware - should use weak references if command instance lifetime is longer than lifetime of UI objects that get hooked up to command // Prism commands solve this in their implementation public event EventHandler CanExecuteChanged = delegate { }; void ICommand.Execute(object parameter) { if (_TargetExecuteMethod != null) { _TargetExecuteMethod((T)parameter); } } #endregion } } We now need to set up some top level navigation to these to ViewModels and logic for that switching should belong inside MainWindowViewModel. For this we're going to use a method called on navigate that takes a string destination and returns the CurrentViewModel property. private void OnNav(string destination) { switch (destination) { case "orders": CurrentViewModel = orderViewModelModel; break; case "customers": default: CurrentViewModel = custListViewModel; break; } } For navigation of these different Views, we need to add two buttons in our MainWindow.xaml file. Following is the complete XAML file implementation. <Window x:Class = "MVVMHierarchiesDemo.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local = "clr-namespace:MVVMHierarchiesDemo" xmlns:views = "clr-namespace:MVVMHierarchiesDemo.Views" xmlns:viewModels = "clr-namespace:MVVMHierarchiesDemo.ViewModel" mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "525"> <Window.DataContext> <local:MainWindowViewModel/> </Window.DataContext> <Window.Resources> <DataTemplate DataType = "{x:Type viewModels:CustomerListViewModel}"> <views:CustomerListView/> </DataTemplate> <DataTemplate DataType = "{x:Type viewModels:OrderViewModel}"> <views:OrderView/> </DataTemplate> </Window.Resources> <Grid> <Grid.RowDefinitions> <RowDefinition Height = "Auto" /> <RowDefinition Height = "*" /> </Grid.RowDefinitions> <Grid x:Name = "NavBar"> <Grid.ColumnDefinitions> <ColumnDefinition Width = "*" /> <ColumnDefinition Width = "*" /> <ColumnDefinition Width = "*" /> </Grid.ColumnDefinitions> <Button Content = "Customers" Command = "{Binding NavCommand}" CommandParameter = "customers" Grid.Column = "0" /> <Button Content = "Order" Command = "{Binding NavCommand}" CommandParameter = "orders" Grid.Column = "2" /> </Grid> <Grid x:Name = "MainContent" Grid.Row = "1"> <ContentControl Content = "{Binding CurrentViewModel}" /> </Grid> </Grid> </Window> Following is the complete MainWindowViewModel implementation. using MVVMHierarchiesDemo.ViewModel; using MVVMHierarchiesDemo.Views; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MVVMHierarchiesDemo { class MainWindowViewModel : BindableBase { public MainWindowViewModel() { NavCommand = new MyICommand<string>(OnNav); } private CustomerListViewModel custListViewModel = new CustomerListViewModel(); private OrderViewModel orderViewModelModel = new OrderViewModel(); private BindableBase _CurrentViewModel; public BindableBase CurrentViewModel { get {return _CurrentViewModel;} set {SetProperty(ref _CurrentViewModel, value);} } public MyICommand<string> NavCommand { get; private set; } private void OnNav(string destination) { switch (destination) { case "orders": CurrentViewModel = orderViewModelModel; break; case "customers": default: CurrentViewModel = custListViewModel; break; } } } } Derive all of your ViewModels from BindableBase class. When the above code is compiled and executed, you will see the following output. As you can see, we have added only two buttons and a CurrentViewModel on our MainWindow. If you click any button then it will navigate to that particular View. Let’s click on Customers button and you will see that the CustomerListView is displayed. We recommend you to execute the above example in a step-by-step manner for better understanding. 38 Lectures 2 hours Skillbakerystudios 22 Lectures 1 hours CLEMENT OCHIENG 14 Lectures 2 hours DevTechie Print Add Notes Bookmark this page
[ { "code": null, "e": 2202, "s": 1942, "text": "When building MVVM applications, you typically decompose complex screens of information into a set of parent and child views, where the child views are contained within the parent views in panels or container controls, and forms a hierarchy of use themselves." }, { "code": null, "e": 2376, "s": 2202, "text": "After decomposing the complex Views it doesn’t mean that each and every piece of child content that you separate into its own XAML file necessarily needs to be an MVVM view." }, { "code": null, "e": 2550, "s": 2376, "text": "After decomposing the complex Views it doesn’t mean that each and every piece of child content that you separate into its own XAML file necessarily needs to be an MVVM view." }, { "code": null, "e": 2710, "s": 2550, "text": "The chunk of content just provides the structure to render something to the screen and does not support any input or manipulation by the user for that content." }, { "code": null, "e": 2870, "s": 2710, "text": "The chunk of content just provides the structure to render something to the screen and does not support any input or manipulation by the user for that content." }, { "code": null, "e": 3009, "s": 2870, "text": "It may not need a separate ViewModel, but it could just be a chunk XAML that renders based on properties exposed by the parents ViewModel." }, { "code": null, "e": 3148, "s": 3009, "text": "It may not need a separate ViewModel, but it could just be a chunk XAML that renders based on properties exposed by the parents ViewModel." }, { "code": null, "e": 3388, "s": 3148, "text": "Finally, if you have a hierarchy of Views and ViewModels, the parent ViewModel can become a hub for communications so that each child ViewModel can remain decoupled from the other child ViewModels and from their parent as much as possible." }, { "code": null, "e": 3628, "s": 3388, "text": "Finally, if you have a hierarchy of Views and ViewModels, the parent ViewModel can become a hub for communications so that each child ViewModel can remain decoupled from the other child ViewModels and from their parent as much as possible." }, { "code": null, "e": 3785, "s": 3628, "text": "Let’s take a look at an example in which we will define a simple hierarchy between different views. Create a new WPF Application project MVVMHierarchiesDemo" }, { "code": null, "e": 3865, "s": 3785, "text": "Step 1 βˆ’ Add the three folders (Model, ViewModel, and Views) into your project." }, { "code": null, "e": 4068, "s": 3865, "text": "Step 2 βˆ’ Add Customer and Order classes in Model folder, CustomerListView and OrderView in Views folder, and CustomerListViewModel and OrderViewModel in ViewModel folder as shown in the following image." }, { "code": null, "e": 4168, "s": 4068, "text": "Step 3 βˆ’ Add textblocks in both CustomerListView and OrderView. Here is CustomerListView.xaml file." }, { "code": null, "e": 4734, "s": 4168, "text": "<UserControl x:Class=\"MVVMHierarchiesDemo.Views.CustomerListView\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:local = \"clr-namespace:MVVMHierarchiesDemo.Views\" \n mc:Ignorable = \"d\" \n d:DesignHeight = \"300\" d:DesignWidth = \"300\">\n\t\n <Grid> \n <TextBlock Text = \"Customer List View\"/> \n </Grid> \n\t\n</UserControl>" }, { "code": null, "e": 4772, "s": 4734, "text": "Following is the OrderView.xaml file." }, { "code": null, "e": 5318, "s": 4772, "text": "<UserControl x:Class = \"MVVMHierarchiesDemo.Views.OrderView\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x =\"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:mc =\"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:d =\"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:local = \"clr-namespace:MVVMHierarchiesDemo.Views\" mc:Ignorable = \"d\" \n d:DesignHeight = \"300\" d:DesignWidth = \"300\">\n\t\n <Grid> \n <TextBlock Text = \"Order View\"/> \n </Grid> \n\t\n</UserControl>" }, { "code": null, "e": 5696, "s": 5318, "text": "Now we need something to host these views, and a good place for that in our MainWindow because it is a simple application. We need a container control that we can place our views and switch them in a navigation fashion. For this purpose, we need to add ContentControl in our MainWindow.xaml file and we will be using its content property and bind that to a ViewModel reference." }, { "code": null, "e": 5896, "s": 5696, "text": "Now define the data templates for each view in a resource dictionary. Following is the MainWindow.xaml file. Note how each data template maps a data type (the ViewModel type) to a corresponding View." }, { "code": null, "e": 6979, "s": 5896, "text": "<Window x:Class = \"MVVMHierarchiesDemo.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:local = \"clr-namespace:MVVMHierarchiesDemo\" \n xmlns:views = \"clr-namespace:MVVMHierarchiesDemo.Views\" \n xmlns:viewModels = \"clr-namespace:MVVMHierarchiesDemo.ViewModel\" \n mc:Ignorable = \"d\" \n Title = \"MainWindow\" Height = \"350\" Width = \"525\"> \n \n <Window.DataContext> \n <local:MainWindowViewModel/> \n </Window.DataContext>\n\t\n <Window.Resources> \n <DataTemplate DataType = \"{x:Type viewModels:CustomerListViewModel}\">\n <views:CustomerListView/> \n </DataTemplate>\n\t\t\n <DataTemplate DataType = \"{x:Type viewModels:OrderViewModel}\"> \n <views:OrderView/> \n </DataTemplate> \n </Window.Resources>\n\t\n <Grid> \n <ContentControl Content = \"{Binding CurrentView}\"/> \n </Grid> \n\t\n</Window>" }, { "code": null, "e": 7194, "s": 6979, "text": "Anytime the current view model is set to an instance of a CustomerListViewModel, it will render out a CustomerListView with the ViewModel is hooked up. It’s an order ViewModel, it'll render out OrderView and so on." }, { "code": null, "e": 7362, "s": 7194, "text": "We now need a ViewModel that has a CurrentViewModel property and some logic and commanding to be able to switch the current reference of ViewModel inside the property." }, { "code": null, "e": 7674, "s": 7362, "text": "Let's create a ViewModel for this MainWindow called MainWindowViewModel. We can just create an instance of our ViewModel from XAML and use that to set the DataContext property of the window. For this, we need to create a base class to encapsulate the implementation of INotifyPropertyChanged for our ViewModels." }, { "code": null, "e": 7932, "s": 7674, "text": "The main idea behind this class is to encapsulate the INotifyPropertyChanged implementation and provide helper methods to the derived class so that they can easily trigger the appropriate notifications. Following is the implementation of BindableBase class." }, { "code": null, "e": 8756, "s": 7932, "text": "using System; \nusing System.Collections.Generic; \nusing System.ComponentModel; \nusing System.Linq; \nusing System.Runtime.CompilerServices; \nusing System.Text; \nusing System.Threading.Tasks;\n\nnamespace MVVMHierarchiesDemo { \n\n class BindableBase : INotifyPropertyChanged { \n\t\n protected virtual void SetProperty<T>(ref T member, T val,\n [CallerMemberName] string propertyName = null) { \n if (object.Equals(member, val)) return;\n\t\t\t\t\n member = val;\n PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); \n }\n\t\t\t\n protected virtual void OnPropertyChanged(string propertyName) { \n PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); \n } \n\t\t\n public event PropertyChangedEventHandler PropertyChanged = delegate { }; \n } \n}" }, { "code": null, "e": 9159, "s": 8756, "text": "Now it's time to actually start doing some view switching using our CurrentViewModel property. We just need some way to drive the setting of this property. And we're going to make it so that the end user can command going to the customer list or to the order view. First add a new class in your project which will implement the ICommand interface. Following is the implementation of ICommand interface." }, { "code": null, "e": 10624, "s": 9159, "text": "using System; \nusing System.Windows.Input;\n\nnamespace MVVMHierarchiesDemo { \n\n public class MyICommand<T> : ICommand { \n\t\n Action<T> _TargetExecuteMethod; \n Func<T, bool> _TargetCanExecuteMethod;\n\t\t\n public MyICommand(Action<T> executeMethod) {\n _TargetExecuteMethod = executeMethod; \n }\n\t\t\n public MyICommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod) {\n _TargetExecuteMethod = executeMethod;\n _TargetCanExecuteMethod = canExecuteMethod; \n }\n\n public void RaiseCanExecuteChanged() {\n CanExecuteChanged(this, EventArgs.Empty); \n } \n\t\t\n #region ICommand Members\n\n bool ICommand.CanExecute(object parameter) { \n\t\t\n if (_TargetCanExecuteMethod != null) { \n T tparm = (T)parameter; \n return _TargetCanExecuteMethod(tparm); \n } \n\t\t\t\n if (_TargetExecuteMethod != null) { \n return true; \n } \n\t\t\t\n return false; \n }\n\t\t\n // Beware - should use weak references if command instance lifetime is\n longer than lifetime of UI objects that get hooked up to command \n\t\t\t\n // Prism commands solve this in their implementation \n\n public event EventHandler CanExecuteChanged = delegate { };\n\t\n void ICommand.Execute(object parameter) { \n if (_TargetExecuteMethod != null) {\n _TargetExecuteMethod((T)parameter); \n } \n } \n\t\t\n #endregion \n } \n}" }, { "code": null, "e": 10897, "s": 10624, "text": "We now need to set up some top level navigation to these to ViewModels and logic for that switching should belong inside MainWindowViewModel. For this we're going to use a method called on navigate that takes a string destination and returns the CurrentViewModel property." }, { "code": null, "e": 11164, "s": 10897, "text": "private void OnNav(string destination) {\n \n switch (destination) { \n case \"orders\": \n CurrentViewModel = orderViewModelModel; \n break; \n case \"customers\": \n default: \n CurrentViewModel = custListViewModel; \n break; \n } \n}" }, { "code": null, "e": 11313, "s": 11164, "text": "For navigation of these different Views, we need to add two buttons in our MainWindow.xaml file. Following is the complete XAML file implementation." }, { "code": null, "e": 13199, "s": 11313, "text": "<Window x:Class = \"MVVMHierarchiesDemo.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:local = \"clr-namespace:MVVMHierarchiesDemo\" \n xmlns:views = \"clr-namespace:MVVMHierarchiesDemo.Views\" \n xmlns:viewModels = \"clr-namespace:MVVMHierarchiesDemo.ViewModel\" \n mc:Ignorable = \"d\" \n Title = \"MainWindow\" Height = \"350\" Width = \"525\">\n\n <Window.DataContext> \n <local:MainWindowViewModel/> \n </Window.DataContext>\n\t\n <Window.Resources> \n <DataTemplate DataType = \"{x:Type viewModels:CustomerListViewModel}\">\n <views:CustomerListView/> \n </DataTemplate> \n\t\t\n <DataTemplate DataType = \"{x:Type viewModels:OrderViewModel}\">\n <views:OrderView/> \n </DataTemplate> \n </Window.Resources>\n\t\n <Grid>\n <Grid.RowDefinitions> \n <RowDefinition Height = \"Auto\" /> \n <RowDefinition Height = \"*\" /> \n </Grid.RowDefinitions> \n\t\n <Grid x:Name = \"NavBar\"> \n <Grid.ColumnDefinitions> \n <ColumnDefinition Width = \"*\" /> \n <ColumnDefinition Width = \"*\" /> \n <ColumnDefinition Width = \"*\" /> \n </Grid.ColumnDefinitions> \n\t\n <Button Content = \"Customers\" \n Command = \"{Binding NavCommand}\"\n CommandParameter = \"customers\" \n Grid.Column = \"0\" />\n\t\t\t\t\n <Button Content = \"Order\" \n Command = \"{Binding NavCommand}\" \n CommandParameter = \"orders\" \n Grid.Column = \"2\" />\n </Grid> \n\t\n <Grid x:Name = \"MainContent\" Grid.Row = \"1\"> \n <ContentControl Content = \"{Binding CurrentViewModel}\" /> \n </Grid> \n\t\t\n </Grid> \n\t\n</Window>" }, { "code": null, "e": 13261, "s": 13199, "text": "Following is the complete MainWindowViewModel implementation." }, { "code": null, "e": 14429, "s": 13261, "text": "using MVVMHierarchiesDemo.ViewModel; \nusing MVVMHierarchiesDemo.Views; \n\nusing System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Text; \nusing System.Threading.Tasks;\n\nnamespace MVVMHierarchiesDemo {\n \n class MainWindowViewModel : BindableBase {\n\t\n public MainWindowViewModel() { \n NavCommand = new MyICommand<string>(OnNav); \n } \n\t\t\n private CustomerListViewModel custListViewModel = new CustomerListViewModel(); \n\t\t\n private OrderViewModel orderViewModelModel = new OrderViewModel();\n\t\t\n private BindableBase _CurrentViewModel; \n\t\t\n public BindableBase CurrentViewModel { \n get {return _CurrentViewModel;} \n set {SetProperty(ref _CurrentViewModel, value);} \n }\n\t\t\n public MyICommand<string> NavCommand { get; private set; }\n\n private void OnNav(string destination) {\n\t\t\n switch (destination) { \n case \"orders\": \n CurrentViewModel = orderViewModelModel; \n break; \n case \"customers\": \n default: \n CurrentViewModel = custListViewModel; \n break; \n } \n } \n } \n}" }, { "code": null, "e": 14565, "s": 14429, "text": "Derive all of your ViewModels from BindableBase class. When the above code is compiled and executed, you will see the following output." }, { "code": null, "e": 14814, "s": 14565, "text": "As you can see, we have added only two buttons and a CurrentViewModel on our MainWindow. If you click any button then it will navigate to that particular View. Let’s click on Customers button and you will see that the CustomerListView is displayed." }, { "code": null, "e": 14911, "s": 14814, "text": "We recommend you to execute the above example in a step-by-step manner for better understanding." }, { "code": null, "e": 14944, "s": 14911, "text": "\n 38 Lectures \n 2 hours \n" }, { "code": null, "e": 14964, "s": 14944, "text": " Skillbakerystudios" }, { "code": null, "e": 14997, "s": 14964, "text": "\n 22 Lectures \n 1 hours \n" }, { "code": null, "e": 15014, "s": 14997, "text": " CLEMENT OCHIENG" }, { "code": null, "e": 15047, "s": 15014, "text": "\n 14 Lectures \n 2 hours \n" }, { "code": null, "e": 15058, "s": 15047, "text": " DevTechie" }, { "code": null, "e": 15065, "s": 15058, "text": " Print" }, { "code": null, "e": 15076, "s": 15065, "text": " Add Notes" } ]
React Custom Hooks
Hooks are reusable functions. When you have component logic that needs to be used by multiple components, we can extract that logic to a custom Hook. Custom Hooks start with "use". Example: useFetch. In the following code, we are fetching data in our Home component and displaying it. We will use the JSONPlaceholder service to fetch fake data. This service is great for testing applications when there is no existing data. To learn more, check out the JavaScript Fetch API section. Use the JSONPlaceholder service to fetch fake "todo" items and display the titles on the page: index.js: import { useState, useEffect } from "react"; import ReactDOM from "react-dom/client"; const Home = () => { const [data, setData] = useState(null); useEffect(() => { fetch("https://jsonplaceholder.typicode.com/todos") .then((res) => res.json()) .then((data) => setData(data)); }, []); return ( <> {data && data.map((item) => { return <p key={item.id}>{item.title}</p>; })} </> ); }; const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Home />); Run Example Β» The fetch logic may be needed in other components as well, so we will extract that into a custom Hook. Move the fetch logic to a new file to be used as a custom Hook: useFetch.js: import { useState, useEffect } from "react"; const useFetch = (url) => { const [data, setData] = useState(null); useEffect(() => { fetch(url) .then((res) => res.json()) .then((data) => setData(data)); }, [url]); return [data]; }; export default useFetch; index.js: import ReactDOM from "react-dom/client"; import useFetch from "./useFetch"; const Home = () => { const [data] = useFetch("https://jsonplaceholder.typicode.com/todos"); return ( <> {data && data.map((item) => { return <p key={item.id}>{item.title}</p>; })} </> ); }; const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Home />); Run Example Β» We have created a new file called useFetch.js containing a function called useFetch which contains all of the logic needed to fetch our data. We removed the hard-coded URL and replaced it with a url variable that can be passed to the custom Hook. Lastly, we are returning our data from our Hook. In index.js, we are importing our useFetch Hook and utilizing it like any other Hook. This is where we pass in the URL to fetch data from. Now we can reuse this custom Hook in any component to fetch data from any URL. We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 30, "s": 0, "text": "Hooks are reusable functions." }, { "code": null, "e": 150, "s": 30, "text": "When you have component logic that needs to be used by multiple components, we can extract that logic to a custom Hook." }, { "code": null, "e": 200, "s": 150, "text": "Custom Hooks start with \"use\". Example: useFetch." }, { "code": null, "e": 285, "s": 200, "text": "In the following code, we are fetching data in our Home component and displaying it." }, { "code": null, "e": 424, "s": 285, "text": "We will use the JSONPlaceholder service to fetch fake data. This service is great for testing applications when there is no existing data." }, { "code": null, "e": 483, "s": 424, "text": "To learn more, check out the JavaScript Fetch API section." }, { "code": null, "e": 578, "s": 483, "text": "Use the JSONPlaceholder service to fetch fake \"todo\" items and display the titles on the page:" }, { "code": null, "e": 588, "s": 578, "text": "index.js:" }, { "code": null, "e": 1130, "s": 588, "text": "import { useState, useEffect } from \"react\";\nimport ReactDOM from \"react-dom/client\";\n\nconst Home = () => {\n const [data, setData] = useState(null);\n\n useEffect(() => {\n fetch(\"https://jsonplaceholder.typicode.com/todos\")\n .then((res) => res.json())\n .then((data) => setData(data));\n }, []);\n\n return (\n <>\n {data &&\n data.map((item) => {\n return <p key={item.id}>{item.title}</p>;\n })}\n </>\n );\n};\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Home />);\n" }, { "code": null, "e": 1147, "s": 1130, "text": "\nRun \nExample Β»\n" }, { "code": null, "e": 1250, "s": 1147, "text": "The fetch logic may be needed in other components as well, so we will extract that into a custom Hook." }, { "code": null, "e": 1314, "s": 1250, "text": "Move the fetch logic to a new file to be used as a custom Hook:" }, { "code": null, "e": 1327, "s": 1314, "text": "useFetch.js:" }, { "code": null, "e": 1611, "s": 1327, "text": "import { useState, useEffect } from \"react\";\n\nconst useFetch = (url) => {\n const [data, setData] = useState(null);\n\n useEffect(() => {\n fetch(url)\n .then((res) => res.json())\n .then((data) => setData(data));\n }, [url]);\n\n return [data];\n};\n\nexport default useFetch;\n" }, { "code": null, "e": 1621, "s": 1611, "text": "index.js:" }, { "code": null, "e": 2027, "s": 1621, "text": "import ReactDOM from \"react-dom/client\";\nimport useFetch from \"./useFetch\";\n\nconst Home = () => {\n const [data] = useFetch(\"https://jsonplaceholder.typicode.com/todos\");\n\n return (\n <>\n {data &&\n data.map((item) => {\n return <p key={item.id}>{item.title}</p>;\n })}\n </>\n );\n};\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Home />);\n" }, { "code": null, "e": 2044, "s": 2027, "text": "\nRun \nExample Β»\n" }, { "code": null, "e": 2186, "s": 2044, "text": "We have created a new file called useFetch.js containing a function called useFetch which contains all of the logic needed to fetch our data." }, { "code": null, "e": 2291, "s": 2186, "text": "We removed the hard-coded URL and replaced it with a url variable that can be passed to the custom Hook." }, { "code": null, "e": 2340, "s": 2291, "text": "Lastly, we are returning our data from our Hook." }, { "code": null, "e": 2479, "s": 2340, "text": "In index.js, we are importing our useFetch Hook and utilizing it like any other Hook. This is where we pass in the URL to fetch data from." }, { "code": null, "e": 2558, "s": 2479, "text": "Now we can reuse this custom Hook in any component to fetch data from any URL." }, { "code": null, "e": 2591, "s": 2558, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 2633, "s": 2591, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2740, "s": 2633, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 2759, "s": 2740, "text": "[email protected]" } ]
Biopython - Cluster Analysis
In general, Cluster analysis is grouping a set of objects in the same group. This concept is mainly used in data mining, statistical data analysis, machine learning, pattern recognition, image analysis, bioinformatics, etc. It can be achieved by various algorithms to understand how the cluster is widely used in different analysis. According to Bioinformatics, cluster analysis is mainly used in gene expression data analysis to find groups of genes with similar gene expression. In this chapter, we will check out important algorithms in Biopython to understand the fundamentals of clustering on a real dataset. Biopython uses Bio.Cluster module for implementing all the algorithms. It supports the following algorithms βˆ’ Hierarchical Clustering K - Clustering Self-Organizing Maps Principal Component Analysis Let us have a brief introduction on the above algorithms. Hierarchical clustering is used to link each node by a distance measure to its nearest neighbor and create a cluster. Bio.Cluster node has three attributes: left, right and distance. Let us create a simple cluster as shown below βˆ’ >>> from Bio.Cluster import Node >>> n = Node(1,10) >>> n.left = 11 >>> n.right = 0 >>> n.distance = 1 >>> print(n) (11, 0): 1 If you want to construct Tree based clustering, use the below command βˆ’ >>> n1 = [Node(1, 2, 0.2), Node(0, -1, 0.5)] >>> n1_tree = Tree(n1) >>> print(n1_tree) (1, 2): 0.2 (0, -1): 0.5 >>> print(n1_tree[0]) (1, 2): 0.2 Let us perform hierarchical clustering using Bio.Cluster module. Consider the distance is defined in an array. >>> import numpy as np >>> distance = array([[1,2,3],[4,5,6],[3,5,7]]) Now add the distance array in tree cluster. >>> from Bio.Cluster import treecluster >>> cluster = treecluster(distance) >>> print(cluster) (2, 1): 0.666667 (-1, 0): 9.66667 The above function returns a Tree cluster object. This object contains nodes where the number of items are clustered as rows or columns. It is a type of partitioning algorithm and classified into k - means, medians and medoids clustering. Let us understand each of the clustering in brief. This approach is popular in data mining. The goal of this algorithm is to find groups in the data, with the number of groups represented by the variable K. The algorithm works iteratively to assign each data point to one of the K groups based on the features that are provided. Data points are clustered based on feature similarity. >>> from Bio.Cluster import kcluster >>> from numpy import array >>> data = array([[1, 2], [3, 4], [5, 6]]) >>> clusterid, error,found = kcluster(data) >>> print(clusterid) [0 0 1] >>> print(found) 1 It is another type of clustering algorithm which calculates the mean for each cluster to determine its centroid. This approach is based on a given set of items, using the distance matrix and the number of clusters passed by the user. Consider the distance matrix as defined below βˆ’ >>> distance = array([[1,2,3],[4,5,6],[3,5,7]]) We can calculate k-medoids clustering using the below command βˆ’ >>> from Bio.Cluster import kmedoids >>> clusterid, error, found = kmedoids(distance) Let us consider an example. The kcluster function takes a data matrix as input and not Seq instances. You need to convert your sequences to a matrix and provide that to the kcluster function. One way of converting the data to a matrix containing numerical elements only is by using the numpy.fromstring function. It basically translates each letter in a sequence to its ASCII counterpart. This creates a 2D array of encoded sequences that the kcluster function recognized and uses to cluster your sequences. >>> from Bio.Cluster import kcluster >>> import numpy as np >>> sequence = [ 'AGCT','CGTA','AAGT','TCCG'] >>> matrix = np.asarray([np.fromstring(s, dtype=np.uint8) for s in sequence]) >>> clusterid,error,found = kcluster(matrix) >>> print(clusterid) [1 0 0 1] This approach is a type of artificial neural network. It is developed by Kohonen and often called as Kohonen map. It organizes items into clusters based on rectangular topology. Let us create a simple cluster using the same array distance as shown below βˆ’ >>> from Bio.Cluster import somcluster >>> from numpy import array >>> data = array([[1, 2], [3, 4], [5, 6]]) >>> clusterid,map = somcluster(data) >>> print(map) [[[-1.36032469 0.38667395]] [[-0.41170578 1.35295911]]] >>> print(clusterid) [[1 0] [1 0] [1 0]] Here, clusterid is an array with two columns, where the number of rows is equal to the number of items that were clustered, and data is an array with dimensions either rows or columns. Principal Component Analysis is useful to visualize high-dimensional data. It is a method that uses simple matrix operations from linear algebra and statistics to calculate a projection of the original data into the same number or fewer dimensions. Principal Component Analysis returns a tuple columnmean, coordinates, components, and eigenvalues. Let us look into the basics of this concept. >>> from numpy import array >>> from numpy import mean >>> from numpy import cov >>> from numpy.linalg import eig # define a matrix >>> A = array([[1, 2], [3, 4], [5, 6]]) >>> print(A) [[1 2] [3 4] [5 6]] # calculate the mean of each column >>> M = mean(A.T, axis = 1) >>> print(M) [ 3. 4.] # center columns by subtracting column means >>> C = A - M >>> print(C) [[-2. -2.] [ 0. 0.] [ 2. 2.]] # calculate covariance matrix of centered matrix >>> V = cov(C.T) >>> print(V) [[ 4. 4.] [ 4. 4.]] # eigendecomposition of covariance matrix >>> values, vectors = eig(V) >>> print(vectors) [[ 0.70710678 -0.70710678] [ 0.70710678 0.70710678]] >>> print(values) [ 8. 0.] Let us apply the same rectangular matrix data to Bio.Cluster module as defined below βˆ’ >>> from Bio.Cluster import pca >>> from numpy import array >>> data = array([[1, 2], [3, 4], [5, 6]]) >>> columnmean, coordinates, components, eigenvalues = pca(data) >>> print(columnmean) [ 3. 4.] >>> print(coordinates) [[-2.82842712 0. ] [ 0. 0. ] [ 2.82842712 0. ]] >>> print(components) [[ 0.70710678 0.70710678] [ 0.70710678 -0.70710678]] >>> print(eigenvalues) [ 4. 0.] Print Add Notes Bookmark this page
[ { "code": null, "e": 2439, "s": 2106, "text": "In general, Cluster analysis is grouping a set of objects in the same group. This concept is mainly used in data mining, statistical data analysis, machine learning, pattern recognition, image analysis, bioinformatics, etc. It can be achieved by various algorithms to understand how the cluster is widely used in different analysis." }, { "code": null, "e": 2587, "s": 2439, "text": "According to Bioinformatics, cluster analysis is mainly used in gene expression data analysis to find groups of genes with similar gene expression." }, { "code": null, "e": 2720, "s": 2587, "text": "In this chapter, we will check out important algorithms in Biopython to understand the fundamentals of clustering on a real dataset." }, { "code": null, "e": 2830, "s": 2720, "text": "Biopython uses Bio.Cluster module for implementing all the algorithms. It supports the following algorithms βˆ’" }, { "code": null, "e": 2854, "s": 2830, "text": "Hierarchical Clustering" }, { "code": null, "e": 2869, "s": 2854, "text": "K - Clustering" }, { "code": null, "e": 2890, "s": 2869, "text": "Self-Organizing Maps" }, { "code": null, "e": 2919, "s": 2890, "text": "Principal Component Analysis" }, { "code": null, "e": 2977, "s": 2919, "text": "Let us have a brief introduction on the above algorithms." }, { "code": null, "e": 3208, "s": 2977, "text": "Hierarchical clustering is used to link each node by a distance measure to its nearest neighbor and create a cluster. Bio.Cluster node has three attributes: left, right and distance. Let us create a simple cluster as shown below βˆ’" }, { "code": null, "e": 3341, "s": 3208, "text": ">>> from Bio.Cluster import Node \n>>> n = Node(1,10) \n>>> n.left = 11 \n>>> n.right = 0 \n>>> n.distance = 1 \n>>> print(n) \n(11, 0): 1" }, { "code": null, "e": 3413, "s": 3341, "text": "If you want to construct Tree based clustering, use the below command βˆ’" }, { "code": null, "e": 3564, "s": 3413, "text": ">>> n1 = [Node(1, 2, 0.2), Node(0, -1, 0.5)] >>> n1_tree = Tree(n1) \n>>> print(n1_tree) \n(1, 2): 0.2 \n(0, -1): 0.5 \n>>> print(n1_tree[0]) \n(1, 2): 0.2" }, { "code": null, "e": 3629, "s": 3564, "text": "Let us perform hierarchical clustering using Bio.Cluster module." }, { "code": null, "e": 3675, "s": 3629, "text": "Consider the distance is defined in an array." }, { "code": null, "e": 3747, "s": 3675, "text": ">>> import numpy as np \n>>> distance = array([[1,2,3],[4,5,6],[3,5,7]])" }, { "code": null, "e": 3791, "s": 3747, "text": "Now add the distance array in tree cluster." }, { "code": null, "e": 3924, "s": 3791, "text": ">>> from Bio.Cluster import treecluster \n>>> cluster = treecluster(distance) \n>>> print(cluster) \n(2, 1): 0.666667 \n(-1, 0): 9.66667" }, { "code": null, "e": 4061, "s": 3924, "text": "The above function returns a Tree cluster object. This object contains nodes where the number of items are clustered as rows or columns." }, { "code": null, "e": 4214, "s": 4061, "text": "It is a type of partitioning algorithm and classified into k - means, medians and medoids clustering. Let us understand each of the clustering in brief." }, { "code": null, "e": 4370, "s": 4214, "text": "This approach is popular in data mining. The goal of this algorithm is to find groups in the data, with the number of groups represented by the variable K." }, { "code": null, "e": 4547, "s": 4370, "text": "The algorithm works iteratively to assign each data point to one of the K groups based on the features that are provided. Data points are clustered based on feature similarity." }, { "code": null, "e": 4753, "s": 4547, "text": ">>> from Bio.Cluster import kcluster \n>>> from numpy import array \n>>> data = array([[1, 2], [3, 4], [5, 6]]) \n>>> clusterid, error,found = kcluster(data) \n>>> print(clusterid) [0 0 1] \n>>> print(found) \n1" }, { "code": null, "e": 4866, "s": 4753, "text": "It is another type of clustering algorithm which calculates the mean for each cluster to determine its centroid." }, { "code": null, "e": 4987, "s": 4866, "text": "This approach is based on a given set of items, using the distance matrix and the number of clusters passed by the user." }, { "code": null, "e": 5035, "s": 4987, "text": "Consider the distance matrix as defined below βˆ’" }, { "code": null, "e": 5084, "s": 5035, "text": ">>> distance = array([[1,2,3],[4,5,6],[3,5,7]])\n" }, { "code": null, "e": 5148, "s": 5084, "text": "We can calculate k-medoids clustering using the below command βˆ’" }, { "code": null, "e": 5235, "s": 5148, "text": ">>> from Bio.Cluster import kmedoids \n>>> clusterid, error, found = kmedoids(distance)" }, { "code": null, "e": 5263, "s": 5235, "text": "Let us consider an example." }, { "code": null, "e": 5427, "s": 5263, "text": "The kcluster function takes a data matrix as input and not Seq instances. You need to convert your sequences to a matrix and provide that to the kcluster function." }, { "code": null, "e": 5624, "s": 5427, "text": "One way of converting the data to a matrix containing numerical elements only is by using the numpy.fromstring function. It basically translates each letter in a sequence to its ASCII counterpart." }, { "code": null, "e": 5743, "s": 5624, "text": "This creates a 2D array of encoded sequences that the kcluster function recognized and uses to cluster your sequences." }, { "code": null, "e": 6008, "s": 5743, "text": ">>> from Bio.Cluster import kcluster \n>>> import numpy as np \n>>> sequence = [ 'AGCT','CGTA','AAGT','TCCG'] \n>>> matrix = np.asarray([np.fromstring(s, dtype=np.uint8) for s in sequence]) \n>>> clusterid,error,found = kcluster(matrix) \n>>> print(clusterid) [1 0 0 1]" }, { "code": null, "e": 6186, "s": 6008, "text": "This approach is a type of artificial neural network. It is developed by Kohonen and often called as Kohonen map. It organizes items into clusters based on rectangular topology." }, { "code": null, "e": 6264, "s": 6186, "text": "Let us create a simple cluster using the same array distance as shown below βˆ’" }, { "code": null, "e": 6542, "s": 6264, "text": ">>> from Bio.Cluster import somcluster \n>>> from numpy import array \n>>> data = array([[1, 2], [3, 4], [5, 6]]) \n>>> clusterid,map = somcluster(data) \n\n>>> print(map) \n[[[-1.36032469 0.38667395]] \n [[-0.41170578 1.35295911]]] \n\n>>> print(clusterid) \n[[1 0]\n [1 0]\n [1 0]]" }, { "code": null, "e": 6727, "s": 6542, "text": "Here, clusterid is an array with two columns, where the number of rows is equal to the number of items that were clustered, and data is an array with dimensions either rows or columns." }, { "code": null, "e": 6976, "s": 6727, "text": "Principal Component Analysis is useful to visualize high-dimensional data. It is a method that uses simple matrix operations from linear algebra and statistics to calculate a projection of the original data into the same number or fewer dimensions." }, { "code": null, "e": 7120, "s": 6976, "text": "Principal Component Analysis returns a tuple columnmean, coordinates, components, and eigenvalues. Let us look into the basics of this concept." }, { "code": null, "e": 7837, "s": 7120, "text": ">>> from numpy import array \n>>> from numpy import mean \n>>> from numpy import cov \n>>> from numpy.linalg import eig \n\n# define a matrix \n>>> A = array([[1, 2], [3, 4], [5, 6]]) \n\n>>> print(A) \n[[1 2]\n [3 4]\n [5 6]] \n \n# calculate the mean of each column \n>>> M = mean(A.T, axis = 1) \n>>> print(M) \n[ 3. 4.] \n\n# center columns by subtracting column means \n>>> C = A - M\n\n>>> print(C) \n[[-2. -2.]\n [ 0. 0.]\n [ 2. 2.]] \n\n# calculate covariance matrix of centered matrix \n>>> V = cov(C.T) \n\n>>> print(V) \n[[ 4. 4.]\n [ 4. 4.]] \n \n# eigendecomposition of covariance matrix \n>>> values, vectors = eig(V) \n\n>>> print(vectors) \n[[ 0.70710678 -0.70710678]\n [ 0.70710678 0.70710678]] \n \n>>> print(values) \n[ 8. 0.]" }, { "code": null, "e": 7924, "s": 7837, "text": "Let us apply the same rectangular matrix data to Bio.Cluster module as defined below βˆ’" }, { "code": null, "e": 8329, "s": 7924, "text": ">>> from Bio.Cluster import pca \n>>> from numpy import array \n>>> data = array([[1, 2], [3, 4], [5, 6]]) \n>>> columnmean, coordinates, components, eigenvalues = pca(data) \n>>> print(columnmean) \n[ 3. 4.] \n>>> print(coordinates) \n[[-2.82842712 0. ]\n [ 0. 0. ]\n [ 2.82842712 0. ]] \n>>> print(components) \n[[ 0.70710678 0.70710678]\n [ 0.70710678 -0.70710678]] \n>>> print(eigenvalues) \n[ 4. 0.]" }, { "code": null, "e": 8336, "s": 8329, "text": " Print" }, { "code": null, "e": 8347, "s": 8336, "text": " Add Notes" } ]
A tutorial to explanatory modeling and statistical causal inference | Towards Data Science
Perhaps a positive side-effect of the recent pandemic and the associated lockdown is that we get to materialize projects that had been set aside. For a while I’ve wanted to write an article about statistical model interpretation and all I needed was time, motivation, and data. This Kaggle dataset consists of 1085 COVID-19 cases sampled in the city of Wuhan between December 2019 and March 2020, and it was one of the first published datasets to contain records at patient-level. This TDS article provides a nice overview of the data and its fields. Having records at patient-level means that there is enough granularity to derive medical insights about how a person’s individual attributes relate to the risk of dying from exposure to COVID-19. This guide to explanatory modeling requires an intermediate understanding of the following topics: Probability theory and distributions Statistical estimation and inference Machine learning concepts such as logistic regression and bagging Computational statistics concepts such as bootstrap resampling The R programming language A mortality risk analysis requires a response variable with records on the event of death. We will consequently try to express this response as a function of predictor variables, which are directly or indirectly related to the effect of COVID-19 on man’s health. The purpose of an explanatory model is to explain rather than predict the outcome of death, where the objective of explanation is the application of statistical inference in order to: identify predictor variables with statistically significant impact to the event of death estimate the magnitude of impact of the significant predictors quantify the uncertainty of our estimates In other words, we’re interested in a model that will be used for inference rather than prediction or β€” to state it more accurately β€” one that favors causal inference over predictive inference. It’s crucial to understand the distinction between the two as it determines our rationale behind our choice of modeling approach. Explanatory analysis requires a less flexible (high bias) but more interpretable model, which uses probabilistic reasoning to approximate a hypothesized data generation process. After a model selection procedure is performed, the resulting β€œbest” model may include predictors that have a significant effect on the response albeit without necessarily improving predictive accuracy. Seemingly, a good choice of model would be the binomial logit model, commonly known as binary logistic regression. Given the lack of tools for inference after model selection as well as our intention to validate causal hypotheses, we will use domain knowledge to handpick the independent variables which are assumed to have a direct or indirect effect on the event of death; then we will quantify their effect by fitting our data into the data generation process that our model assumes. The purpose of this article is to implement a pipeline for explanatory modeling, which shows how to use a small and sparse dataset to derive medical insights on COVID-19. For this purpose, I’ve selectively combined theoretical concepts with code snippets in the R programming language. In order to reach the desirable result, the following steps are taken: Definition of a generalized linear model Data imputation versus data removal Model selection with asymptotic criteria Model validation with bootstrap inference Model interpretation The codebase used in this work can be found here. Let’s start off by loading the necessary libraries and data. # Load required libraries:library(mice)library(VIM)library(jtools)library(ggplot2)library(gridExtra)options(repr.plot.width = 14, repr.plot.height = 8)# Load COVID-19 data:dat0 = read.csv('./data/COVID19_line_list_data.csv', header = T, sep = ',')print(names(dat0)) In a predictive modeling scenario we could, at this point, pick any amount of variables we want and then let a model selection algorithm decide for us which ones to consider. In an explanatory modeling scenario, however, inference after algorithmic model selection is not a viable option. An intense variable selection process is expected to bias coefficient p-values and deprive us from using the model’s asymptotic properties. There are various ways to overcome this phenomenon but, in order to explain causal effects, we must rely on domain knowledge to isolate the variables that we consider impactful. For example, an obvious selection of variables would be those related to a patient’s age, gender, country of origin, date on which symptoms started, date on which hospitalization took place, and whether he/she is native to Wuhan. Variables such as β€˜symptom’, β€˜recovered’, β€˜hosp_visit_date’ and β€˜exposure_start’ seem relevant but are simply too sparse to be of any use. dat1 = dat0[c("location", "country", "gender", "age", "reporting.date", "symptom_onset", "hosp_visit_date", "visiting.Wuhan", "from.Wuhan", "death", "recovered", "symptom")]print(head(dat1, 5)) After isolating the most relevant predictors, our new dataset should look like this: # Binarize response:dat1$y = 0dat1$y[dat1$death==1] = 1 dat1$y = as.factor(dat1$y) We have a binary response variable that represents the event of death and we’re ready to dig deeper into the modeling process. Without intending to go into too much detail, I think it’s important to go through some basic steps in order to understand how model interpretability is obtained. Recall that in a binomial logit model, the response variable is a random vector that follows a Binomial or Bernoulli distribution: where P(Y=1)=p, for all observations i=1,...,N. This is an important difference from linear regression where the stochastic element comes from the covariates and not the response. Our model makes several other assumptions and the first step in the analysis should be to make sure that our scenario meets them. The first assumption on the distribution of the response has been already laid down, but it can be expanded with the assumption that its expected value E[Y=1]=np, for all i, can be linked to the linear combination of the covariates: which is equivalent to: for observations i=1,...,N, explanatory variables j=1,...,M, and link function g. Secondly, explanatory variables X are assumed to be independent of each other and uncorrelated. Thirdly, observations too are assumed to be independent of each other and uncorrelated. Some further assumptions have to do with the limitations of Maximum Likelihood Estimation on the size of data. It is well known that MLE tends to overfit when the number of parameters increases beyond a certain limit but, luckily, our data is nowhere near that danger zone. A more generic assumption is that our data is the result of random sampling. This is particularly important in the case of prediction, as the distribution of the response variable (sample class balance) has a direct effect on the estimate of the intercept term and, therefore, on model predictions. On the bright side, slope coefficients remain unaffected. In other words, non-representative class balance in logistic regression has a direct effect on prediction but not interpretation. Since our goal is the latter, we can proceed without making the balanced sample assumption. We can now define our model as a Binomial GLM. Recall that any GLM is defined by three components: a stochastic component a systematic component a link function Suppose that random variable Y maps the binary outcome of a COVID-19 case as a Bernoulli trial, such that: where p is the probability of observing the outcome of death P(Y=1) in a single patient, N is the number of patients with observed values for Y, and n is the number of trials per patient (in our case, n=1, for all n). This is our stochastic component. Let Ξ· be the expectation of Y, E[Y]=Ξ·, and suppose that there exists a function g(.) such that g(Ξ·) be a linear combination of the covariates: For X=x, for all j, the RHS of the above equation is our systematic component. We choose g(.)=logit(.) as the link function whose inverse, logistic(.), can squeeze the output of our model inside the [0,1] interval, which also happens to be the desired range for E[Y]=Ξ·=p, for n=1. Therefore, by plugging Ξ·=np=p into our link function g(.), we get: from which we derive the final structure of our model: Leaving out index i for simplicity’s sake, we have: The stochastic component can now be rewritten as: NB: This last expression explains why logistic regression is literally a regression and not classification. This step involves inspecting variance and sparsity in our dataset, as well as generating new predictors. After having defined our GLM and checked its assumptions, we can move on to inspect class balance in our data: table(dat1$y) The dataset agrees with our prior knowledge on the mortality rate of COVID-19, which places our analysis into the realm of rare event detection. Using domain knowledge on COVID-19 we can instantly consider β€˜age’ and β€˜gender’ as relevant predictors but we can also try to create new predictors. Something that could be informative is the time between the day the first symptoms appeared and the day the individual got hospitalized. We can easily create this predictor by taking the distance in days between hospitalization date and symptom onset date. # Cast 'Date' types:dat1$hosp_visit_date = as.character(dat1$hosp_visit_date)dat1$symptom_onset = as.character(dat1$symptom_onset)dat1$hosp_visit_date = as.Date(dat1$hosp_visit_date, format="%m/%d/%y")dat1$symptom_onset = as.Date(dat1$symptom_onset, format="%m/%d/%y")dat1$from.Wuhan = as.factor(dat1$from.Wuhan)# Create 'days before hospitalization' variable:dat1$days_before_hosp = as.numeric(as.Date(dat1$hosp_visit_date, format="%m/%d/%y") - as.Date(dat1$symptom_onset, format="%m/%d/%y"))dat1$days_before_hosp[dat1$days_before_hosp < 0] = NA So the variable that counts the days between symptom onset and hospitalization can be added to our model later on in the model selection process. The current state of the data seems to include quite a few missing values (appearing as β€˜NA’) so it would be insightful to visualize the sparsity landscape. # Plot missing values:aggr(dat1, col = c('green','red'), numbers = TRUE, sortVars = TRUE, labels = names(dat1), cex.axis = .5, gap = 2, ylab = c("Proportion in variable","Proportion in dataset")) The above table shows the proportion of missing values in every variable. The same insight is visualized on the barplot below (left image). The grid on the right illustrates the proportion of missing values of individual predictions over all values in the dataset. For example, the last row of the matrix, which is full green, tells us that 39% of our datasets cases have no missing values throughout all variables. The row before that tells us that 20% of cases are missing in the first three variables (order of appearance), the row before that shows 15% missing values in the first 5 variables, and so on. Clearly, there’s a lot of missing data and it’s scattered all over, so the choice between removal and imputation is not that obvious. Before trying to answer this question, we should try fitting a baseline model using few but substantial predictors. We want to have a model fitted on a dataset that is close to the raw dataset, but instead of imputation we will perform missing value removal. Variables with sparsity or low variance (such as β€˜country’, β€˜hosp_visit_date’, β€˜symptom_onset’) should be left out and, to minimize data removal, variables included into the baseline model should have as little missing values as possible. The model selection process will involve fitting several candidate models until we run into the one that’s closest to the β€œtrue” model. At every comparison, candidate models will be evaluated with respect to specific asymptotic criteria (to be explained). We’ll start off with a very simple model that regresses mortality rate against variables β€˜age’ and β€˜gender’. Expressing mortality risk as a function of age and gender allows us to rewrite our GLM from equation [1] as: # Loading custom functions used in the analysis:source('../input/glmlib/myglm-lib.r') #modify path as required We fit the model using R’s standard β€˜glm’ function and inspect goodness-of-fit with the help of the β€˜jtools’ package and some custom functions. We use the β€˜summ’ function from package β€˜jtools’ to get a nicely presented summary of model diagnostics. It should be noted that R’s built-in β€˜glm’ function removes by default all rows with β€˜NA’ values, so we’re being informed in the summary that only 825 out of our total 1082 observations were used in training. We also see reports on goodness-of-fit statistics and criteria such as AIC, BIC, Deviance, which can be used for model selection under certain conditions. #---------------------------------------------# Model 0: gender + age#---------------------------------------------# Train model:gfit0 = glm(y~gender+age, data = dat1, binomial)# Summarize and inspect:summ(gfit0, confint = TRUE, pvals = TRUE, digits = 3) Let’s provide some context for this output. Recall that the deviance is a generalization of the sum of squared residuals in ordinary least squares regression, so it expresses the distance of the current model from the saturated model as a function of the difference of their respective log-likelihoods l(.). Therefore, the (scaled) deviance of the current model is obtained by: which follows the asymptotic distribution: Naturally, the deviance is always positive and inversely proportional to goodness-of-fit, with D = 0 indicating the perfect fit. The null deviance D0 is the deviance of intercept-only (null) model β€” the worst possible model: β€” obtained by setting: into the above formula. Ds is the deviance of the saturated model β€” the best possible model β€” a model that has n parameters for n sample size, whose likelihood is equal to 1 and deviance is equal to 0. The deviance can be used to assess whether any two models are equal. This can be done by testing the null hypothesis that all the extra coefficients of the larger model are equal to zero. For any given pair of nested models m1 and m2, the comparison can be done by the statistic: In other words, for two nested models to be equal, the difference of their corresponding deviances should follow a Ο‡2 distribution with k degrees of freedom being equal to the difference of their corresponding degrees of freedom. Consequently, this means that we can also test whether an arbitrary model is statistically equal to either the null model (for a very bad fit) or the saturated model (for a very good fit). The code for these comparisons is provided below: # Comparing current model to the null model (LTR):pval_m0 = 1 - pchisq(gfit0$null.deviance - gfit0$deviance, gfit0$df.null - gfit0$df.residual)round(pval_m0, 3) The above comparison tests the null hypothesis: i.e. whether the current model is equal to the intercept-only model. Naturally, we want this null to be rejected in order for the current model not be deemed useless, so we expect a p-value below the accepted decision threshold (conventionally 0.05). # Comparing current model to the saturated model (Deviance test):pval_ms = 1 - pchisq(gfit0$deviance, df = gfit0$df.residual)round(pval_ms, 3) Here, we test the null: i.e. whether the current model is statistically equal to the saturated model. Failing to reject the null is the desired outcome, albeit it can’t serve as evidence for the null’s acceptance. We can assess the statistical significance of model coefficients by looking at their p-values. There is a lot of discussion these days about the reliability of p-values so I believe some explanation is due about how those p-values are obtained what they really mean. Recall that inference in GLM is asymptotic and the true distributions of fitted coefficients are unknown. The asymptotic properties of MLE give us a Gaussian distribution for model coefficients: where where I(Ξ²) denotes the Fisher information matrix. Solving for Normal(0,1) in the RHS, we derive the Wald statistic for j=0,...,M: which we use to compute confidence intervals and apply hypothesis tests (as we do with the t-statistic in linear regression). We can, therefore, compute the 100(1βˆ’Ξ±)% confidence intervals for the coefficients using: Naturally, we can also use the asymptotic distribution of the coefficients to conduct formal hypothesis tests regarding their significance by testing the null hypothesis: which uses the Wald statistic and is commonly known as the Wald test. McFadden’s pseudo-R2 is a measure of explained variation defined as: where we have the log-likelihood of the current model over 1 minus the log-likelihood of the intercept-only model. This equation is an adaptation of the R2 formula in linear regression 1βˆ’SSE/SST, however, the interpretation of the pseudo-R2 is the model’s proximity to the best fit, not the percentage of variance explained by the model. A rule of the thumb here is that a value between 0.2–0.4 generally indicates a β€œgood” fit (ranging from good to very good). Having gone through some aspects of goodness-of-fit, we realize that our baseline model is objectively not that bad. We’ve got significant p-values for the overall fit as well as one of our coefficients (using the Fisherian 95% confidence level), and we’ve got a decent pseudo-R2 of 0.20. Furthermore, we can use function β€˜plot_summs’ from package β€˜jtools’ to plot the asymptotic distributions of model coefficients and visualize the results of the Wald test by noticing how the tail of Ξ²2 (coefficient of Gender) includes the value of zero and does not reject the null : # Asymptotic distribution of model coefficients (model 0)plot_summs(gfit0, scale = TRUE, plot.distributions = TRUE) The above density plots can help us understand how asymptotic inference works. Asymptotic confidence intervals and p-values are computed by estimating integrals on this theoretical density plot and β€” under the right conditions β€” the output of asymptotic inference should match that of any objective non-asymptotic method such as (frequentist) Monte Carlo, bootstrap, or flat-prior Bayesian estimation. It would be interesting to use the model’s predictive ability to visualize the effect of age on mortality risk, for both men and women. A reconstitution of the functional relation between mortality risk and age can be seen below: # Mortality risk as a function of Age: x1 = data.frame(gender="male", age=1:90)plot(predict(gfit0, x1, type = "response"), type = 'l', xlab = "Age", ylab = "Mortality risk")x2 = data.frame(gender="female", age=1:90)lines(predict(gfit0, x2, type = "response"), col="red") This model is fine for a baseline, so we can start building up from here. The obvious next steps are to add more predictors into the model and see whether the fit improves. As previously seen, the bottleneck with this dataset is that we have too many missing values scattered throughout our predictors. If we continue adding variables and removing rows with missing values, our dataset is bound to be dangerously diminished. For example, variables β€˜age’ and β€˜gender’, that we used in our baseline, have already cost us 260 observations. Variable β€˜days_before_hosp’ is intuitively an interesting predictor but if we add it into the baseline model and apply row-wise removal, the overall number of observations in our dataset will be reduced to half its original size. The same goes for variable β€˜from.Wuhan’, which denotes whether the sampled individual was a native to Wuhan (more on the meaning of that predictor later). So if we were to exclude all rows in the dataset that have at least one missing value, we’re going to end up with a much smaller albeit complete dataset. On the other hand, if trust an imputation algorithm to β€œguess” all of our missing values, we’ll end up with a large portion of our data being the result of simulated observations. Given the current state of affairs, if we’re going to enrich the baseline model with more explanatory variables we’re facing two options: Data removal: If we assume that our data is β€œmissing at random” (MAR) or β€œmissing completely at random” (MCAR), then removal of cases should be considered. However, if this assumption is wrong then we’re at risk of introducing bias into the resulting reduced dataset. Data imputation: With the assumption that the data is β€œmissing not at random” (MNAR), there is a wide range of imputation methods to choose from. Neither of these approaches is necessarily wrong and there is no way for us to know a priori which one fits best our scenario, unless we have a clear understanding of why the data is missing. As we do not have this prior understanding in our case, it would be wise to use both approaches and generate both a reduced and an imputed dataset; then compare a model that was fitted on the former with one that was fitted on the latter. The comparison will not be straight-forward since the use of different datasets (in terms of row inputs) will result to models which will not be comparable by means of likelihood-based criteria such as AIC/BIC, Deviance, and McFadden’s pseudo-R2. The choice of the better approach will depend on the validation of the β€œmissing at random” hypothesis. If the results of data removal are similar to those of data imputation we can safely assume that the missing data was in fact β€œmissing at random”, in which case we will favor the imputed data over the reduced one. As previously stated, two interesting variables that could be added the baseline mode are: β€˜days_before_hosp’: the number of days taken between the appearance of the first COVID-19 symptoms and the patient’s subsequent hospitalization (created earlier) β€˜from.Wuhan’: the factor indicating whether the patient was from Wuhan. Again, it is somewhat counter-intuitive for this latter variable to have a significant effect to mortality rate, but there will be a rational explanation along the way. It should be noted that we intentionally refrain from automating this selection process, in an effort of keeping model comparisons down to a minimum. The purpose of this practice is to avoid dwelling into the realms of stepwise selection, a widespread technique which is nowadays wisely regarded as a statistical sin. Our next candidate models will be of the following nested form: At this point, we must create the imputed dataset. There are plenty of imputation methods to choose from depending on the nature, amount, and distribution of missing values in our data. Under a mild β€œmissing at random” assumption, we decide that the best method for our scenario would be multiple imputation by chained equation, commonly known as the MICE algorithm. Using the β€˜mice’ library, we can simulate values for all our missing data as shown below: # Create imputed dataset using 'mice':dat1_obj <- mice(dat1[c("gender", "age", "days_before_hosp", "from.Wuhan", "country")], m=5, maxit = 50, method = 'pmm', seed = 400)dat1_imp = complete(dat1_obj)dat1_imp$y = dat1$y Now we have our imputed dataset in β€˜dat1_imp’. Next we’re going to refit the baseline model plus the two new candidate models on the newly imputed dataset and summarize their diagnostics. We’re refitting our baseline model because the multiple imputation has also filled in the missing data on Gender and Age that were previously automatically removed by the β€˜glm’ function. We’re not expecting this to cause a dramatic change on the diagnostics of baseline model yet it’s essential to refit it to the exact same dataset as the new candidate models in order to make all models comparable to each other. # Train models on imputed data:gfit1a = glm(y~gender+age, data = dat1_imp, binomial)gfit1b = glm(y~gender+age+days_before_hosp, data = dat1_imp, binomial)gfit1c = glm(y~gender+age+days_before_hosp+from.Wuhan, data = dat1_imp, binomial)# Compare fits:export_summs(gfit1a, gfit1b, gfit1c, scale = F, error_format = "[{conf.low}, {conf.high}]", digits = 3, model.names = c("model 1a", "model 1b", "model 1c"))plot_summs(gfit1a, gfit1b, gfit1c, scale = TRUE, plot.distributions = F, inner_ci_level = .95, model.names = c("model 1a", "model 1b", "model 1c")) So now we have three nested models fitted on the same input cases that we can directly compare using likelihood-based criteria. As expected, there is a clear improvement in all aspects as we see both AIC and BIC values drop significantly, while pseudo-R2 has almost doubled in the third model. It’s safe to conclude that the model with both new variables is the one we should be focusing on. The 95% confidence interval plot can be thought of as a β€œpanoramic” view of the asymptotic distributions of coefficients which allows us to assess the consistency of estimation. Whether two confidence intervals overlap gives us an idea of whether the estimates of the same coefficients differ significantly between two models. This helps us detect the presence of multicollinearity, that may have been caused by the addition of new variables into the model. One might wonder, at this point, what is the best way to compare models using likelihood-based measures. As a rule of the thumb, the Akaike information criterion (AIC) has been characterized as the asymptotic equivalent of leave-one-out cross validation, therefore it’s the better metric for the purpose of prediction. The Bayesian information criterion (BIC), on the other hand, has been previously cited to be the better criterion for finding the true model among a set of candidate models, which is what we need for the purpose of explanation. Note that the β€œtrue model” is the model with the correct functional form and the correct set of regressors regarding what best explain the response, but it is not necessarily the best model for making predictions (some variables required to interpret the response might compromise the precision of estimates without adding predictive value). With that in mind, we are going to be looking at BIC as the criterion for model selection. We move onto fitting the same candidate models to a dataset that has undergone data removal. The reduced dataset will be created by listwise deletion, i.e. the removal of an input case (observation) with one or more missing values. We create the following using the following code: # Create reduced dataset for model 2:# (filter out rows with NA values)not_na_mask = !is.na(dat1$y) & !is.na(dat1$days_before_hosp) & !is.na(dat1$age) & !is.na(dat1$gender) & dat1$days_before_hosp >= 0dat2 = dat1[not_na_mask, ]table(dat2$y) We can see the total number of observations being reduced by 40%. Now let’s see what the diagnostics of the fitted models will look like. #------------------------------------------------------------------# Model 2: gender + age + time to hospitalization (on reduced # dataset)#------------------------------------------------------------------# Train model:gfit2a = glm(y~gender+age, data = dat2, binomial)gfit2b = glm(y~gender+age+days_before_hosp, data = dat2, binomial)gfit2c = glm(y~gender+age+days_before_hosp+from.Wuhan, data = dat2, binomial)# Merge model summaries:export_summs(gfit2a, gfit2b, gfit2c, scale = F, error_format = "[{conf.low}, {conf.high}]", digits = 3, model.names = c("model 2a", "model 2b", "model 2c"))# Compare asymptotic distributions of coefficients:plot_summs(gfit2a, gfit2b, gfit2c, scale = TRUE, plot.distributions = F, inner_ci_level = .95, model.names = c("model 2a", "model 2b", "model 2c")) Given how we reduced our dataset to about half its original size, the fit of this model is surprisingly good. The comparison of asymptotic distributions shows that the diagnostics of the three models fitted on the reduced dataset are as stable as the ones fitted on the imputed dataset. This is a positive result, indicating that the missing data is in fact missing at random as hypothesized, and that the imputation algorithm has done a good job at filling in missing values. This assumption is further strengthened in the next section, where we compare the best candidate models (in terms of BIC) from both datasets. # Merge summaries of two models (imputed vs. reduced)export_summs(gfit1c, gfit2c, scale = TRUE, error_format = "[{conf.low}, {conf.high}]", digits = 3, model.names = c("model 1c", "model 2c"))# Compare asymptotic distributions of coefficients:p1 = plot_summs(gfit1c, gfit2c, scale = TRUE, plot.distributions = T, model.names = c("model 1c", "model 2c"))p2 = plot_summs(gfit1c, gfit2c, scale = TRUE, plot.distributions = F, inner_ci_level = .95, model.names = c("model 1c", "model 2c"))grid.arrange(p1, p2, ncol=2) As already mentioned, likelihood-based scores are not directly comparable between models fitted on different datasets, still, given our rule of the thumb it’s safe to say a McFadden’s score of 0.56 indicates a very good fit on its own. Plotting the asymptotic distributions of the imputed dataset model’s coefficients next to those of the reduced model is a good way to compare standard errors and confirm that there is no radical change between the two approaches. The estimated coefficients of all predictors were found significant in both approaches, so we’re glad to observe that their inference remains consistent. The point estimate of the coefficient of Gender is higher in the model fitted to the reduced data, but its confidence interval overlaps with the one of the one fitted to the imputed model, therefore the inference between the two estimates is not significantly different. By now we have enough evidence to believe that our missing data is, in fact, β€œmissing at random” (MAR), i.e. the probability that a value is missing depends only on observed values and not on unobserved ones. If the MAR assumption holds, then MICE has done a good job at producing simulated observations that correctly represent the β€œreal” missing data. Consequently, the model on the MICE-imputed dataset is consistent with the model on the reduced (listwise-deleted) dataset and, therefore, it’s safe to assume that both datasets are representative random subsamples of the population. We could, in theory, use any of the two datasets for the next steps of our analysis, but for the reasons of information gain we’ll go with the imputed dataset. Having settled to the imputed dataset, we can proceed to the final stage of model selection that requires the creation and addition of a new predictor. We noticed that the addition of variable β€˜from.Wuhan’ to the model improves the fit significantly by reducing BIC and increases pseudo-R2 by about .20. At this point, it isn’t obvious to us why a variable indicating whether a person is native to Wuhan should be of any relevance to mortality rate, let alone be so influential. Let’s have a closer look at this factor by testing the number of deaths per Wuhan natives versus non-natives. There seems to be a striking difference between the mortality rates of those who are from Wuhan and those who are not. If we trust our data, such a counter-intuitive insight should not be ignored, but what could be the reason behind this difference? An unfortunate yet realistic assumption would be that people who are visitors in Wuhan either for business or tourism are, in average, of a higher income than the locals. We can challenge this assumption by comparing the death rates between those who are natives to Wuhan and those who are not. This can be achieved via a simple two-sample z-test for proportions and visualized as a barplot. #-------------------------------------------------------------------#Inspecting proportion of mortality rate in Wuhan natives:#-------------------------------------------------------------------# Create dataframe:tmp = data.frame(rbind( table(dat1_imp$y[dat1_imp$from.Wuhan==1]), table(dat1_imp$y[dat1_imp$from.Wuhan==0])))names(tmp) = c("total", "deaths")tmp$death_rate = round(tmp$deaths/tmp$total, 3)tmp$from_wuhan = as.factor(c(1,0))# Compare proportions (deaths per cases between groups):se1 = sqrt(tmp$death_rate[1]*(1-tmp$death_rate[1])/tmp$total[1]) # Standard errors of proportions:se2 = sqrt(tmp$death_rate[2]*(1-tmp$death_rate[2])/tmp$total[2])tmp$prop_se = round(c(se1, se2), 4)print(tmp)print(prop.test(x = tmp$deaths, n = tmp$total, alternative = "greater"))# Barplot of proportions:ggplot(tmp, aes( y=death_rate, x=from_wuhan)) + geom_bar(position="dodge", stat="identity", width=0.4, color="black", fill="cyan", alpha=.2) + geom_errorbar(aes(ymin=death_rate - prop_se, ymax=death_rate + prop_se), width=.1, position=position_dodge(.9)) Clearly, there’s a significant difference in the average mortality rate between Wuhan natives and non-natives. Let’s explore the same test for different covariates, such as the average number of days gone by before hospitalization between the two groups: # Compare average number of days gone by before hospitalization # between both groups:d1 = dat1_imp$days_before_hosp[dat1_imp$from.Wuhan==1]d2 = dat1_imp$days_before_hosp[dat1_imp$from.Wuhan==0]sem1 = t.test(d1)$stderrsem2 = t.test(d1)$stderrtmp$avg_days = c(mean(d1), mean(d2))tmp$mean_se = c(sem1, sem2)print(tmp)t.test(d1, d2, alternative = "greater")# Barplot:b1 = ggplot(tmp, aes( y=avg_days, x=from_wuhan, fill=from_wuhan)) + geom_bar(position="dodge", stat="identity", width = .4, alpha=1) + geom_errorbar(aes(ymin=avg_days - mean_se, ymax=avg_days + mean_se), width=.1, position=position_dodge(.9)) # Boxplot:df = data.frame(days = c(d1, d2), from_wuhan = as.factor(c(numeric(length(d1))+1, numeric(length(d2)) )) )b2 = ggplot(df, aes( y=days, x=from_wuhan, fill=from_wuhan)) + geom_boxplot(outlier.colour="black", outlier.shape=16, outlier.size=2, notch=T) + stat_summary(fun=mean, geom="point", shape=23, size=4) grid.arrange(b1, b2, ncol=2) As suspected, there is also a significant difference in this test. The distance between their means may be small (3.70 versus 2.68), but their difference is statistically significant, which further strengthens our hypothesis about a latent connection between the factor β€˜from.Wuhan’ and the individual’s socioeconomic status. At this point we can speculate that variable β€˜from.Wuhan’ acts as confounding factor for another latent variable. In other words, there might be another predictor carrying all socioeconomic information, to which β€˜from.Wuhan’ correlates. A logical assumption would be that this latent predictor is β€˜country’, on the grounds that someone’s ethnicity is directly correlated to both his/her socioeconomic status as well as the event of being a native to Wuhan. We’ve already established that can’t add β€˜country’ into the model because of its low variance, but we can β€˜from.Wuhan’ under the assumption that it acts as its proxy. There has to be another latent variable that is more granular than β€˜from.Wuhan’ and, at the time, is correlated to β€˜country’. We will introduce a country-level macroeconomic variable such as GDP (PPP), which expresses a country’s gross domestic product (at purchasing power parity) per capita. If there is a significant difference in the average GDP value per country between groups (from Wuhan, not from Wuhan), then our initial assumption about the patient’s wealth being associated to mortality rate will be further strengthened. Ultimately, this variable should also improve the fit of our model. Let’s create a data vector for GDP, where the order of elements corresponds to the order of country names (as listed by β€˜levels(dat$country)’): # Adding GDP (PPP):dat = dat1_impdat$gdp = 0gdp_per_country = c(2182, 16091, 54799, 55171, 51991, 50904, 5004, 52144, 20984, 29207, 14800, 49548, 48640, 55306, 66527, 9027, 17832, 40337, 41582, 46827, 67891, 15599, 34567, 3550, 10094, 30820, 105689, 46452, 43007, 14509, 55989, 67558, 57214, 21361, 70441, 48169, 67426, 8677)for(i in 1:length(gdp_per_country)){ country = levels(dat$country)[i] country_inds = dat$country == country dat$gdp[country_inds] = gdp_per_country[i]} A new column called β€˜gdp’ is now part of the imputed data. Let’s see what happens when we introduce that variable into our model. The model with GDP will, therefore, be of the following form: #----------------------------------------------------------------# Model 4: Adding GDP (PPP)#----------------------------------------------------------------# Fit model with GDP:gfit1d = glm(y~gender+age+days_before_hosp+from.Wuhan+gdp, data = dat, binomial)# Compare models with GDP with and without GDP:# Merge model summaries:export_summs(gfit1c, gfit1d, scale = F, error_format = "[{conf.low}, {conf.high}]", model.names = c("without GDP", "with GDP"))# Compare asymtotic distributions:f1 = plot_summs(gfit1c, gfit1d, scale = TRUE, plot.distributions = TRUE, model.names = c("without GDP", "with GDP"))f2 = plot_summs(gfit1c, gfit2c, scale = TRUE, plot.distributions = F, inner_ci_level = .95, model.names = c("without GDP", "with GDP"))grid.arrange(f1, f2, ncol=2)# Final model summary:summ(gfit1d, scale = F, plot.distributions = TRUE, inner_ci_level = .9, digits = 3)gfit = gfit1d #rename final model As speculated, adding GDP into our model has further improved the fit as shown by a significant reduction in BIC and an increase in pseudo-R2. Its coefficient may be very small (possibly due to the presence of β€˜from.Wuhan’ in our model) but its impact is nonetheless significant. We can further compare the average GDP per group (Wuhan natives versus non-natives) to assess whether their difference is significant: # Mean GDP per group (from Wuhan):d3 = dat$gdp[dat$from.Wuhan==1]d4 = dat$gdp[dat$from.Wuhan==0]t.test(d3, d4)sem3 = t.test(d3)$stderrsem4 = t.test(d4)$stderrtmp$avg_gdp = c(mean(d3), mean(d4))tmp$mean_se_gdp = c(sem3, sem4)# Barplot:f3 = ggplot(tmp, aes( y=avg_gdp, x=from_wuhan, fill=from_wuhan)) + geom_bar(position="dodge", stat="identity", width = .5) + geom_errorbar(aes(ymin=avg_gdp-mean_se_gdp, ymax=avg_gdp+mean_se_gdp), width=.1, position=position_dodge(.9)) # Boxplot:df = data.frame(days = c(d1, d2), gdp = c(d3, d4), from_wuhan = as.factor(c(numeric(length(d1))+1, numeric(length(d2)) )) )f4 = ggplot(df, aes( y=gdp, x=from_wuhan, fill=from_wuhan)) + geom_boxplot(outlier.colour="black", outlier.shape=16, outlier.size=2, notch=FALSE) + stat_summary(fun=mean, geom="point", shape=23, size=4)grid.arrange(f3, f4, ncol=2) Our hypothesis test confirms that the average GDP (PPP) in deceased patients from Wuhan is significantly different to the average GDP (PPP) from deceased patients who are not from Wuhan. This is a further confirmation in favor of our model’s coefficient p-values. So far we’ve confirmed that the imputed dataset is the β€œbest” dataset, and that the model with predictors β€˜age’, β€˜gender’, β€˜days_before_hosp’, β€˜from.Wuhan’, β€˜gdp’, is the one closest to the β€œtrue” model. As a last step in our modeling process, we will use computational inference in order to assess coefficient stability and evaluate the homogeneity of our sample. So far we’ve been through a conservative model selection process which has led to a model that we believe to be close to the true model. A final step in the validation process would be to test the stability of model coefficients through a bootstrap procedure. If our coefficients are found to be β€œstable” then our sample can be considered homogeneous and our estimates reliable. The stability of coefficients here is evaluated using two criteria: The statistical significance of computational/bagged coefficient estimates (i.e. assessed when the empirical distribution does not include zero) The closeness of computational/bagged estimates to asymptotic estimates (i.e. assessed when the distribution of the difference between the asymptotic and computational means does include zero) Note that the purpose of bootstrap aggregation (bagging) and resampling, in this context, is not exactly identical to that of Random Forest. We will use random subsampling with replacement to train multiple models, but our goal is to create bagged estimates and bootstrap confidence intervals for model coefficients, not for model predictions. Bagging will be used to produce point estimates for model parameters (bagged coefficients), while the empirical bootstrap distributions and associated bootstrap confidence intervals of those bagged estimates will allow us to evaluate model stability of estimation. In its simplest form, this evaluation consists of testing the hypothesis that the bagged estimates are equal to the asymptotic estimates, which comes down to comparing the asymptotic distribution and the bootstrap distribution of the same parameter. One way to achieve this is by testing the null that the difference between bagged and asymptotic estimates is equal to zero. If we can show that the asymptotic estimate is likely not different from the computational (bootstrap) estimate, we can safely assume that we have converged to the β€œtrue” coefficients. We use our custom function β€˜bagged_glm’ to obtain bootstrap distributions for model parameters. The β€˜alpha’ argument is used in model summary statistics, the β€˜class_balancing’ flag resamples the undersampled class at 50% (not used), the β€˜bag_pct’ argument determines the size of the training bag, and flag β€˜ocv’ activates out-of-bad cross validation (equivalent to Random Forest’s out-of-bag error). #-------------------------------------------------# Coefficient stability (final model):#-------------------------------------------------bagged_results = bagged_glm(dat = dat, gfit = gfit, alpha = 0.05, class_balancing = F, bag_pct = 0.80, ocv = T)coef_bags_df = bagged_results$coef_bags_df Let’s have a look at the results of computational inference: # Bootstrap means of transformed coefficients:cat( "\n Bootstrap means of back-transformed coefficients:\n", "Intercept: ", mean(coef_bags_df$`(Intercept)`), "Gender: ", mean(coef_bags_df$gendermale), "Age: ", mean(coef_bags_df$age), "Days before hospitalization: ", mean(coef_bags_df$days_before_hosp), "From Wuhan: ", mean(coef_bags_df$from.Wuhan1), "\n")# Compare with asymptotic values: (merge with table above)coefficients(gfit)confint(gfit) # Test null distribution directly: H0: m2-m1 = 0 par(mfcol=c(3,2))for(i in 1:length(bagged_results$coef_bags_df)){ d = bagged_results$coef_bags_df[[i]] - coefficients(gfit)[i] qtt = quantile(d, c(.975, .025)) att = t.test(d) hist(d, col="lightblue", main = names(coefficients(gfit)[i]), breaks = 30) abline(v = 0, col="blue", lwd=3, lty=2) abline(v = qtt[1], col="red", lwd=3, lty=2) abline(v = qtt[2], col="red", lwd=3, lty=2)}dev.off() As we see in the above histograms, the distribution of the difference d between bagged and asymptotic estimates ΞΌ2 - ΞΌ1 does include zero (blue line) within its bootstrap confidence interval (red lines). Therefore, the null hypothesis: fails to be rejected at the 95% significance level. Even though the failure to reject a null hypothesis does not imply its acceptance, this finding combined to all our previous findings should suffice to assume the reliability of our estimation and allow us to move onto model interpretation. As the long-awaited step in the analysis, we can finally move onto to interpreting the coefficients of our model. Recall that any binomial logit model (equation [1]) can be expressed as: Solving for Ξ²0 yields: Solving for Ξ²j yields: and finally: The value of Ξ²0 in expression [2] can be translated as the odds of the response being 1, when all continuous regressors are 0 and categorical regressors are at their base level. In our scenario, we can say that β€œthe average probability of death when days before hospitalization, age of patient, and GDP, are at zero, and the patient is not a native to Wuhan”. Obviously, patient age and GDP being equal to 0 is a nonsensical interpretation but, as previously stated, we’re not interested in the direct interpretation of Ξ²0 in this analysis (otherwise we could have used an intercept correction technique). The interpretation of Ξ²j in expression [3] is the one that interests us, and it can be generically interpreted as the percentage change in the odds of the response (being equal to 1) for every unit-increase in regressor j, if x continuous, or for the transition from the base level to the current level if x is categorical; ceteris paribus. For this interpretation to make any sense, we must adapt it to our scenario and look at Ξ²j simply as: β€œThe percentage change in the probability of mortality”, for whatever change corresponds to regressor j, all else being equal. We can apply this interpretation to the coefficients of our final model: So let’s summarize the coefficients of our model in both raw and transformed form: glm.transform(gfit, alpha = .10, logodds_str = "exp(beta)%", ci = T, stdout = F) glm.plot(gfit, alpha = 0.10, logodds_str = "exp(beta)%", stdout = F) We can keep the transformed coefficient as a factor and interpret the odds of Y to be a number of times higher to those of X, or we can use the percentage change form and say that the probability of Y changes by a certain proportion for every change in X, as explained. Personally, I find the latter interpretation to be more intuitive and below we can see its application on each of our model’s coefficients at the 90% confidence level: [Age] β€” exp(Ξ²1): The risk of death for a patient with COVID-19 increases by roughly 11% for every yearly increase in age. (CI: 8.36%-14.97%)A more intuitive way to express this insight would be to multiply the transformed coefficient by a factor of 10 and derive a 114% increase in odds for a 10-year increase in age. We can, therefore, say that:COVID-19’s mortality risk almost doubles with every 10-year increase of age. [Gender] β€” exp(Ξ²2): COVID-19’s mortality risk is 120% higher in men, compared to that of women. (CI: 8.67%-367%) [daysBeforeHosp] β€” exp(Ξ²3): The risk of death for a patient with COVID-19 increases by 12% every day the patient stays unhospitalized after the first day he/she developed first symptoms. (CI: 2.7%-20.9%) [fromWuhan] β€” exp(Ξ²4): COVID-19’s mortality risk is roughly 6 times higher for patients native to Wuhan. (CI: 231%-1577%) [GDP] β€” exp(Ξ²5): COVID-19’s mortality risk is indirectly impacted by the patient’s country of origin GDP (PPP). The effect is too weak to quantify though, combined with β€˜fromWuhan’, it likely implies a dependence between a patient’s chance to survive and their individual wealth.
[ { "code": null, "e": 919, "s": 172, "text": "Perhaps a positive side-effect of the recent pandemic and the associated lockdown is that we get to materialize projects that had been set aside. For a while I’ve wanted to write an article about statistical model interpretation and all I needed was time, motivation, and data. This Kaggle dataset consists of 1085 COVID-19 cases sampled in the city of Wuhan between December 2019 and March 2020, and it was one of the first published datasets to contain records at patient-level. This TDS article provides a nice overview of the data and its fields. Having records at patient-level means that there is enough granularity to derive medical insights about how a person’s individual attributes relate to the risk of dying from exposure to COVID-19." }, { "code": null, "e": 1018, "s": 919, "text": "This guide to explanatory modeling requires an intermediate understanding of the following topics:" }, { "code": null, "e": 1055, "s": 1018, "text": "Probability theory and distributions" }, { "code": null, "e": 1092, "s": 1055, "text": "Statistical estimation and inference" }, { "code": null, "e": 1158, "s": 1092, "text": "Machine learning concepts such as logistic regression and bagging" }, { "code": null, "e": 1221, "s": 1158, "text": "Computational statistics concepts such as bootstrap resampling" }, { "code": null, "e": 1248, "s": 1221, "text": "The R programming language" }, { "code": null, "e": 1695, "s": 1248, "text": "A mortality risk analysis requires a response variable with records on the event of death. We will consequently try to express this response as a function of predictor variables, which are directly or indirectly related to the effect of COVID-19 on man’s health. The purpose of an explanatory model is to explain rather than predict the outcome of death, where the objective of explanation is the application of statistical inference in order to:" }, { "code": null, "e": 1784, "s": 1695, "text": "identify predictor variables with statistically significant impact to the event of death" }, { "code": null, "e": 1847, "s": 1784, "text": "estimate the magnitude of impact of the significant predictors" }, { "code": null, "e": 1889, "s": 1847, "text": "quantify the uncertainty of our estimates" }, { "code": null, "e": 2594, "s": 1889, "text": "In other words, we’re interested in a model that will be used for inference rather than prediction or β€” to state it more accurately β€” one that favors causal inference over predictive inference. It’s crucial to understand the distinction between the two as it determines our rationale behind our choice of modeling approach. Explanatory analysis requires a less flexible (high bias) but more interpretable model, which uses probabilistic reasoning to approximate a hypothesized data generation process. After a model selection procedure is performed, the resulting β€œbest” model may include predictors that have a significant effect on the response albeit without necessarily improving predictive accuracy." }, { "code": null, "e": 3438, "s": 2594, "text": "Seemingly, a good choice of model would be the binomial logit model, commonly known as binary logistic regression. Given the lack of tools for inference after model selection as well as our intention to validate causal hypotheses, we will use domain knowledge to handpick the independent variables which are assumed to have a direct or indirect effect on the event of death; then we will quantify their effect by fitting our data into the data generation process that our model assumes. The purpose of this article is to implement a pipeline for explanatory modeling, which shows how to use a small and sparse dataset to derive medical insights on COVID-19. For this purpose, I’ve selectively combined theoretical concepts with code snippets in the R programming language. In order to reach the desirable result, the following steps are taken:" }, { "code": null, "e": 3479, "s": 3438, "text": "Definition of a generalized linear model" }, { "code": null, "e": 3515, "s": 3479, "text": "Data imputation versus data removal" }, { "code": null, "e": 3556, "s": 3515, "text": "Model selection with asymptotic criteria" }, { "code": null, "e": 3598, "s": 3556, "text": "Model validation with bootstrap inference" }, { "code": null, "e": 3619, "s": 3598, "text": "Model interpretation" }, { "code": null, "e": 3669, "s": 3619, "text": "The codebase used in this work can be found here." }, { "code": null, "e": 3730, "s": 3669, "text": "Let’s start off by loading the necessary libraries and data." }, { "code": null, "e": 4012, "s": 3730, "text": "# Load required libraries:library(mice)library(VIM)library(jtools)library(ggplot2)library(gridExtra)options(repr.plot.width = 14, repr.plot.height = 8)# Load COVID-19 data:dat0 = read.csv('./data/COVID19_line_list_data.csv', header = T, sep = ',')print(names(dat0))" }, { "code": null, "e": 4988, "s": 4012, "text": "In a predictive modeling scenario we could, at this point, pick any amount of variables we want and then let a model selection algorithm decide for us which ones to consider. In an explanatory modeling scenario, however, inference after algorithmic model selection is not a viable option. An intense variable selection process is expected to bias coefficient p-values and deprive us from using the model’s asymptotic properties. There are various ways to overcome this phenomenon but, in order to explain causal effects, we must rely on domain knowledge to isolate the variables that we consider impactful. For example, an obvious selection of variables would be those related to a patient’s age, gender, country of origin, date on which symptoms started, date on which hospitalization took place, and whether he/she is native to Wuhan. Variables such as β€˜symptom’, β€˜recovered’, β€˜hosp_visit_date’ and β€˜exposure_start’ seem relevant but are simply too sparse to be of any use." }, { "code": null, "e": 5182, "s": 4988, "text": "dat1 = dat0[c(\"location\", \"country\", \"gender\", \"age\", \"reporting.date\", \"symptom_onset\", \"hosp_visit_date\", \"visiting.Wuhan\", \"from.Wuhan\", \"death\", \"recovered\", \"symptom\")]print(head(dat1, 5))" }, { "code": null, "e": 5267, "s": 5182, "text": "After isolating the most relevant predictors, our new dataset should look like this:" }, { "code": null, "e": 5352, "s": 5267, "text": "# Binarize response:dat1$y = 0dat1$y[dat1$death==1] = 1 dat1$y = as.factor(dat1$y)" }, { "code": null, "e": 5479, "s": 5352, "text": "We have a binary response variable that represents the event of death and we’re ready to dig deeper into the modeling process." }, { "code": null, "e": 5642, "s": 5479, "text": "Without intending to go into too much detail, I think it’s important to go through some basic steps in order to understand how model interpretability is obtained." }, { "code": null, "e": 5773, "s": 5642, "text": "Recall that in a binomial logit model, the response variable is a random vector that follows a Binomial or Bernoulli distribution:" }, { "code": null, "e": 5821, "s": 5773, "text": "where P(Y=1)=p, for all observations i=1,...,N." }, { "code": null, "e": 6083, "s": 5821, "text": "This is an important difference from linear regression where the stochastic element comes from the covariates and not the response. Our model makes several other assumptions and the first step in the analysis should be to make sure that our scenario meets them." }, { "code": null, "e": 6316, "s": 6083, "text": "The first assumption on the distribution of the response has been already laid down, but it can be expanded with the assumption that its expected value E[Y=1]=np, for all i, can be linked to the linear combination of the covariates:" }, { "code": null, "e": 6340, "s": 6316, "text": "which is equivalent to:" }, { "code": null, "e": 6880, "s": 6340, "text": "for observations i=1,...,N, explanatory variables j=1,...,M, and link function g. Secondly, explanatory variables X are assumed to be independent of each other and uncorrelated. Thirdly, observations too are assumed to be independent of each other and uncorrelated. Some further assumptions have to do with the limitations of Maximum Likelihood Estimation on the size of data. It is well known that MLE tends to overfit when the number of parameters increases beyond a certain limit but, luckily, our data is nowhere near that danger zone." }, { "code": null, "e": 7459, "s": 6880, "text": "A more generic assumption is that our data is the result of random sampling. This is particularly important in the case of prediction, as the distribution of the response variable (sample class balance) has a direct effect on the estimate of the intercept term and, therefore, on model predictions. On the bright side, slope coefficients remain unaffected. In other words, non-representative class balance in logistic regression has a direct effect on prediction but not interpretation. Since our goal is the latter, we can proceed without making the balanced sample assumption." }, { "code": null, "e": 7558, "s": 7459, "text": "We can now define our model as a Binomial GLM. Recall that any GLM is defined by three components:" }, { "code": null, "e": 7581, "s": 7558, "text": "a stochastic component" }, { "code": null, "e": 7604, "s": 7581, "text": "a systematic component" }, { "code": null, "e": 7620, "s": 7604, "text": "a link function" }, { "code": null, "e": 7727, "s": 7620, "text": "Suppose that random variable Y maps the binary outcome of a COVID-19 case as a Bernoulli trial, such that:" }, { "code": null, "e": 7979, "s": 7727, "text": "where p is the probability of observing the outcome of death P(Y=1) in a single patient, N is the number of patients with observed values for Y, and n is the number of trials per patient (in our case, n=1, for all n). This is our stochastic component." }, { "code": null, "e": 8122, "s": 7979, "text": "Let Ξ· be the expectation of Y, E[Y]=Ξ·, and suppose that there exists a function g(.) such that g(Ξ·) be a linear combination of the covariates:" }, { "code": null, "e": 8201, "s": 8122, "text": "For X=x, for all j, the RHS of the above equation is our systematic component." }, { "code": null, "e": 8470, "s": 8201, "text": "We choose g(.)=logit(.) as the link function whose inverse, logistic(.), can squeeze the output of our model inside the [0,1] interval, which also happens to be the desired range for E[Y]=Ξ·=p, for n=1. Therefore, by plugging Ξ·=np=p into our link function g(.), we get:" }, { "code": null, "e": 8525, "s": 8470, "text": "from which we derive the final structure of our model:" }, { "code": null, "e": 8577, "s": 8525, "text": "Leaving out index i for simplicity’s sake, we have:" }, { "code": null, "e": 8627, "s": 8577, "text": "The stochastic component can now be rewritten as:" }, { "code": null, "e": 8735, "s": 8627, "text": "NB: This last expression explains why logistic regression is literally a regression and not classification." }, { "code": null, "e": 8952, "s": 8735, "text": "This step involves inspecting variance and sparsity in our dataset, as well as generating new predictors. After having defined our GLM and checked its assumptions, we can move on to inspect class balance in our data:" }, { "code": null, "e": 8966, "s": 8952, "text": "table(dat1$y)" }, { "code": null, "e": 9517, "s": 8966, "text": "The dataset agrees with our prior knowledge on the mortality rate of COVID-19, which places our analysis into the realm of rare event detection. Using domain knowledge on COVID-19 we can instantly consider β€˜age’ and β€˜gender’ as relevant predictors but we can also try to create new predictors. Something that could be informative is the time between the day the first symptoms appeared and the day the individual got hospitalized. We can easily create this predictor by taking the distance in days between hospitalization date and symptom onset date." }, { "code": null, "e": 10064, "s": 9517, "text": "# Cast 'Date' types:dat1$hosp_visit_date = as.character(dat1$hosp_visit_date)dat1$symptom_onset = as.character(dat1$symptom_onset)dat1$hosp_visit_date = as.Date(dat1$hosp_visit_date, format=\"%m/%d/%y\")dat1$symptom_onset = as.Date(dat1$symptom_onset, format=\"%m/%d/%y\")dat1$from.Wuhan = as.factor(dat1$from.Wuhan)# Create 'days before hospitalization' variable:dat1$days_before_hosp = as.numeric(as.Date(dat1$hosp_visit_date, format=\"%m/%d/%y\") - as.Date(dat1$symptom_onset, format=\"%m/%d/%y\"))dat1$days_before_hosp[dat1$days_before_hosp < 0] = NA" }, { "code": null, "e": 10367, "s": 10064, "text": "So the variable that counts the days between symptom onset and hospitalization can be added to our model later on in the model selection process. The current state of the data seems to include quite a few missing values (appearing as β€˜NA’) so it would be insightful to visualize the sparsity landscape." }, { "code": null, "e": 10573, "s": 10367, "text": "# Plot missing values:aggr(dat1, col = c('green','red'), numbers = TRUE, sortVars = TRUE, labels = names(dat1), cex.axis = .5, gap = 2, ylab = c(\"Proportion in variable\",\"Proportion in dataset\"))" }, { "code": null, "e": 10713, "s": 10573, "text": "The above table shows the proportion of missing values in every variable. The same insight is visualized on the barplot below (left image)." }, { "code": null, "e": 11182, "s": 10713, "text": "The grid on the right illustrates the proportion of missing values of individual predictions over all values in the dataset. For example, the last row of the matrix, which is full green, tells us that 39% of our datasets cases have no missing values throughout all variables. The row before that tells us that 20% of cases are missing in the first three variables (order of appearance), the row before that shows 15% missing values in the first 5 variables, and so on." }, { "code": null, "e": 11814, "s": 11182, "text": "Clearly, there’s a lot of missing data and it’s scattered all over, so the choice between removal and imputation is not that obvious. Before trying to answer this question, we should try fitting a baseline model using few but substantial predictors. We want to have a model fitted on a dataset that is close to the raw dataset, but instead of imputation we will perform missing value removal. Variables with sparsity or low variance (such as β€˜country’, β€˜hosp_visit_date’, β€˜symptom_onset’) should be left out and, to minimize data removal, variables included into the baseline model should have as little missing values as possible." }, { "code": null, "e": 12070, "s": 11814, "text": "The model selection process will involve fitting several candidate models until we run into the one that’s closest to the β€œtrue” model. At every comparison, candidate models will be evaluated with respect to specific asymptotic criteria (to be explained)." }, { "code": null, "e": 12179, "s": 12070, "text": "We’ll start off with a very simple model that regresses mortality rate against variables β€˜age’ and β€˜gender’." }, { "code": null, "e": 12288, "s": 12179, "text": "Expressing mortality risk as a function of age and gender allows us to rewrite our GLM from equation [1] as:" }, { "code": null, "e": 12399, "s": 12288, "text": "# Loading custom functions used in the analysis:source('../input/glmlib/myglm-lib.r') #modify path as required" }, { "code": null, "e": 13012, "s": 12399, "text": "We fit the model using R’s standard β€˜glm’ function and inspect goodness-of-fit with the help of the β€˜jtools’ package and some custom functions. We use the β€˜summ’ function from package β€˜jtools’ to get a nicely presented summary of model diagnostics. It should be noted that R’s built-in β€˜glm’ function removes by default all rows with β€˜NA’ values, so we’re being informed in the summary that only 825 out of our total 1082 observations were used in training. We also see reports on goodness-of-fit statistics and criteria such as AIC, BIC, Deviance, which can be used for model selection under certain conditions." }, { "code": null, "e": 13267, "s": 13012, "text": "#---------------------------------------------# Model 0: gender + age#---------------------------------------------# Train model:gfit0 = glm(y~gender+age, data = dat1, binomial)# Summarize and inspect:summ(gfit0, confint = TRUE, pvals = TRUE, digits = 3)" }, { "code": null, "e": 13311, "s": 13267, "text": "Let’s provide some context for this output." }, { "code": null, "e": 13645, "s": 13311, "text": "Recall that the deviance is a generalization of the sum of squared residuals in ordinary least squares regression, so it expresses the distance of the current model from the saturated model as a function of the difference of their respective log-likelihoods l(.). Therefore, the (scaled) deviance of the current model is obtained by:" }, { "code": null, "e": 13688, "s": 13645, "text": "which follows the asymptotic distribution:" }, { "code": null, "e": 13913, "s": 13688, "text": "Naturally, the deviance is always positive and inversely proportional to goodness-of-fit, with D = 0 indicating the perfect fit. The null deviance D0 is the deviance of intercept-only (null) model β€” the worst possible model:" }, { "code": null, "e": 13936, "s": 13913, "text": "β€” obtained by setting:" }, { "code": null, "e": 14138, "s": 13936, "text": "into the above formula. Ds is the deviance of the saturated model β€” the best possible model β€” a model that has n parameters for n sample size, whose likelihood is equal to 1 and deviance is equal to 0." }, { "code": null, "e": 14418, "s": 14138, "text": "The deviance can be used to assess whether any two models are equal. This can be done by testing the null hypothesis that all the extra coefficients of the larger model are equal to zero. For any given pair of nested models m1 and m2, the comparison can be done by the statistic:" }, { "code": null, "e": 14887, "s": 14418, "text": "In other words, for two nested models to be equal, the difference of their corresponding deviances should follow a Ο‡2 distribution with k degrees of freedom being equal to the difference of their corresponding degrees of freedom. Consequently, this means that we can also test whether an arbitrary model is statistically equal to either the null model (for a very bad fit) or the saturated model (for a very good fit). The code for these comparisons is provided below:" }, { "code": null, "e": 15048, "s": 14887, "text": "# Comparing current model to the null model (LTR):pval_m0 = 1 - pchisq(gfit0$null.deviance - gfit0$deviance, gfit0$df.null - gfit0$df.residual)round(pval_m0, 3)" }, { "code": null, "e": 15096, "s": 15048, "text": "The above comparison tests the null hypothesis:" }, { "code": null, "e": 15347, "s": 15096, "text": "i.e. whether the current model is equal to the intercept-only model. Naturally, we want this null to be rejected in order for the current model not be deemed useless, so we expect a p-value below the accepted decision threshold (conventionally 0.05)." }, { "code": null, "e": 15490, "s": 15347, "text": "# Comparing current model to the saturated model (Deviance test):pval_ms = 1 - pchisq(gfit0$deviance, df = gfit0$df.residual)round(pval_ms, 3)" }, { "code": null, "e": 15514, "s": 15490, "text": "Here, we test the null:" }, { "code": null, "e": 15704, "s": 15514, "text": "i.e. whether the current model is statistically equal to the saturated model. Failing to reject the null is the desired outcome, albeit it can’t serve as evidence for the null’s acceptance." }, { "code": null, "e": 16166, "s": 15704, "text": "We can assess the statistical significance of model coefficients by looking at their p-values. There is a lot of discussion these days about the reliability of p-values so I believe some explanation is due about how those p-values are obtained what they really mean. Recall that inference in GLM is asymptotic and the true distributions of fitted coefficients are unknown. The asymptotic properties of MLE give us a Gaussian distribution for model coefficients:" }, { "code": null, "e": 16302, "s": 16166, "text": "where where I(Ξ²) denotes the Fisher information matrix. Solving for Normal(0,1) in the RHS, we derive the Wald statistic for j=0,...,M:" }, { "code": null, "e": 16518, "s": 16302, "text": "which we use to compute confidence intervals and apply hypothesis tests (as we do with the t-statistic in linear regression). We can, therefore, compute the 100(1βˆ’Ξ±)% confidence intervals for the coefficients using:" }, { "code": null, "e": 16689, "s": 16518, "text": "Naturally, we can also use the asymptotic distribution of the coefficients to conduct formal hypothesis tests regarding their significance by testing the null hypothesis:" }, { "code": null, "e": 16759, "s": 16689, "text": "which uses the Wald statistic and is commonly known as the Wald test." }, { "code": null, "e": 16828, "s": 16759, "text": "McFadden’s pseudo-R2 is a measure of explained variation defined as:" }, { "code": null, "e": 17290, "s": 16828, "text": "where we have the log-likelihood of the current model over 1 minus the log-likelihood of the intercept-only model. This equation is an adaptation of the R2 formula in linear regression 1βˆ’SSE/SST, however, the interpretation of the pseudo-R2 is the model’s proximity to the best fit, not the percentage of variance explained by the model. A rule of the thumb here is that a value between 0.2–0.4 generally indicates a β€œgood” fit (ranging from good to very good)." }, { "code": null, "e": 17862, "s": 17290, "text": "Having gone through some aspects of goodness-of-fit, we realize that our baseline model is objectively not that bad. We’ve got significant p-values for the overall fit as well as one of our coefficients (using the Fisherian 95% confidence level), and we’ve got a decent pseudo-R2 of 0.20. Furthermore, we can use function β€˜plot_summs’ from package β€˜jtools’ to plot the asymptotic distributions of model coefficients and visualize the results of the Wald test by noticing how the tail of Ξ²2 (coefficient of Gender) includes the value of zero and does not reject the null :" }, { "code": null, "e": 17978, "s": 17862, "text": "# Asymptotic distribution of model coefficients (model 0)plot_summs(gfit0, scale = TRUE, plot.distributions = TRUE)" }, { "code": null, "e": 18380, "s": 17978, "text": "The above density plots can help us understand how asymptotic inference works. Asymptotic confidence intervals and p-values are computed by estimating integrals on this theoretical density plot and β€” under the right conditions β€” the output of asymptotic inference should match that of any objective non-asymptotic method such as (frequentist) Monte Carlo, bootstrap, or flat-prior Bayesian estimation." }, { "code": null, "e": 18610, "s": 18380, "text": "It would be interesting to use the model’s predictive ability to visualize the effect of age on mortality risk, for both men and women. A reconstitution of the functional relation between mortality risk and age can be seen below:" }, { "code": null, "e": 18885, "s": 18610, "text": "# Mortality risk as a function of Age: x1 = data.frame(gender=\"male\", age=1:90)plot(predict(gfit0, x1, type = \"response\"), type = 'l', xlab = \"Age\", ylab = \"Mortality risk\")x2 = data.frame(gender=\"female\", age=1:90)lines(predict(gfit0, x2, type = \"response\"), col=\"red\")" }, { "code": null, "e": 20279, "s": 18885, "text": "This model is fine for a baseline, so we can start building up from here. The obvious next steps are to add more predictors into the model and see whether the fit improves. As previously seen, the bottleneck with this dataset is that we have too many missing values scattered throughout our predictors. If we continue adding variables and removing rows with missing values, our dataset is bound to be dangerously diminished. For example, variables β€˜age’ and β€˜gender’, that we used in our baseline, have already cost us 260 observations. Variable β€˜days_before_hosp’ is intuitively an interesting predictor but if we add it into the baseline model and apply row-wise removal, the overall number of observations in our dataset will be reduced to half its original size. The same goes for variable β€˜from.Wuhan’, which denotes whether the sampled individual was a native to Wuhan (more on the meaning of that predictor later). So if we were to exclude all rows in the dataset that have at least one missing value, we’re going to end up with a much smaller albeit complete dataset. On the other hand, if trust an imputation algorithm to β€œguess” all of our missing values, we’ll end up with a large portion of our data being the result of simulated observations. Given the current state of affairs, if we’re going to enrich the baseline model with more explanatory variables we’re facing two options:" }, { "code": null, "e": 20547, "s": 20279, "text": "Data removal: If we assume that our data is β€œmissing at random” (MAR) or β€œmissing completely at random” (MCAR), then removal of cases should be considered. However, if this assumption is wrong then we’re at risk of introducing bias into the resulting reduced dataset." }, { "code": null, "e": 20693, "s": 20547, "text": "Data imputation: With the assumption that the data is β€œmissing not at random” (MNAR), there is a wide range of imputation methods to choose from." }, { "code": null, "e": 21688, "s": 20693, "text": "Neither of these approaches is necessarily wrong and there is no way for us to know a priori which one fits best our scenario, unless we have a clear understanding of why the data is missing. As we do not have this prior understanding in our case, it would be wise to use both approaches and generate both a reduced and an imputed dataset; then compare a model that was fitted on the former with one that was fitted on the latter. The comparison will not be straight-forward since the use of different datasets (in terms of row inputs) will result to models which will not be comparable by means of likelihood-based criteria such as AIC/BIC, Deviance, and McFadden’s pseudo-R2. The choice of the better approach will depend on the validation of the β€œmissing at random” hypothesis. If the results of data removal are similar to those of data imputation we can safely assume that the missing data was in fact β€œmissing at random”, in which case we will favor the imputed data over the reduced one." }, { "code": null, "e": 21779, "s": 21688, "text": "As previously stated, two interesting variables that could be added the baseline mode are:" }, { "code": null, "e": 21941, "s": 21779, "text": "β€˜days_before_hosp’: the number of days taken between the appearance of the first COVID-19 symptoms and the patient’s subsequent hospitalization (created earlier)" }, { "code": null, "e": 22182, "s": 21941, "text": "β€˜from.Wuhan’: the factor indicating whether the patient was from Wuhan. Again, it is somewhat counter-intuitive for this latter variable to have a significant effect to mortality rate, but there will be a rational explanation along the way." }, { "code": null, "e": 22500, "s": 22182, "text": "It should be noted that we intentionally refrain from automating this selection process, in an effort of keeping model comparisons down to a minimum. The purpose of this practice is to avoid dwelling into the realms of stepwise selection, a widespread technique which is nowadays wisely regarded as a statistical sin." }, { "code": null, "e": 22564, "s": 22500, "text": "Our next candidate models will be of the following nested form:" }, { "code": null, "e": 23021, "s": 22564, "text": "At this point, we must create the imputed dataset. There are plenty of imputation methods to choose from depending on the nature, amount, and distribution of missing values in our data. Under a mild β€œmissing at random” assumption, we decide that the best method for our scenario would be multiple imputation by chained equation, commonly known as the MICE algorithm. Using the β€˜mice’ library, we can simulate values for all our missing data as shown below:" }, { "code": null, "e": 23240, "s": 23021, "text": "# Create imputed dataset using 'mice':dat1_obj <- mice(dat1[c(\"gender\", \"age\", \"days_before_hosp\", \"from.Wuhan\", \"country\")], m=5, maxit = 50, method = 'pmm', seed = 400)dat1_imp = complete(dat1_obj)dat1_imp$y = dat1$y" }, { "code": null, "e": 23843, "s": 23240, "text": "Now we have our imputed dataset in β€˜dat1_imp’. Next we’re going to refit the baseline model plus the two new candidate models on the newly imputed dataset and summarize their diagnostics. We’re refitting our baseline model because the multiple imputation has also filled in the missing data on Gender and Age that were previously automatically removed by the β€˜glm’ function. We’re not expecting this to cause a dramatic change on the diagnostics of baseline model yet it’s essential to refit it to the exact same dataset as the new candidate models in order to make all models comparable to each other." }, { "code": null, "e": 24397, "s": 23843, "text": "# Train models on imputed data:gfit1a = glm(y~gender+age, data = dat1_imp, binomial)gfit1b = glm(y~gender+age+days_before_hosp, data = dat1_imp, binomial)gfit1c = glm(y~gender+age+days_before_hosp+from.Wuhan, data = dat1_imp, binomial)# Compare fits:export_summs(gfit1a, gfit1b, gfit1c, scale = F, error_format = \"[{conf.low}, {conf.high}]\", digits = 3, model.names = c(\"model 1a\", \"model 1b\", \"model 1c\"))plot_summs(gfit1a, gfit1b, gfit1c, scale = TRUE, plot.distributions = F, inner_ci_level = .95, model.names = c(\"model 1a\", \"model 1b\", \"model 1c\"))" }, { "code": null, "e": 24789, "s": 24397, "text": "So now we have three nested models fitted on the same input cases that we can directly compare using likelihood-based criteria. As expected, there is a clear improvement in all aspects as we see both AIC and BIC values drop significantly, while pseudo-R2 has almost doubled in the third model. It’s safe to conclude that the model with both new variables is the one we should be focusing on." }, { "code": null, "e": 25247, "s": 24789, "text": "The 95% confidence interval plot can be thought of as a β€œpanoramic” view of the asymptotic distributions of coefficients which allows us to assess the consistency of estimation. Whether two confidence intervals overlap gives us an idea of whether the estimates of the same coefficients differ significantly between two models. This helps us detect the presence of multicollinearity, that may have been caused by the addition of new variables into the model." }, { "code": null, "e": 26227, "s": 25247, "text": "One might wonder, at this point, what is the best way to compare models using likelihood-based measures. As a rule of the thumb, the Akaike information criterion (AIC) has been characterized as the asymptotic equivalent of leave-one-out cross validation, therefore it’s the better metric for the purpose of prediction. The Bayesian information criterion (BIC), on the other hand, has been previously cited to be the better criterion for finding the true model among a set of candidate models, which is what we need for the purpose of explanation. Note that the β€œtrue model” is the model with the correct functional form and the correct set of regressors regarding what best explain the response, but it is not necessarily the best model for making predictions (some variables required to interpret the response might compromise the precision of estimates without adding predictive value). With that in mind, we are going to be looking at BIC as the criterion for model selection." }, { "code": null, "e": 26320, "s": 26227, "text": "We move onto fitting the same candidate models to a dataset that has undergone data removal." }, { "code": null, "e": 26509, "s": 26320, "text": "The reduced dataset will be created by listwise deletion, i.e. the removal of an input case (observation) with one or more missing values. We create the following using the following code:" }, { "code": null, "e": 26750, "s": 26509, "text": "# Create reduced dataset for model 2:# (filter out rows with NA values)not_na_mask = !is.na(dat1$y) & !is.na(dat1$days_before_hosp) & !is.na(dat1$age) & !is.na(dat1$gender) & dat1$days_before_hosp >= 0dat2 = dat1[not_na_mask, ]table(dat2$y)" }, { "code": null, "e": 26888, "s": 26750, "text": "We can see the total number of observations being reduced by 40%. Now let’s see what the diagnostics of the fitted models will look like." }, { "code": null, "e": 27680, "s": 26888, "text": "#------------------------------------------------------------------# Model 2: gender + age + time to hospitalization (on reduced # dataset)#------------------------------------------------------------------# Train model:gfit2a = glm(y~gender+age, data = dat2, binomial)gfit2b = glm(y~gender+age+days_before_hosp, data = dat2, binomial)gfit2c = glm(y~gender+age+days_before_hosp+from.Wuhan, data = dat2, binomial)# Merge model summaries:export_summs(gfit2a, gfit2b, gfit2c, scale = F, error_format = \"[{conf.low}, {conf.high}]\", digits = 3, model.names = c(\"model 2a\", \"model 2b\", \"model 2c\"))# Compare asymptotic distributions of coefficients:plot_summs(gfit2a, gfit2b, gfit2c, scale = TRUE, plot.distributions = F, inner_ci_level = .95, model.names = c(\"model 2a\", \"model 2b\", \"model 2c\"))" }, { "code": null, "e": 28299, "s": 27680, "text": "Given how we reduced our dataset to about half its original size, the fit of this model is surprisingly good. The comparison of asymptotic distributions shows that the diagnostics of the three models fitted on the reduced dataset are as stable as the ones fitted on the imputed dataset. This is a positive result, indicating that the missing data is in fact missing at random as hypothesized, and that the imputation algorithm has done a good job at filling in missing values. This assumption is further strengthened in the next section, where we compare the best candidate models (in terms of BIC) from both datasets." }, { "code": null, "e": 28813, "s": 28299, "text": "# Merge summaries of two models (imputed vs. reduced)export_summs(gfit1c, gfit2c, scale = TRUE, error_format = \"[{conf.low}, {conf.high}]\", digits = 3, model.names = c(\"model 1c\", \"model 2c\"))# Compare asymptotic distributions of coefficients:p1 = plot_summs(gfit1c, gfit2c, scale = TRUE, plot.distributions = T, model.names = c(\"model 1c\", \"model 2c\"))p2 = plot_summs(gfit1c, gfit2c, scale = TRUE, plot.distributions = F, inner_ci_level = .95, model.names = c(\"model 1c\", \"model 2c\"))grid.arrange(p1, p2, ncol=2)" }, { "code": null, "e": 29704, "s": 28813, "text": "As already mentioned, likelihood-based scores are not directly comparable between models fitted on different datasets, still, given our rule of the thumb it’s safe to say a McFadden’s score of 0.56 indicates a very good fit on its own. Plotting the asymptotic distributions of the imputed dataset model’s coefficients next to those of the reduced model is a good way to compare standard errors and confirm that there is no radical change between the two approaches. The estimated coefficients of all predictors were found significant in both approaches, so we’re glad to observe that their inference remains consistent. The point estimate of the coefficient of Gender is higher in the model fitted to the reduced data, but its confidence interval overlaps with the one of the one fitted to the imputed model, therefore the inference between the two estimates is not significantly different." }, { "code": null, "e": 30452, "s": 29704, "text": "By now we have enough evidence to believe that our missing data is, in fact, β€œmissing at random” (MAR), i.e. the probability that a value is missing depends only on observed values and not on unobserved ones. If the MAR assumption holds, then MICE has done a good job at producing simulated observations that correctly represent the β€œreal” missing data. Consequently, the model on the MICE-imputed dataset is consistent with the model on the reduced (listwise-deleted) dataset and, therefore, it’s safe to assume that both datasets are representative random subsamples of the population. We could, in theory, use any of the two datasets for the next steps of our analysis, but for the reasons of information gain we’ll go with the imputed dataset." }, { "code": null, "e": 31041, "s": 30452, "text": "Having settled to the imputed dataset, we can proceed to the final stage of model selection that requires the creation and addition of a new predictor. We noticed that the addition of variable β€˜from.Wuhan’ to the model improves the fit significantly by reducing BIC and increases pseudo-R2 by about .20. At this point, it isn’t obvious to us why a variable indicating whether a person is native to Wuhan should be of any relevance to mortality rate, let alone be so influential. Let’s have a closer look at this factor by testing the number of deaths per Wuhan natives versus non-natives." }, { "code": null, "e": 31683, "s": 31041, "text": "There seems to be a striking difference between the mortality rates of those who are from Wuhan and those who are not. If we trust our data, such a counter-intuitive insight should not be ignored, but what could be the reason behind this difference? An unfortunate yet realistic assumption would be that people who are visitors in Wuhan either for business or tourism are, in average, of a higher income than the locals. We can challenge this assumption by comparing the death rates between those who are natives to Wuhan and those who are not. This can be achieved via a simple two-sample z-test for proportions and visualized as a barplot." }, { "code": null, "e": 32741, "s": 31683, "text": "#-------------------------------------------------------------------#Inspecting proportion of mortality rate in Wuhan natives:#-------------------------------------------------------------------# Create dataframe:tmp = data.frame(rbind( table(dat1_imp$y[dat1_imp$from.Wuhan==1]), table(dat1_imp$y[dat1_imp$from.Wuhan==0])))names(tmp) = c(\"total\", \"deaths\")tmp$death_rate = round(tmp$deaths/tmp$total, 3)tmp$from_wuhan = as.factor(c(1,0))# Compare proportions (deaths per cases between groups):se1 = sqrt(tmp$death_rate[1]*(1-tmp$death_rate[1])/tmp$total[1]) # Standard errors of proportions:se2 = sqrt(tmp$death_rate[2]*(1-tmp$death_rate[2])/tmp$total[2])tmp$prop_se = round(c(se1, se2), 4)print(tmp)print(prop.test(x = tmp$deaths, n = tmp$total, alternative = \"greater\"))# Barplot of proportions:ggplot(tmp, aes( y=death_rate, x=from_wuhan)) + geom_bar(position=\"dodge\", stat=\"identity\", width=0.4, color=\"black\", fill=\"cyan\", alpha=.2) + geom_errorbar(aes(ymin=death_rate - prop_se, ymax=death_rate + prop_se), width=.1, position=position_dodge(.9))" }, { "code": null, "e": 32996, "s": 32741, "text": "Clearly, there’s a significant difference in the average mortality rate between Wuhan natives and non-natives. Let’s explore the same test for different covariates, such as the average number of days gone by before hospitalization between the two groups:" }, { "code": null, "e": 33957, "s": 32996, "text": "# Compare average number of days gone by before hospitalization # between both groups:d1 = dat1_imp$days_before_hosp[dat1_imp$from.Wuhan==1]d2 = dat1_imp$days_before_hosp[dat1_imp$from.Wuhan==0]sem1 = t.test(d1)$stderrsem2 = t.test(d1)$stderrtmp$avg_days = c(mean(d1), mean(d2))tmp$mean_se = c(sem1, sem2)print(tmp)t.test(d1, d2, alternative = \"greater\")# Barplot:b1 = ggplot(tmp, aes( y=avg_days, x=from_wuhan, fill=from_wuhan)) + geom_bar(position=\"dodge\", stat=\"identity\", width = .4, alpha=1) + geom_errorbar(aes(ymin=avg_days - mean_se, ymax=avg_days + mean_se), width=.1, position=position_dodge(.9)) # Boxplot:df = data.frame(days = c(d1, d2), from_wuhan = as.factor(c(numeric(length(d1))+1, numeric(length(d2)) )) )b2 = ggplot(df, aes( y=days, x=from_wuhan, fill=from_wuhan)) + geom_boxplot(outlier.colour=\"black\", outlier.shape=16, outlier.size=2, notch=T) + stat_summary(fun=mean, geom=\"point\", shape=23, size=4) grid.arrange(b1, b2, ncol=2)" }, { "code": null, "e": 35033, "s": 33957, "text": "As suspected, there is also a significant difference in this test. The distance between their means may be small (3.70 versus 2.68), but their difference is statistically significant, which further strengthens our hypothesis about a latent connection between the factor β€˜from.Wuhan’ and the individual’s socioeconomic status. At this point we can speculate that variable β€˜from.Wuhan’ acts as confounding factor for another latent variable. In other words, there might be another predictor carrying all socioeconomic information, to which β€˜from.Wuhan’ correlates. A logical assumption would be that this latent predictor is β€˜country’, on the grounds that someone’s ethnicity is directly correlated to both his/her socioeconomic status as well as the event of being a native to Wuhan. We’ve already established that can’t add β€˜country’ into the model because of its low variance, but we can β€˜from.Wuhan’ under the assumption that it acts as its proxy. There has to be another latent variable that is more granular than β€˜from.Wuhan’ and, at the time, is correlated to β€˜country’." }, { "code": null, "e": 35508, "s": 35033, "text": "We will introduce a country-level macroeconomic variable such as GDP (PPP), which expresses a country’s gross domestic product (at purchasing power parity) per capita. If there is a significant difference in the average GDP value per country between groups (from Wuhan, not from Wuhan), then our initial assumption about the patient’s wealth being associated to mortality rate will be further strengthened. Ultimately, this variable should also improve the fit of our model." }, { "code": null, "e": 35652, "s": 35508, "text": "Let’s create a data vector for GDP, where the order of elements corresponds to the order of country names (as listed by β€˜levels(dat$country)’):" }, { "code": null, "e": 36232, "s": 35652, "text": "# Adding GDP (PPP):dat = dat1_impdat$gdp = 0gdp_per_country = c(2182, 16091, 54799, 55171, 51991, 50904, 5004, 52144, 20984, 29207, 14800, 49548, 48640, 55306, 66527, 9027, 17832, 40337, 41582, 46827, 67891, 15599, 34567, 3550, 10094, 30820, 105689, 46452, 43007, 14509, 55989, 67558, 57214, 21361, 70441, 48169, 67426, 8677)for(i in 1:length(gdp_per_country)){ country = levels(dat$country)[i] country_inds = dat$country == country dat$gdp[country_inds] = gdp_per_country[i]}" }, { "code": null, "e": 36362, "s": 36232, "text": "A new column called β€˜gdp’ is now part of the imputed data. Let’s see what happens when we introduce that variable into our model." }, { "code": null, "e": 36424, "s": 36362, "text": "The model with GDP will, therefore, be of the following form:" }, { "code": null, "e": 37334, "s": 36424, "text": "#----------------------------------------------------------------# Model 4: Adding GDP (PPP)#----------------------------------------------------------------# Fit model with GDP:gfit1d = glm(y~gender+age+days_before_hosp+from.Wuhan+gdp, data = dat, binomial)# Compare models with GDP with and without GDP:# Merge model summaries:export_summs(gfit1c, gfit1d, scale = F, error_format = \"[{conf.low}, {conf.high}]\", model.names = c(\"without GDP\", \"with GDP\"))# Compare asymtotic distributions:f1 = plot_summs(gfit1c, gfit1d, scale = TRUE, plot.distributions = TRUE, model.names = c(\"without GDP\", \"with GDP\"))f2 = plot_summs(gfit1c, gfit2c, scale = TRUE, plot.distributions = F, inner_ci_level = .95, model.names = c(\"without GDP\", \"with GDP\"))grid.arrange(f1, f2, ncol=2)# Final model summary:summ(gfit1d, scale = F, plot.distributions = TRUE, inner_ci_level = .9, digits = 3)gfit = gfit1d #rename final model" }, { "code": null, "e": 37749, "s": 37334, "text": "As speculated, adding GDP into our model has further improved the fit as shown by a significant reduction in BIC and an increase in pseudo-R2. Its coefficient may be very small (possibly due to the presence of β€˜from.Wuhan’ in our model) but its impact is nonetheless significant. We can further compare the average GDP per group (Wuhan natives versus non-natives) to assess whether their difference is significant:" }, { "code": null, "e": 38588, "s": 37749, "text": "# Mean GDP per group (from Wuhan):d3 = dat$gdp[dat$from.Wuhan==1]d4 = dat$gdp[dat$from.Wuhan==0]t.test(d3, d4)sem3 = t.test(d3)$stderrsem4 = t.test(d4)$stderrtmp$avg_gdp = c(mean(d3), mean(d4))tmp$mean_se_gdp = c(sem3, sem4)# Barplot:f3 = ggplot(tmp, aes( y=avg_gdp, x=from_wuhan, fill=from_wuhan)) + geom_bar(position=\"dodge\", stat=\"identity\", width = .5) + geom_errorbar(aes(ymin=avg_gdp-mean_se_gdp, ymax=avg_gdp+mean_se_gdp), width=.1, position=position_dodge(.9)) # Boxplot:df = data.frame(days = c(d1, d2), gdp = c(d3, d4), from_wuhan = as.factor(c(numeric(length(d1))+1, numeric(length(d2)) )) )f4 = ggplot(df, aes( y=gdp, x=from_wuhan, fill=from_wuhan)) + geom_boxplot(outlier.colour=\"black\", outlier.shape=16, outlier.size=2, notch=FALSE) + stat_summary(fun=mean, geom=\"point\", shape=23, size=4)grid.arrange(f3, f4, ncol=2)" }, { "code": null, "e": 38852, "s": 38588, "text": "Our hypothesis test confirms that the average GDP (PPP) in deceased patients from Wuhan is significantly different to the average GDP (PPP) from deceased patients who are not from Wuhan. This is a further confirmation in favor of our model’s coefficient p-values." }, { "code": null, "e": 39217, "s": 38852, "text": "So far we’ve confirmed that the imputed dataset is the β€œbest” dataset, and that the model with predictors β€˜age’, β€˜gender’, β€˜days_before_hosp’, β€˜from.Wuhan’, β€˜gdp’, is the one closest to the β€œtrue” model. As a last step in our modeling process, we will use computational inference in order to assess coefficient stability and evaluate the homogeneity of our sample." }, { "code": null, "e": 39664, "s": 39217, "text": "So far we’ve been through a conservative model selection process which has led to a model that we believe to be close to the true model. A final step in the validation process would be to test the stability of model coefficients through a bootstrap procedure. If our coefficients are found to be β€œstable” then our sample can be considered homogeneous and our estimates reliable. The stability of coefficients here is evaluated using two criteria:" }, { "code": null, "e": 39809, "s": 39664, "text": "The statistical significance of computational/bagged coefficient estimates (i.e. assessed when the empirical distribution does not include zero)" }, { "code": null, "e": 40002, "s": 39809, "text": "The closeness of computational/bagged estimates to asymptotic estimates (i.e. assessed when the distribution of the difference between the asymptotic and computational means does include zero)" }, { "code": null, "e": 41171, "s": 40002, "text": "Note that the purpose of bootstrap aggregation (bagging) and resampling, in this context, is not exactly identical to that of Random Forest. We will use random subsampling with replacement to train multiple models, but our goal is to create bagged estimates and bootstrap confidence intervals for model coefficients, not for model predictions. Bagging will be used to produce point estimates for model parameters (bagged coefficients), while the empirical bootstrap distributions and associated bootstrap confidence intervals of those bagged estimates will allow us to evaluate model stability of estimation. In its simplest form, this evaluation consists of testing the hypothesis that the bagged estimates are equal to the asymptotic estimates, which comes down to comparing the asymptotic distribution and the bootstrap distribution of the same parameter. One way to achieve this is by testing the null that the difference between bagged and asymptotic estimates is equal to zero. If we can show that the asymptotic estimate is likely not different from the computational (bootstrap) estimate, we can safely assume that we have converged to the β€œtrue” coefficients." }, { "code": null, "e": 41571, "s": 41171, "text": "We use our custom function β€˜bagged_glm’ to obtain bootstrap distributions for model parameters. The β€˜alpha’ argument is used in model summary statistics, the β€˜class_balancing’ flag resamples the undersampled class at 50% (not used), the β€˜bag_pct’ argument determines the size of the training bag, and flag β€˜ocv’ activates out-of-bad cross validation (equivalent to Random Forest’s out-of-bag error)." }, { "code": null, "e": 41863, "s": 41571, "text": "#-------------------------------------------------# Coefficient stability (final model):#-------------------------------------------------bagged_results = bagged_glm(dat = dat, gfit = gfit, alpha = 0.05, class_balancing = F, bag_pct = 0.80, ocv = T)coef_bags_df = bagged_results$coef_bags_df" }, { "code": null, "e": 41924, "s": 41863, "text": "Let’s have a look at the results of computational inference:" }, { "code": null, "e": 42407, "s": 41924, "text": "# Bootstrap means of transformed coefficients:cat( \"\\n Bootstrap means of back-transformed coefficients:\\n\", \"Intercept: \", mean(coef_bags_df$`(Intercept)`), \"Gender: \", mean(coef_bags_df$gendermale), \"Age: \", mean(coef_bags_df$age), \"Days before hospitalization: \", mean(coef_bags_df$days_before_hosp), \"From Wuhan: \", mean(coef_bags_df$from.Wuhan1), \"\\n\")# Compare with asymptotic values: (merge with table above)coefficients(gfit)confint(gfit)" }, { "code": null, "e": 42856, "s": 42407, "text": "# Test null distribution directly: H0: m2-m1 = 0 par(mfcol=c(3,2))for(i in 1:length(bagged_results$coef_bags_df)){ d = bagged_results$coef_bags_df[[i]] - coefficients(gfit)[i] qtt = quantile(d, c(.975, .025)) att = t.test(d) hist(d, col=\"lightblue\", main = names(coefficients(gfit)[i]), breaks = 30) abline(v = 0, col=\"blue\", lwd=3, lty=2) abline(v = qtt[1], col=\"red\", lwd=3, lty=2) abline(v = qtt[2], col=\"red\", lwd=3, lty=2)}dev.off()" }, { "code": null, "e": 43092, "s": 42856, "text": "As we see in the above histograms, the distribution of the difference d between bagged and asymptotic estimates ΞΌ2 - ΞΌ1 does include zero (blue line) within its bootstrap confidence interval (red lines). Therefore, the null hypothesis:" }, { "code": null, "e": 43385, "s": 43092, "text": "fails to be rejected at the 95% significance level. Even though the failure to reject a null hypothesis does not imply its acceptance, this finding combined to all our previous findings should suffice to assume the reliability of our estimation and allow us to move onto model interpretation." }, { "code": null, "e": 43572, "s": 43385, "text": "As the long-awaited step in the analysis, we can finally move onto to interpreting the coefficients of our model. Recall that any binomial logit model (equation [1]) can be expressed as:" }, { "code": null, "e": 43595, "s": 43572, "text": "Solving for Ξ²0 yields:" }, { "code": null, "e": 43618, "s": 43595, "text": "Solving for Ξ²j yields:" }, { "code": null, "e": 43631, "s": 43618, "text": "and finally:" }, { "code": null, "e": 44680, "s": 43631, "text": "The value of Ξ²0 in expression [2] can be translated as the odds of the response being 1, when all continuous regressors are 0 and categorical regressors are at their base level. In our scenario, we can say that β€œthe average probability of death when days before hospitalization, age of patient, and GDP, are at zero, and the patient is not a native to Wuhan”. Obviously, patient age and GDP being equal to 0 is a nonsensical interpretation but, as previously stated, we’re not interested in the direct interpretation of Ξ²0 in this analysis (otherwise we could have used an intercept correction technique). The interpretation of Ξ²j in expression [3] is the one that interests us, and it can be generically interpreted as the percentage change in the odds of the response (being equal to 1) for every unit-increase in regressor j, if x continuous, or for the transition from the base level to the current level if x is categorical; ceteris paribus. For this interpretation to make any sense, we must adapt it to our scenario and look at Ξ²j simply as:" }, { "code": null, "e": 44737, "s": 44680, "text": "β€œThe percentage change in the probability of mortality”," }, { "code": null, "e": 44880, "s": 44737, "text": "for whatever change corresponds to regressor j, all else being equal. We can apply this interpretation to the coefficients of our final model:" }, { "code": null, "e": 44963, "s": 44880, "text": "So let’s summarize the coefficients of our model in both raw and transformed form:" }, { "code": null, "e": 45044, "s": 44963, "text": "glm.transform(gfit, alpha = .10, logodds_str = \"exp(beta)%\", ci = T, stdout = F)" }, { "code": null, "e": 45113, "s": 45044, "text": "glm.plot(gfit, alpha = 0.10, logodds_str = \"exp(beta)%\", stdout = F)" }, { "code": null, "e": 45551, "s": 45113, "text": "We can keep the transformed coefficient as a factor and interpret the odds of Y to be a number of times higher to those of X, or we can use the percentage change form and say that the probability of Y changes by a certain proportion for every change in X, as explained. Personally, I find the latter interpretation to be more intuitive and below we can see its application on each of our model’s coefficients at the 90% confidence level:" }, { "code": null, "e": 45974, "s": 45551, "text": "[Age] β€” exp(Ξ²1): The risk of death for a patient with COVID-19 increases by roughly 11% for every yearly increase in age. (CI: 8.36%-14.97%)A more intuitive way to express this insight would be to multiply the transformed coefficient by a factor of 10 and derive a 114% increase in odds for a 10-year increase in age. We can, therefore, say that:COVID-19’s mortality risk almost doubles with every 10-year increase of age." }, { "code": null, "e": 46087, "s": 45974, "text": "[Gender] β€” exp(Ξ²2): COVID-19’s mortality risk is 120% higher in men, compared to that of women. (CI: 8.67%-367%)" }, { "code": null, "e": 46291, "s": 46087, "text": "[daysBeforeHosp] β€” exp(Ξ²3): The risk of death for a patient with COVID-19 increases by 12% every day the patient stays unhospitalized after the first day he/she developed first symptoms. (CI: 2.7%-20.9%)" }, { "code": null, "e": 46413, "s": 46291, "text": "[fromWuhan] β€” exp(Ξ²4): COVID-19’s mortality risk is roughly 6 times higher for patients native to Wuhan. (CI: 231%-1577%)" } ]
Getting more value from the Pandas count() | by B. Chen | Towards Data Science
The Pandas library is one of the most preferred tools for data manipulation and analysis. Data Scientists often spend most of their time exploring and preprocessing the data. When it comes to data profiling and understanding the dataset, Pandas count() is one of the most commonly used methods for knowing the number of non-NA. The method is quick, fast, easy to understand, however, most of the time, we end up using count() with the default arguments. In this article, you’ll learn how to get more value from it. This article is structured as follows: Counting non-NA cells for each column and rowCounting non-NA cells on a MultiIndex DataFrameCounting numeric only with numeric_onlyApplying count() to the groupby() resultCombine the count back into the original DataFrame Counting non-NA cells for each column and row Counting non-NA cells on a MultiIndex DataFrame Counting numeric only with numeric_only Applying count() to the groupby() result Combine the count back into the original DataFrame Please check out Notebook for source code. Visit Github Repo for other tutorials Pandas count() is used to count the number of non-NA cells across the given axis. The values None, NaN, NaT, and optionally numpy.inf are considered NA. The method is counting non-NA for each column by default, for instance df = pd.DataFrame({ "Person": ["John", "Tom", "Lewis", "John", "Myla"], "Age": [24., np.nan, 21., 33, 26], "Single": [False, True, True, None, np.datetime64('NaT')], "Department": ["Product", "IT", "IT", "IT", "Product"]})>>> df.count()Person 5Age 4Single 3Department 5dtype: int64 If we would like to count non-NA for each row, we can set the axis argument to 1 or 'columns': >>> df.count(axis = 1)0 41 32 43 34 3dtype: int64>>> df.count(axis = 'columns')0 41 32 43 34 3dtype: int64 A MultiIndex DataFrame allows multiple columns acting as a row identifier and multiple rows acting as a header identifier. For example, let’s load the Titanic dataset with the Sex and Survived columns as the index. df = pd.read_csv( 'titanic_train.csv', index_col=['Sex', 'Survived'])df.head() We can set the argument level to count the non-NA along with a particular index level, for instance df.count(level='Sex') df.count(level='Survived') If you want to learn more about MultiIndex, please check out: towardsdatascience.com There is an argument numeric_only in Pandas count() to configure the count on numeric only. The values float, int, and boolean are considered numeric. The argument defaults to False, and we can set it to True to count on numeric only: >>> df.count(numeric_only=True)PassengerId 891Pclass 891Age 714SibSp 891Parch 891Fare 891dtype: int64 Pandas groupby() allows us to split data into separate groups to perform computations for better analysis. One of the common use cases is to group by a certain column and then get the count of another column. For example, let’s group by β€œDepartment” column and get the count of β€œSingle” values. df = pd.DataFrame({ "Person": ["John", "Tom", "Lewis", "John", "Myla"], "Age": [24., np.nan, 21., 33, 26], "Single": [False, True, True, None, np.datetime64('NaT')], "Department": ["Product", "IT", "IT", "IT", "Product"]})>>> df.groupby('Department')['Single'].count()DepartmentIT 2Product 1Name: Single, dtype: int64 Alternatively, we can also use the aggregation agg('count') method. >>> df.groupby('Department')['Single'].agg('count')DepartmentIT 2Product 1Name: Single, dtype: int64 We have been performing count() to a specific column of groupby() result. Turns out we don’t actually have to specify a column like Single. Without a column, it will apply count() across all columns, for instance: >>> df.groupby('Department').count()>>> df.groupby('Department').agg('count') If you want to learn more about groupby(), please check out: towardsdatascience.com In some cases, you may want to write the count back to the original DataFrame, for instance, we would like to append a column department_total_single as follows: The tricky part in this task is that the df.groupby()['Single'].cout() returns a Series with only 2 rows (as shown below) and it won’t match the number of rows in the original DataFrame. >>> df.groupby('Department')['Single'].count()DepartmentIT 2Product 1Name: Single, dtype: int64 One solution is to convert the above result into a DataFrame and use merge() method to combine the result. >>> temp_df = df.groupby('Department')['Single'].count().rename('department_total_count').to_frame()>>> temp_df.reset_index()>>> df_new = pd.merge(df, temp_df, on='Department', how='left') This certainly does our work. But it is a multistep process and requires extra code to get the data in the form we require. We can solve this effectively using the transform() function. A single line of code can solve the apply and merge. >>> df.groupby('Department')['Single'].transform('count')0 11 22 23 24 1Name: Single, dtype: int64 We can see that the result of transform() retains the same number of rows as the original dataset. So we can simply assign the result to a new column in the original DataFrame: >>> df['department_total_single'] = df.groupby('Department')['Single'].transform('count') If you want to learn more about merge() and transform(), please check out: towardsdatascience.com towardsdatascience.com In this article, we have explored the different use cases of Pandas counts(). It’s very handy and one of the top favorite methods during Exploratory Data Analysis and Data Preprocessing. I hope this article will help you to save time in learning Pandas. I recommend you to check out the documentation for the counts() API and to know about other things you can do. Thanks for reading. Please check out the notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning. 9 Pandas value_counts() tricks to improve your data analysis All Pandas json_normalize() you should know for flattening JSON Using Pandas method chaining to improve code readability How to do a Custom Sort on Pandas DataFrame All the Pandas shift() you should know for data analysis When to use Pandas transform() function Pandas concat() tricks you should know Difference between apply() and transform() in Pandas All the Pandas merge() you should know Working with datetime in Pandas DataFrame Pandas read_csv() tricks you should know 4 tricks you should know to parse date columns with Pandas read_csv() More tutorials can be found on Github
[ { "code": null, "e": 499, "s": 171, "text": "The Pandas library is one of the most preferred tools for data manipulation and analysis. Data Scientists often spend most of their time exploring and preprocessing the data. When it comes to data profiling and understanding the dataset, Pandas count() is one of the most commonly used methods for knowing the number of non-NA." }, { "code": null, "e": 725, "s": 499, "text": "The method is quick, fast, easy to understand, however, most of the time, we end up using count() with the default arguments. In this article, you’ll learn how to get more value from it. This article is structured as follows:" }, { "code": null, "e": 947, "s": 725, "text": "Counting non-NA cells for each column and rowCounting non-NA cells on a MultiIndex DataFrameCounting numeric only with numeric_onlyApplying count() to the groupby() resultCombine the count back into the original DataFrame" }, { "code": null, "e": 993, "s": 947, "text": "Counting non-NA cells for each column and row" }, { "code": null, "e": 1041, "s": 993, "text": "Counting non-NA cells on a MultiIndex DataFrame" }, { "code": null, "e": 1081, "s": 1041, "text": "Counting numeric only with numeric_only" }, { "code": null, "e": 1122, "s": 1081, "text": "Applying count() to the groupby() result" }, { "code": null, "e": 1173, "s": 1122, "text": "Combine the count back into the original DataFrame" }, { "code": null, "e": 1216, "s": 1173, "text": "Please check out Notebook for source code." }, { "code": null, "e": 1254, "s": 1216, "text": "Visit Github Repo for other tutorials" }, { "code": null, "e": 1407, "s": 1254, "text": "Pandas count() is used to count the number of non-NA cells across the given axis. The values None, NaN, NaT, and optionally numpy.inf are considered NA." }, { "code": null, "e": 1478, "s": 1407, "text": "The method is counting non-NA for each column by default, for instance" }, { "code": null, "e": 1799, "s": 1478, "text": "df = pd.DataFrame({ \"Person\": [\"John\", \"Tom\", \"Lewis\", \"John\", \"Myla\"], \"Age\": [24., np.nan, 21., 33, 26], \"Single\": [False, True, True, None, np.datetime64('NaT')], \"Department\": [\"Product\", \"IT\", \"IT\", \"IT\", \"Product\"]})>>> df.count()Person 5Age 4Single 3Department 5dtype: int64" }, { "code": null, "e": 1894, "s": 1799, "text": "If we would like to count non-NA for each row, we can set the axis argument to 1 or 'columns':" }, { "code": null, "e": 2031, "s": 1894, "text": ">>> df.count(axis = 1)0 41 32 43 34 3dtype: int64>>> df.count(axis = 'columns')0 41 32 43 34 3dtype: int64" }, { "code": null, "e": 2246, "s": 2031, "text": "A MultiIndex DataFrame allows multiple columns acting as a row identifier and multiple rows acting as a header identifier. For example, let’s load the Titanic dataset with the Sex and Survived columns as the index." }, { "code": null, "e": 2332, "s": 2246, "text": "df = pd.read_csv( 'titanic_train.csv', index_col=['Sex', 'Survived'])df.head()" }, { "code": null, "e": 2432, "s": 2332, "text": "We can set the argument level to count the non-NA along with a particular index level, for instance" }, { "code": null, "e": 2454, "s": 2432, "text": "df.count(level='Sex')" }, { "code": null, "e": 2481, "s": 2454, "text": "df.count(level='Survived')" }, { "code": null, "e": 2543, "s": 2481, "text": "If you want to learn more about MultiIndex, please check out:" }, { "code": null, "e": 2566, "s": 2543, "text": "towardsdatascience.com" }, { "code": null, "e": 2717, "s": 2566, "text": "There is an argument numeric_only in Pandas count() to configure the count on numeric only. The values float, int, and boolean are considered numeric." }, { "code": null, "e": 2801, "s": 2717, "text": "The argument defaults to False, and we can set it to True to count on numeric only:" }, { "code": null, "e": 2953, "s": 2801, "text": ">>> df.count(numeric_only=True)PassengerId 891Pclass 891Age 714SibSp 891Parch 891Fare 891dtype: int64" }, { "code": null, "e": 3060, "s": 2953, "text": "Pandas groupby() allows us to split data into separate groups to perform computations for better analysis." }, { "code": null, "e": 3248, "s": 3060, "text": "One of the common use cases is to group by a certain column and then get the count of another column. For example, let’s group by β€œDepartment” column and get the count of β€œSingle” values." }, { "code": null, "e": 3589, "s": 3248, "text": "df = pd.DataFrame({ \"Person\": [\"John\", \"Tom\", \"Lewis\", \"John\", \"Myla\"], \"Age\": [24., np.nan, 21., 33, 26], \"Single\": [False, True, True, None, np.datetime64('NaT')], \"Department\": [\"Product\", \"IT\", \"IT\", \"IT\", \"Product\"]})>>> df.groupby('Department')['Single'].count()DepartmentIT 2Product 1Name: Single, dtype: int64" }, { "code": null, "e": 3657, "s": 3589, "text": "Alternatively, we can also use the aggregation agg('count') method." }, { "code": null, "e": 3769, "s": 3657, "text": ">>> df.groupby('Department')['Single'].agg('count')DepartmentIT 2Product 1Name: Single, dtype: int64" }, { "code": null, "e": 3983, "s": 3769, "text": "We have been performing count() to a specific column of groupby() result. Turns out we don’t actually have to specify a column like Single. Without a column, it will apply count() across all columns, for instance:" }, { "code": null, "e": 4061, "s": 3983, "text": ">>> df.groupby('Department').count()>>> df.groupby('Department').agg('count')" }, { "code": null, "e": 4122, "s": 4061, "text": "If you want to learn more about groupby(), please check out:" }, { "code": null, "e": 4145, "s": 4122, "text": "towardsdatascience.com" }, { "code": null, "e": 4307, "s": 4145, "text": "In some cases, you may want to write the count back to the original DataFrame, for instance, we would like to append a column department_total_single as follows:" }, { "code": null, "e": 4494, "s": 4307, "text": "The tricky part in this task is that the df.groupby()['Single'].cout() returns a Series with only 2 rows (as shown below) and it won’t match the number of rows in the original DataFrame." }, { "code": null, "e": 4601, "s": 4494, "text": ">>> df.groupby('Department')['Single'].count()DepartmentIT 2Product 1Name: Single, dtype: int64" }, { "code": null, "e": 4708, "s": 4601, "text": "One solution is to convert the above result into a DataFrame and use merge() method to combine the result." }, { "code": null, "e": 4897, "s": 4708, "text": ">>> temp_df = df.groupby('Department')['Single'].count().rename('department_total_count').to_frame()>>> temp_df.reset_index()>>> df_new = pd.merge(df, temp_df, on='Department', how='left')" }, { "code": null, "e": 5021, "s": 4897, "text": "This certainly does our work. But it is a multistep process and requires extra code to get the data in the form we require." }, { "code": null, "e": 5136, "s": 5021, "text": "We can solve this effectively using the transform() function. A single line of code can solve the apply and merge." }, { "code": null, "e": 5250, "s": 5136, "text": ">>> df.groupby('Department')['Single'].transform('count')0 11 22 23 24 1Name: Single, dtype: int64" }, { "code": null, "e": 5427, "s": 5250, "text": "We can see that the result of transform() retains the same number of rows as the original dataset. So we can simply assign the result to a new column in the original DataFrame:" }, { "code": null, "e": 5517, "s": 5427, "text": ">>> df['department_total_single'] = df.groupby('Department')['Single'].transform('count')" }, { "code": null, "e": 5592, "s": 5517, "text": "If you want to learn more about merge() and transform(), please check out:" }, { "code": null, "e": 5615, "s": 5592, "text": "towardsdatascience.com" }, { "code": null, "e": 5638, "s": 5615, "text": "towardsdatascience.com" }, { "code": null, "e": 5825, "s": 5638, "text": "In this article, we have explored the different use cases of Pandas counts(). It’s very handy and one of the top favorite methods during Exploratory Data Analysis and Data Preprocessing." }, { "code": null, "e": 6003, "s": 5825, "text": "I hope this article will help you to save time in learning Pandas. I recommend you to check out the documentation for the counts() API and to know about other things you can do." }, { "code": null, "e": 6155, "s": 6003, "text": "Thanks for reading. Please check out the notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning." }, { "code": null, "e": 6216, "s": 6155, "text": "9 Pandas value_counts() tricks to improve your data analysis" }, { "code": null, "e": 6280, "s": 6216, "text": "All Pandas json_normalize() you should know for flattening JSON" }, { "code": null, "e": 6337, "s": 6280, "text": "Using Pandas method chaining to improve code readability" }, { "code": null, "e": 6381, "s": 6337, "text": "How to do a Custom Sort on Pandas DataFrame" }, { "code": null, "e": 6438, "s": 6381, "text": "All the Pandas shift() you should know for data analysis" }, { "code": null, "e": 6478, "s": 6438, "text": "When to use Pandas transform() function" }, { "code": null, "e": 6517, "s": 6478, "text": "Pandas concat() tricks you should know" }, { "code": null, "e": 6570, "s": 6517, "text": "Difference between apply() and transform() in Pandas" }, { "code": null, "e": 6609, "s": 6570, "text": "All the Pandas merge() you should know" }, { "code": null, "e": 6651, "s": 6609, "text": "Working with datetime in Pandas DataFrame" }, { "code": null, "e": 6692, "s": 6651, "text": "Pandas read_csv() tricks you should know" }, { "code": null, "e": 6762, "s": 6692, "text": "4 tricks you should know to parse date columns with Pandas read_csv()" } ]
How to Merge DataFrames of different length in Pandas ? - GeeksforGeeks
28 Apr, 2021 In this article, we will discuss how to merge the two dataframes with different lengths in Pandas. It can be done using the merge() method. Syntax: DataFrame.merge(parameters) Below are some examples that depict how to merge data frames of different lengths using the above method: Example 1: Below is a program to merge two student data frames of different lengths. Python3 # importing pandas module import pandas as pd # create a list that contains # student id of subject 1list1 = [7058, 7059, 7075, 7076] # create a list that contains# student id of subject 2list2 = [7058, 7059, 7012, 7075, 7076] # create a list that contains # student names of subject 1list11 = ["Sravan", "Jyothika", "Deepika", "Kyathi"] # create a list that contains # student names of subject 2list22 = ["Sravan", "Jyothika", "Salma", "Deepika", "Kyathi"] # pass list1 and list11 to the# dataframe1dataframe1 = pd.DataFrame( {"Student ID": list1, "Student Name": list11})print('First data frame:')display(dataframe1) # pass list2 and list22 to the# dataframe1dataframe2 = pd.DataFrame( {"Student ID": list2, "Student Name": list22})print('Second data frame:')display(dataframe2) # apply merge function to merge the# two dataframesmergedf = dataframe2.merge(dataframe1, how='left')print('Merged data frame:')display(mergedf) Output: Example 2: Here is another program to merge one data frame of length 4 and another dataframe of length 9. Python3 # importing pandas moduleimport pandas as pd # create a list that contains# student id of subject 1list1 = [7058, 7059, 7075, 7076] # create a list that contains# student id of subject 2list2 = [7058, 7059, 7012, 7075, 7076, 7034, 7046, 7036, 7015] # create a list that contains# student names of subject 1list11 = ["Sravan", "Jyothika", "Deepika", "Kyathi"] # create a list that contains# student names of subject 2list22 = ["Sravan", "Jyothika", "salma", "Deepika", "Kyathi", "meghana", "pranathi", "bhanu", "keshav"] # pass list1 and list11 to the# dataframe1dataframe1 = pd.DataFrame( {"Student ID": list1, "Student Name": list11})print('First data frame:')display(dataframe1) # pass list2 and list22 to the # dataframe1dataframe2 = pd.DataFrame( {"Student ID": list2, "Student Name": list22})print('Second data frame:')display(dataframe2) # apply merge function to merge# the two dataframesmergedf = dataframe2.merge(dataframe1, how='inner')print('Merged data frame:')display(mergedf) 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. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Python Classes and Objects Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n28 Apr, 2021" }, { "code": null, "e": 24041, "s": 23901, "text": "In this article, we will discuss how to merge the two dataframes with different lengths in Pandas. It can be done using the merge() method." }, { "code": null, "e": 24049, "s": 24041, "text": "Syntax:" }, { "code": null, "e": 24077, "s": 24049, "text": "DataFrame.merge(parameters)" }, { "code": null, "e": 24183, "s": 24077, "text": "Below are some examples that depict how to merge data frames of different lengths using the above method:" }, { "code": null, "e": 24195, "s": 24183, "text": "Example 1: " }, { "code": null, "e": 24269, "s": 24195, "text": "Below is a program to merge two student data frames of different lengths." }, { "code": null, "e": 24277, "s": 24269, "text": "Python3" }, { "code": "# importing pandas module import pandas as pd # create a list that contains # student id of subject 1list1 = [7058, 7059, 7075, 7076] # create a list that contains# student id of subject 2list2 = [7058, 7059, 7012, 7075, 7076] # create a list that contains # student names of subject 1list11 = [\"Sravan\", \"Jyothika\", \"Deepika\", \"Kyathi\"] # create a list that contains # student names of subject 2list22 = [\"Sravan\", \"Jyothika\", \"Salma\", \"Deepika\", \"Kyathi\"] # pass list1 and list11 to the# dataframe1dataframe1 = pd.DataFrame( {\"Student ID\": list1, \"Student Name\": list11})print('First data frame:')display(dataframe1) # pass list2 and list22 to the# dataframe1dataframe2 = pd.DataFrame( {\"Student ID\": list2, \"Student Name\": list22})print('Second data frame:')display(dataframe2) # apply merge function to merge the# two dataframesmergedf = dataframe2.merge(dataframe1, how='left')print('Merged data frame:')display(mergedf)", "e": 25234, "s": 24277, "text": null }, { "code": null, "e": 25242, "s": 25234, "text": "Output:" }, { "code": null, "e": 25253, "s": 25242, "text": "Example 2:" }, { "code": null, "e": 25348, "s": 25253, "text": "Here is another program to merge one data frame of length 4 and another dataframe of length 9." }, { "code": null, "e": 25356, "s": 25348, "text": "Python3" }, { "code": "# importing pandas moduleimport pandas as pd # create a list that contains# student id of subject 1list1 = [7058, 7059, 7075, 7076] # create a list that contains# student id of subject 2list2 = [7058, 7059, 7012, 7075, 7076, 7034, 7046, 7036, 7015] # create a list that contains# student names of subject 1list11 = [\"Sravan\", \"Jyothika\", \"Deepika\", \"Kyathi\"] # create a list that contains# student names of subject 2list22 = [\"Sravan\", \"Jyothika\", \"salma\", \"Deepika\", \"Kyathi\", \"meghana\", \"pranathi\", \"bhanu\", \"keshav\"] # pass list1 and list11 to the# dataframe1dataframe1 = pd.DataFrame( {\"Student ID\": list1, \"Student Name\": list11})print('First data frame:')display(dataframe1) # pass list2 and list22 to the # dataframe1dataframe2 = pd.DataFrame( {\"Student ID\": list2, \"Student Name\": list22})print('Second data frame:')display(dataframe2) # apply merge function to merge# the two dataframesmergedf = dataframe2.merge(dataframe1, how='inner')print('Merged data frame:')display(mergedf)", "e": 26393, "s": 25356, "text": null }, { "code": null, "e": 26401, "s": 26393, "text": "Output:" }, { "code": null, "e": 26408, "s": 26401, "text": "Picked" }, { "code": null, "e": 26432, "s": 26408, "text": "Python pandas-dataFrame" }, { "code": null, "e": 26455, "s": 26432, "text": "Python Pandas-exercise" }, { "code": null, "e": 26469, "s": 26455, "text": "Python-pandas" }, { "code": null, "e": 26476, "s": 26469, "text": "Python" }, { "code": null, "e": 26574, "s": 26476, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26583, "s": 26574, "text": "Comments" }, { "code": null, "e": 26596, "s": 26583, "text": "Old Comments" }, { "code": null, "e": 26628, "s": 26596, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26684, "s": 26628, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26726, "s": 26684, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26768, "s": 26726, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26804, "s": 26768, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 26843, "s": 26804, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26874, "s": 26843, "text": "Python | os.path.join() method" }, { "code": null, "e": 26896, "s": 26874, "text": "Defaultdict in Python" }, { "code": null, "e": 26923, "s": 26896, "text": "Python Classes and Objects" } ]
Python | Check if dictionary is empty - GeeksforGeeks
22 May, 2019 Sometimes, we need to check if a particular dictionary is empty or not. And this particular task has its application in web development domain in which we sometimes need to test for results of a particular query or check whether we have any key to add info into database. Let’s discuss certain ways in which this task can be performed. Method #1 : Using bool() The bool function can be used to perform this particular task. As name suggests it performs the task of converting an object to a boolean value, but here, passing an empty string returns a False, as failure to convert something that is empty. # Python3 code to demonstrate# Check if dictionary is empty# using bool() # initializing empty dictionarytest_dict = {} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # using bool()# Check if dictionary is empty res = not bool(test_dict) # print resultprint("Is dictionary empty ? : " + str(res)) The original dictionary : {} Is dictionary empty ? : True Method #2 : Using not operator This task can also be performed using the not operator that checks for a dictionary existence, this evaluates to True, if any key in the dictionary is not found. # Python3 code to demonstrate# Check if dictionary is empty# using not operator # initializing empty dictionarytest_dict = {} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # using not operator# Check if dictionary is empty res = not test_dict # print resultprint("Is dictionary empty ? : " + str(res)) The original dictionary : {} Is dictionary empty ? : True Python dictionary-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 ? Iterate over a list in Python 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": 24511, "s": 24483, "text": "\n22 May, 2019" }, { "code": null, "e": 24847, "s": 24511, "text": "Sometimes, we need to check if a particular dictionary is empty or not. And this particular task has its application in web development domain in which we sometimes need to test for results of a particular query or check whether we have any key to add info into database. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 24872, "s": 24847, "text": "Method #1 : Using bool()" }, { "code": null, "e": 25115, "s": 24872, "text": "The bool function can be used to perform this particular task. As name suggests it performs the task of converting an object to a boolean value, but here, passing an empty string returns a False, as failure to convert something that is empty." }, { "code": "# Python3 code to demonstrate# Check if dictionary is empty# using bool() # initializing empty dictionarytest_dict = {} # printing original dictionaryprint(\"The original dictionary : \" + str(test_dict)) # using bool()# Check if dictionary is empty res = not bool(test_dict) # print resultprint(\"Is dictionary empty ? : \" + str(res))", "e": 25452, "s": 25115, "text": null }, { "code": null, "e": 25511, "s": 25452, "text": "The original dictionary : {}\nIs dictionary empty ? : True\n" }, { "code": null, "e": 25544, "s": 25513, "text": "Method #2 : Using not operator" }, { "code": null, "e": 25706, "s": 25544, "text": "This task can also be performed using the not operator that checks for a dictionary existence, this evaluates to True, if any key in the dictionary is not found." }, { "code": "# Python3 code to demonstrate# Check if dictionary is empty# using not operator # initializing empty dictionarytest_dict = {} # printing original dictionaryprint(\"The original dictionary : \" + str(test_dict)) # using not operator# Check if dictionary is empty res = not test_dict # print resultprint(\"Is dictionary empty ? : \" + str(res))", "e": 26049, "s": 25706, "text": null }, { "code": null, "e": 26108, "s": 26049, "text": "The original dictionary : {}\nIs dictionary empty ? : True\n" }, { "code": null, "e": 26135, "s": 26108, "text": "Python dictionary-programs" }, { "code": null, "e": 26142, "s": 26135, "text": "Python" }, { "code": null, "e": 26158, "s": 26142, "text": "Python Programs" }, { "code": null, "e": 26256, "s": 26158, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26265, "s": 26256, "text": "Comments" }, { "code": null, "e": 26278, "s": 26265, "text": "Old Comments" }, { "code": null, "e": 26296, "s": 26278, "text": "Python Dictionary" }, { "code": null, "e": 26331, "s": 26296, "text": "Read a file line by line in Python" }, { "code": null, "e": 26353, "s": 26331, "text": "Enumerate() in Python" }, { "code": null, "e": 26385, "s": 26353, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26415, "s": 26385, "text": "Iterate over a list in Python" }, { "code": null, "e": 26458, "s": 26415, "text": "Python program to convert a list to string" }, { "code": null, "e": 26480, "s": 26458, "text": "Defaultdict in Python" }, { "code": null, "e": 26519, "s": 26480, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26565, "s": 26519, "text": "Python | Split string into list of characters" } ]
Getting started with Git and GitHub: the complete beginner’s guide | by Anne Bonner | Towards Data Science
Looking to get started with Git and GitHub? Do you need to collaborate with a team? Are you working on a project? Have you recently discovered that you pretty much need to be on GitHub if you want anyone to take you seriously in tech? ...do you really just want to contribute to your first open source project? This one’s for you! It’s totally easy to get started with Git. If you’re a fast reader (and you don’t take a lot of time with sign up and installation), you can be up and running on GitHub about ten minutes from right now. If you go all the way through the article, you can practice cloning an existing repository, creating a branch, making changes, and creating a pull request. Along the way, you might also learn how to find your terminal, use terminal commands, and edit a markdown (.md) file! If you do all that, congratulations! You will have contributed to your first open source project β€” the GitHub Welcome Wall! (If you want to go straight to the open source contribution part, scroll down until you hit the section called, β€œLet’s do this!”) This article will get you up and running with the basics. There’s a lot of stuff to learn if you want to use Git and GitHub like a pro, of course. You can go way beyond this introductory information! We’re going to leave the next-level stuff for another time, though. Let’s get started! Git is the version control tech of choice for basically everybody right now, from developers to designers. GitHub is the social code-hosting platform that’s currently used more than any other. It’s a place where you can play and experiment. It’s a place where you can find (and play around with) the most incredible open-source information, emerging technologies, features, and designs. It’s a place to learn and it’s a place to get involved. You can keep code there for work or for school, and you can grab some sweet code that you want to explore further. You can even host websites for free directly from your repository! (If you want to know how to do that, check out this article!) There are a ton of ways to use Git and GitHub, but getting started with GitHub doesn’t have to be overwhelming. You don’t need to be some kind of master coder or anything. You can even do the most important things right on the GitHub website! That being said, it’s a good idea to find your terminal and get just the tiniest bit comfortable with it. Terminal commands make things so much faster! I’ll definitely show you how to get started using the GitHub website. I’ll also show you some terminal commands that you might want to use to make your life just a little bit nicer. Any time you see a command in this article that includes these marks: < > , you want to delete those marks and replace what’s between them with your own information. Let’s say you see something like git add <filename>. That means that you would type, for example, git add hello_world.py if you wanted to add a file named β€œhello_world.py” to your GitHub repository. I’m going to give you a lot of explanation here, but these are all the terminal commands that you really need to know to get started: git clonegit statusgit addgit commit -m β€œ β€œgit push That’s it! Those are the big ones! If you have a handle of those, you’re good to go. You can start working on your projects immediately! We’ll also talk about git initgit branchgit mergegit checkout You might be working with other people, or you might want to make changes and test them out before you really commit them. The commands above are what you need to get started with collaboration. git help is also seriously useful if you’re just starting out! We’ll discuss that too. (If you’re on a Mac, you already have a terminal! You can search for it by clicking on the magnifying glass icon in the upper right-hand corner of your screen and searching for the word β€œterminal.” ) Go to GitHub and sign up for an account. You could just stop there and GitHub would work just fine. It’s a good idea, though, to install Git if you haven’t already. You can absolutely get started without it, but if you want to work on your local computer, then you want to have Git installed. You can download it or install it via your package manager instead. Now go to your terminal and introduce yourself to Git! To set your username for every repository on your computer, type git config --global user.name "<your_name_here>" replacing β€œ<your name here>” with your own name in quotations. You can use any name or handle you want. If you want to set your name for just one repository, leave out the word β€œglobal.” Now you can tell Git your email, and make sure it’s the same email you used when you signed up for GitHub git config --global user.email "<[email protected]>" It’s easy to keep your email private, and you can find those instructions in this article. You only need to check two boxes in your GitHub account. Now you’re ready to start using Git on your computer! To get started, you can create a new repository on the GitHub website or perform a git init to create a new repository from your project directory. The repository consists of three β€˜trees.’ First is the working directory, which holds the actual files. The second one is the index or the staging area. Then there’s the head, which points to the last commit you made. Here’s how you can get started right from the terminal: If you have a project directory, just go to your terminal and in your project directory run the command git init If you want to initialize your project with all of the files in your project directory, run git init . to include everything. Let’s say you have a folder for your project called β€œnew_project.” You could head on over to that folder in your terminal window and add a local repository to it by running cd new_projectgit init Now you have a new hidden directory called .git in your project directory. This is where Git stores what it needs so that it can track your project. Now you can add files to the staging area one by one with git add <filename_one> or run git add . to add all of your files to the staging area. You can commit these changes with the command git commit -m "<add a commit message here>" and if you’re happy with your changes, you can run git push to push your changes through. You can check whether or not you have changes to push through any time by running git status If you made some changes, you can update your files on at a time with git add <filename> or git add --all Then commit them with your commit message and push them through. That’s it! You can now initialize a repository, commit files, commit changes, and push them through to the master branch. If you’ve got this, just scroll down to β€œLearning to work with others” to move on to branching and collaboration! I’m going to assume that anyone who’s interested in option 2 is brand new to all of this and maybe has a folder full of files (or you plan to have one) that you want to put on GitHub and you just don’t know how to do that. Let’s make that happen! Say you want to create a new repository. (You probably do! That’s where your project will live. If you aren’t going to create a new repository, you probably want to clone an existing repository. We’ll talk about that next, but that’s how you grab someone else’s project and information that you need for your job or the course you’re taking.) Your repository is where you’ll organize your project. You can keep folders, files, images, videos, spreadsheets, Jupyter notebooks, data sets, and anything else your project needs. Before you can work with Git, you have to initialize a repository for your project and set it up so that Git will manage it. You can do this right on the GitHub website. It’s a smart idea to include a README file with information about your project. You can create one at the same time that you create your repository with the click of a checkbox. Go to the GitHub website, look in the upper right corner, and click the + sign and then click β€œNew repository.” Name the repository, and add a quick description. Decide whether you want this to be a public or a private repository Click β€œInitialize this repository with a README” if you want to include the README file. (I definitely recommend doing this! It’s the first thing people are going to look at when they check out your repository. It’s also a great place to put information that you need to have in order to understand or run the project.) You can totally start working right from this point if you want to! You can upload files, edit files, and so on right from your repository on the GitHub website. However, you might not be satisfied with only this option. There are two ways to make changes to your project. You can make changes in your files/notebooks on your computer and you can also make changes right on GitHub. Let’s say you want to make some changes to your README file right on GitHub. First, go to your repository. Click the name of the file to bring up that file (for example, click β€œREADME.md” to go to the readme file). Click the pencil icon in the upper right corner of the file and make some changes. Write a short message in the box that describes the changes you made (and an extended description if you want). Click the β€œCommit changes” button. Now the changes have been made to the README file in your new repository! (I quickly want to draw your attention to the little button you can check in the image above that will let you create a new branch for this commit and start a pull request. We’ll talk about this later!) Pretty easy, right? I prefer to work with files on my local computer rather than try to make everything work from the GitHub website, so let’s set that up now. You might want to clone your new repository so that you can work on it on your local computer, or you might have an existing repository that you want to clone. (That’s something you might need to do that for a project or course.) In order to clone a repository onto your computer, go to the repository on the GitHub website and click the big green button that says β€œClone or download.” (You can definitely download the repository right there and skip the terminal stuff if you just can’t deal with it. But I believe in you, so keep going!) Make sure it says β€œClone with HTTPS.” Now click the clipboard icon to copy and paste it to your clipboard (or highlight that link and copy it). Now you’ll open up your terminal and get yourself to the place where you want that repository to land. You might be able to, for instance, type cd Desktop to get onto the desktop. Then clone your repository right there to make it easy to find. To clone the repository, you type git clone <that_thing_you_just_copied> Simple! (Don’t forget to change the information between the < > marks to that string of letters and numbers you just copied! Also, make sure you delete the < >.) If you haven’t moved around in your terminal before, you can move around slowly with the cd command until you get where you want to go. For example, open up your terminal and type ls to list the choices of where you might go next. You might see β€œDesktop” listed, and you could just type cd Desktop to get to your desktop. Then you can run the git clone command above to clone your repository right onto your desktop. You might see some user names instead of choices like β€œDesktop.” In that case, you need to choose a user before you see β€œDesktop,” so choose the user with cd <user> (replacing <user> with the user name) and then type ls again to see your choices. There’s a very good chance you’ll see β€œDesktop” now. You’ll type cd Desktop if you see the Desktop listed. Now go ahead with that git clone! If you ever want to move back a step in your terminal, just type cd .. Now you have a new GitHub repository that you can work with cloned right on your desktop! That command pulled in a complete copy of the repository right to your system where you can work on it, make changes, stage the changes, commit the changes, and then push the changes back to GitHub. You don’t need to put the repository on your desktop if you don’t want to. You can clone it anywhere. You can even run the git clone command as soon as you open up your terminal. I will say, though, that if you aren’t really comfortable navigating around your computer, it’s not a bad idea to have your project sitting right on your desktop where you can see it... If you ever want to just play with a project on your own, you can fork it on the GitHub website instead of cloning it. Look up near the top right corner of the screen for the β€œfork” button and click it. This will make a copy of the repository in your repositories for you to play with on your own without doing anything to the original. This is all we’re about to do: git statusgit addgit commit -m " "git push Nothing to worry about! I’m thinking you probably have some files that you want to put in your new repository. Go ahead and find your files and drag and drop them into the new folder for the repository that you created on your desktop, just like you normally would with any set of files you might want to move into a folder. Now, check out the status of your project! Go to your terminal and get yourself into the folder for your repository. Then run git status to see if everything is up to date. (If you just dragged some files into your project folder, it definitely isn’t!) To add one of your files to the repository, you would run git add <fileneame> Otherwise, you can add everything with git add --all or even git add . These are your proposed changes. You can do this exact same thing with brand new files and with files that are already in there but have some changes. You aren’t actually adding anything just yet. You’re bringing new files and changes to Git’s attention. To commit the changes, you will start the process by running git commit -m β€œ<commit message>” You’re committing the changes to the HEAD, but not to the remote repository. (Make sure you replace that message in quotes with your own.) After you make a change, you take a β€œsnapshot” of the repository with the β€œcommit” command. Youβ€˜ll include a message on that β€œsnapshot” with -m. When you save a change, that’s called a commit. When you make a commit, you’ll include a message about what you changed and/or why you changed it. This is a great way to let others know what you’ve changed and why. Now your changes are in the head of your local working copy. To send the changes to your remote repository, run git push to push your changes right into your repository. If you’re working on your local computer and you want your commits to be visible online too, you would push the changes up to git hub with the git push command. You can see if everything is up to date any time by running the git status command! So now you have a GitHub repository and you know how to add files and changes to it! Congratulations!!! Collaboration is the name of the game on GitHub! Let’s say you have a project going and you maybe have a lot of different ideas and features in mind at any given time. Some features might be ready to go, but some might not. Maybe you’re working with other people who are all kind of doing their own thing. This is where branching comes in! A branch is a separate space where you can try out new ideas. If you change something on a branch, it doesn’t affect the master branch until you want it to. This means that you can do whatever you want to do on that branch until you decide it’s time to merge it. The only branch that’s going to permanently change things is the master branch. If you don’t want your changes to deploy immediately, then make your changes on a separate branch and merge them into the master branch when you’re ready. If you’re working with others and want to make changes on your own, or if you’re working on your own and want to make changes without affecting the master branch, you want a separate branch. You can create a new branch at any time. It’s also pretty simple to create a branch named β€œnew_feature” in your terminal and switch to it with git checkout -b new_feature Once you create a branch, you can make changes on that branch. This makes it easy to see what you’ve changed and why you’ve changed it. Every time you commit your changes, you’ll add a message that you can use to describe what you’ve done. Let’s talk about checkout! git checkout lets you check out a repository that you’re not currently inside of. You can check out the master branch with git checkout master or look at the β€œnew_feature” branch with git checkout new_feature When you’re done with a branch, you can merge all of your changes back so that they’re visible to everyone. git merge new_feature will take all of the changes you made to the β€œnew_feature” branch and add them to the master. In order to create an upstream branch so that you can push your changes and set the remote branch as upstream, you will push your feature by running git push --set-upstream origin new_feature After you make some changes and decide you like them, you open a pull request. If you’re on a team, this is when other people on your team can start checking out your changes and discussing them. You can open a pull request at any point, whether it’s to have people look over your final changes or ask for help because you’re stuck on something. You can! One way to do this is simply by checking that button that we mentioned earlier when we were editing the README file. Super easy! You can also create a new branch any time right on the website by going to your repository, clicking the drop-down menu near the left-middle side of your screen that says β€œBranch: master,” typing a branch name, and selecting the β€œCreate branch” link (or hitting enter on your keyboard). Now you have two branches that look the same! This is a great place to make changes and test them out before you want to make them affect the master branch. If you’re working on a separate branch, your changes only affect that branch. If you’re happy with your changes and you want to merge your changes to the master branch, you can open a pull request. This is how, if you were on a team, you would propose your changes and ask someone to review them or pull in your contribution and merge them into their branch. You can open a pull request as soon as you make a commit, even if you haven’t finished your code. You can do this right on the website if you’re more comfortable with that. If you’ve made some changes on your branch and you want to merge them, you can Click the pull request tab near the top center of the screen Click the green β€œNew pull request” button Go to the β€œExample Comparisons” box and select the branch you made to compare with the original branch. Look over your changes to make sure they’re really what you want to commit. Then click the big green β€œCreate pull request” button. Give it a title and write a brief description of your changes. Then click β€œCreate Pull Request!” Now if this is your repository, you can merge your pull request by clicking the green β€œMerge pull request” button to merge the changes into master. Click β€œConfirm merge,” then delete the branch after your branch has been incorporated with the β€œDelete branch” button in the purple box. If you’re contributing to a project, people on the team (or the reviewer) might have questions or comments. If you need to change something, this is the time! If everything is good to go, they can deploy the changes right from the branch for final testing before you merge it. And you can deploy your changes to verify them in production. If your changes have been verified, you can go ahead and merge your code into the master branch. The pull requests will preserve a record of your changes, which means that you can go through them any time to understand the changes and decisions that have been made. If you’re working on your computer and want the most up-to-date version of a repository, you’d pull the changes down from GitHub with the git pull command. To update your local repository to the newest commit, run git pull in your working directory. To merge another branch into your active branch, use git merge <branch_name> Git will try to auto-merge changes, but this isn’t always possible. Conflicts might arise. If they do, you’ll need to merge the conflicts manually. After changing them, you can mark them as merged with git add <filename>. You can preview your changes before you merge them with git diff <source_branch> <target_branch> You can switch back to to the master branch with git checkout master You’ll make your changes and then delete the branch when you’re done with git branch -d new_feature This branch isn’t available to anyone else unless you push the branch to your remote repository with git push origin <branch> First of all, this is my favorite GitHub cheatsheet. Check it out for all of the most useful Git commands! You can see the commit history of the repository if you run git log You can see one person’s commits with git log --author=<name> You can see what has been changed but not staged yet with git diff Need help remembering what command you’re supposed to run? Try git help to see the 21 most common commands. You can also type something like git help clone to figure out how to use a specific command like β€œclone.” Why not leave your mark and welcome everyone who’s here to learn about Git and GitHub? We’re going to create a simple welcome wall with notes from everyone who wants to try out Git and GitHub and contribute to their first open-source project. You can add whatever you want to the welcome wall, as long as you keep it warm and encouraging. Add a note, add an image, whatever. Make our little world better in whatever way makes you happy. (If you’re an overthinker (I see you ❀️), I have a pre-written message in the README file that you can just copy and paste.) Clone the repository, either on the GitHub website or by running git clone https://github.com/bonn0062/github_welcome_wall.git Create a new branch and add a welcoming and encouraging thought to the β€œwelcome_wall.md” file. You can do this on the website, but I really encourage you to try cloning the repository to your computer, opening the file with your favorite text editor, and adding your message there. It’s just good learning! Create a pull request. Write a quick note describing your change and click the green button to create your pull request. That’s it! If it’s a decent message, thought, image, or idea, I’ll merge your request and you will have successfully contributed to an open-source project. Congratulations!!! You did it! As always, if you do anything awesome with this information, I’d love to hear about it! Leave a message in the responses section or reach out any time on Twitter @annebonnerdata. Thanks for reading! If you want to reach out or find more cool articles, please come and join me at Content Simplicity!
[ { "code": null, "e": 406, "s": 171, "text": "Looking to get started with Git and GitHub? Do you need to collaborate with a team? Are you working on a project? Have you recently discovered that you pretty much need to be on GitHub if you want anyone to take you seriously in tech?" }, { "code": null, "e": 482, "s": 406, "text": "...do you really just want to contribute to your first open source project?" }, { "code": null, "e": 502, "s": 482, "text": "This one’s for you!" }, { "code": null, "e": 705, "s": 502, "text": "It’s totally easy to get started with Git. If you’re a fast reader (and you don’t take a lot of time with sign up and installation), you can be up and running on GitHub about ten minutes from right now." }, { "code": null, "e": 979, "s": 705, "text": "If you go all the way through the article, you can practice cloning an existing repository, creating a branch, making changes, and creating a pull request. Along the way, you might also learn how to find your terminal, use terminal commands, and edit a markdown (.md) file!" }, { "code": null, "e": 1016, "s": 979, "text": "If you do all that, congratulations!" }, { "code": null, "e": 1233, "s": 1016, "text": "You will have contributed to your first open source project β€” the GitHub Welcome Wall! (If you want to go straight to the open source contribution part, scroll down until you hit the section called, β€œLet’s do this!”)" }, { "code": null, "e": 1501, "s": 1233, "text": "This article will get you up and running with the basics. There’s a lot of stuff to learn if you want to use Git and GitHub like a pro, of course. You can go way beyond this introductory information! We’re going to leave the next-level stuff for another time, though." }, { "code": null, "e": 1520, "s": 1501, "text": "Let’s get started!" }, { "code": null, "e": 2207, "s": 1520, "text": "Git is the version control tech of choice for basically everybody right now, from developers to designers. GitHub is the social code-hosting platform that’s currently used more than any other. It’s a place where you can play and experiment. It’s a place where you can find (and play around with) the most incredible open-source information, emerging technologies, features, and designs. It’s a place to learn and it’s a place to get involved. You can keep code there for work or for school, and you can grab some sweet code that you want to explore further. You can even host websites for free directly from your repository! (If you want to know how to do that, check out this article!)" }, { "code": null, "e": 2450, "s": 2207, "text": "There are a ton of ways to use Git and GitHub, but getting started with GitHub doesn’t have to be overwhelming. You don’t need to be some kind of master coder or anything. You can even do the most important things right on the GitHub website!" }, { "code": null, "e": 2784, "s": 2450, "text": "That being said, it’s a good idea to find your terminal and get just the tiniest bit comfortable with it. Terminal commands make things so much faster! I’ll definitely show you how to get started using the GitHub website. I’ll also show you some terminal commands that you might want to use to make your life just a little bit nicer." }, { "code": null, "e": 2950, "s": 2784, "text": "Any time you see a command in this article that includes these marks: < > , you want to delete those marks and replace what’s between them with your own information." }, { "code": null, "e": 3149, "s": 2950, "text": "Let’s say you see something like git add <filename>. That means that you would type, for example, git add hello_world.py if you wanted to add a file named β€œhello_world.py” to your GitHub repository." }, { "code": null, "e": 3283, "s": 3149, "text": "I’m going to give you a lot of explanation here, but these are all the terminal commands that you really need to know to get started:" }, { "code": null, "e": 3335, "s": 3283, "text": "git clonegit statusgit addgit commit -m β€œ β€œgit push" }, { "code": null, "e": 3472, "s": 3335, "text": "That’s it! Those are the big ones! If you have a handle of those, you’re good to go. You can start working on your projects immediately!" }, { "code": null, "e": 3494, "s": 3472, "text": "We’ll also talk about" }, { "code": null, "e": 3534, "s": 3494, "text": "git initgit branchgit mergegit checkout" }, { "code": null, "e": 3729, "s": 3534, "text": "You might be working with other people, or you might want to make changes and test them out before you really commit them. The commands above are what you need to get started with collaboration." }, { "code": null, "e": 3738, "s": 3729, "text": "git help" }, { "code": null, "e": 3816, "s": 3738, "text": "is also seriously useful if you’re just starting out! We’ll discuss that too." }, { "code": null, "e": 4016, "s": 3816, "text": "(If you’re on a Mac, you already have a terminal! You can search for it by clicking on the magnifying glass icon in the upper right-hand corner of your screen and searching for the word β€œterminal.” )" }, { "code": null, "e": 4377, "s": 4016, "text": "Go to GitHub and sign up for an account. You could just stop there and GitHub would work just fine. It’s a good idea, though, to install Git if you haven’t already. You can absolutely get started without it, but if you want to work on your local computer, then you want to have Git installed. You can download it or install it via your package manager instead." }, { "code": null, "e": 4497, "s": 4377, "text": "Now go to your terminal and introduce yourself to Git! To set your username for every repository on your computer, type" }, { "code": null, "e": 4546, "s": 4497, "text": "git config --global user.name \"<your_name_here>\"" }, { "code": null, "e": 4733, "s": 4546, "text": "replacing β€œ<your name here>” with your own name in quotations. You can use any name or handle you want. If you want to set your name for just one repository, leave out the word β€œglobal.”" }, { "code": null, "e": 4839, "s": 4733, "text": "Now you can tell Git your email, and make sure it’s the same email you used when you signed up for GitHub" }, { "code": null, "e": 4895, "s": 4839, "text": "git config --global user.email \"<[email protected]>\"" }, { "code": null, "e": 5043, "s": 4895, "text": "It’s easy to keep your email private, and you can find those instructions in this article. You only need to check two boxes in your GitHub account." }, { "code": null, "e": 5097, "s": 5043, "text": "Now you’re ready to start using Git on your computer!" }, { "code": null, "e": 5245, "s": 5097, "text": "To get started, you can create a new repository on the GitHub website or perform a git init to create a new repository from your project directory." }, { "code": null, "e": 5463, "s": 5245, "text": "The repository consists of three β€˜trees.’ First is the working directory, which holds the actual files. The second one is the index or the staging area. Then there’s the head, which points to the last commit you made." }, { "code": null, "e": 5519, "s": 5463, "text": "Here’s how you can get started right from the terminal:" }, { "code": null, "e": 5623, "s": 5519, "text": "If you have a project directory, just go to your terminal and in your project directory run the command" }, { "code": null, "e": 5633, "s": 5623, "text": "git init " }, { "code": null, "e": 5725, "s": 5633, "text": "If you want to initialize your project with all of the files in your project directory, run" }, { "code": null, "e": 5736, "s": 5725, "text": "git init ." }, { "code": null, "e": 5759, "s": 5736, "text": "to include everything." }, { "code": null, "e": 5932, "s": 5759, "text": "Let’s say you have a folder for your project called β€œnew_project.” You could head on over to that folder in your terminal window and add a local repository to it by running" }, { "code": null, "e": 5955, "s": 5932, "text": "cd new_projectgit init" }, { "code": null, "e": 6162, "s": 5955, "text": "Now you have a new hidden directory called .git in your project directory. This is where Git stores what it needs so that it can track your project. Now you can add files to the staging area one by one with" }, { "code": null, "e": 6185, "s": 6162, "text": "git add <filename_one>" }, { "code": null, "e": 6192, "s": 6185, "text": "or run" }, { "code": null, "e": 6202, "s": 6192, "text": "git add ." }, { "code": null, "e": 6294, "s": 6202, "text": "to add all of your files to the staging area. You can commit these changes with the command" }, { "code": null, "e": 6338, "s": 6294, "text": "git commit -m \"<add a commit message here>\"" }, { "code": null, "e": 6389, "s": 6338, "text": "and if you’re happy with your changes, you can run" }, { "code": null, "e": 6398, "s": 6389, "text": "git push" }, { "code": null, "e": 6510, "s": 6398, "text": "to push your changes through. You can check whether or not you have changes to push through any time by running" }, { "code": null, "e": 6521, "s": 6510, "text": "git status" }, { "code": null, "e": 6591, "s": 6521, "text": "If you made some changes, you can update your files on at a time with" }, { "code": null, "e": 6610, "s": 6591, "text": "git add <filename>" }, { "code": null, "e": 6613, "s": 6610, "text": "or" }, { "code": null, "e": 6627, "s": 6613, "text": "git add --all" }, { "code": null, "e": 6692, "s": 6627, "text": "Then commit them with your commit message and push them through." }, { "code": null, "e": 6814, "s": 6692, "text": "That’s it! You can now initialize a repository, commit files, commit changes, and push them through to the master branch." }, { "code": null, "e": 6928, "s": 6814, "text": "If you’ve got this, just scroll down to β€œLearning to work with others” to move on to branching and collaboration!" }, { "code": null, "e": 7151, "s": 6928, "text": "I’m going to assume that anyone who’s interested in option 2 is brand new to all of this and maybe has a folder full of files (or you plan to have one) that you want to put on GitHub and you just don’t know how to do that." }, { "code": null, "e": 7175, "s": 7151, "text": "Let’s make that happen!" }, { "code": null, "e": 7518, "s": 7175, "text": "Say you want to create a new repository. (You probably do! That’s where your project will live. If you aren’t going to create a new repository, you probably want to clone an existing repository. We’ll talk about that next, but that’s how you grab someone else’s project and information that you need for your job or the course you’re taking.)" }, { "code": null, "e": 7870, "s": 7518, "text": "Your repository is where you’ll organize your project. You can keep folders, files, images, videos, spreadsheets, Jupyter notebooks, data sets, and anything else your project needs. Before you can work with Git, you have to initialize a repository for your project and set it up so that Git will manage it. You can do this right on the GitHub website." }, { "code": null, "e": 8048, "s": 7870, "text": "It’s a smart idea to include a README file with information about your project. You can create one at the same time that you create your repository with the click of a checkbox." }, { "code": null, "e": 8160, "s": 8048, "text": "Go to the GitHub website, look in the upper right corner, and click the + sign and then click β€œNew repository.”" }, { "code": null, "e": 8210, "s": 8160, "text": "Name the repository, and add a quick description." }, { "code": null, "e": 8278, "s": 8210, "text": "Decide whether you want this to be a public or a private repository" }, { "code": null, "e": 8598, "s": 8278, "text": "Click β€œInitialize this repository with a README” if you want to include the README file. (I definitely recommend doing this! It’s the first thing people are going to look at when they check out your repository. It’s also a great place to put information that you need to have in order to understand or run the project.)" }, { "code": null, "e": 8819, "s": 8598, "text": "You can totally start working right from this point if you want to! You can upload files, edit files, and so on right from your repository on the GitHub website. However, you might not be satisfied with only this option." }, { "code": null, "e": 8980, "s": 8819, "text": "There are two ways to make changes to your project. You can make changes in your files/notebooks on your computer and you can also make changes right on GitHub." }, { "code": null, "e": 9057, "s": 8980, "text": "Let’s say you want to make some changes to your README file right on GitHub." }, { "code": null, "e": 9087, "s": 9057, "text": "First, go to your repository." }, { "code": null, "e": 9195, "s": 9087, "text": "Click the name of the file to bring up that file (for example, click β€œREADME.md” to go to the readme file)." }, { "code": null, "e": 9278, "s": 9195, "text": "Click the pencil icon in the upper right corner of the file and make some changes." }, { "code": null, "e": 9390, "s": 9278, "text": "Write a short message in the box that describes the changes you made (and an extended description if you want)." }, { "code": null, "e": 9425, "s": 9390, "text": "Click the β€œCommit changes” button." }, { "code": null, "e": 9702, "s": 9425, "text": "Now the changes have been made to the README file in your new repository! (I quickly want to draw your attention to the little button you can check in the image above that will let you create a new branch for this commit and start a pull request. We’ll talk about this later!)" }, { "code": null, "e": 9722, "s": 9702, "text": "Pretty easy, right?" }, { "code": null, "e": 9862, "s": 9722, "text": "I prefer to work with files on my local computer rather than try to make everything work from the GitHub website, so let’s set that up now." }, { "code": null, "e": 10092, "s": 9862, "text": "You might want to clone your new repository so that you can work on it on your local computer, or you might have an existing repository that you want to clone. (That’s something you might need to do that for a project or course.)" }, { "code": null, "e": 10546, "s": 10092, "text": "In order to clone a repository onto your computer, go to the repository on the GitHub website and click the big green button that says β€œClone or download.” (You can definitely download the repository right there and skip the terminal stuff if you just can’t deal with it. But I believe in you, so keep going!) Make sure it says β€œClone with HTTPS.” Now click the clipboard icon to copy and paste it to your clipboard (or highlight that link and copy it)." }, { "code": null, "e": 10690, "s": 10546, "text": "Now you’ll open up your terminal and get yourself to the place where you want that repository to land. You might be able to, for instance, type" }, { "code": null, "e": 10702, "s": 10690, "text": "cd Desktop " }, { "code": null, "e": 10825, "s": 10702, "text": "to get onto the desktop. Then clone your repository right there to make it easy to find. To clone the repository, you type" }, { "code": null, "e": 10864, "s": 10825, "text": "git clone <that_thing_you_just_copied>" }, { "code": null, "e": 11026, "s": 10864, "text": "Simple! (Don’t forget to change the information between the < > marks to that string of letters and numbers you just copied! Also, make sure you delete the < >.)" }, { "code": null, "e": 11443, "s": 11026, "text": "If you haven’t moved around in your terminal before, you can move around slowly with the cd command until you get where you want to go. For example, open up your terminal and type ls to list the choices of where you might go next. You might see β€œDesktop” listed, and you could just type cd Desktop to get to your desktop. Then you can run the git clone command above to clone your repository right onto your desktop." }, { "code": null, "e": 11831, "s": 11443, "text": "You might see some user names instead of choices like β€œDesktop.” In that case, you need to choose a user before you see β€œDesktop,” so choose the user with cd <user> (replacing <user> with the user name) and then type ls again to see your choices. There’s a very good chance you’ll see β€œDesktop” now. You’ll type cd Desktop if you see the Desktop listed. Now go ahead with that git clone!" }, { "code": null, "e": 11902, "s": 11831, "text": "If you ever want to move back a step in your terminal, just type cd .." }, { "code": null, "e": 12191, "s": 11902, "text": "Now you have a new GitHub repository that you can work with cloned right on your desktop! That command pulled in a complete copy of the repository right to your system where you can work on it, make changes, stage the changes, commit the changes, and then push the changes back to GitHub." }, { "code": null, "e": 12556, "s": 12191, "text": "You don’t need to put the repository on your desktop if you don’t want to. You can clone it anywhere. You can even run the git clone command as soon as you open up your terminal. I will say, though, that if you aren’t really comfortable navigating around your computer, it’s not a bad idea to have your project sitting right on your desktop where you can see it..." }, { "code": null, "e": 12893, "s": 12556, "text": "If you ever want to just play with a project on your own, you can fork it on the GitHub website instead of cloning it. Look up near the top right corner of the screen for the β€œfork” button and click it. This will make a copy of the repository in your repositories for you to play with on your own without doing anything to the original." }, { "code": null, "e": 12924, "s": 12893, "text": "This is all we’re about to do:" }, { "code": null, "e": 12967, "s": 12924, "text": "git statusgit addgit commit -m \" \"git push" }, { "code": null, "e": 12991, "s": 12967, "text": "Nothing to worry about!" }, { "code": null, "e": 13292, "s": 12991, "text": "I’m thinking you probably have some files that you want to put in your new repository. Go ahead and find your files and drag and drop them into the new folder for the repository that you created on your desktop, just like you normally would with any set of files you might want to move into a folder." }, { "code": null, "e": 13335, "s": 13292, "text": "Now, check out the status of your project!" }, { "code": null, "e": 13418, "s": 13335, "text": "Go to your terminal and get yourself into the folder for your repository. Then run" }, { "code": null, "e": 13429, "s": 13418, "text": "git status" }, { "code": null, "e": 13603, "s": 13429, "text": "to see if everything is up to date. (If you just dragged some files into your project folder, it definitely isn’t!) To add one of your files to the repository, you would run" }, { "code": null, "e": 13623, "s": 13603, "text": "git add <fileneame>" }, { "code": null, "e": 13662, "s": 13623, "text": "Otherwise, you can add everything with" }, { "code": null, "e": 13676, "s": 13662, "text": "git add --all" }, { "code": null, "e": 13684, "s": 13676, "text": "or even" }, { "code": null, "e": 13694, "s": 13684, "text": "git add ." }, { "code": null, "e": 13949, "s": 13694, "text": "These are your proposed changes. You can do this exact same thing with brand new files and with files that are already in there but have some changes. You aren’t actually adding anything just yet. You’re bringing new files and changes to Git’s attention." }, { "code": null, "e": 14010, "s": 13949, "text": "To commit the changes, you will start the process by running" }, { "code": null, "e": 14043, "s": 14010, "text": "git commit -m β€œ<commit message>”" }, { "code": null, "e": 14327, "s": 14043, "text": "You’re committing the changes to the HEAD, but not to the remote repository. (Make sure you replace that message in quotes with your own.) After you make a change, you take a β€œsnapshot” of the repository with the β€œcommit” command. Youβ€˜ll include a message on that β€œsnapshot” with -m." }, { "code": null, "e": 14542, "s": 14327, "text": "When you save a change, that’s called a commit. When you make a commit, you’ll include a message about what you changed and/or why you changed it. This is a great way to let others know what you’ve changed and why." }, { "code": null, "e": 14654, "s": 14542, "text": "Now your changes are in the head of your local working copy. To send the changes to your remote repository, run" }, { "code": null, "e": 14663, "s": 14654, "text": "git push" }, { "code": null, "e": 14873, "s": 14663, "text": "to push your changes right into your repository. If you’re working on your local computer and you want your commits to be visible online too, you would push the changes up to git hub with the git push command." }, { "code": null, "e": 14957, "s": 14873, "text": "You can see if everything is up to date any time by running the git status command!" }, { "code": null, "e": 15042, "s": 14957, "text": "So now you have a GitHub repository and you know how to add files and changes to it!" }, { "code": null, "e": 15061, "s": 15042, "text": "Congratulations!!!" }, { "code": null, "e": 15110, "s": 15061, "text": "Collaboration is the name of the game on GitHub!" }, { "code": null, "e": 15401, "s": 15110, "text": "Let’s say you have a project going and you maybe have a lot of different ideas and features in mind at any given time. Some features might be ready to go, but some might not. Maybe you’re working with other people who are all kind of doing their own thing. This is where branching comes in!" }, { "code": null, "e": 15664, "s": 15401, "text": "A branch is a separate space where you can try out new ideas. If you change something on a branch, it doesn’t affect the master branch until you want it to. This means that you can do whatever you want to do on that branch until you decide it’s time to merge it." }, { "code": null, "e": 15899, "s": 15664, "text": "The only branch that’s going to permanently change things is the master branch. If you don’t want your changes to deploy immediately, then make your changes on a separate branch and merge them into the master branch when you’re ready." }, { "code": null, "e": 16131, "s": 15899, "text": "If you’re working with others and want to make changes on your own, or if you’re working on your own and want to make changes without affecting the master branch, you want a separate branch. You can create a new branch at any time." }, { "code": null, "e": 16233, "s": 16131, "text": "It’s also pretty simple to create a branch named β€œnew_feature” in your terminal and switch to it with" }, { "code": null, "e": 16261, "s": 16233, "text": "git checkout -b new_feature" }, { "code": null, "e": 16501, "s": 16261, "text": "Once you create a branch, you can make changes on that branch. This makes it easy to see what you’ve changed and why you’ve changed it. Every time you commit your changes, you’ll add a message that you can use to describe what you’ve done." }, { "code": null, "e": 16528, "s": 16501, "text": "Let’s talk about checkout!" }, { "code": null, "e": 16541, "s": 16528, "text": "git checkout" }, { "code": null, "e": 16651, "s": 16541, "text": "lets you check out a repository that you’re not currently inside of. You can check out the master branch with" }, { "code": null, "e": 16671, "s": 16651, "text": "git checkout master" }, { "code": null, "e": 16712, "s": 16671, "text": "or look at the β€œnew_feature” branch with" }, { "code": null, "e": 16737, "s": 16712, "text": "git checkout new_feature" }, { "code": null, "e": 16845, "s": 16737, "text": "When you’re done with a branch, you can merge all of your changes back so that they’re visible to everyone." }, { "code": null, "e": 16867, "s": 16845, "text": "git merge new_feature" }, { "code": null, "e": 16961, "s": 16867, "text": "will take all of the changes you made to the β€œnew_feature” branch and add them to the master." }, { "code": null, "e": 17110, "s": 16961, "text": "In order to create an upstream branch so that you can push your changes and set the remote branch as upstream, you will push your feature by running" }, { "code": null, "e": 17153, "s": 17110, "text": "git push --set-upstream origin new_feature" }, { "code": null, "e": 17499, "s": 17153, "text": "After you make some changes and decide you like them, you open a pull request. If you’re on a team, this is when other people on your team can start checking out your changes and discussing them. You can open a pull request at any point, whether it’s to have people look over your final changes or ask for help because you’re stuck on something." }, { "code": null, "e": 17508, "s": 17499, "text": "You can!" }, { "code": null, "e": 17637, "s": 17508, "text": "One way to do this is simply by checking that button that we mentioned earlier when we were editing the README file. Super easy!" }, { "code": null, "e": 18081, "s": 17637, "text": "You can also create a new branch any time right on the website by going to your repository, clicking the drop-down menu near the left-middle side of your screen that says β€œBranch: master,” typing a branch name, and selecting the β€œCreate branch” link (or hitting enter on your keyboard). Now you have two branches that look the same! This is a great place to make changes and test them out before you want to make them affect the master branch." }, { "code": null, "e": 18159, "s": 18081, "text": "If you’re working on a separate branch, your changes only affect that branch." }, { "code": null, "e": 18440, "s": 18159, "text": "If you’re happy with your changes and you want to merge your changes to the master branch, you can open a pull request. This is how, if you were on a team, you would propose your changes and ask someone to review them or pull in your contribution and merge them into their branch." }, { "code": null, "e": 18692, "s": 18440, "text": "You can open a pull request as soon as you make a commit, even if you haven’t finished your code. You can do this right on the website if you’re more comfortable with that. If you’ve made some changes on your branch and you want to merge them, you can" }, { "code": null, "e": 18753, "s": 18692, "text": "Click the pull request tab near the top center of the screen" }, { "code": null, "e": 18795, "s": 18753, "text": "Click the green β€œNew pull request” button" }, { "code": null, "e": 18899, "s": 18795, "text": "Go to the β€œExample Comparisons” box and select the branch you made to compare with the original branch." }, { "code": null, "e": 18975, "s": 18899, "text": "Look over your changes to make sure they’re really what you want to commit." }, { "code": null, "e": 19127, "s": 18975, "text": "Then click the big green β€œCreate pull request” button. Give it a title and write a brief description of your changes. Then click β€œCreate Pull Request!”" }, { "code": null, "e": 19412, "s": 19127, "text": "Now if this is your repository, you can merge your pull request by clicking the green β€œMerge pull request” button to merge the changes into master. Click β€œConfirm merge,” then delete the branch after your branch has been incorporated with the β€œDelete branch” button in the purple box." }, { "code": null, "e": 19751, "s": 19412, "text": "If you’re contributing to a project, people on the team (or the reviewer) might have questions or comments. If you need to change something, this is the time! If everything is good to go, they can deploy the changes right from the branch for final testing before you merge it. And you can deploy your changes to verify them in production." }, { "code": null, "e": 20017, "s": 19751, "text": "If your changes have been verified, you can go ahead and merge your code into the master branch. The pull requests will preserve a record of your changes, which means that you can go through them any time to understand the changes and decisions that have been made." }, { "code": null, "e": 20231, "s": 20017, "text": "If you’re working on your computer and want the most up-to-date version of a repository, you’d pull the changes down from GitHub with the git pull command. To update your local repository to the newest commit, run" }, { "code": null, "e": 20241, "s": 20231, "text": "git pull " }, { "code": null, "e": 20268, "s": 20241, "text": "in your working directory." }, { "code": null, "e": 20321, "s": 20268, "text": "To merge another branch into your active branch, use" }, { "code": null, "e": 20345, "s": 20321, "text": "git merge <branch_name>" }, { "code": null, "e": 20623, "s": 20345, "text": "Git will try to auto-merge changes, but this isn’t always possible. Conflicts might arise. If they do, you’ll need to merge the conflicts manually. After changing them, you can mark them as merged with git add <filename>. You can preview your changes before you merge them with" }, { "code": null, "e": 20664, "s": 20623, "text": "git diff <source_branch> <target_branch>" }, { "code": null, "e": 20713, "s": 20664, "text": "You can switch back to to the master branch with" }, { "code": null, "e": 20733, "s": 20713, "text": "git checkout master" }, { "code": null, "e": 20807, "s": 20733, "text": "You’ll make your changes and then delete the branch when you’re done with" }, { "code": null, "e": 20833, "s": 20807, "text": "git branch -d new_feature" }, { "code": null, "e": 20934, "s": 20833, "text": "This branch isn’t available to anyone else unless you push the branch to your remote repository with" }, { "code": null, "e": 20959, "s": 20934, "text": "git push origin <branch>" }, { "code": null, "e": 21066, "s": 20959, "text": "First of all, this is my favorite GitHub cheatsheet. Check it out for all of the most useful Git commands!" }, { "code": null, "e": 21126, "s": 21066, "text": "You can see the commit history of the repository if you run" }, { "code": null, "e": 21135, "s": 21126, "text": "git log " }, { "code": null, "e": 21173, "s": 21135, "text": "You can see one person’s commits with" }, { "code": null, "e": 21198, "s": 21173, "text": "git log --author=<name> " }, { "code": null, "e": 21256, "s": 21198, "text": "You can see what has been changed but not staged yet with" }, { "code": null, "e": 21265, "s": 21256, "text": "git diff" }, { "code": null, "e": 21328, "s": 21265, "text": "Need help remembering what command you’re supposed to run? Try" }, { "code": null, "e": 21337, "s": 21328, "text": "git help" }, { "code": null, "e": 21406, "s": 21337, "text": "to see the 21 most common commands. You can also type something like" }, { "code": null, "e": 21422, "s": 21406, "text": "git help clone " }, { "code": null, "e": 21480, "s": 21422, "text": "to figure out how to use a specific command like β€œclone.”" }, { "code": null, "e": 21723, "s": 21480, "text": "Why not leave your mark and welcome everyone who’s here to learn about Git and GitHub? We’re going to create a simple welcome wall with notes from everyone who wants to try out Git and GitHub and contribute to their first open-source project." }, { "code": null, "e": 22042, "s": 21723, "text": "You can add whatever you want to the welcome wall, as long as you keep it warm and encouraging. Add a note, add an image, whatever. Make our little world better in whatever way makes you happy. (If you’re an overthinker (I see you ❀️), I have a pre-written message in the README file that you can just copy and paste.)" }, { "code": null, "e": 22107, "s": 22042, "text": "Clone the repository, either on the GitHub website or by running" }, { "code": null, "e": 22169, "s": 22107, "text": "git clone https://github.com/bonn0062/github_welcome_wall.git" }, { "code": null, "e": 22476, "s": 22169, "text": "Create a new branch and add a welcoming and encouraging thought to the β€œwelcome_wall.md” file. You can do this on the website, but I really encourage you to try cloning the repository to your computer, opening the file with your favorite text editor, and adding your message there. It’s just good learning!" }, { "code": null, "e": 22499, "s": 22476, "text": "Create a pull request." }, { "code": null, "e": 22597, "s": 22499, "text": "Write a quick note describing your change and click the green button to create your pull request." }, { "code": null, "e": 22753, "s": 22597, "text": "That’s it! If it’s a decent message, thought, image, or idea, I’ll merge your request and you will have successfully contributed to an open-source project." }, { "code": null, "e": 22784, "s": 22753, "text": "Congratulations!!! You did it!" }, { "code": null, "e": 22963, "s": 22784, "text": "As always, if you do anything awesome with this information, I’d love to hear about it! Leave a message in the responses section or reach out any time on Twitter @annebonnerdata." }, { "code": null, "e": 22983, "s": 22963, "text": "Thanks for reading!" } ]
Angular Highcharts - Heat Map Chart
Following is an example of a Heat Map Chart. We have already seen the configuration used to draw a chart in Highcharts Configuration Syntax chapter. An example of a Heat Map Chart is given below. Let us now see the additional configurations/steps taken. Configure the chart type to be 'heatmap' based. chart.type decides the series type for the chart. Here, the default value is "line". chart : { type: 'heatmap', marginTop: 40, marginBottom: 80 }, app.component.ts import { Component } from '@angular/core'; import * as Highcharts from 'highcharts'; import * as highchartsHeatmap from 'highcharts/modules/heatmap'; highchartsHeatmap(Highcharts); @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { highcharts = Highcharts; chartOptions = { chart : { type: 'heatmap', marginTop: 40, marginBottom: 80 }, title : { text: 'Sales per employee per weekday' }, xAxis : { categories: ['Alexander', 'Marie', 'Maximilian', 'Sophia', 'Lukas', 'Maria', 'Leon', 'Anna', 'Tim', 'Laura'] }, yAxis : { categories: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], title: null }, colorAxis : { min: 0, minColor: '#FFFFFF', maxColor: Highcharts.getOptions().colors[0] }, legend : { align: 'right', layout: 'vertical', margin: 0, verticalAlign: 'top', y: 25, symbolHeight: 280 }, tooltip : { formatter: function () { return '<b>' + this.series.xAxis.categories[this.point.x] + '</b> sold <br><b>' + this.point.value + '</b> items on <br><b>' + this.series.yAxis.categories[this.point.y] + '</b>'; } }, series : [{ name: 'Sales per employee', borderWidth: 1, data: [[0, 0, 10], [0, 1, 19], [0, 2, 8], [0, 3, 24], [0, 4, 67], [1, 0, 92], [1, 1, 58], [1, 2, 78], [1, 3, 117], [1, 4, 48], [2, 0, 35], [2, 1, 15], [2, 2, 123], [2, 3, 64], [2, 4, 52], [3, 0, 72], [3, 1, 132], [3, 2, 114], [3, 3, 19], [3, 4, 16], [4, 0, 38], [4, 1, 5], [4, 2, 8], [4, 3, 117], [4, 4, 115], [5, 0, 88], [5, 1, 32], [5, 2, 12], [5, 3, 6], [5, 4, 120], [6, 0, 13], [6, 1, 44], [6, 2, 88], [6, 3, 98], [6, 4, 96], [7, 0, 31], [7, 1, 1], [7, 2, 82], [7, 3, 32], [7, 4, 30], [8, 0, 85], [8, 1, 97], [8, 2, 123], [8, 3, 64], [8, 4, 84], [9, 0, 47], [9, 1, 114], [9, 2, 31], [9, 3, 48], [9, 4, 91]], dataLabels: { enabled: true, color: '#000000' } }] }; } Verify the result. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2080, "s": 2035, "text": "Following is an example of a Heat Map Chart." }, { "code": null, "e": 2184, "s": 2080, "text": "We have already seen the configuration used to draw a chart in Highcharts Configuration Syntax chapter." }, { "code": null, "e": 2231, "s": 2184, "text": "An example of a Heat Map Chart is given below." }, { "code": null, "e": 2289, "s": 2231, "text": "Let us now see the additional configurations/steps taken." }, { "code": null, "e": 2422, "s": 2289, "text": "Configure the chart type to be 'heatmap' based. chart.type decides the series type for the chart. Here, the default value is \"line\"." }, { "code": null, "e": 2493, "s": 2422, "text": "chart : {\n type: 'heatmap',\n marginTop: 40,\n marginBottom: 80\n}," }, { "code": null, "e": 2510, "s": 2493, "text": "app.component.ts" }, { "code": null, "e": 4878, "s": 2510, "text": "import { Component } from '@angular/core';\nimport * as Highcharts from 'highcharts';\nimport * as highchartsHeatmap from 'highcharts/modules/heatmap';\nhighchartsHeatmap(Highcharts);\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n highcharts = Highcharts;\n chartOptions = { \n chart : {\n type: 'heatmap',\n marginTop: 40,\n marginBottom: 80\n },\n title : {\n text: 'Sales per employee per weekday' \n },\n xAxis : {\n categories: ['Alexander', 'Marie', 'Maximilian', 'Sophia', 'Lukas',\n 'Maria', 'Leon', 'Anna', 'Tim', 'Laura']\n },\n yAxis : {\n categories: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],\n title: null\n },\n colorAxis : {\n min: 0,\n minColor: '#FFFFFF',\n maxColor: Highcharts.getOptions().colors[0]\n },\n legend : {\n align: 'right',\n layout: 'vertical',\n margin: 0,\n verticalAlign: 'top',\n y: 25,\n symbolHeight: 280\n },\n tooltip : {\n formatter: function () {\n return '<b>' + this.series.xAxis.categories[this.point.x] +\n '</b> sold <br><b>' +\n this.point.value +\n '</b> items on <br><b>' +\n this.series.yAxis.categories[this.point.y] + '</b>';\n }\n },\n series : [{\n name: 'Sales per employee',\n borderWidth: 1,\n data: [[0, 0, 10], [0, 1, 19], [0, 2, 8], [0, 3, 24], [0, 4, 67],\n [1, 0, 92], [1, 1, 58], [1, 2, 78], [1, 3, 117], [1, 4, 48],\n [2, 0, 35], [2, 1, 15], [2, 2, 123], [2, 3, 64], [2, 4, 52],\n [3, 0, 72], [3, 1, 132], [3, 2, 114], [3, 3, 19], [3, 4, 16],\n [4, 0, 38], [4, 1, 5], [4, 2, 8], [4, 3, 117], [4, 4, 115],\n [5, 0, 88], [5, 1, 32], [5, 2, 12], [5, 3, 6], [5, 4, 120],\n [6, 0, 13], [6, 1, 44], [6, 2, 88], [6, 3, 98], [6, 4, 96],\n [7, 0, 31], [7, 1, 1], [7, 2, 82], [7, 3, 32], [7, 4, 30],\n [8, 0, 85], [8, 1, 97], [8, 2, 123], [8, 3, 64], [8, 4, 84],\n [9, 0, 47], [9, 1, 114], [9, 2, 31], [9, 3, 48], [9, 4, 91]],\n \n dataLabels: {\n enabled: true,\n color: '#000000'\n }\n }]\n \n };\n}" }, { "code": null, "e": 4897, "s": 4878, "text": "Verify the result." }, { "code": null, "e": 4932, "s": 4897, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4946, "s": 4932, "text": " Anadi Sharma" }, { "code": null, "e": 4981, "s": 4946, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4995, "s": 4981, "text": " Anadi Sharma" }, { "code": null, "e": 5030, "s": 4995, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 5050, "s": 5030, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 5085, "s": 5050, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5102, "s": 5085, "text": " Frahaan Hussain" }, { "code": null, "e": 5135, "s": 5102, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 5147, "s": 5135, "text": " Senol Atac" }, { "code": null, "e": 5182, "s": 5147, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5194, "s": 5182, "text": " Senol Atac" }, { "code": null, "e": 5201, "s": 5194, "text": " Print" }, { "code": null, "e": 5212, "s": 5201, "text": " Add Notes" } ]
Insert in MongoDB without duplicates
To insert records in MongoDB and avoid duplicates, use β€œunique:true”. Let us first create a collection with documents. Here, we are trying to add duplicate records βˆ’ > db.insertWithoutDuplicateDemo.createIndex({"StudentFirstName":1},{ unique: true } ); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.insertWithoutDuplicateDemo.insert({"StudentFirstName":"Chris"},{ upsert: true }); WriteResult({ "nInserted" : 1 }) > db.insertWithoutDuplicateDemo.insert({"StudentFirstName":"David"},{ upsert: true }); WriteResult({ "nInserted" : 1 }) > db.insertWithoutDuplicateDemo.insert({"StudentFirstName":"Chris"},{ upsert: true }); WriteResult({ "nInserted" : 0, "writeError" : { "code" : 11000, "errmsg" : "E11000 duplicate key error collection: test.insertWithoutDuplicateDemo index: StudentFirstName_1 dup key: { : \"Chris\" }" } }) > db.insertWithoutDuplicateDemo.insert({"StudentFirstName":"Bob"},{ upsert: true }); WriteResult({ "nInserted" : 1 }) Following is the query to display all documents from a collection with the help of find() method βˆ’ > db.insertWithoutDuplicateDemo.find().pretty(); This will produce the following output βˆ’ { "_id" : ObjectId("5e064405150ee0e76c06a054"), "StudentFirstName" : "Chris" } { "_id" : ObjectId("5e064410150ee0e76c06a055"), "StudentFirstName" : "David" } { "_id" : ObjectId("5e06441f150ee0e76c06a057"), "StudentFirstName" : "Bob" }
[ { "code": null, "e": 1181, "s": 1062, "text": "To insert records in MongoDB and avoid duplicates, use β€œunique:true”. Let us first create a collection with documents." }, { "code": null, "e": 1228, "s": 1181, "text": "Here, we are trying to add duplicate records βˆ’" }, { "code": null, "e": 2110, "s": 1228, "text": "> db.insertWithoutDuplicateDemo.createIndex({\"StudentFirstName\":1},{ unique: true } );\n{\n \"createdCollectionAutomatically\" : true,\n \"numIndexesBefore\" : 1,\n \"numIndexesAfter\" : 2,\n \"ok\" : 1\n}\n> db.insertWithoutDuplicateDemo.insert({\"StudentFirstName\":\"Chris\"},{ upsert: true });\nWriteResult({ \"nInserted\" : 1 })\n> db.insertWithoutDuplicateDemo.insert({\"StudentFirstName\":\"David\"},{ upsert: true });\nWriteResult({ \"nInserted\" : 1 })\n> db.insertWithoutDuplicateDemo.insert({\"StudentFirstName\":\"Chris\"},{ upsert: true });\nWriteResult({\n \"nInserted\" : 0,\n \"writeError\" : {\n \"code\" : 11000,\n \"errmsg\" : \"E11000 duplicate key error collection: test.insertWithoutDuplicateDemo index: StudentFirstName_1 dup key: { : \\\"Chris\\\" }\"\n }\n})\n> db.insertWithoutDuplicateDemo.insert({\"StudentFirstName\":\"Bob\"},{ upsert: true });\nWriteResult({ \"nInserted\" : 1 })" }, { "code": null, "e": 2209, "s": 2110, "text": "Following is the query to display all documents from a collection with the help of find() method βˆ’" }, { "code": null, "e": 2258, "s": 2209, "text": "> db.insertWithoutDuplicateDemo.find().pretty();" }, { "code": null, "e": 2299, "s": 2258, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 2546, "s": 2299, "text": "{\n \"_id\" : ObjectId(\"5e064405150ee0e76c06a054\"),\n \"StudentFirstName\" : \"Chris\"\n}\n{\n \"_id\" : ObjectId(\"5e064410150ee0e76c06a055\"),\n \"StudentFirstName\" : \"David\"\n}\n{ \"_id\" : ObjectId(\"5e06441f150ee0e76c06a057\"), \"StudentFirstName\" : \"Bob\" }" } ]
JSF - h:selectManyCheckbox
The h:selectManyCheckbox tag renders a set of HTML input element of type "checkbox", and format it with HTML table and label tags. <h:selectManyCheckbox value = "#{userData.data}"> <f:selectItem itemValue = "1" itemLabel = "Item 1" /> <f:selectItem itemValue = "2" itemLabel = "Item 2" /> </h:selectManyCheckbox> <table> <tr> <td> <input name = "j_idt6:j_idt8" id = "j_idt6:j_idt8:0" value = "1" type = "checkbox" checked = "checked" /> <label for = "j_idt6:j_idt8:0" class = ""> Item 1</label> </td> <td> <input name = "j_idt6:j_idt8" id = "j_idt6:j_idt8:1" value = "2" type = "checkbox" checked = "checked" /> <label for = "j_idt6:j_idt8:1" class = ""> Item 2</label> </td> </tr> </table> id Identifier for a component binding Reference to the component that can be used in a backing bean rendered A boolean; false suppresses rendering styleClass Cascading stylesheet (CSS) class name value A component’s value, typically a value binding valueChangeListener A method binding to a method that responds to value changes converter Converter class name validator Class name of a validator that’s created and attached to a component required A boolean; if true, requires a value to be entered in the associated field accesskey A key, typically combined with a system-defined metakey, that gives focus to an element accept Comma-separated list of content types for a form accept-charset Comma- or space-separated list of character encodings for a form. The accept-charset attribute is specified with the JSF HTML attribute named acceptcharset. alt Alternative text for nontextual elements such as images or applets charset Character encoding for a linked resource coords Coordinates for an element whose shape is a rectangle, circle, or polygon dir Direction for text. Valid values are ltr (left to right) and rtl (right to left) disabled Disabled state of an input element or button hreflang Base language of a resource specified with the href attribute; hreflang may only be used with href. lang Base language of an element’s attributes and text maxlength Maximum number of characters for text fields readonly Read-only state of an input field; text can be selected in a readonly field but not edited rel Relationship between the current document and a link specified with the href attribute rev Reverse link from the anchor specified with href to the current document. The value of the attribute is a space-separated list of link types rows Number of visible rows in a text area. h:dataTable has a rows attribute, but it’s not an HTML pass-through attribute. shape Shape of a region. Valid values: default, rect, circle, poly. (default signifies the entire region) style Inline style information tabindex Numerical value specifying a tab index target The name of a frame in which a document is opened title A title, used for accessibility, that describes an element. Visual browsers typically create tooltips for the title’s value type Type of a link; for example, stylesheet width Width of an element onblur Element loses focus onchange Element’s value changes onclick Mouse button is clicked over the element ondblclick Mouse button is double-clicked over the element onfocus Element receives focus onkeydown Key is pressed onkeypress Key is pressed and subsequently released onkeyup Key is released onmousedown Mouse button is pressed over the element onmousemove Mouse moves over the element onmouseout Mouse leaves the element’s area onmouseover Mouse moves onto an element onmouseup Mouse button is released onreset Form is reset onselect Text is selected in an input field disabledClass CSS class for disabled elements enabledClass CSS class for enabled elements layout Specification for how elements are laid out: lineDirection (horizontal) or pageDirection (vertical) border Border of the element Let us create a test JSF application to test the above tag. package com.tutorialspoint.test; import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; @ManagedBean(name = "userData", eager = true) @SessionScoped public class UserData implements Serializable { private static final long serialVersionUID = 1L; public String[] data = {"1","2","3"}; public String[] getData() { return data; } public void setData(String[] data) { this.data = data; } } <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:f = "http://java.sun.com/jsf/core" xmlns:h = "http://java.sun.com/jsf/html"> <head> <title>JSF Tutorial!</title> </head> <h:body> <h2>h:selectManyCheckbox example</h2> <hr /> <h:form> <h3>Mutiple checkboxes</h3> <h:selectManyCheckbox value = "#{userData.data}"> <f:selectItem itemValue = "1" itemLabel = "Item 1" /> <f:selectItem itemValue = "2" itemLabel = "Item 2" /> <f:selectItem itemValue = "3" itemLabel = "Item 3" /> <f:selectItem itemValue = "4" itemLabel = "Item 4" /> <f:selectItem itemValue = "5" itemLabel = "Item 5" /> </h:selectManyCheckbox> <h:commandButton value = "Submit" action = "result" /> </h:form> </h:body> </html> <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:f = "http://java.sun.com/jsf/core" xmlns:h = "http://java.sun.com/jsf/html" xmlns:ui = "http://java.sun.com/jsf/facelets"> <h:body> <h2>Result</h2> <hr /> <ui:repeat value = "#{userData.data}" var = "s"> #{s} </ui:repeat> </h:body> </html> Once you are ready with all the changes done, let us compile and run the application as we did in JSF - Create Application chapter. If everything is fine with your application, this will produce the following result. Select multiple checkboxes and press Submit button. We've selected four items. You will see the selected results. 37 Lectures 3.5 hours Chaand Sheikh Print Add Notes Bookmark this page
[ { "code": null, "e": 2083, "s": 1952, "text": "The h:selectManyCheckbox tag renders a set of HTML input element of type \"checkbox\", and format it with HTML table and label tags." }, { "code": null, "e": 2274, "s": 2083, "text": "<h:selectManyCheckbox value = \"#{userData.data}\"> \n <f:selectItem itemValue = \"1\" itemLabel = \"Item 1\" /> \n <f:selectItem itemValue = \"2\" itemLabel = \"Item 2\" /> \n</h:selectManyCheckbox>" }, { "code": null, "e": 2756, "s": 2274, "text": "<table>\n <tr>\n <td>\n <input name = \"j_idt6:j_idt8\" id = \"j_idt6:j_idt8:0\" value = \"1\" \n type = \"checkbox\" checked = \"checked\" />\n <label for = \"j_idt6:j_idt8:0\" class = \"\"> Item 1</label>\n </td>\n \n <td>\n <input name = \"j_idt6:j_idt8\" id = \"j_idt6:j_idt8:1\" value = \"2\" \n type = \"checkbox\" checked = \"checked\" />\n <label for = \"j_idt6:j_idt8:1\" class = \"\"> Item 2</label>\n </td> \n </tr>\n</table>" }, { "code": null, "e": 2759, "s": 2756, "text": "id" }, { "code": null, "e": 2786, "s": 2759, "text": "Identifier for a component" }, { "code": null, "e": 2794, "s": 2786, "text": "binding" }, { "code": null, "e": 2856, "s": 2794, "text": "Reference to the component that can be used in a backing bean" }, { "code": null, "e": 2865, "s": 2856, "text": "rendered" }, { "code": null, "e": 2903, "s": 2865, "text": "A boolean; false suppresses rendering" }, { "code": null, "e": 2914, "s": 2903, "text": "styleClass" }, { "code": null, "e": 2952, "s": 2914, "text": "Cascading stylesheet (CSS) class name" }, { "code": null, "e": 2958, "s": 2952, "text": "value" }, { "code": null, "e": 3005, "s": 2958, "text": "A component’s value, typically a value binding" }, { "code": null, "e": 3025, "s": 3005, "text": "valueChangeListener" }, { "code": null, "e": 3085, "s": 3025, "text": "A method binding to a method that responds to value changes" }, { "code": null, "e": 3095, "s": 3085, "text": "converter" }, { "code": null, "e": 3116, "s": 3095, "text": "Converter class name" }, { "code": null, "e": 3126, "s": 3116, "text": "validator" }, { "code": null, "e": 3195, "s": 3126, "text": "Class name of a validator that’s created and attached to a component" }, { "code": null, "e": 3204, "s": 3195, "text": "required" }, { "code": null, "e": 3279, "s": 3204, "text": "A boolean; if true, requires a value to be entered in the associated field" }, { "code": null, "e": 3289, "s": 3279, "text": "accesskey" }, { "code": null, "e": 3377, "s": 3289, "text": "A key, typically combined with a system-defined metakey, that gives focus to an element" }, { "code": null, "e": 3384, "s": 3377, "text": "accept" }, { "code": null, "e": 3433, "s": 3384, "text": "Comma-separated list of content types for a form" }, { "code": null, "e": 3448, "s": 3433, "text": "accept-charset" }, { "code": null, "e": 3605, "s": 3448, "text": "Comma- or space-separated list of character encodings for a form. The accept-charset attribute is specified with the JSF HTML attribute named acceptcharset." }, { "code": null, "e": 3609, "s": 3605, "text": "alt" }, { "code": null, "e": 3676, "s": 3609, "text": "Alternative text for nontextual elements such as images or applets" }, { "code": null, "e": 3684, "s": 3676, "text": "charset" }, { "code": null, "e": 3725, "s": 3684, "text": "Character encoding for a linked resource" }, { "code": null, "e": 3732, "s": 3725, "text": "coords" }, { "code": null, "e": 3806, "s": 3732, "text": "Coordinates for an element whose shape is a rectangle, circle, or polygon" }, { "code": null, "e": 3810, "s": 3806, "text": "dir" }, { "code": null, "e": 3891, "s": 3810, "text": "Direction for text. Valid values are ltr (left to right) and rtl (right to left)" }, { "code": null, "e": 3900, "s": 3891, "text": "disabled" }, { "code": null, "e": 3945, "s": 3900, "text": "Disabled state of an input element or button" }, { "code": null, "e": 3954, "s": 3945, "text": "hreflang" }, { "code": null, "e": 4054, "s": 3954, "text": "Base language of a resource specified with the href attribute; hreflang may only be used with href." }, { "code": null, "e": 4059, "s": 4054, "text": "lang" }, { "code": null, "e": 4109, "s": 4059, "text": "Base language of an element’s attributes and text" }, { "code": null, "e": 4119, "s": 4109, "text": "maxlength" }, { "code": null, "e": 4164, "s": 4119, "text": "Maximum number of characters for text fields" }, { "code": null, "e": 4173, "s": 4164, "text": "readonly" }, { "code": null, "e": 4264, "s": 4173, "text": "Read-only state of an input field; text can be selected in a readonly field but not edited" }, { "code": null, "e": 4268, "s": 4264, "text": "rel" }, { "code": null, "e": 4355, "s": 4268, "text": "Relationship between the current document and a link specified with the href attribute" }, { "code": null, "e": 4359, "s": 4355, "text": "rev" }, { "code": null, "e": 4500, "s": 4359, "text": "Reverse link from the anchor specified with href to the current document. The value of the attribute is a space-separated list of link types" }, { "code": null, "e": 4505, "s": 4500, "text": "rows" }, { "code": null, "e": 4623, "s": 4505, "text": "Number of visible rows in a text area. h:dataTable has a rows attribute, but it’s not an HTML pass-through attribute." }, { "code": null, "e": 4629, "s": 4623, "text": "shape" }, { "code": null, "e": 4729, "s": 4629, "text": "Shape of a region. Valid values: default, rect, circle, poly. (default signifies the entire region)" }, { "code": null, "e": 4735, "s": 4729, "text": "style" }, { "code": null, "e": 4760, "s": 4735, "text": "Inline style information" }, { "code": null, "e": 4769, "s": 4760, "text": "tabindex" }, { "code": null, "e": 4808, "s": 4769, "text": "Numerical value specifying a tab index" }, { "code": null, "e": 4815, "s": 4808, "text": "target" }, { "code": null, "e": 4865, "s": 4815, "text": "The name of a frame in which a document is opened" }, { "code": null, "e": 4871, "s": 4865, "text": "title" }, { "code": null, "e": 4995, "s": 4871, "text": "A title, used for accessibility, that describes an element. Visual browsers typically create tooltips for the title’s value" }, { "code": null, "e": 5000, "s": 4995, "text": "type" }, { "code": null, "e": 5040, "s": 5000, "text": "Type of a link; for example, stylesheet" }, { "code": null, "e": 5046, "s": 5040, "text": "width" }, { "code": null, "e": 5066, "s": 5046, "text": "Width of an element" }, { "code": null, "e": 5073, "s": 5066, "text": "onblur" }, { "code": null, "e": 5093, "s": 5073, "text": "Element loses focus" }, { "code": null, "e": 5102, "s": 5093, "text": "onchange" }, { "code": null, "e": 5126, "s": 5102, "text": "Element’s value changes" }, { "code": null, "e": 5134, "s": 5126, "text": "onclick" }, { "code": null, "e": 5175, "s": 5134, "text": "Mouse button is clicked over the element" }, { "code": null, "e": 5186, "s": 5175, "text": "ondblclick" }, { "code": null, "e": 5234, "s": 5186, "text": "Mouse button is double-clicked over the element" }, { "code": null, "e": 5242, "s": 5234, "text": "onfocus" }, { "code": null, "e": 5265, "s": 5242, "text": "Element receives focus" }, { "code": null, "e": 5275, "s": 5265, "text": "onkeydown" }, { "code": null, "e": 5290, "s": 5275, "text": "Key is pressed" }, { "code": null, "e": 5301, "s": 5290, "text": "onkeypress" }, { "code": null, "e": 5342, "s": 5301, "text": "Key is pressed and subsequently released" }, { "code": null, "e": 5350, "s": 5342, "text": "onkeyup" }, { "code": null, "e": 5366, "s": 5350, "text": "Key is released" }, { "code": null, "e": 5378, "s": 5366, "text": "onmousedown" }, { "code": null, "e": 5419, "s": 5378, "text": "Mouse button is pressed over the element" }, { "code": null, "e": 5431, "s": 5419, "text": "onmousemove" }, { "code": null, "e": 5460, "s": 5431, "text": "Mouse moves over the element" }, { "code": null, "e": 5471, "s": 5460, "text": "onmouseout" }, { "code": null, "e": 5503, "s": 5471, "text": "Mouse leaves the element’s area" }, { "code": null, "e": 5515, "s": 5503, "text": "onmouseover" }, { "code": null, "e": 5543, "s": 5515, "text": "Mouse moves onto an element" }, { "code": null, "e": 5553, "s": 5543, "text": "onmouseup" }, { "code": null, "e": 5578, "s": 5553, "text": "Mouse button is released" }, { "code": null, "e": 5586, "s": 5578, "text": "onreset" }, { "code": null, "e": 5600, "s": 5586, "text": "Form is reset" }, { "code": null, "e": 5609, "s": 5600, "text": "onselect" }, { "code": null, "e": 5644, "s": 5609, "text": "Text is selected in an input field" }, { "code": null, "e": 5658, "s": 5644, "text": "disabledClass" }, { "code": null, "e": 5690, "s": 5658, "text": "CSS class for disabled elements" }, { "code": null, "e": 5703, "s": 5690, "text": "enabledClass" }, { "code": null, "e": 5734, "s": 5703, "text": "CSS class for enabled elements" }, { "code": null, "e": 5741, "s": 5734, "text": "layout" }, { "code": null, "e": 5841, "s": 5741, "text": "Specification for how elements are laid out: lineDirection (horizontal) or pageDirection (vertical)" }, { "code": null, "e": 5848, "s": 5841, "text": "border" }, { "code": null, "e": 5870, "s": 5848, "text": "Border of the element" }, { "code": null, "e": 5930, "s": 5870, "text": "Let us create a test JSF application to test the above tag." }, { "code": null, "e": 6404, "s": 5930, "text": "package com.tutorialspoint.test;\n\nimport java.io.Serializable;\n\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.SessionScoped;\n\n@ManagedBean(name = \"userData\", eager = true)\n@SessionScoped\npublic class UserData implements Serializable {\n private static final long serialVersionUID = 1L;\n public String[] data = {\"1\",\"2\",\"3\"};\n \n public String[] getData() {\n return data;\n }\n\n public void setData(String[] data) {\n this.data = data;\n }\n}" }, { "code": null, "e": 7436, "s": 6404, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\"\n xmlns:f = \"http://java.sun.com/jsf/core\" \n xmlns:h = \"http://java.sun.com/jsf/html\">\n \n <head>\n <title>JSF Tutorial!</title>\n </head>\n \n <h:body>\n <h2>h:selectManyCheckbox example</h2>\n <hr />\n \n <h:form>\n <h3>Mutiple checkboxes</h3> \n <h:selectManyCheckbox value = \"#{userData.data}\">\n <f:selectItem itemValue = \"1\" itemLabel = \"Item 1\" />\n <f:selectItem itemValue = \"2\" itemLabel = \"Item 2\" />\n <f:selectItem itemValue = \"3\" itemLabel = \"Item 3\" />\n <f:selectItem itemValue = \"4\" itemLabel = \"Item 4\" />\n <f:selectItem itemValue = \"5\" itemLabel = \"Item 5\" />\n </h:selectManyCheckbox>\n <h:commandButton value = \"Submit\" action = \"result\" />\n </h:form> \t\t\n \n </h:body>\n</html> " }, { "code": null, "e": 7964, "s": 7436, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\"\n xmlns:f = \"http://java.sun.com/jsf/core\" \n xmlns:h = \"http://java.sun.com/jsf/html\"\n xmlns:ui = \"http://java.sun.com/jsf/facelets\">\n \n <h:body>\n <h2>Result</h2>\n <hr />\n \n <ui:repeat value = \"#{userData.data}\" var = \"s\">\t\t\n #{s}\n </ui:repeat> \t\n </h:body>\n</html> " }, { "code": null, "e": 8181, "s": 7964, "text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - Create Application chapter. If everything is fine with your application, this will produce the following result." }, { "code": null, "e": 8295, "s": 8181, "text": "Select multiple checkboxes and press Submit button. We've selected four items. You will see the selected results." }, { "code": null, "e": 8330, "s": 8295, "text": "\n 37 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8345, "s": 8330, "text": " Chaand Sheikh" }, { "code": null, "e": 8352, "s": 8345, "text": " Print" }, { "code": null, "e": 8363, "s": 8352, "text": " Add Notes" } ]
Azure Synapse Analytics β€” Introduction | by Pankaj Jainani | Towards Data Science
Synapse Analytics is an integrated platform service from Microsoft Azure that combines the capabilities of data warehousing, data integrations, ETL pipelines, analytics tools & services, the scale for big-data capabilities, visualization & dashboards. The platform enables enterprise-wide analytics requirements for decision-making. The tools, processes, and techniques support β€” Analytics capabilities across the dimensions: Descriptive & Diagnostic Analytics by leveraging its data-warehouse capabilities whereby gathering business insights with the help of T-SQL queries. It empowers an organization’s decision-making by leveraging Predictive and Prescriptive Analytics capabilities using its integration with Apache Spark, Databricks, Stream Analytics. Azure Synapse Analytics is a one-stop-shop analytics solution that offers the following capabilities: The dedicated-pool of SQL Servers, known as, Synapse SQL, is the backbone for the entire analytics data storage, these provide the necessary infrastructure for implementing a data warehouse under its hood. Enables engineers to execute T-SQL queries native to their existing experience. It also enables empower with the serverless model is for unplanned or ad-hoc workloads, by using data virtualization allows unlocking insights from their own data stores without going through the formal processes of setting up a data warehouse. ETL and data integration capabilities from disparate sources using Synapse Pipelines enables the organization to churn the data efficiently for warehousing and analytical purpose. The reusable workflows and Pipeline orchestration capabilities are easy to adapt. The support for big-data compute services such as HDInsight for Hadoop and DataBricks make this a more powerful ETL tool. Enable the development of big-data workloads and machine learning solutions with Apache Spark for Azure Synapse. This platform processes big data workloads by enabling massively scalable high-performance-compute resources. SparkML algorithms and Azure ML integration make it a complete solution for training machine learning workloads. Deliver real-time operational analytics from operational data sources using Synapse Link. The most common business use-cases for Azure Synapse Analytics are: Data Warehouse: Ability to integrate with various data platforms and services. Descriptive/Diagnostic Analytics: Use T-SQL queries against the Synapse database to perform data exploration and discovery. Realtime Analytics: Azure Synapse Link enables integration with disparate operational data sources to implement real-time analytics solutions. Advanced Analytics: Uses Azure Databricks to support decision-making by leveraging Azure Databricks. Reporting & Visualization: Integrate with PowerBI to empower and enhance business decision-making. www.linkedin.com Assuming that you have already set up and configured the Azure Synapse Analytics workspace in your Azure subscription. Setting up and configuration of Azure Synapse Analytics workspace is beyond the scope of this article. Please look into the references section for more details. From Data Hub, Browse the gallery and the covid-tracking dataset. Open the new Spark notebook using the dataset as below. The notebook contains the following default code, with further capabilities to analyze the dataset using Spark backbone framework:- ## ---- ##df = spark.read.parquet(wasbs_path)display(df.limit(10)) Again, load the sample dataset from the Data Hub, but, this time create a New SQL Script as shown below: This will give you the free hand script to analyze the data set using native T-SQL queries This small demo will show to integrate pipeline tasks in Azure Synapse From the Integrate hub of the Synapse Analytics Studio select the Pipeline. Once the pipeline is instantiated β€” you can add workflow Activities according to the problem at hand. You can add trigger conditions to respond to an event or manual execution of the Pipeline workflow. Also, select the Monitor hub, and choose the Pipeline runs to monitor any pipeline execution progress. Use Synapse Analytics Studio to integrate and enable various Linked Services, e.g. Power BI Use Manage Hub to see existing Linked services Also, create a link to the PowerBI workspace to leverage data visualization and reporting. In this brief introduction of Azure Synapse Analytics, I have navigated through the shallow waters to understand the basic functional capabilities of this managed service from Azure. You now understand what is Synapse Analytics, why it is very important to solve optimize organizations' goals, and very slightly about how its capabilities can be leveraged for various analytical use-case. Hope you have gained some insights, do let me know about your feedback and queries. Connect with me on LinkedIn to discuss further www.linkedin.com [1] Microsoft Documentation | Azure Synapse Analytics
[ { "code": null, "e": 424, "s": 172, "text": "Synapse Analytics is an integrated platform service from Microsoft Azure that combines the capabilities of data warehousing, data integrations, ETL pipelines, analytics tools & services, the scale for big-data capabilities, visualization & dashboards." }, { "code": null, "e": 929, "s": 424, "text": "The platform enables enterprise-wide analytics requirements for decision-making. The tools, processes, and techniques support β€” Analytics capabilities across the dimensions: Descriptive & Diagnostic Analytics by leveraging its data-warehouse capabilities whereby gathering business insights with the help of T-SQL queries. It empowers an organization’s decision-making by leveraging Predictive and Prescriptive Analytics capabilities using its integration with Apache Spark, Databricks, Stream Analytics." }, { "code": null, "e": 1031, "s": 929, "text": "Azure Synapse Analytics is a one-stop-shop analytics solution that offers the following capabilities:" }, { "code": null, "e": 1562, "s": 1031, "text": "The dedicated-pool of SQL Servers, known as, Synapse SQL, is the backbone for the entire analytics data storage, these provide the necessary infrastructure for implementing a data warehouse under its hood. Enables engineers to execute T-SQL queries native to their existing experience. It also enables empower with the serverless model is for unplanned or ad-hoc workloads, by using data virtualization allows unlocking insights from their own data stores without going through the formal processes of setting up a data warehouse." }, { "code": null, "e": 1946, "s": 1562, "text": "ETL and data integration capabilities from disparate sources using Synapse Pipelines enables the organization to churn the data efficiently for warehousing and analytical purpose. The reusable workflows and Pipeline orchestration capabilities are easy to adapt. The support for big-data compute services such as HDInsight for Hadoop and DataBricks make this a more powerful ETL tool." }, { "code": null, "e": 2282, "s": 1946, "text": "Enable the development of big-data workloads and machine learning solutions with Apache Spark for Azure Synapse. This platform processes big data workloads by enabling massively scalable high-performance-compute resources. SparkML algorithms and Azure ML integration make it a complete solution for training machine learning workloads." }, { "code": null, "e": 2372, "s": 2282, "text": "Deliver real-time operational analytics from operational data sources using Synapse Link." }, { "code": null, "e": 2440, "s": 2372, "text": "The most common business use-cases for Azure Synapse Analytics are:" }, { "code": null, "e": 2519, "s": 2440, "text": "Data Warehouse: Ability to integrate with various data platforms and services." }, { "code": null, "e": 2643, "s": 2519, "text": "Descriptive/Diagnostic Analytics: Use T-SQL queries against the Synapse database to perform data exploration and discovery." }, { "code": null, "e": 2786, "s": 2643, "text": "Realtime Analytics: Azure Synapse Link enables integration with disparate operational data sources to implement real-time analytics solutions." }, { "code": null, "e": 2887, "s": 2786, "text": "Advanced Analytics: Uses Azure Databricks to support decision-making by leveraging Azure Databricks." }, { "code": null, "e": 2986, "s": 2887, "text": "Reporting & Visualization: Integrate with PowerBI to empower and enhance business decision-making." }, { "code": null, "e": 3003, "s": 2986, "text": "www.linkedin.com" }, { "code": null, "e": 3122, "s": 3003, "text": "Assuming that you have already set up and configured the Azure Synapse Analytics workspace in your Azure subscription." }, { "code": null, "e": 3283, "s": 3122, "text": "Setting up and configuration of Azure Synapse Analytics workspace is beyond the scope of this article. Please look into the references section for more details." }, { "code": null, "e": 3349, "s": 3283, "text": "From Data Hub, Browse the gallery and the covid-tracking dataset." }, { "code": null, "e": 3405, "s": 3349, "text": "Open the new Spark notebook using the dataset as below." }, { "code": null, "e": 3537, "s": 3405, "text": "The notebook contains the following default code, with further capabilities to analyze the dataset using Spark backbone framework:-" }, { "code": null, "e": 3604, "s": 3537, "text": "## ---- ##df = spark.read.parquet(wasbs_path)display(df.limit(10))" }, { "code": null, "e": 3709, "s": 3604, "text": "Again, load the sample dataset from the Data Hub, but, this time create a New SQL Script as shown below:" }, { "code": null, "e": 3800, "s": 3709, "text": "This will give you the free hand script to analyze the data set using native T-SQL queries" }, { "code": null, "e": 3871, "s": 3800, "text": "This small demo will show to integrate pipeline tasks in Azure Synapse" }, { "code": null, "e": 3947, "s": 3871, "text": "From the Integrate hub of the Synapse Analytics Studio select the Pipeline." }, { "code": null, "e": 4049, "s": 3947, "text": "Once the pipeline is instantiated β€” you can add workflow Activities according to the problem at hand." }, { "code": null, "e": 4252, "s": 4049, "text": "You can add trigger conditions to respond to an event or manual execution of the Pipeline workflow. Also, select the Monitor hub, and choose the Pipeline runs to monitor any pipeline execution progress." }, { "code": null, "e": 4344, "s": 4252, "text": "Use Synapse Analytics Studio to integrate and enable various Linked Services, e.g. Power BI" }, { "code": null, "e": 4391, "s": 4344, "text": "Use Manage Hub to see existing Linked services" }, { "code": null, "e": 4482, "s": 4391, "text": "Also, create a link to the PowerBI workspace to leverage data visualization and reporting." }, { "code": null, "e": 4665, "s": 4482, "text": "In this brief introduction of Azure Synapse Analytics, I have navigated through the shallow waters to understand the basic functional capabilities of this managed service from Azure." }, { "code": null, "e": 4871, "s": 4665, "text": "You now understand what is Synapse Analytics, why it is very important to solve optimize organizations' goals, and very slightly about how its capabilities can be leveraged for various analytical use-case." }, { "code": null, "e": 4955, "s": 4871, "text": "Hope you have gained some insights, do let me know about your feedback and queries." }, { "code": null, "e": 5002, "s": 4955, "text": "Connect with me on LinkedIn to discuss further" }, { "code": null, "e": 5019, "s": 5002, "text": "www.linkedin.com" } ]
set_window_position driver method – Selenium Python
03 Dec, 2020 Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc. This article revolves around set_window_position driver method in Selenium. set_window_position method sets the x, y position of the current window (window.moveTo). Syntax – driver.set_window_position(x, y, windowHandle='current') Example – Now one can use set_window_position method as a driver method as below – driver.get("https://www.geeksforgeeks.org/") driver.set_window_position(1024, 1024, windowHandle='current') To demonstrate, set_window_position method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s set window position, Program – Python3 # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # set window positiondriver.set_window_position(1024, 1024, windowHandle ='current') Output – Screenshot added – Akanksha_Rai Python-selenium selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Dec, 2020" }, { "code": null, "e": 768, "s": 28, "text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc. " }, { "code": null, "e": 933, "s": 768, "text": "This article revolves around set_window_position driver method in Selenium. set_window_position method sets the x, y position of the current window (window.moveTo)." }, { "code": null, "e": 943, "s": 933, "text": "Syntax – " }, { "code": null, "e": 1000, "s": 943, "text": "driver.set_window_position(x, y, windowHandle='current')" }, { "code": null, "e": 1084, "s": 1000, "text": "Example – Now one can use set_window_position method as a driver method as below – " }, { "code": null, "e": 1192, "s": 1084, "text": "driver.get(\"https://www.geeksforgeeks.org/\")\ndriver.set_window_position(1024, 1024, windowHandle='current')" }, { "code": null, "e": 1369, "s": 1192, "text": "To demonstrate, set_window_position method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s set window position," }, { "code": null, "e": 1380, "s": 1369, "text": "Program – " }, { "code": null, "e": 1388, "s": 1380, "text": "Python3" }, { "code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # set window positiondriver.set_window_position(1024, 1024, windowHandle ='current')", "e": 1644, "s": 1388, "text": null }, { "code": null, "e": 1674, "s": 1644, "text": "Output – Screenshot added – " }, { "code": null, "e": 1689, "s": 1676, "text": "Akanksha_Rai" }, { "code": null, "e": 1705, "s": 1689, "text": "Python-selenium" }, { "code": null, "e": 1714, "s": 1705, "text": "selenium" }, { "code": null, "e": 1721, "s": 1714, "text": "Python" } ]
Python | Updating value list in dictionary
26 Jul, 2019 While working with dictionary with list as value is always vulnerable of getting it’s value updated. The ways or shorthands to perform this task can be handy in such situations. This can occur in web development domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using list comprehensionThe naive method to perform this particular task, in this, we just extract the key and then iterate over it’s value in list comprehensive format in packed list. This solved the problem. # Python3 code to demonstrate working of# Updating value list in dictionary# Using list comprehension # Initialize dictionarytest_dict = {'gfg' : [1, 5, 6], 'is' : 2, 'best' : 3} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # Using list comprehension# Updating value list in dictionarytest_dict['gfg'] = [x * 2 for x in test_dict['gfg']] # printing result print("Dictionary after updation is : " + str(test_dict)) The original dictionary : {β€˜is’: 2, β€˜gfg’: [1, 5, 6], β€˜best’: 3}Dictionary after updation is : {β€˜is’: 2, β€˜gfg’: [2, 10, 12], β€˜best’: 3} Method #2 : Using map() + lambdaThis task can be performed using the combination of above two functions in which we use the map() to link the function of updation to each of element of value list and lambda is used to specify the updation. # Python3 code to demonstrate working of# Updating value list in dictionary# Using map() + lambda # Initialize dictionarytest_dict = {'gfg' : [1, 5, 6], 'is' : 2, 'best' : 3} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # Using map() + lambda# Updating value list in dictionarytest_dict['gfg'] = list(map(lambda x:x * 2, test_dict['gfg'])) # printing result print("Dictionary after updation is : " + str(test_dict)) The original dictionary : {β€˜is’: 2, β€˜gfg’: [1, 5, 6], β€˜best’: 3}Dictionary after updation is : {β€˜is’: 2, β€˜gfg’: [2, 10, 12], β€˜best’: 3} Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jul, 2019" }, { "code": null, "e": 312, "s": 28, "text": "While working with dictionary with list as value is always vulnerable of getting it’s value updated. The ways or shorthands to perform this task can be handy in such situations. This can occur in web development domain. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 534, "s": 312, "text": "Method #1 : Using list comprehensionThe naive method to perform this particular task, in this, we just extract the key and then iterate over it’s value in list comprehensive format in packed list. This solved the problem." }, { "code": "# Python3 code to demonstrate working of# Updating value list in dictionary# Using list comprehension # Initialize dictionarytest_dict = {'gfg' : [1, 5, 6], 'is' : 2, 'best' : 3} # printing original dictionaryprint(\"The original dictionary : \" + str(test_dict)) # Using list comprehension# Updating value list in dictionarytest_dict['gfg'] = [x * 2 for x in test_dict['gfg']] # printing result print(\"Dictionary after updation is : \" + str(test_dict))", "e": 995, "s": 534, "text": null }, { "code": null, "e": 1131, "s": 995, "text": "The original dictionary : {β€˜is’: 2, β€˜gfg’: [1, 5, 6], β€˜best’: 3}Dictionary after updation is : {β€˜is’: 2, β€˜gfg’: [2, 10, 12], β€˜best’: 3}" }, { "code": null, "e": 1373, "s": 1133, "text": "Method #2 : Using map() + lambdaThis task can be performed using the combination of above two functions in which we use the map() to link the function of updation to each of element of value list and lambda is used to specify the updation." }, { "code": "# Python3 code to demonstrate working of# Updating value list in dictionary# Using map() + lambda # Initialize dictionarytest_dict = {'gfg' : [1, 5, 6], 'is' : 2, 'best' : 3} # printing original dictionaryprint(\"The original dictionary : \" + str(test_dict)) # Using map() + lambda# Updating value list in dictionarytest_dict['gfg'] = list(map(lambda x:x * 2, test_dict['gfg'])) # printing result print(\"Dictionary after updation is : \" + str(test_dict))", "e": 1836, "s": 1373, "text": null }, { "code": null, "e": 1972, "s": 1836, "text": "The original dictionary : {β€˜is’: 2, β€˜gfg’: [1, 5, 6], β€˜best’: 3}Dictionary after updation is : {β€˜is’: 2, β€˜gfg’: [2, 10, 12], β€˜best’: 3}" }, { "code": null, "e": 1999, "s": 1972, "text": "Python dictionary-programs" }, { "code": null, "e": 2006, "s": 1999, "text": "Python" }, { "code": null, "e": 2022, "s": 2006, "text": "Python Programs" }, { "code": null, "e": 2120, "s": 2022, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2152, "s": 2120, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2179, "s": 2152, "text": "Python Classes and Objects" }, { "code": null, "e": 2200, "s": 2179, "text": "Python OOPs Concepts" }, { "code": null, "e": 2223, "s": 2200, "text": "Introduction To PYTHON" }, { "code": null, "e": 2254, "s": 2223, "text": "Python | os.path.join() method" }, { "code": null, "e": 2276, "s": 2254, "text": "Defaultdict in Python" }, { "code": null, "e": 2315, "s": 2276, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2353, "s": 2315, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2390, "s": 2353, "text": "Python Program for Fibonacci numbers" } ]
Spring @Repository Annotation with Example
03 Dec, 2021 Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier than compared to classic Java frameworks and application programming interfaces (APIs), such as Java database connectivity (JDBC), JavaServer Pages(JSP), and Java Servlet. This framework uses various new techniques such as Aspect-Oriented Programming (AOP), Plain Old Java Object (POJO), and dependency injection (DI), to develop enterprise applications. Now talking about Spring Annotation Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. There are many annotations are available in Spring Framework. Some of the Spring Framework Annotations are listed below as follows where here we are going to discuss one of the most important annotations that is @Repository Annotation @Required @Autowired @Configuration @ComponentScan @Bean @Component @Controller @Service @Repository, etc. @Repository Annotation is a specialization of @Component annotation which is used to indicate that the class provides the mechanism for storage, retrieval, update, delete and search operation on objects. Though it is a specialization of @Component annotation, so Spring Repository classes are autodetected by spring framework through classpath scanning. This annotation is a general-purpose stereotype annotation which very close to the DAO pattern where DAO classes are responsible for providing CRUD operations on database tables. Step 1: Create a Simple Spring Boot Project Refer to this article Create and Setup Spring Boot Project in Eclipse IDE and create a simple spring boot project. Step 2: Add the spring-context dependency in your pom.xml file. Go to the pom.xml file inside your project and add the following spring-context dependency. XML <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.13</version></dependency> Step 3: In your project create two packages and name the package as β€œentity” and β€œrepository”. In the entity, package creates a class name it as Student. In the repository, the package creates a Generic Interface named as DemoRepository and a class name it as StudentRepository. This is going to be our final project structure. Step 4: Create an entity class for which we will implement a spring repository. Here our entity class is Student. Below is the code for the Student.java file. This is a simple POJO (Plain Old Java Object) class in java. Java package com.example.demo.entity; public class Student { private Long id; private String name; private int age; public Student(Long id, String name, int age) { this.id = id; this.name = name; this.age = age; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; }} Step 5: Before implementing the Repository class we have created a generic DemoRepository interface to provide the contract for our repository class to implement. Below is the code for the DemoRepository.java file. Java // Java Program to illustrate DemoRepository File package com.example.demo.repository; public interface DemoRepository<T> { // Save method public void save(T t); // Find a student by its id public T findStudentById(Long id); } Step 6: Now let’s look at our StudentRepository class implementation. Java // Java Program to illustrate StudentRepository File package com.example.demo.repository; import com.example.demo.entity.Student;import org.springframework.stereotype.Repository; import java.util.HashMap;import java.util.Map; @Repositorypublic class StudentRepository implements DemoRepository<Student> { // Using an in-memory Map // to store the object data private Map<Long, Student> repository; public StudentRepository() { this.repository = new HashMap<>(); } // Implementation for save method @Override public void save(Student student) { repository.put(student.getId(), student); } // Implementation for findStudentById method @Override public Student findStudentById(Long id) { return repository.get(id); }} In this StudentRepository.java file, you can notice that we have added the @Repository annotation to indicate that the class provides the mechanism for storage, retrieval, update, delete and search operation on objects. Note: Here we have used an in-memory Map to store the object data, you can use any other mechanisms too. In the real world, we use Databases to store object data. Step 7: Spring Repository Test So now our Spring Repository is ready, let’s test it out. Go to the DemoApplication.java file and refer to the below code. Java package com.example.demo; import com.example.demo.entity.Student;import com.example.demo.repository.StudentRepository;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.AnnotationConfigApplicationContext; @SpringBootApplicationpublic class DemoApplication { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.scan("com.example.demo"); context.refresh(); StudentRepository repository = context.getBean(StudentRepository.class); // testing the store method repository.save(new Student(1L, "Anshul", 25)); repository.save(new Student(2L, "Mayank", 23)); // testing the retrieve method Student student = repository.findStudentById(1L); System.out.println(student); // close the spring context context.close(); } } Output: Lastly, run your application and you should get the following output as shown below as follows: Java-Spring Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Dec, 2021" }, { "code": null, "e": 768, "s": 28, "text": "Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier than compared to classic Java frameworks and application programming interfaces (APIs), such as Java database connectivity (JDBC), JavaServer Pages(JSP), and Java Servlet. This framework uses various new techniques such as Aspect-Oriented Programming (AOP), Plain Old Java Object (POJO), and dependency injection (DI), to develop enterprise applications. Now talking about Spring Annotation" }, { "code": null, "e": 1053, "s": 768, "text": "Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. " }, { "code": null, "e": 1288, "s": 1053, "text": "There are many annotations are available in Spring Framework. Some of the Spring Framework Annotations are listed below as follows where here we are going to discuss one of the most important annotations that is @Repository Annotation" }, { "code": null, "e": 1298, "s": 1288, "text": "@Required" }, { "code": null, "e": 1309, "s": 1298, "text": "@Autowired" }, { "code": null, "e": 1324, "s": 1309, "text": "@Configuration" }, { "code": null, "e": 1339, "s": 1324, "text": "@ComponentScan" }, { "code": null, "e": 1345, "s": 1339, "text": "@Bean" }, { "code": null, "e": 1356, "s": 1345, "text": "@Component" }, { "code": null, "e": 1368, "s": 1356, "text": "@Controller" }, { "code": null, "e": 1377, "s": 1368, "text": "@Service" }, { "code": null, "e": 1395, "s": 1377, "text": "@Repository, etc." }, { "code": null, "e": 1929, "s": 1395, "text": "@Repository Annotation is a specialization of @Component annotation which is used to indicate that the class provides the mechanism for storage, retrieval, update, delete and search operation on objects. Though it is a specialization of @Component annotation, so Spring Repository classes are autodetected by spring framework through classpath scanning. This annotation is a general-purpose stereotype annotation which very close to the DAO pattern where DAO classes are responsible for providing CRUD operations on database tables. " }, { "code": null, "e": 1973, "s": 1929, "text": "Step 1: Create a Simple Spring Boot Project" }, { "code": null, "e": 2089, "s": 1973, "text": "Refer to this article Create and Setup Spring Boot Project in Eclipse IDE and create a simple spring boot project. " }, { "code": null, "e": 2245, "s": 2089, "text": "Step 2: Add the spring-context dependency in your pom.xml file. Go to the pom.xml file inside your project and add the following spring-context dependency." }, { "code": null, "e": 2249, "s": 2245, "text": "XML" }, { "code": "<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.13</version></dependency>", "e": 2389, "s": 2249, "text": null }, { "code": null, "e": 2717, "s": 2389, "text": "Step 3: In your project create two packages and name the package as β€œentity” and β€œrepository”. In the entity, package creates a class name it as Student. In the repository, the package creates a Generic Interface named as DemoRepository and a class name it as StudentRepository. This is going to be our final project structure." }, { "code": null, "e": 2938, "s": 2717, "text": "Step 4: Create an entity class for which we will implement a spring repository. Here our entity class is Student. Below is the code for the Student.java file. This is a simple POJO (Plain Old Java Object) class in java. " }, { "code": null, "e": 2943, "s": 2938, "text": "Java" }, { "code": "package com.example.demo.entity; public class Student { private Long id; private String name; private int age; public Student(Long id, String name, int age) { this.id = id; this.name = name; this.age = age; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return \"Student{\" + \"id=\" + id + \", name='\" + name + '\\'' + \", age=\" + age + '}'; }}", "e": 3743, "s": 2943, "text": null }, { "code": null, "e": 3958, "s": 3743, "text": "Step 5: Before implementing the Repository class we have created a generic DemoRepository interface to provide the contract for our repository class to implement. Below is the code for the DemoRepository.java file." }, { "code": null, "e": 3963, "s": 3958, "text": "Java" }, { "code": "// Java Program to illustrate DemoRepository File package com.example.demo.repository; public interface DemoRepository<T> { // Save method public void save(T t); // Find a student by its id public T findStudentById(Long id); }", "e": 4209, "s": 3963, "text": null }, { "code": null, "e": 4280, "s": 4209, "text": "Step 6: Now let’s look at our StudentRepository class implementation. " }, { "code": null, "e": 4285, "s": 4280, "text": "Java" }, { "code": "// Java Program to illustrate StudentRepository File package com.example.demo.repository; import com.example.demo.entity.Student;import org.springframework.stereotype.Repository; import java.util.HashMap;import java.util.Map; @Repositorypublic class StudentRepository implements DemoRepository<Student> { // Using an in-memory Map // to store the object data private Map<Long, Student> repository; public StudentRepository() { this.repository = new HashMap<>(); } // Implementation for save method @Override public void save(Student student) { repository.put(student.getId(), student); } // Implementation for findStudentById method @Override public Student findStudentById(Long id) { return repository.get(id); }}", "e": 5072, "s": 4285, "text": null }, { "code": null, "e": 5292, "s": 5072, "text": "In this StudentRepository.java file, you can notice that we have added the @Repository annotation to indicate that the class provides the mechanism for storage, retrieval, update, delete and search operation on objects." }, { "code": null, "e": 5456, "s": 5292, "text": "Note: Here we have used an in-memory Map to store the object data, you can use any other mechanisms too. In the real world, we use Databases to store object data. " }, { "code": null, "e": 5487, "s": 5456, "text": "Step 7: Spring Repository Test" }, { "code": null, "e": 5611, "s": 5487, "text": "So now our Spring Repository is ready, let’s test it out. Go to the DemoApplication.java file and refer to the below code. " }, { "code": null, "e": 5616, "s": 5611, "text": "Java" }, { "code": "package com.example.demo; import com.example.demo.entity.Student;import com.example.demo.repository.StudentRepository;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.AnnotationConfigApplicationContext; @SpringBootApplicationpublic class DemoApplication { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.scan(\"com.example.demo\"); context.refresh(); StudentRepository repository = context.getBean(StudentRepository.class); // testing the store method repository.save(new Student(1L, \"Anshul\", 25)); repository.save(new Student(2L, \"Mayank\", 23)); // testing the retrieve method Student student = repository.findStudentById(1L); System.out.println(student); // close the spring context context.close(); } }", "e": 6587, "s": 5616, "text": null }, { "code": null, "e": 6691, "s": 6587, "text": "Output: Lastly, run your application and you should get the following output as shown below as follows:" }, { "code": null, "e": 6703, "s": 6691, "text": "Java-Spring" }, { "code": null, "e": 6708, "s": 6703, "text": "Java" }, { "code": null, "e": 6713, "s": 6708, "text": "Java" } ]
Program to Convert Octal to Hexadecimal
25 May, 2022 Given an Octal number, the task is to convert it into a Hexadecimal number. Examples: Input: 47 Output: 27 Explanation: Decimal value of 47 is = (7 * 1) + (4 * 8) = 39 Now, convert this number to hexadecimal 39/16 -> quotient = 2, remainder = 7 2/16 -> quotient = 0, remainder = 2 So, the equivalent hexadecimal number is = 27 Input: 235 Output: 9d Approach:An Octal Number or oct for short is the base-8 number and uses the digits 0 to 7. Octal numerals can be made from binary numerals by grouping consecutive binary digits into groups of three (starting from the right). A Hexadecimal Number is a positional numeral system with a radix, or base, of 16 and uses sixteen distinct symbols. It may be a combination of alphabets and numbers. It uses numbers from 0 to 9 and alphabets A to F. Steps of Conversion:The simplest way is to convert the octal number into a decimal, then the decimal into hexadecimal form. Write the powers of 8 (1, 8, 64, 512, 4096, and so on) beside the octal digits from bottom to top.Multiply each digit by its power.Add up the answers. This is the decimal solution.Divide the decimal number by 16.Get the integer quotient for the next iteration (if the number will not divide equally by 16, then round down the result to the nearest whole number).Keep a note of the remainder, it should be between 0 and 15.Repeat the steps from step 4. until the quotient is equal to 0.Write out all the remainders, from bottom to top.Convert any remainders bigger than 9 into hex letters. This is the hex solution. Write the powers of 8 (1, 8, 64, 512, 4096, and so on) beside the octal digits from bottom to top. Multiply each digit by its power. Add up the answers. This is the decimal solution. Divide the decimal number by 16. Get the integer quotient for the next iteration (if the number will not divide equally by 16, then round down the result to the nearest whole number). Keep a note of the remainder, it should be between 0 and 15. Repeat the steps from step 4. until the quotient is equal to 0. Write out all the remainders, from bottom to top. Convert any remainders bigger than 9 into hex letters. This is the hex solution. For example, if the given octal number is 5123: Then the decimal number (2560 + 64 + 16 + 3) is: 2643 Finally, the hexadecimal number is: a53 Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to convert Octal// to Hexadecimal#include<bits/stdc++.h>using namespace std; // Function to convert octal to decimalint octalToDecimal(int n){ int num = n; int dec_value = 0; // Initializing base value // to 1, i.e 8^0 int base = 1; int temp = num; while (temp) { // Extracting last digit int last_digit = temp % 10; temp = temp / 10; // Multiplying last digit with // appropriate base value and // adding it to dec_value dec_value += last_digit * base; base = base * 8; } return dec_value;} // Function to convert decimal// to hexadecimalstring decToHexa(int n){ // char array to store // hexadecimal number char hexaDeciNum[100]; // counter for hexadecimal // number array int i = 0; while(n != 0) { // Temporary variable to // store remainder int temp = 0; // Storing remainder in // temp variable. temp = n % 16; // Check if temp < 10 if (temp < 10) { hexaDeciNum[i] = temp + 48; i++; } else { hexaDeciNum[i] = temp + 87; i++; } n = n / 16; } string ans = ""; // Printing hexadecimal number array // in reverse order for(int j = i - 1; j >= 0; j--) { ans += hexaDeciNum[j]; } return ans;} // Driver Codeint main(){ string hexnum; int decnum, octnum; // Taking 5123 as an example of // Octal Number. octnum = 5123; // Convert Octal to Decimal decnum = octalToDecimal(octnum); // Convert Decimal to Hexadecimal hexnum = decToHexa(decnum); cout << "Equivalent Hexadecimal Value = " << hexnum << endl;} // This code is contributed by pratham76 // Java Program to Convert Octal// to Hexadecimal import java.util.Scanner; public class JavaProgram { public static void main(String args[]) { String octnum, hexnum; int decnum; Scanner scan = new Scanner(System.in); // Taking 5123 as an example of // Octal Number. octnum = "5123"; // Convert Octal to Decimal decnum = Integer.parseInt(octnum, 8); // Convert Decimal to Hexadecimal hexnum = Integer.toHexString(decnum); System.out.print("Equivalent Hexadecimal Value = " + hexnum); }} # Python3 program to convert octal# to hexadecimal # Taking 5123 as an example of# octal numberoctnum = "5123" # Convert octal to decimaldecnum = int(octnum, 8) # Convert decimal to hexadecimalhexadecimal = hex(decnum).replace("0x", "") # Printing the hexadecimal valueprint("Equivalent Hexadecimal Value =", hexadecimal) # This code is contributed by virusbuddah_ // C# Program to Convert Octal// to Hexadecimalusing System;class GFG{ // Function to convert octal// to decimalstatic int octalToDecimal(int n){ int num = n; int dec_value = 0; // Initializing base value // to 1, i.e 8^0 int b_ase = 1; int temp = num; while (temp > 0) { // Extracting last digit int last_digit = temp % 10; temp = temp / 10; // Multiplying last digit // with appropriate base // value and adding it to // dec_value dec_value += last_digit * b_ase; b_ase = b_ase * 8; } return dec_value;} // Function to convert decimal// to hexadecimalstatic string decToHexa(int n){ // char array to store // hexadecimal number char []hexaDeciNum = new char[100]; // counter for hexadecimal // number array int i = 0; string ans = ""; while(n != 0) { // temporary variable to // store remainder int temp = 0; // storing remainder // in temp variable. temp = n % 16; // check if temp < 10 if(temp < 10) { hexaDeciNum[i] = (char)(temp + 48); i++; } else { hexaDeciNum[i] = (char)(temp + 87); i++; } n = n / 16; } for(int j = i - 1; j >= 0; j--) { ans += hexaDeciNum[j]; } return ans;} // Driver codepublic static void Main(string []args){ string octnum, hexnum; int decnum; // Taking 5123 as an // example of Octal Number. octnum = "5123"; // Convert Octal to Decimal decnum = octalToDecimal(Int32.Parse(octnum)); // Convert Decimal to Hexadecimal hexnum = decToHexa(decnum); Console.Write("Equivalent Hexadecimal Value = " + hexnum);}} // This code is contributed by rutvik_56 // JavaScript program to convert Octal// to Hexadecimal // Function to convert octal to decimalfunction octalToDecimal( n){ var num = n; var dec_value = 0; // Initializing base value // to 1, i.e 8^0 var base = 1; var temp = num; while (temp > 0) { // Extracting last digit var last_digit = temp % 10; temp = Math.floor(temp / 10); // Multiplying last digit with // appropriate base value and // adding it to dec_value dec_value += last_digit * base; base = base * 8; } return dec_value;} // Function to convert decimal// to hexadecimalfunction decToHexa( n){ // char array to store // hexadecimal number var hexaDeciNum = new Array(100); // counter for hexadecimal // number array var i = 0; while(n != 0) { // Temporary variable to // store remainder var temp = 0; // Storing remainder in // temp variable. temp = n % 16; // Check if temp < 10 if (temp < 10) { hexaDeciNum[i] = temp + 48; i++; } else { hexaDeciNum[i] = temp + 87; i++; } n = Math.floor(n / 16); } var ans = ""; // Printing hexadecimal number array // in reverse order for(var j = i - 1; j >= 0; j--) { ans += String.fromCharCode(hexaDeciNum[j]); } return ans;} // Driver Codevar hexnum;var decnum, octnum; // Taking 5123 as an example of// Octal Number.octnum = 5123; // Convert Octal to Decimaldecnum = octalToDecimal(octnum); // Convert Decimal to Hexadecimalhexnum = decToHexa(decnum); console.log("Equivalent Hexadecimal Value = " + hexnum); // This code is contributed by phasing17 Equivalent Hexadecimal Value = a53 virusbuddha rutvik_56 pratham76 phasing17 number-theory Java Programs Mathematical number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate Over the Characters of a String in Java How to Convert Char to String in Java? How to Get Elements By Index from HashSet in Java? Java Program to Write into a File How to Write Data into Excel Sheet using Java? Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 53, "s": 25, "text": "\n25 May, 2022" }, { "code": null, "e": 129, "s": 53, "text": "Given an Octal number, the task is to convert it into a Hexadecimal number." }, { "code": null, "e": 140, "s": 129, "text": "Examples: " }, { "code": null, "e": 410, "s": 140, "text": "Input: 47 \nOutput: 27\nExplanation:\nDecimal value of 47 is = (7 * 1) + (4 * 8) = 39\n\nNow, convert this number to hexadecimal\n39/16 -> quotient = 2, remainder = 7\n2/16 -> quotient = 0, remainder = 2\n\nSo, the equivalent hexadecimal number is = 27\n\nInput: 235\nOutput: 9d" }, { "code": null, "e": 635, "s": 410, "text": "Approach:An Octal Number or oct for short is the base-8 number and uses the digits 0 to 7. Octal numerals can be made from binary numerals by grouping consecutive binary digits into groups of three (starting from the right)." }, { "code": null, "e": 851, "s": 635, "text": "A Hexadecimal Number is a positional numeral system with a radix, or base, of 16 and uses sixteen distinct symbols. It may be a combination of alphabets and numbers. It uses numbers from 0 to 9 and alphabets A to F." }, { "code": null, "e": 976, "s": 851, "text": "Steps of Conversion:The simplest way is to convert the octal number into a decimal, then the decimal into hexadecimal form. " }, { "code": null, "e": 1591, "s": 976, "text": "Write the powers of 8 (1, 8, 64, 512, 4096, and so on) beside the octal digits from bottom to top.Multiply each digit by its power.Add up the answers. This is the decimal solution.Divide the decimal number by 16.Get the integer quotient for the next iteration (if the number will not divide equally by 16, then round down the result to the nearest whole number).Keep a note of the remainder, it should be between 0 and 15.Repeat the steps from step 4. until the quotient is equal to 0.Write out all the remainders, from bottom to top.Convert any remainders bigger than 9 into hex letters. This is the hex solution." }, { "code": null, "e": 1690, "s": 1591, "text": "Write the powers of 8 (1, 8, 64, 512, 4096, and so on) beside the octal digits from bottom to top." }, { "code": null, "e": 1724, "s": 1690, "text": "Multiply each digit by its power." }, { "code": null, "e": 1774, "s": 1724, "text": "Add up the answers. This is the decimal solution." }, { "code": null, "e": 1807, "s": 1774, "text": "Divide the decimal number by 16." }, { "code": null, "e": 1958, "s": 1807, "text": "Get the integer quotient for the next iteration (if the number will not divide equally by 16, then round down the result to the nearest whole number)." }, { "code": null, "e": 2019, "s": 1958, "text": "Keep a note of the remainder, it should be between 0 and 15." }, { "code": null, "e": 2083, "s": 2019, "text": "Repeat the steps from step 4. until the quotient is equal to 0." }, { "code": null, "e": 2133, "s": 2083, "text": "Write out all the remainders, from bottom to top." }, { "code": null, "e": 2214, "s": 2133, "text": "Convert any remainders bigger than 9 into hex letters. This is the hex solution." }, { "code": null, "e": 2262, "s": 2214, "text": "For example, if the given octal number is 5123:" }, { "code": null, "e": 2316, "s": 2262, "text": "Then the decimal number (2560 + 64 + 16 + 3) is: 2643" }, { "code": null, "e": 2356, "s": 2316, "text": "Finally, the hexadecimal number is: a53" }, { "code": null, "e": 2408, "s": 2356, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 2412, "s": 2408, "text": "C++" }, { "code": null, "e": 2417, "s": 2412, "text": "Java" }, { "code": null, "e": 2425, "s": 2417, "text": "Python3" }, { "code": null, "e": 2428, "s": 2425, "text": "C#" }, { "code": null, "e": 2439, "s": 2428, "text": "Javascript" }, { "code": "// C++ program to convert Octal// to Hexadecimal#include<bits/stdc++.h>using namespace std; // Function to convert octal to decimalint octalToDecimal(int n){ int num = n; int dec_value = 0; // Initializing base value // to 1, i.e 8^0 int base = 1; int temp = num; while (temp) { // Extracting last digit int last_digit = temp % 10; temp = temp / 10; // Multiplying last digit with // appropriate base value and // adding it to dec_value dec_value += last_digit * base; base = base * 8; } return dec_value;} // Function to convert decimal// to hexadecimalstring decToHexa(int n){ // char array to store // hexadecimal number char hexaDeciNum[100]; // counter for hexadecimal // number array int i = 0; while(n != 0) { // Temporary variable to // store remainder int temp = 0; // Storing remainder in // temp variable. temp = n % 16; // Check if temp < 10 if (temp < 10) { hexaDeciNum[i] = temp + 48; i++; } else { hexaDeciNum[i] = temp + 87; i++; } n = n / 16; } string ans = \"\"; // Printing hexadecimal number array // in reverse order for(int j = i - 1; j >= 0; j--) { ans += hexaDeciNum[j]; } return ans;} // Driver Codeint main(){ string hexnum; int decnum, octnum; // Taking 5123 as an example of // Octal Number. octnum = 5123; // Convert Octal to Decimal decnum = octalToDecimal(octnum); // Convert Decimal to Hexadecimal hexnum = decToHexa(decnum); cout << \"Equivalent Hexadecimal Value = \" << hexnum << endl;} // This code is contributed by pratham76", "e": 4325, "s": 2439, "text": null }, { "code": "// Java Program to Convert Octal// to Hexadecimal import java.util.Scanner; public class JavaProgram { public static void main(String args[]) { String octnum, hexnum; int decnum; Scanner scan = new Scanner(System.in); // Taking 5123 as an example of // Octal Number. octnum = \"5123\"; // Convert Octal to Decimal decnum = Integer.parseInt(octnum, 8); // Convert Decimal to Hexadecimal hexnum = Integer.toHexString(decnum); System.out.print(\"Equivalent Hexadecimal Value = \" + hexnum); }}", "e": 4973, "s": 4325, "text": null }, { "code": "# Python3 program to convert octal# to hexadecimal # Taking 5123 as an example of# octal numberoctnum = \"5123\" # Convert octal to decimaldecnum = int(octnum, 8) # Convert decimal to hexadecimalhexadecimal = hex(decnum).replace(\"0x\", \"\") # Printing the hexadecimal valueprint(\"Equivalent Hexadecimal Value =\", hexadecimal) # This code is contributed by virusbuddah_", "e": 5338, "s": 4973, "text": null }, { "code": "// C# Program to Convert Octal// to Hexadecimalusing System;class GFG{ // Function to convert octal// to decimalstatic int octalToDecimal(int n){ int num = n; int dec_value = 0; // Initializing base value // to 1, i.e 8^0 int b_ase = 1; int temp = num; while (temp > 0) { // Extracting last digit int last_digit = temp % 10; temp = temp / 10; // Multiplying last digit // with appropriate base // value and adding it to // dec_value dec_value += last_digit * b_ase; b_ase = b_ase * 8; } return dec_value;} // Function to convert decimal// to hexadecimalstatic string decToHexa(int n){ // char array to store // hexadecimal number char []hexaDeciNum = new char[100]; // counter for hexadecimal // number array int i = 0; string ans = \"\"; while(n != 0) { // temporary variable to // store remainder int temp = 0; // storing remainder // in temp variable. temp = n % 16; // check if temp < 10 if(temp < 10) { hexaDeciNum[i] = (char)(temp + 48); i++; } else { hexaDeciNum[i] = (char)(temp + 87); i++; } n = n / 16; } for(int j = i - 1; j >= 0; j--) { ans += hexaDeciNum[j]; } return ans;} // Driver codepublic static void Main(string []args){ string octnum, hexnum; int decnum; // Taking 5123 as an // example of Octal Number. octnum = \"5123\"; // Convert Octal to Decimal decnum = octalToDecimal(Int32.Parse(octnum)); // Convert Decimal to Hexadecimal hexnum = decToHexa(decnum); Console.Write(\"Equivalent Hexadecimal Value = \" + hexnum);}} // This code is contributed by rutvik_56", "e": 6993, "s": 5338, "text": null }, { "code": "// JavaScript program to convert Octal// to Hexadecimal // Function to convert octal to decimalfunction octalToDecimal( n){ var num = n; var dec_value = 0; // Initializing base value // to 1, i.e 8^0 var base = 1; var temp = num; while (temp > 0) { // Extracting last digit var last_digit = temp % 10; temp = Math.floor(temp / 10); // Multiplying last digit with // appropriate base value and // adding it to dec_value dec_value += last_digit * base; base = base * 8; } return dec_value;} // Function to convert decimal// to hexadecimalfunction decToHexa( n){ // char array to store // hexadecimal number var hexaDeciNum = new Array(100); // counter for hexadecimal // number array var i = 0; while(n != 0) { // Temporary variable to // store remainder var temp = 0; // Storing remainder in // temp variable. temp = n % 16; // Check if temp < 10 if (temp < 10) { hexaDeciNum[i] = temp + 48; i++; } else { hexaDeciNum[i] = temp + 87; i++; } n = Math.floor(n / 16); } var ans = \"\"; // Printing hexadecimal number array // in reverse order for(var j = i - 1; j >= 0; j--) { ans += String.fromCharCode(hexaDeciNum[j]); } return ans;} // Driver Codevar hexnum;var decnum, octnum; // Taking 5123 as an example of// Octal Number.octnum = 5123; // Convert Octal to Decimaldecnum = octalToDecimal(octnum); // Convert Decimal to Hexadecimalhexnum = decToHexa(decnum); console.log(\"Equivalent Hexadecimal Value = \" + hexnum); // This code is contributed by phasing17", "e": 8823, "s": 6993, "text": null }, { "code": null, "e": 8858, "s": 8823, "text": "Equivalent Hexadecimal Value = a53" }, { "code": null, "e": 8872, "s": 8860, "text": "virusbuddha" }, { "code": null, "e": 8882, "s": 8872, "text": "rutvik_56" }, { "code": null, "e": 8892, "s": 8882, "text": "pratham76" }, { "code": null, "e": 8902, "s": 8892, "text": "phasing17" }, { "code": null, "e": 8916, "s": 8902, "text": "number-theory" }, { "code": null, "e": 8930, "s": 8916, "text": "Java Programs" }, { "code": null, "e": 8943, "s": 8930, "text": "Mathematical" }, { "code": null, "e": 8957, "s": 8943, "text": "number-theory" }, { "code": null, "e": 8970, "s": 8957, "text": "Mathematical" }, { "code": null, "e": 9068, "s": 8970, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9116, "s": 9068, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 9155, "s": 9116, "text": "How to Convert Char to String in Java?" }, { "code": null, "e": 9206, "s": 9155, "text": "How to Get Elements By Index from HashSet in Java?" }, { "code": null, "e": 9240, "s": 9206, "text": "Java Program to Write into a File" }, { "code": null, "e": 9287, "s": 9240, "text": "How to Write Data into Excel Sheet using Java?" }, { "code": null, "e": 9317, "s": 9287, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 9360, "s": 9317, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 9420, "s": 9360, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 9435, "s": 9420, "text": "C++ Data Types" } ]
2's Complement | Practice | GeeksforGeeks
For a given string of binary number bi. Find the two’s complement of it. Example 1: Input: bi = 00000101 Output: 11111011 Explaination: 2's complement is reversing all the bits of the given number and then adding 1 to it. Example 2: Input: bi = 101 Output: 011 Explaination: Follow the process of figuring out 2's complement. This will be the answer. Your Task: You do not need to read input or print anything. Your task is to complete the function complement() which takes bi as input parameter and returns the 2's complement of the number. Expected Time Complexity: O(|bi|) Expected Auxiliary Space: O(|bi|) Constraints: 1 ≀ |bi| ≀ 10 0 mayank20211 month ago C++ : 0.0/1.1 string complement(string bi){ for(int i=0; i<bi.size() ; i++) { if(bi[i]=='0') bi[i]='1'; else bi[i]='0'; } for(int i=bi.size()-1; i>=0 ; i--) { if(bi[i]=='0') { bi[i]='1'; break; } else bi[i]='0'; } return bi; } 0 Amar Prakash1 year ago Amar Prakash string complement(string bi){ string res = ""; int index = 0; int n = bi.length() - 1; for(int i=n; i>=0; i--) { if(bi[i] == '1') { index = i; break; } } for(int i=0; i<index ;="" i++)="" {="" if(bi[i]="=" '1')="" {="" res="" +="0" ;="" }="" else="" if(bi[i]="=" '0')="" {="" res="" +="1" ;="" }="" }="" for(int="" i="index;" i<bi.length();="" i++)="" {="" res="" +="bi[i];" }="" return="" res;="" code="" here="" }=""> 0 Saxena Vivek1 year ago Saxena Vivek *********python plz check this code below i want help***********class Solution: def complement(self, bi): bits="" #empty string for var in bi: bits+="1" #after that deindent for loop diff=int(bits)-int(bi) # 1s compliment binary1=("0b"+str(diff)) binary2=("0b"+"001") # 2s comp = 1s complimenr + binary 1 integer_sum = int(binary1, 2) + int(binary2, 2) binary_sum = bin(integer_sum) return (str(binary_sum[2:])) 0 Saxena Vivek1 year ago Saxena Vivek *******************python not working ********************** # code here #x=len(bi) #print(x) bits="" for var in bi: bits+="1" #print(type(bits)) diff=int(bits)-int(bi) #print(diff) # 1s compliment binary1=("0b"+str(diff)) binary2=("0b"+"001") # 2s compliment = 1s complimenr + binary 1 integer_sum = int(binary1, 2) + int(binary2, 2) binary_sum = bin(integer_sum) return (str(binary_sum[2:])) 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": 226, "text": "For a given string of binary number bi. Find the two’s complement of it." }, { "code": null, "e": 310, "s": 299, "text": "Example 1:" }, { "code": null, "e": 450, "s": 310, "text": "Input: bi = 00000101\nOutput: 11111011\nExplaination: 2's complement is reversing all \nthe bits of the given number and then adding \n1 to it." }, { "code": null, "e": 461, "s": 450, "text": "Example 2:" }, { "code": null, "e": 580, "s": 461, "text": "Input: bi = 101\nOutput: 011\nExplaination: Follow the process of figuring \nout 2's complement. This will be the answer." }, { "code": null, "e": 771, "s": 580, "text": "Your Task:\nYou do not need to read input or print anything. Your task is to complete the function complement() which takes bi as input parameter and returns the 2's complement of the number." }, { "code": null, "e": 839, "s": 771, "text": "Expected Time Complexity: O(|bi|)\nExpected Auxiliary Space: O(|bi|)" }, { "code": null, "e": 866, "s": 839, "text": "Constraints:\n1 ≀ |bi| ≀ 10" }, { "code": null, "e": 868, "s": 866, "text": "0" }, { "code": null, "e": 890, "s": 868, "text": "mayank20211 month ago" }, { "code": null, "e": 904, "s": 890, "text": "C++ : 0.0/1.1" }, { "code": null, "e": 1326, "s": 904, "text": "string complement(string bi){ for(int i=0; i<bi.size() ; i++) { if(bi[i]=='0') bi[i]='1'; else bi[i]='0'; } for(int i=bi.size()-1; i>=0 ; i--) { if(bi[i]=='0') { bi[i]='1'; break; } else bi[i]='0'; } return bi; }" }, { "code": null, "e": 1328, "s": 1326, "text": "0" }, { "code": null, "e": 1351, "s": 1328, "text": "Amar Prakash1 year ago" }, { "code": null, "e": 1364, "s": 1351, "text": "Amar Prakash" }, { "code": null, "e": 1614, "s": 1364, "text": "string complement(string bi){ string res = \"\"; int index = 0; int n = bi.length() - 1; for(int i=n; i>=0; i--) { if(bi[i] == '1') { index = i; break; }" }, { "code": null, "e": 1897, "s": 1614, "text": " } for(int i=0; i<index ;=\"\" i++)=\"\" {=\"\" if(bi[i]=\"=\" '1')=\"\" {=\"\" res=\"\" +=\"0\" ;=\"\" }=\"\" else=\"\" if(bi[i]=\"=\" '0')=\"\" {=\"\" res=\"\" +=\"1\" ;=\"\" }=\"\" }=\"\" for(int=\"\" i=\"index;\" i<bi.length();=\"\" i++)=\"\" {=\"\" res=\"\" +=\"bi[i];\" }=\"\" return=\"\" res;=\"\" code=\"\" here=\"\" }=\"\">" }, { "code": null, "e": 1899, "s": 1897, "text": "0" }, { "code": null, "e": 1922, "s": 1899, "text": "Saxena Vivek1 year ago" }, { "code": null, "e": 1935, "s": 1922, "text": "Saxena Vivek" }, { "code": null, "e": 2421, "s": 1935, "text": "*********python plz check this code below i want help***********class Solution: def complement(self, bi): bits=\"\" #empty string for var in bi: bits+=\"1\" #after that deindent for loop diff=int(bits)-int(bi) # 1s compliment binary1=(\"0b\"+str(diff)) binary2=(\"0b\"+\"001\") # 2s comp = 1s complimenr + binary 1 integer_sum = int(binary1, 2) + int(binary2, 2) binary_sum = bin(integer_sum) return (str(binary_sum[2:]))" }, { "code": null, "e": 2423, "s": 2421, "text": "0" }, { "code": null, "e": 2446, "s": 2423, "text": "Saxena Vivek1 year ago" }, { "code": null, "e": 2459, "s": 2446, "text": "Saxena Vivek" }, { "code": null, "e": 2960, "s": 2459, "text": "*******************python not working ********************** # code here #x=len(bi) #print(x) bits=\"\" for var in bi: bits+=\"1\" #print(type(bits)) diff=int(bits)-int(bi) #print(diff) # 1s compliment binary1=(\"0b\"+str(diff)) binary2=(\"0b\"+\"001\") # 2s compliment = 1s complimenr + binary 1 integer_sum = int(binary1, 2) + int(binary2, 2) binary_sum = bin(integer_sum) return (str(binary_sum[2:]))" }, { "code": null, "e": 3106, "s": 2960, "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": 3142, "s": 3106, "text": " Login to access your submissions. " }, { "code": null, "e": 3152, "s": 3142, "text": "\nProblem\n" }, { "code": null, "e": 3162, "s": 3152, "text": "\nContest\n" }, { "code": null, "e": 3225, "s": 3162, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3373, "s": 3225, "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": 3581, "s": 3373, "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": 3687, "s": 3581, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to delete a localStorage item when the browser window/tab is closed?
To clear a localStorage data on browser close, you can use the window.onunload event to check for tab close. Let's say you have a local storage object called MyStorage as a global for the sake of this example. Then you can write an event handler βˆ’ window.onunload = () => { // Clear the local storage window.MyStorage.clear() } This will clear the local storage on the tab/window close.
[ { "code": null, "e": 1171, "s": 1062, "text": "To clear a localStorage data on browser close, you can use the window.onunload event to check for tab close." }, { "code": null, "e": 1310, "s": 1171, "text": "Let's say you have a local storage object called MyStorage as a global\nfor the sake of this example. Then you can write an event handler βˆ’" }, { "code": null, "e": 1396, "s": 1310, "text": "window.onunload = () => {\n // Clear the local storage\n window.MyStorage.clear()\n}" }, { "code": null, "e": 1455, "s": 1396, "text": "This will clear the local storage on the tab/window close." } ]
MVC Framework - Action Filters
In ASP.NET MVC, controllers define action methods and these action methods generally have a one-to-one relationship with UI controls, such as clicking a button or a link, etc. For example, in one of our previous examples, the UserController class contained methods UserAdd, UserDelete, etc. However, many times we would like to perform some action before or after a particular operation. For achieving this functionality, ASP.NET MVC provides a feature to add pre- and post-action behaviors on the controller's action methods. ASP.NET MVC framework supports the following action filters βˆ’ Action Filters βˆ’ Action filters are used to implement logic that gets executed before and after a controller action executes. We will look at Action Filters in detail in this chapter. Action Filters βˆ’ Action filters are used to implement logic that gets executed before and after a controller action executes. We will look at Action Filters in detail in this chapter. Authorization Filters βˆ’ Authorization filters are used to implement authentication and authorization for controller actions. Authorization Filters βˆ’ Authorization filters are used to implement authentication and authorization for controller actions. Result Filters βˆ’ Result filters contain logic that is executed before and after a view result is executed. For example, you might want to modify a view result right before the view is rendered to the browser. Result Filters βˆ’ Result filters contain logic that is executed before and after a view result is executed. For example, you might want to modify a view result right before the view is rendered to the browser. Exception Filters βˆ’ Exception filters are the last type of filter to run. You can use an exception filter to handle errors raised by either your controller actions or controller action results. You also can use exception filters to log errors. Exception Filters βˆ’ Exception filters are the last type of filter to run. You can use an exception filter to handle errors raised by either your controller actions or controller action results. You also can use exception filters to log errors. Action filters are one of the most commonly used filters to perform additional data processing, or manipulating the return values or cancelling the execution of action or modifying the view structure at run time. Action Filters are additional attributes that can be applied to either a controller section or the entire controller to modify the way in which an action is executed. These attributes are special .NET classes derived from System.Attribute which can be attached to classes, methods, properties, and fields. ASP.NET MVC provides the following action filters βˆ’ Output Cache βˆ’ This action filter caches the output of a controller action for a specified amount of time. Output Cache βˆ’ This action filter caches the output of a controller action for a specified amount of time. Handle Error βˆ’ This action filter handles errors raised when a controller action executes. Handle Error βˆ’ This action filter handles errors raised when a controller action executes. Authorize βˆ’ This action filter enables you to restrict access to a particular user or role. Authorize βˆ’ This action filter enables you to restrict access to a particular user or role. Now, we will see the code example to apply these filters on an example controller ActionFilterDemoController. (ActionFilterDemoController is just used as an example. You can use these filters on any of your controllers.) Example βˆ’ Specifies the return value to be cached for 10 seconds. public class ActionFilterDemoController : Controller { [HttpGet] OutputCache(Duration = 10)] public string Index() { return DateTime.Now.ToString("T"); } } Example βˆ’ Redirects application to a custom error page when an error is triggered by the controller. [HandleError] public class ActionFilterDemoController : Controller { public ActionResult Index() { throw new NullReferenceException(); } public ActionResult About() { return View(); } } With the above code, if any error happens during the action execution, it will find a view named Error in the Views folder and render that page to the user. Example βˆ’ Allowing only authorized users to log in the application. public class ActionFilterDemoController: Controller { [Authorize] public ActionResult Index() { ViewBag.Message = "This can be viewed only by authenticated users only"; return View(); } [Authorize(Roles="admin")] public ActionResult AdminIndex() { ViewBag.Message = "This can be viewed only by users in Admin role only"; return View(); } } With the above code, if you would try to access the application without logging in, it will throw an error similar to the one shown in the following screenshot. 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 55 Lectures 4.5 hours University Code 40 Lectures 2.5 hours University Code 140 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2316, "s": 2025, "text": "In ASP.NET MVC, controllers define action methods and these action methods generally have a one-to-one relationship with UI controls, such as clicking a button or a link, etc. For example, in one of our previous examples, the UserController class contained methods UserAdd, UserDelete, etc." }, { "code": null, "e": 2552, "s": 2316, "text": "However, many times we would like to perform some action before or after a particular operation. For achieving this functionality, ASP.NET MVC provides a feature to add pre- and post-action behaviors on the controller's action methods." }, { "code": null, "e": 2614, "s": 2552, "text": "ASP.NET MVC framework supports the following action filters βˆ’" }, { "code": null, "e": 2798, "s": 2614, "text": "Action Filters βˆ’ Action filters are used to implement logic that gets executed before and after a controller action executes. We will look at Action Filters in detail in this chapter." }, { "code": null, "e": 2982, "s": 2798, "text": "Action Filters βˆ’ Action filters are used to implement logic that gets executed before and after a controller action executes. We will look at Action Filters in detail in this chapter." }, { "code": null, "e": 3107, "s": 2982, "text": "Authorization Filters βˆ’ Authorization filters are used to implement authentication and authorization for controller actions." }, { "code": null, "e": 3232, "s": 3107, "text": "Authorization Filters βˆ’ Authorization filters are used to implement authentication and authorization for controller actions." }, { "code": null, "e": 3441, "s": 3232, "text": "Result Filters βˆ’ Result filters contain logic that is executed before and after a view result is executed. For example, you might want to modify a view result right before the view is rendered to the browser." }, { "code": null, "e": 3650, "s": 3441, "text": "Result Filters βˆ’ Result filters contain logic that is executed before and after a view result is executed. For example, you might want to modify a view result right before the view is rendered to the browser." }, { "code": null, "e": 3894, "s": 3650, "text": "Exception Filters βˆ’ Exception filters are the last type of filter to run. You can use an exception filter to handle errors raised by either your controller actions or controller action results. You also can use exception filters to log errors." }, { "code": null, "e": 4138, "s": 3894, "text": "Exception Filters βˆ’ Exception filters are the last type of filter to run. You can use an exception filter to handle errors raised by either your controller actions or controller action results. You also can use exception filters to log errors." }, { "code": null, "e": 4351, "s": 4138, "text": "Action filters are one of the most commonly used filters to perform additional data processing, or manipulating the return values or cancelling the execution of action or modifying the view structure at run time." }, { "code": null, "e": 4657, "s": 4351, "text": "Action Filters are additional attributes that can be applied to either a controller section or the entire controller to modify the way in which an action is executed. These attributes are special .NET classes derived from System.Attribute which can be attached to classes, methods, properties, and fields." }, { "code": null, "e": 4709, "s": 4657, "text": "ASP.NET MVC provides the following action filters βˆ’" }, { "code": null, "e": 4816, "s": 4709, "text": "Output Cache βˆ’ This action filter caches the output of a controller action for a specified amount of time." }, { "code": null, "e": 4923, "s": 4816, "text": "Output Cache βˆ’ This action filter caches the output of a controller action for a specified amount of time." }, { "code": null, "e": 5014, "s": 4923, "text": "Handle Error βˆ’ This action filter handles errors raised when a controller action executes." }, { "code": null, "e": 5105, "s": 5014, "text": "Handle Error βˆ’ This action filter handles errors raised when a controller action executes." }, { "code": null, "e": 5197, "s": 5105, "text": "Authorize βˆ’ This action filter enables you to restrict access to a particular user or role." }, { "code": null, "e": 5289, "s": 5197, "text": "Authorize βˆ’ This action filter enables you to restrict access to a particular user or role." }, { "code": null, "e": 5510, "s": 5289, "text": "Now, we will see the code example to apply these filters on an example controller ActionFilterDemoController. (ActionFilterDemoController is just used as an example. You can use these filters on any of your controllers.)" }, { "code": null, "e": 5576, "s": 5510, "text": "Example βˆ’ Specifies the return value to be cached for 10 seconds." }, { "code": null, "e": 5761, "s": 5576, "text": "public class ActionFilterDemoController : Controller { \n [HttpGet] \n OutputCache(Duration = 10)] \n \n public string Index() { \n return DateTime.Now.ToString(\"T\"); \n } \n}" }, { "code": null, "e": 5862, "s": 5761, "text": "Example βˆ’ Redirects application to a custom error page when an error is triggered by the controller." }, { "code": null, "e": 6090, "s": 5862, "text": "[HandleError] \npublic class ActionFilterDemoController : Controller { \n \n public ActionResult Index() { \n throw new NullReferenceException(); \n } \n \n public ActionResult About() { \n return View(); \n } \n} " }, { "code": null, "e": 6247, "s": 6090, "text": "With the above code, if any error happens during the action execution, it will find a view named Error in the Views folder and render that page to the user." }, { "code": null, "e": 6315, "s": 6247, "text": "Example βˆ’ Allowing only authorized users to log in the application." }, { "code": null, "e": 6717, "s": 6315, "text": "public class ActionFilterDemoController: Controller { \n [Authorize] \n \n public ActionResult Index() { \n ViewBag.Message = \"This can be viewed only by authenticated users only\"; \n return View(); \n } \n \n [Authorize(Roles=\"admin\")] \n public ActionResult AdminIndex() { \n ViewBag.Message = \"This can be viewed only by users in Admin role only\"; \n return View(); \n } \n}" }, { "code": null, "e": 6878, "s": 6717, "text": "With the above code, if you would try to access the application without logging in, it will throw an error similar to the one shown in the following screenshot." }, { "code": null, "e": 6913, "s": 6878, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6936, "s": 6913, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 6970, "s": 6936, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 6990, "s": 6970, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 7025, "s": 6990, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7042, "s": 7025, "text": " University Code" }, { "code": null, "e": 7077, "s": 7042, "text": "\n 55 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7094, "s": 7077, "text": " University Code" }, { "code": null, "e": 7129, "s": 7094, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7146, "s": 7129, "text": " University Code" }, { "code": null, "e": 7180, "s": 7146, "text": "\n 140 Lectures \n 9 hours \n" }, { "code": null, "e": 7195, "s": 7180, "text": " Bhrugen Patel" }, { "code": null, "e": 7202, "s": 7195, "text": " Print" }, { "code": null, "e": 7213, "s": 7202, "text": " Add Notes" } ]
Minimum time required to rot all oranges - GeeksforGeeks
28 Feb, 2022 Given a matrix of dimension m*n where each cell in the matrix can have values 0, 1 or 2 which has the following meaning: 0: Empty cell 1: Cells have fresh oranges 2: Cells have rotten oranges Determine what is the minimum time required so that all the oranges become rotten. A rotten orange at index [i,j] can rot other fresh orange at indexes [i-1,j], [i+1,j], [i,j-1], [i,j+1] (up, down, left and right). If it is impossible to rot every orange then simply return -1. Examples: Input: arr[][C] = { {2, 1, 0, 2, 1}, {1, 0, 1, 2, 1}, {1, 0, 0, 2, 1}}; Output: All oranges can become rotten in 2-time frames. Explanation: At 0th time frame: {2, 1, 0, 2, 1} {1, 0, 1, 2, 1} {1, 0, 0, 2, 1} At 1st time frame: {2, 2, 0, 2, 2} {2, 0, 2, 2, 2} {1, 0, 0, 2, 2} At 2nd time frame: {2, 2, 0, 2, 2} {2, 0, 2, 2, 2} {2, 0, 0, 2, 2} Input: arr[][C] = { {2, 1, 0, 2, 1}, {0, 0, 1, 2, 1}, {1, 0, 0, 2, 1}}; Output: All oranges cannot be rotten. Explanation: At 0th time frame: {2, 1, 0, 2, 1} {0, 0, 1, 2, 1} {1, 0, 0, 2, 1} At 1st time frame: {2, 2, 0, 2, 2} {0, 0, 2, 2, 2} {1, 0, 0, 2, 2} At 2nd time frame: {2, 2, 0, 2, 2} {0, 0, 2, 2, 2} {1, 0, 0, 2, 2} ... The 1 at the bottom left corner of the matrix is never rotten. Naive Solution: Approach: The idea is very basic. Traverse through all oranges in multiple rounds. In every round, rot the oranges to the adjacent position of oranges which were rotten in the last round. Algorithm: Create a variable no = 2 and changed = falseRun a loop until there is no cell of the matrix which is changed in an iteration.Run a nested loop and traverse the matrix. If the element of the matrix is equal to no then assign the adjacent elements to no + 1 if the adjacent element’s value is equal to 1, i.e. not rotten, and update changed to true.Traverse the matrix and check if there is any cell which is 1. If 1 is present return -1Else return no – 2 Create a variable no = 2 and changed = falseRun a loop until there is no cell of the matrix which is changed in an iteration.Run a nested loop and traverse the matrix. If the element of the matrix is equal to no then assign the adjacent elements to no + 1 if the adjacent element’s value is equal to 1, i.e. not rotten, and update changed to true.Traverse the matrix and check if there is any cell which is 1. If 1 is present return -1Else return no – 2 Create a variable no = 2 and changed = false Run a loop until there is no cell of the matrix which is changed in an iteration. Run a nested loop and traverse the matrix. If the element of the matrix is equal to no then assign the adjacent elements to no + 1 if the adjacent element’s value is equal to 1, i.e. not rotten, and update changed to true. Traverse the matrix and check if there is any cell which is 1. If 1 is present return -1 Else return no – 2 Implementation: C++14 Java Python3 C# Javascript // C++ program to rot all oranges when u can move// in all the four direction from a rotten orange#include <bits/stdc++.h>using namespace std; const int R = 3;const int C = 5; // Check if i, j is under the array limits of row and columnbool issafe(int i, int j){ if (i >= 0 && i < R && j >= 0 && j < C) return true; return false;} int rotOranges(int v[R][C]){ bool changed = false; int no = 2; while (true) { for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { // Rot all other oranges present at // (i+1, j), (i, j-1), (i, j+1), (i-1, j) if (v[i][j] == no) { if (issafe(i + 1, j) && v[i + 1][j] == 1) { v[i + 1][j] = v[i][j] + 1; changed = true; } if (issafe(i, j + 1) && v[i][j + 1] == 1) { v[i][j + 1] = v[i][j] + 1; changed = true; } if (issafe(i - 1, j) && v[i - 1][j] == 1) { v[i - 1][j] = v[i][j] + 1; changed = true; } if (issafe(i, j - 1) && v[i][j - 1] == 1) { v[i][j - 1] = v[i][j] + 1; changed = true; } } } } // if no rotten orange found it means all // oranges rottened now if (!changed) break; changed = false; no++; } for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { // if any orange is found to be // not rotten then ans is not possible if (v[i][j] == 1) return -1; } } // Because initial value for a rotten // orange was 2 return no - 2;} // Driver functionint main(){ int v[R][C] = { { 2, 1, 0, 2, 1 }, { 1, 0, 1, 2, 1 }, { 1, 0, 0, 2, 1 } }; cout << "Max time incurred: " << rotOranges(v); return 0;} // Java program to rot all oranges when u can move// in all the four direction from a rotten orangeclass GFG{ static int R = 3;static int C = 5; // Check if i, j is under the array// limits of row and columnstatic boolean issafe(int i, int j){ if (i >= 0 && i < R && j >= 0 && j < C) return true; return false;} static int rotOranges(int v[][]){ boolean changed = false; int no = 2; while (true) { for(int i = 0; i < R; i++) { for(int j = 0; j < C; j++) { // Rot all other oranges present at // (i+1, j), (i, j-1), (i, j+1), (i-1, j) if (v[i][j] == no) { if (issafe(i + 1, j) && v[i + 1][j] == 1) { v[i + 1][j] = v[i][j] + 1; changed = true; } if (issafe(i, j + 1) && v[i][j + 1] == 1) { v[i][j + 1] = v[i][j] + 1; changed = true; } if (issafe(i - 1, j) && v[i - 1][j] == 1) { v[i - 1][j] = v[i][j] + 1; changed = true; } if (issafe(i, j - 1) && v[i][j - 1] == 1) { v[i][j - 1] = v[i][j] + 1; changed = true; } } } } // If no rotten orange found it means all // oranges rottened now if (!changed) break; changed = false; no++; } for(int i = 0; i < R; i++) { for(int j = 0; j < C; j++) { // If any orange is found to be // not rotten then ans is not possible if (v[i][j] == 1) return -1; } } // Because initial value for a rotten // orange was 2 return no - 2;} // Driver Codepublic static void main(String[] args){ int v[][] = { { 2, 1, 0, 2, 1 }, { 1, 0, 1, 2, 1 }, { 1, 0, 0, 2, 1 } }; System.out.println("Max time incurred: " + rotOranges(v));}} // This code is contributed by divyesh072019 # Python3 program to rot all# oranges when u can move# in all the four direction# from a rotten orangeR = 3C = 5 # Check if i, j is under the# array limits of row and# columndef issafe(i, j): if (i >= 0 and i < R and j >= 0 and j < C): return True return False def rotOranges(v): changed = False no = 2 while (True): for i in range(R): for j in range(C): # Rot all other oranges # present at (i+1, j), # (i, j-1), (i, j+1), # (i-1, j) if (v[i][j] == no): if (issafe(i + 1, j) and v[i + 1][j] == 1): v[i + 1][j] = v[i][j] + 1 changed = True if (issafe(i, j + 1) and v[i][j + 1] == 1): v[i][j + 1] = v[i][j] + 1 changed = True if (issafe(i - 1, j) and v[i - 1][j] == 1): v[i - 1][j] = v[i][j] + 1 changed = True if (issafe(i, j - 1) and v[i][j - 1] == 1): v[i][j - 1] = v[i][j] + 1 changed = True # if no rotten orange found # it means all oranges rottened # now if (not changed): break changed = False no += 1 for i in range(R): for j in range(C): # if any orange is found # to be not rotten then # ans is not possible if (v[i][j] == 1): return -1 # Because initial value # for a rotten orange was 2 return no - 2 # Driver functionif __name__ == "__main__": v = [[2, 1, 0, 2, 1], [1, 0, 1, 2, 1], [1, 0, 0, 2, 1]] print("Max time incurred: ", rotOranges(v)) # This code is contributed by Chitranayal // C# program to rot all oranges when u can move// in all the four direction from a rotten orangeusing System;class GFG { static int R = 3; static int C = 5; // Check if i, j is under the array // limits of row and column static bool issafe(int i, int j) { if (i >= 0 && i < R && j >= 0 && j < C) return true; return false; } static int rotOranges(int[,] v) { bool changed = false; int no = 2; while (true) { for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { // Rot all other oranges present at // (i+1, j), (i, j-1), (i, j+1), (i-1, j) if (v[i, j] == no) { if (issafe(i + 1, j) && v[i + 1, j] == 1) { v[i + 1, j] = v[i, j] + 1; changed = true; } if (issafe(i, j + 1) && v[i, j + 1] == 1) { v[i, j + 1] = v[i, j] + 1; changed = true; } if (issafe(i - 1, j) && v[i - 1, j] == 1) { v[i - 1, j] = v[i, j] + 1; changed = true; } if (issafe(i, j - 1) && v[i, j - 1] == 1) { v[i, j - 1] = v[i, j] + 1; changed = true; } } } } // if no rotten orange found it means all // oranges rottened now if (!changed) break; changed = false; no++; } for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { // if any orange is found to be // not rotten then ans is not possible if (v[i, j] == 1) return -1; } } // Because initial value for a rotten // orange was 2 return no - 2; } static void Main() { int[ , ] v = { { 2, 1, 0, 2, 1 }, { 1, 0, 1, 2, 1 }, { 1, 0, 0, 2, 1 } }; Console.Write("Max time incurred: " + rotOranges(v)); }} // This code is contributed by divyeshrabadiya07 <script> // Javascript program to rot all oranges when u can move // in all the four direction from a rotten orange let R = 3; let C = 5; // Check if i, j is under the array limits of row and column function issafe(i, j) { if (i >= 0 && i < R && j >= 0 && j < C) return true; return false; } function rotOranges(v) { let changed = false; let no = 2; while (true) { for (let i = 0; i < R; i++) { for (let j = 0; j < C; j++) { // Rot all other oranges present at // (i+1, j), (i, j-1), (i, j+1), (i-1, j) if (v[i][j] == no) { if (issafe(i + 1, j) && v[i + 1][j] == 1) { v[i + 1][j] = v[i][j] + 1; changed = true; } if (issafe(i, j + 1) && v[i][j + 1] == 1) { v[i][j + 1] = v[i][j] + 1; changed = true; } if (issafe(i - 1, j) && v[i - 1][j] == 1) { v[i - 1][j] = v[i][j] + 1; changed = true; } if (issafe(i, j - 1) && v[i][j - 1] == 1) { v[i][j - 1] = v[i][j] + 1; changed = true; } } } } // if no rotten orange found it means all // oranges rottened now if (!changed) break; changed = false; no++; } for (let i = 0; i < R; i++) { for (let j = 0; j < C; j++) { // if any orange is found to be // not rotten then ans is not possible if (v[i][j] == 1) return -1; } } // Because initial value for a rotten // orange was 2 return no - 2; } // Driver code let v = [ [ 2, 1, 0, 2, 1 ], [ 1, 0, 1, 2, 1 ], [ 1, 0, 0, 2, 1 ] ]; document.write("Max time incurred: " + rotOranges(v)); // This code is contributed by mukesh07.</script> Max time incurred: 2 Complexity Analysis: Time Complexity : O((R*C) * (R *C)). The matrix needs to be traversed again and again until there is no change in the matrix, that can happen max(R *C)/2 times. So time complexity is O((R * C) * (R *C)).Space Complexity:O(1). No extra space is required. Time Complexity : O((R*C) * (R *C)). The matrix needs to be traversed again and again until there is no change in the matrix, that can happen max(R *C)/2 times. So time complexity is O((R * C) * (R *C)). Space Complexity:O(1). No extra space is required. Efficient Solution Approach: The idea is to use Breadth First Search. The condition of oranges getting rotten is when they come in contact with other rotten oranges. This is similar to breadth-first search where the graph is divided into layers or circles and the search is done from lower or closer layers to deeper or higher layers. In the previous approach, the idea was based on BFS but the implementation was poor and inefficient. To find the elements whose values are no the whole matrix had to be traversed. So that time can be reduced by using this efficient approach of BFS. Algorithm: Create an empty queue Q. Find all rotten oranges and enqueue them to Q. Also, enqueue a delimiter to indicate the beginning of the next time frame.Run a loop While Q is not emptyDo following while delimiter in Q is not reachedDequeue an orange from the queue, rot all adjacent oranges. While rotting the adjacent, make sure that the time frame is incremented only once. And the time frame is not incremented if there are no adjacent oranges.Dequeue the old delimiter and enqueue a new delimiter. The oranges rotten in the previous time frame lie between the two delimiters. Create an empty queue Q. Find all rotten oranges and enqueue them to Q. Also, enqueue a delimiter to indicate the beginning of the next time frame.Run a loop While Q is not emptyDo following while delimiter in Q is not reachedDequeue an orange from the queue, rot all adjacent oranges. While rotting the adjacent, make sure that the time frame is incremented only once. And the time frame is not incremented if there are no adjacent oranges.Dequeue the old delimiter and enqueue a new delimiter. The oranges rotten in the previous time frame lie between the two delimiters. Create an empty queue Q. Find all rotten oranges and enqueue them to Q. Also, enqueue a delimiter to indicate the beginning of the next time frame.Run a loop While Q is not emptyDo following while delimiter in Q is not reached Find all rotten oranges and enqueue them to Q. Also, enqueue a delimiter to indicate the beginning of the next time frame.Run a loop While Q is not emptyDo following while delimiter in Q is not reached Find all rotten oranges and enqueue them to Q. Also, enqueue a delimiter to indicate the beginning of the next time frame. Run a loop While Q is not empty Do following while delimiter in Q is not reached Dequeue an orange from the queue, rot all adjacent oranges. While rotting the adjacent, make sure that the time frame is incremented only once. And the time frame is not incremented if there are no adjacent oranges. Dequeue the old delimiter and enqueue a new delimiter. The oranges rotten in the previous time frame lie between the two delimiters. Dry run of the above approach: Implementation: C++ Java Python3 C# // C++ program to find minimum time required to make all// oranges rotten#include<bits/stdc++.h>#define R 3#define C 5using namespace std; // function to check whether a cell is valid / invalidbool isvalid(int i, int j){ return (i >= 0 && j >= 0 && i < R && j < C);} // structure for storing coordinates of the cellstruct ele { int x, y;}; // Function to check whether the cell is delimiter// which is (-1, -1)bool isdelim(ele temp){ return (temp.x == -1 && temp.y == -1);} // Function to check whether there is still a fresh// orange remainingbool checkall(int arr[][C]){ for (int i=0; i<R; i++) for (int j=0; j<C; j++) if (arr[i][j] == 1) return true; return false;} // This function finds if it is possible to rot all oranges or not.// If possible, then it returns minimum time required to rot all,// otherwise returns -1int rotOranges(int arr[][C]){ // Create a queue of cells queue<ele> Q; ele temp; int ans = 0; // Store all the cells having rotten orange in first time frame for (int i=0; i<R; i++) { for (int j=0; j<C; j++) { if (arr[i][j] == 2) { temp.x = i; temp.y = j; Q.push(temp); } } } // Separate these rotten oranges from the oranges which will rotten // due the oranges in first time frame using delimiter which is (-1, -1) temp.x = -1; temp.y = -1; Q.push(temp); // Process the grid while there are rotten oranges in the Queue while (!Q.empty()) { // This flag is used to determine whether even a single fresh // orange gets rotten due to rotten oranges in current time // frame so we can increase the count of the required time. bool flag = false; // Process all the rotten oranges in current time frame. while (!isdelim(Q.front())) { temp = Q.front(); // Check right adjacent cell that if it can be rotten if (isvalid(temp.x+1, temp.y) && arr[temp.x+1][temp.y] == 1) { // if this is the first orange to get rotten, increase // count and set the flag. if (!flag) ans++, flag = true; // Make the orange rotten arr[temp.x+1][temp.y] = 2; // push the adjacent orange to Queue temp.x++; Q.push(temp); temp.x--; // Move back to current cell } // Check left adjacent cell that if it can be rotten if (isvalid(temp.x-1, temp.y) && arr[temp.x-1][temp.y] == 1) { if (!flag) ans++, flag = true; arr[temp.x-1][temp.y] = 2; temp.x--; Q.push(temp); // push this cell to Queue temp.x++; } // Check top adjacent cell that if it can be rotten if (isvalid(temp.x, temp.y+1) && arr[temp.x][temp.y+1] == 1) { if (!flag) ans++, flag = true; arr[temp.x][temp.y+1] = 2; temp.y++; Q.push(temp); // Push this cell to Queue temp.y--; } // Check bottom adjacent cell if it can be rotten if (isvalid(temp.x, temp.y-1) && arr[temp.x][temp.y-1] == 1) { if (!flag) ans++, flag = true; arr[temp.x][temp.y-1] = 2; temp.y--; Q.push(temp); // push this cell to Queue } Q.pop(); } // Pop the delimiter Q.pop(); // If oranges were rotten in current frame than separate the // rotten oranges using delimiter for the next frame for processing. if (!Q.empty()) { temp.x = -1; temp.y = -1; Q.push(temp); } // If Queue was empty than no rotten oranges left to process so exit } // Return -1 if all arranges could not rot, otherwise return ans. return (checkall(arr))? -1: ans;} // Driver programint main(){ int arr[][C] = { {2, 1, 0, 2, 1}, {1, 0, 1, 2, 1}, {1, 0, 0, 2, 1}}; int ans = rotOranges(arr); if (ans == -1) cout << "All oranges cannot rotn"; else cout << "Time required for all oranges to rot => " << ans << endl; return 0;} //Java program to find minimum time required to make all//oranges rotten import java.util.LinkedList;import java.util.Queue; public class RotOrange{ public final static int R = 3; public final static int C = 5; // structure for storing coordinates of the cell static class Ele { int x = 0; int y = 0; Ele(int x,int y) { this.x = x; this.y = y; } } // function to check whether a cell is valid / invalid static boolean isValid(int i, int j) { return (i >= 0 && j >= 0 && i < R && j < C); } // Function to check whether the cell is delimiter // which is (-1, -1) static boolean isDelim(Ele temp) { return (temp.x == -1 && temp.y == -1); } // Function to check whether there is still a fresh // orange remaining static boolean checkAll(int arr[][]) { for (int i=0; i<R; i++) for (int j=0; j<C; j++) if (arr[i][j] == 1) return true; return false; } // This function finds if it is possible to rot all oranges or not. // If possible, then it returns minimum time required to rot all, // otherwise returns -1 static int rotOranges(int arr[][]) { // Create a queue of cells Queue<Ele> Q=new LinkedList<>(); Ele temp; int ans = 0; // Store all the cells having rotten orange in first time frame for (int i=0; i < R; i++) for (int j=0; j < C; j++) if (arr[i][j] == 2) Q.add(new Ele(i,j)); // Separate these rotten oranges from the oranges which will rotten // due the oranges in first time frame using delimiter which is (-1, -1) Q.add(new Ele(-1,-1)); // Process the grid while there are rotten oranges in the Queue while(!Q.isEmpty()) { // This flag is used to determine whether even a single fresh // orange gets rotten due to rotten oranges in the current time // frame so we can increase the count of the required time. boolean flag = false; // Process all the rotten oranges in current time frame. while(!isDelim(Q.peek())) { temp = Q.peek(); // Check right adjacent cell that if it can be rotten if(isValid(temp.x+1, temp.y) && arr[temp.x+1][temp.y] == 1) { if(!flag) { // if this is the first orange to get rotten, increase // count and set the flag. ans++; flag = true; } // Make the orange rotten arr[temp.x+1][temp.y] = 2; // push the adjacent orange to Queue temp.x++; Q.add(new Ele(temp.x,temp.y)); // Move back to current cell temp.x--; } // Check left adjacent cell that if it can be rotten if (isValid(temp.x-1, temp.y) && arr[temp.x-1][temp.y] == 1) { if (!flag) { ans++; flag = true; } arr[temp.x-1][temp.y] = 2; temp.x--; Q.add(new Ele(temp.x,temp.y)); // push this cell to Queue temp.x++; } // Check top adjacent cell that if it can be rotten if (isValid(temp.x, temp.y+1) && arr[temp.x][temp.y+1] == 1) { if(!flag) { ans++; flag = true; } arr[temp.x][temp.y+1] = 2; temp.y++; Q.add(new Ele(temp.x,temp.y)); // Push this cell to Queue temp.y--; } // Check bottom adjacent cell if it can be rotten if (isValid(temp.x, temp.y-1) && arr[temp.x][temp.y-1] == 1) { if (!flag) { ans++; flag = true; } arr[temp.x][temp.y-1] = 2; temp.y--; Q.add(new Ele(temp.x,temp.y)); // push this cell to Queue } Q.remove(); } // Pop the delimiter Q.remove(); // If oranges were rotten in current frame than separate the // rotten oranges using delimiter for the next frame for processing. if (!Q.isEmpty()) { Q.add(new Ele(-1,-1)); } // If Queue was empty than no rotten oranges left to process so exit } // Return -1 if all arranges could not rot, otherwise ans return (checkAll(arr))? -1: ans; } // Driver program public static void main(String[] args) { int arr[][] = { {2, 1, 0, 2, 1}, {1, 0, 1, 2, 1}, {1, 0, 0, 2, 1}}; int ans = rotOranges(arr); if(ans == -1) System.out.println("All oranges cannot rot"); else System.out.println("Time required for all oranges to rot = " + ans); } }//This code is contributed by Sumit Ghosh # Python3 program to find minimum time required to make all# oranges rottenfrom collections import deque # function to check whether a cell is valid / invaliddef isvalid(i, j): return (i >= 0 and j >= 0 and i < 3 and j < 5) # Function to check whether the cell is delimiter# which is (-1, -1)def isdelim(temp): return (temp[0] == -1 and temp[1] == -1) # Function to check whether there is still a fresh# orange remainingdef checkall(arr): for i in range(3): for j in range(5): if (arr[i][j] == 1): return True return False # This function finds if it is# possible to rot all oranges or not.# If possible, then it returns# minimum time required to rot all,# otherwise returns -1def rotOranges(arr): # Create a queue of cells Q = deque() temp = [0, 0] ans = 1 # Store all the cells having # rotten orange in first time frame for i in range(3): for j in range(5): if (arr[i][j] == 2): temp[0]= i temp[1] = j Q.append([i, j]) # Separate these rotten oranges # from the oranges which will rotten # due the oranges in first time # frame using delimiter which is (-1, -1) temp[0] = -1 temp[1] = -1 Q.append([-1, -1]) # print(Q) # Process the grid while there are # rotten oranges in the Queue while False: # This flag is used to determine # whether even a single fresh # orange gets rotten due to rotten # oranges in current time # frame so we can increase # the count of the required time. flag = False print(len(Q)) # Process all the rotten # oranges in current time frame. while not isdelim(Q[0]): temp = Q[0] print(len(Q)) # Check right adjacent cell that if it can be rotten if (isvalid(temp[0] + 1, temp[1]) and arr[temp[0] + 1][temp[1]] == 1): # if this is the first orange to get rotten, increase # count and set the flag. if (not flag): ans, flag =ans + 1, True # Make the orange rotten arr[temp[0] + 1][temp[1]] = 2 # append the adjacent orange to Queue temp[0] += 1 Q.append(temp) temp[0] -= 1 # Move back to current cell # Check left adjacent cell that if it can be rotten if (isvalid(temp[0] - 1, temp[1]) and arr[temp[0] - 1][temp[1]] == 1): if (not flag): ans, flag =ans + 1, True arr[temp[0] - 1][temp[1]] = 2 temp[0] -= 1 Q.append(temp) # append this cell to Queue temp[0] += 1 # Check top adjacent cell that if it can be rotten if (isvalid(temp[0], temp[1] + 1) and arr[temp[0]][temp[1] + 1] == 1): if (not flag): ans, flag = ans + 1, True arr[temp[0]][temp[1] + 1] = 2 temp[1] += 1 Q.append(temp) # Push this cell to Queue temp[1] -= 1 # Check bottom adjacent cell if it can be rotten if (isvalid(temp[0], temp[1] - 1) and arr[temp[0]][temp[1] - 1] == 1): if (not flag): ans, flag = ans + 1, True arr[temp[0]][temp[1] - 1] = 2 temp[1] -= 1 Q.append(temp) # append this cell to Queue Q.popleft() # Pop the delimiter Q.popleft() # If oranges were rotten in # current frame than separate the # rotten oranges using delimiter # for the next frame for processing. if (len(Q) == 0): temp[0] = -1 temp[1] = -1 Q.append(temp) # If Queue was empty than no rotten oranges left to process so exit # Return -1 if all arranges could not rot, otherwise return ans. return ans + 1 if(checkall(arr)) else -1 # Driver programif __name__ == '__main__': arr = [[2, 1, 0, 2, 1], [1, 0, 1, 2, 1], [1, 0, 0, 2, 1]] ans = rotOranges(arr) if (ans == -1): print("All oranges cannot rotn") else: print("Time required for all oranges to rot => " , ans) # This code is contributed by mohit kumar 29 // C# program to find minimum time// required to make all oranges rottenusing System;using System.Collections.Generic; class GFG{ public const int R = 3; public const int C = 5; // structure for storing // coordinates of the cell public class Ele { public int x = 0; public int y = 0; public Ele(int x, int y) { this.x = x; this.y = y; } } // function to check whether a cell // is valid / invalid public static bool isValid(int i, int j) { return (i >= 0 && j >= 0 && i < R && j < C); } // Function to check whether the cell // is delimiter which is (-1, -1) public static bool isDelim(Ele temp) { return (temp.x == -1 && temp.y == -1); } // Function to check whether there // is still a fresh orange remaining public static bool checkAll(int[][] arr) { for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { if (arr[i][j] == 1) { return true; } } } return false; } // This function finds if it is possible // to rot all oranges or not. If possible, // then it returns minimum time required // to rot all, otherwise returns -1 public static int rotOranges(int[][] arr) { // Create a queue of cells LinkedList<Ele> Q = new LinkedList<Ele>(); Ele temp; int ans = 0; // Store all the cells having rotten // orange in first time frame for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { if (arr[i][j] == 2) { Q.AddLast(new Ele(i, j)); } } } // Separate these rotten oranges from // the oranges which will rotten // due the oranges in first time frame // using delimiter which is (-1, -1) Q.AddLast(new Ele(-1,-1)); // Process the grid while there are // rotten oranges in the Queue while (Q.Count > 0) { // This flag is used to determine // whether even a single fresh // orange gets rotten due to rotten // oranges in current time frame so // we can increase the count of the // required time. bool flag = false; // Process all the rotten oranges // in current time frame. while (!isDelim(Q.First.Value)) { temp = Q.First.Value; // Check right adjacent cell that // if it can be rotten if (isValid(temp.x + 1, temp.y) && arr[temp.x + 1][temp.y] == 1) { if (!flag) { // if this is the first orange // to get rotten, increase // count and set the flag. ans++; flag = true; } // Make the orange rotten arr[temp.x + 1][temp.y] = 2; // push the adjacent orange to Queue temp.x++; Q.AddLast(new Ele(temp.x,temp.y)); // Move back to current cell temp.x--; } // Check left adjacent cell that // if it can be rotten if (isValid(temp.x - 1, temp.y) && arr[temp.x - 1][temp.y] == 1) { if (!flag) { ans++; flag = true; } arr[temp.x - 1][temp.y] = 2; temp.x--; // push this cell to Queue Q.AddLast(new Ele(temp.x,temp.y)); temp.x++; } // Check top adjacent cell that // if it can be rotten if (isValid(temp.x, temp.y + 1) && arr[temp.x][temp.y + 1] == 1) { if (!flag) { ans++; flag = true; } arr[temp.x][temp.y + 1] = 2; temp.y++; // Push this cell to Queue Q.AddLast(new Ele(temp.x,temp.y)); temp.y--; } // Check bottom adjacent cell // if it can be rotten if (isValid(temp.x, temp.y - 1) && arr[temp.x][temp.y - 1] == 1) { if (!flag) { ans++; flag = true; } arr[temp.x][temp.y - 1] = 2; temp.y--; // push this cell to Queue Q.AddLast(new Ele(temp.x,temp.y)); } Q.RemoveFirst(); } // Pop the delimiter Q.RemoveFirst(); // If oranges were rotten in current // frame than separate the rotten // oranges using delimiter for the // next frame for processing. if (Q.Count > 0) { Q.AddLast(new Ele(-1,-1)); } // If Queue was empty than no rotten // oranges left to process so exit } // Return -1 if all arranges could // not rot, otherwise ans return (checkAll(arr)) ? -1: ans; } // Driver Code public static void Main(string[] args) { int[][] arr = new int[][] { new int[] {2, 1, 0, 2, 1}, new int[] {1, 0, 1, 2, 1}, new int[] {1, 0, 0, 2, 1} }; int ans = rotOranges(arr); if (ans == -1) { Console.WriteLine("All oranges cannot rot"); } else { Console.WriteLine("Time required for all " + "oranges to rot => " + ans); } }} // This code is contributed by Shrikant13 Time required for all oranges to rot => 2 Complexity Analysis: Time Complexity: O( R *C). Each element of the matrix can be inserted into the queue only once so the upper bound of iteration is O(R*C), i.e. the number of elements. So time complexity is O(R *C).Space Complexity: O(R*C). To store the elements in a queue O(R*C) space is needed. Time Complexity: O( R *C). Each element of the matrix can be inserted into the queue only once so the upper bound of iteration is O(R*C), i.e. the number of elements. So time complexity is O(R *C). Space Complexity: O(R*C). To store the elements in a queue O(R*C) space is needed. Thanks to Gaurav Ahirwar for suggesting the above solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above shrikanth13 arpitn30 gp6 md1844 andrew1234 Akanksha_Rai ukasp harshverma31 divyeshrabadiya07 divyesh072019 mohit kumar 29 mukesh07 bicky jaiswal surinderdawra388 Accolite Amazon BFS MakeMyTrip Microsoft Samsung Graph Matrix Queue Accolite Amazon Microsoft Samsung MakeMyTrip Matrix Graph Queue BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Topological Sorting Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Detect Cycle in a Directed Graph Matrix Chain Multiplication | DP-8 Program to find largest element in an array Rat in a Maze | Backtracking-2 Print a given matrix in spiral form Sudoku | Backtracking-7
[ { "code": null, "e": 26908, "s": 26880, "text": "\n28 Feb, 2022" }, { "code": null, "e": 27031, "s": 26908, "text": "Given a matrix of dimension m*n where each cell in the matrix can have values 0, 1 or 2 which has the following meaning: " }, { "code": null, "e": 27102, "s": 27031, "text": "0: Empty cell\n1: Cells have fresh oranges\n2: Cells have rotten oranges" }, { "code": null, "e": 27380, "s": 27102, "text": "Determine what is the minimum time required so that all the oranges become rotten. A rotten orange at index [i,j] can rot other fresh orange at indexes [i-1,j], [i+1,j], [i,j-1], [i,j+1] (up, down, left and right). If it is impossible to rot every orange then simply return -1." }, { "code": null, "e": 27391, "s": 27380, "text": "Examples: " }, { "code": null, "e": 28227, "s": 27391, "text": "Input: arr[][C] = { {2, 1, 0, 2, 1},\n {1, 0, 1, 2, 1},\n {1, 0, 0, 2, 1}};\nOutput:\nAll oranges can become rotten in 2-time frames.\nExplanation: \nAt 0th time frame:\n {2, 1, 0, 2, 1}\n {1, 0, 1, 2, 1}\n {1, 0, 0, 2, 1}\n\nAt 1st time frame:\n {2, 2, 0, 2, 2}\n {2, 0, 2, 2, 2}\n {1, 0, 0, 2, 2}\n\nAt 2nd time frame:\n {2, 2, 0, 2, 2}\n {2, 0, 2, 2, 2}\n {2, 0, 0, 2, 2}\n\n\nInput: arr[][C] = { {2, 1, 0, 2, 1},\n {0, 0, 1, 2, 1},\n {1, 0, 0, 2, 1}};\nOutput:\nAll oranges cannot be rotten.\nExplanation: \nAt 0th time frame:\n{2, 1, 0, 2, 1}\n{0, 0, 1, 2, 1}\n{1, 0, 0, 2, 1}\n\nAt 1st time frame:\n{2, 2, 0, 2, 2}\n{0, 0, 2, 2, 2}\n{1, 0, 0, 2, 2}\n\nAt 2nd time frame:\n{2, 2, 0, 2, 2}\n{0, 0, 2, 2, 2}\n{1, 0, 0, 2, 2}\n...\nThe 1 at the bottom left corner of the matrix is never rotten." }, { "code": null, "e": 28245, "s": 28227, "text": "Naive Solution: " }, { "code": null, "e": 28433, "s": 28245, "text": "Approach: The idea is very basic. Traverse through all oranges in multiple rounds. In every round, rot the oranges to the adjacent position of oranges which were rotten in the last round." }, { "code": null, "e": 28898, "s": 28433, "text": "Algorithm: Create a variable no = 2 and changed = falseRun a loop until there is no cell of the matrix which is changed in an iteration.Run a nested loop and traverse the matrix. If the element of the matrix is equal to no then assign the adjacent elements to no + 1 if the adjacent element’s value is equal to 1, i.e. not rotten, and update changed to true.Traverse the matrix and check if there is any cell which is 1. If 1 is present return -1Else return no – 2" }, { "code": null, "e": 29352, "s": 28898, "text": "Create a variable no = 2 and changed = falseRun a loop until there is no cell of the matrix which is changed in an iteration.Run a nested loop and traverse the matrix. If the element of the matrix is equal to no then assign the adjacent elements to no + 1 if the adjacent element’s value is equal to 1, i.e. not rotten, and update changed to true.Traverse the matrix and check if there is any cell which is 1. If 1 is present return -1Else return no – 2" }, { "code": null, "e": 29397, "s": 29352, "text": "Create a variable no = 2 and changed = false" }, { "code": null, "e": 29479, "s": 29397, "text": "Run a loop until there is no cell of the matrix which is changed in an iteration." }, { "code": null, "e": 29702, "s": 29479, "text": "Run a nested loop and traverse the matrix. If the element of the matrix is equal to no then assign the adjacent elements to no + 1 if the adjacent element’s value is equal to 1, i.e. not rotten, and update changed to true." }, { "code": null, "e": 29791, "s": 29702, "text": "Traverse the matrix and check if there is any cell which is 1. If 1 is present return -1" }, { "code": null, "e": 29810, "s": 29791, "text": "Else return no – 2" }, { "code": null, "e": 29826, "s": 29810, "text": "Implementation:" }, { "code": null, "e": 29832, "s": 29826, "text": "C++14" }, { "code": null, "e": 29837, "s": 29832, "text": "Java" }, { "code": null, "e": 29845, "s": 29837, "text": "Python3" }, { "code": null, "e": 29848, "s": 29845, "text": "C#" }, { "code": null, "e": 29859, "s": 29848, "text": "Javascript" }, { "code": "// C++ program to rot all oranges when u can move// in all the four direction from a rotten orange#include <bits/stdc++.h>using namespace std; const int R = 3;const int C = 5; // Check if i, j is under the array limits of row and columnbool issafe(int i, int j){ if (i >= 0 && i < R && j >= 0 && j < C) return true; return false;} int rotOranges(int v[R][C]){ bool changed = false; int no = 2; while (true) { for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { // Rot all other oranges present at // (i+1, j), (i, j-1), (i, j+1), (i-1, j) if (v[i][j] == no) { if (issafe(i + 1, j) && v[i + 1][j] == 1) { v[i + 1][j] = v[i][j] + 1; changed = true; } if (issafe(i, j + 1) && v[i][j + 1] == 1) { v[i][j + 1] = v[i][j] + 1; changed = true; } if (issafe(i - 1, j) && v[i - 1][j] == 1) { v[i - 1][j] = v[i][j] + 1; changed = true; } if (issafe(i, j - 1) && v[i][j - 1] == 1) { v[i][j - 1] = v[i][j] + 1; changed = true; } } } } // if no rotten orange found it means all // oranges rottened now if (!changed) break; changed = false; no++; } for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { // if any orange is found to be // not rotten then ans is not possible if (v[i][j] == 1) return -1; } } // Because initial value for a rotten // orange was 2 return no - 2;} // Driver functionint main(){ int v[R][C] = { { 2, 1, 0, 2, 1 }, { 1, 0, 1, 2, 1 }, { 1, 0, 0, 2, 1 } }; cout << \"Max time incurred: \" << rotOranges(v); return 0;}", "e": 31934, "s": 29859, "text": null }, { "code": "// Java program to rot all oranges when u can move// in all the four direction from a rotten orangeclass GFG{ static int R = 3;static int C = 5; // Check if i, j is under the array// limits of row and columnstatic boolean issafe(int i, int j){ if (i >= 0 && i < R && j >= 0 && j < C) return true; return false;} static int rotOranges(int v[][]){ boolean changed = false; int no = 2; while (true) { for(int i = 0; i < R; i++) { for(int j = 0; j < C; j++) { // Rot all other oranges present at // (i+1, j), (i, j-1), (i, j+1), (i-1, j) if (v[i][j] == no) { if (issafe(i + 1, j) && v[i + 1][j] == 1) { v[i + 1][j] = v[i][j] + 1; changed = true; } if (issafe(i, j + 1) && v[i][j + 1] == 1) { v[i][j + 1] = v[i][j] + 1; changed = true; } if (issafe(i - 1, j) && v[i - 1][j] == 1) { v[i - 1][j] = v[i][j] + 1; changed = true; } if (issafe(i, j - 1) && v[i][j - 1] == 1) { v[i][j - 1] = v[i][j] + 1; changed = true; } } } } // If no rotten orange found it means all // oranges rottened now if (!changed) break; changed = false; no++; } for(int i = 0; i < R; i++) { for(int j = 0; j < C; j++) { // If any orange is found to be // not rotten then ans is not possible if (v[i][j] == 1) return -1; } } // Because initial value for a rotten // orange was 2 return no - 2;} // Driver Codepublic static void main(String[] args){ int v[][] = { { 2, 1, 0, 2, 1 }, { 1, 0, 1, 2, 1 }, { 1, 0, 0, 2, 1 } }; System.out.println(\"Max time incurred: \" + rotOranges(v));}} // This code is contributed by divyesh072019", "e": 34382, "s": 31934, "text": null }, { "code": "# Python3 program to rot all# oranges when u can move# in all the four direction# from a rotten orangeR = 3C = 5 # Check if i, j is under the# array limits of row and# columndef issafe(i, j): if (i >= 0 and i < R and j >= 0 and j < C): return True return False def rotOranges(v): changed = False no = 2 while (True): for i in range(R): for j in range(C): # Rot all other oranges # present at (i+1, j), # (i, j-1), (i, j+1), # (i-1, j) if (v[i][j] == no): if (issafe(i + 1, j) and v[i + 1][j] == 1): v[i + 1][j] = v[i][j] + 1 changed = True if (issafe(i, j + 1) and v[i][j + 1] == 1): v[i][j + 1] = v[i][j] + 1 changed = True if (issafe(i - 1, j) and v[i - 1][j] == 1): v[i - 1][j] = v[i][j] + 1 changed = True if (issafe(i, j - 1) and v[i][j - 1] == 1): v[i][j - 1] = v[i][j] + 1 changed = True # if no rotten orange found # it means all oranges rottened # now if (not changed): break changed = False no += 1 for i in range(R): for j in range(C): # if any orange is found # to be not rotten then # ans is not possible if (v[i][j] == 1): return -1 # Because initial value # for a rotten orange was 2 return no - 2 # Driver functionif __name__ == \"__main__\": v = [[2, 1, 0, 2, 1], [1, 0, 1, 2, 1], [1, 0, 0, 2, 1]] print(\"Max time incurred: \", rotOranges(v)) # This code is contributed by Chitranayal", "e": 36329, "s": 34382, "text": null }, { "code": "// C# program to rot all oranges when u can move// in all the four direction from a rotten orangeusing System;class GFG { static int R = 3; static int C = 5; // Check if i, j is under the array // limits of row and column static bool issafe(int i, int j) { if (i >= 0 && i < R && j >= 0 && j < C) return true; return false; } static int rotOranges(int[,] v) { bool changed = false; int no = 2; while (true) { for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { // Rot all other oranges present at // (i+1, j), (i, j-1), (i, j+1), (i-1, j) if (v[i, j] == no) { if (issafe(i + 1, j) && v[i + 1, j] == 1) { v[i + 1, j] = v[i, j] + 1; changed = true; } if (issafe(i, j + 1) && v[i, j + 1] == 1) { v[i, j + 1] = v[i, j] + 1; changed = true; } if (issafe(i - 1, j) && v[i - 1, j] == 1) { v[i - 1, j] = v[i, j] + 1; changed = true; } if (issafe(i, j - 1) && v[i, j - 1] == 1) { v[i, j - 1] = v[i, j] + 1; changed = true; } } } } // if no rotten orange found it means all // oranges rottened now if (!changed) break; changed = false; no++; } for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { // if any orange is found to be // not rotten then ans is not possible if (v[i, j] == 1) return -1; } } // Because initial value for a rotten // orange was 2 return no - 2; } static void Main() { int[ , ] v = { { 2, 1, 0, 2, 1 }, { 1, 0, 1, 2, 1 }, { 1, 0, 0, 2, 1 } }; Console.Write(\"Max time incurred: \" + rotOranges(v)); }} // This code is contributed by divyeshrabadiya07", "e": 38703, "s": 36329, "text": null }, { "code": "<script> // Javascript program to rot all oranges when u can move // in all the four direction from a rotten orange let R = 3; let C = 5; // Check if i, j is under the array limits of row and column function issafe(i, j) { if (i >= 0 && i < R && j >= 0 && j < C) return true; return false; } function rotOranges(v) { let changed = false; let no = 2; while (true) { for (let i = 0; i < R; i++) { for (let j = 0; j < C; j++) { // Rot all other oranges present at // (i+1, j), (i, j-1), (i, j+1), (i-1, j) if (v[i][j] == no) { if (issafe(i + 1, j) && v[i + 1][j] == 1) { v[i + 1][j] = v[i][j] + 1; changed = true; } if (issafe(i, j + 1) && v[i][j + 1] == 1) { v[i][j + 1] = v[i][j] + 1; changed = true; } if (issafe(i - 1, j) && v[i - 1][j] == 1) { v[i - 1][j] = v[i][j] + 1; changed = true; } if (issafe(i, j - 1) && v[i][j - 1] == 1) { v[i][j - 1] = v[i][j] + 1; changed = true; } } } } // if no rotten orange found it means all // oranges rottened now if (!changed) break; changed = false; no++; } for (let i = 0; i < R; i++) { for (let j = 0; j < C; j++) { // if any orange is found to be // not rotten then ans is not possible if (v[i][j] == 1) return -1; } } // Because initial value for a rotten // orange was 2 return no - 2; } // Driver code let v = [ [ 2, 1, 0, 2, 1 ], [ 1, 0, 1, 2, 1 ], [ 1, 0, 0, 2, 1 ] ]; document.write(\"Max time incurred: \" + rotOranges(v)); // This code is contributed by mukesh07.</script>", "e": 40991, "s": 38703, "text": null }, { "code": null, "e": 41012, "s": 40991, "text": "Max time incurred: 2" }, { "code": null, "e": 41289, "s": 41014, "text": "Complexity Analysis: Time Complexity : O((R*C) * (R *C)). The matrix needs to be traversed again and again until there is no change in the matrix, that can happen max(R *C)/2 times. So time complexity is O((R * C) * (R *C)).Space Complexity:O(1). No extra space is required." }, { "code": null, "e": 41493, "s": 41289, "text": "Time Complexity : O((R*C) * (R *C)). The matrix needs to be traversed again and again until there is no change in the matrix, that can happen max(R *C)/2 times. So time complexity is O((R * C) * (R *C))." }, { "code": null, "e": 41544, "s": 41493, "text": "Space Complexity:O(1). No extra space is required." }, { "code": null, "e": 41564, "s": 41544, "text": "Efficient Solution " }, { "code": null, "e": 42131, "s": 41564, "text": "Approach: The idea is to use Breadth First Search. The condition of oranges getting rotten is when they come in contact with other rotten oranges. This is similar to breadth-first search where the graph is divided into layers or circles and the search is done from lower or closer layers to deeper or higher layers. In the previous approach, the idea was based on BFS but the implementation was poor and inefficient. To find the elements whose values are no the whole matrix had to be traversed. So that time can be reduced by using this efficient approach of BFS. " }, { "code": null, "e": 42716, "s": 42131, "text": "Algorithm: Create an empty queue Q. Find all rotten oranges and enqueue them to Q. Also, enqueue a delimiter to indicate the beginning of the next time frame.Run a loop While Q is not emptyDo following while delimiter in Q is not reachedDequeue an orange from the queue, rot all adjacent oranges. While rotting the adjacent, make sure that the time frame is incremented only once. And the time frame is not incremented if there are no adjacent oranges.Dequeue the old delimiter and enqueue a new delimiter. The oranges rotten in the previous time frame lie between the two delimiters." }, { "code": null, "e": 43290, "s": 42716, "text": "Create an empty queue Q. Find all rotten oranges and enqueue them to Q. Also, enqueue a delimiter to indicate the beginning of the next time frame.Run a loop While Q is not emptyDo following while delimiter in Q is not reachedDequeue an orange from the queue, rot all adjacent oranges. While rotting the adjacent, make sure that the time frame is incremented only once. And the time frame is not incremented if there are no adjacent oranges.Dequeue the old delimiter and enqueue a new delimiter. The oranges rotten in the previous time frame lie between the two delimiters." }, { "code": null, "e": 43517, "s": 43290, "text": "Create an empty queue Q. Find all rotten oranges and enqueue them to Q. Also, enqueue a delimiter to indicate the beginning of the next time frame.Run a loop While Q is not emptyDo following while delimiter in Q is not reached" }, { "code": null, "e": 43719, "s": 43517, "text": "Find all rotten oranges and enqueue them to Q. Also, enqueue a delimiter to indicate the beginning of the next time frame.Run a loop While Q is not emptyDo following while delimiter in Q is not reached" }, { "code": null, "e": 43842, "s": 43719, "text": "Find all rotten oranges and enqueue them to Q. Also, enqueue a delimiter to indicate the beginning of the next time frame." }, { "code": null, "e": 43874, "s": 43842, "text": "Run a loop While Q is not empty" }, { "code": null, "e": 43923, "s": 43874, "text": "Do following while delimiter in Q is not reached" }, { "code": null, "e": 44139, "s": 43923, "text": "Dequeue an orange from the queue, rot all adjacent oranges. While rotting the adjacent, make sure that the time frame is incremented only once. And the time frame is not incremented if there are no adjacent oranges." }, { "code": null, "e": 44272, "s": 44139, "text": "Dequeue the old delimiter and enqueue a new delimiter. The oranges rotten in the previous time frame lie between the two delimiters." }, { "code": null, "e": 44303, "s": 44272, "text": "Dry run of the above approach:" }, { "code": null, "e": 44319, "s": 44303, "text": "Implementation:" }, { "code": null, "e": 44323, "s": 44319, "text": "C++" }, { "code": null, "e": 44328, "s": 44323, "text": "Java" }, { "code": null, "e": 44336, "s": 44328, "text": "Python3" }, { "code": null, "e": 44339, "s": 44336, "text": "C#" }, { "code": "// C++ program to find minimum time required to make all// oranges rotten#include<bits/stdc++.h>#define R 3#define C 5using namespace std; // function to check whether a cell is valid / invalidbool isvalid(int i, int j){ return (i >= 0 && j >= 0 && i < R && j < C);} // structure for storing coordinates of the cellstruct ele { int x, y;}; // Function to check whether the cell is delimiter// which is (-1, -1)bool isdelim(ele temp){ return (temp.x == -1 && temp.y == -1);} // Function to check whether there is still a fresh// orange remainingbool checkall(int arr[][C]){ for (int i=0; i<R; i++) for (int j=0; j<C; j++) if (arr[i][j] == 1) return true; return false;} // This function finds if it is possible to rot all oranges or not.// If possible, then it returns minimum time required to rot all,// otherwise returns -1int rotOranges(int arr[][C]){ // Create a queue of cells queue<ele> Q; ele temp; int ans = 0; // Store all the cells having rotten orange in first time frame for (int i=0; i<R; i++) { for (int j=0; j<C; j++) { if (arr[i][j] == 2) { temp.x = i; temp.y = j; Q.push(temp); } } } // Separate these rotten oranges from the oranges which will rotten // due the oranges in first time frame using delimiter which is (-1, -1) temp.x = -1; temp.y = -1; Q.push(temp); // Process the grid while there are rotten oranges in the Queue while (!Q.empty()) { // This flag is used to determine whether even a single fresh // orange gets rotten due to rotten oranges in current time // frame so we can increase the count of the required time. bool flag = false; // Process all the rotten oranges in current time frame. while (!isdelim(Q.front())) { temp = Q.front(); // Check right adjacent cell that if it can be rotten if (isvalid(temp.x+1, temp.y) && arr[temp.x+1][temp.y] == 1) { // if this is the first orange to get rotten, increase // count and set the flag. if (!flag) ans++, flag = true; // Make the orange rotten arr[temp.x+1][temp.y] = 2; // push the adjacent orange to Queue temp.x++; Q.push(temp); temp.x--; // Move back to current cell } // Check left adjacent cell that if it can be rotten if (isvalid(temp.x-1, temp.y) && arr[temp.x-1][temp.y] == 1) { if (!flag) ans++, flag = true; arr[temp.x-1][temp.y] = 2; temp.x--; Q.push(temp); // push this cell to Queue temp.x++; } // Check top adjacent cell that if it can be rotten if (isvalid(temp.x, temp.y+1) && arr[temp.x][temp.y+1] == 1) { if (!flag) ans++, flag = true; arr[temp.x][temp.y+1] = 2; temp.y++; Q.push(temp); // Push this cell to Queue temp.y--; } // Check bottom adjacent cell if it can be rotten if (isvalid(temp.x, temp.y-1) && arr[temp.x][temp.y-1] == 1) { if (!flag) ans++, flag = true; arr[temp.x][temp.y-1] = 2; temp.y--; Q.push(temp); // push this cell to Queue } Q.pop(); } // Pop the delimiter Q.pop(); // If oranges were rotten in current frame than separate the // rotten oranges using delimiter for the next frame for processing. if (!Q.empty()) { temp.x = -1; temp.y = -1; Q.push(temp); } // If Queue was empty than no rotten oranges left to process so exit } // Return -1 if all arranges could not rot, otherwise return ans. return (checkall(arr))? -1: ans;} // Driver programint main(){ int arr[][C] = { {2, 1, 0, 2, 1}, {1, 0, 1, 2, 1}, {1, 0, 0, 2, 1}}; int ans = rotOranges(arr); if (ans == -1) cout << \"All oranges cannot rotn\"; else cout << \"Time required for all oranges to rot => \" << ans << endl; return 0;}", "e": 48683, "s": 44339, "text": null }, { "code": "//Java program to find minimum time required to make all//oranges rotten import java.util.LinkedList;import java.util.Queue; public class RotOrange{ public final static int R = 3; public final static int C = 5; // structure for storing coordinates of the cell static class Ele { int x = 0; int y = 0; Ele(int x,int y) { this.x = x; this.y = y; } } // function to check whether a cell is valid / invalid static boolean isValid(int i, int j) { return (i >= 0 && j >= 0 && i < R && j < C); } // Function to check whether the cell is delimiter // which is (-1, -1) static boolean isDelim(Ele temp) { return (temp.x == -1 && temp.y == -1); } // Function to check whether there is still a fresh // orange remaining static boolean checkAll(int arr[][]) { for (int i=0; i<R; i++) for (int j=0; j<C; j++) if (arr[i][j] == 1) return true; return false; } // This function finds if it is possible to rot all oranges or not. // If possible, then it returns minimum time required to rot all, // otherwise returns -1 static int rotOranges(int arr[][]) { // Create a queue of cells Queue<Ele> Q=new LinkedList<>(); Ele temp; int ans = 0; // Store all the cells having rotten orange in first time frame for (int i=0; i < R; i++) for (int j=0; j < C; j++) if (arr[i][j] == 2) Q.add(new Ele(i,j)); // Separate these rotten oranges from the oranges which will rotten // due the oranges in first time frame using delimiter which is (-1, -1) Q.add(new Ele(-1,-1)); // Process the grid while there are rotten oranges in the Queue while(!Q.isEmpty()) { // This flag is used to determine whether even a single fresh // orange gets rotten due to rotten oranges in the current time // frame so we can increase the count of the required time. boolean flag = false; // Process all the rotten oranges in current time frame. while(!isDelim(Q.peek())) { temp = Q.peek(); // Check right adjacent cell that if it can be rotten if(isValid(temp.x+1, temp.y) && arr[temp.x+1][temp.y] == 1) { if(!flag) { // if this is the first orange to get rotten, increase // count and set the flag. ans++; flag = true; } // Make the orange rotten arr[temp.x+1][temp.y] = 2; // push the adjacent orange to Queue temp.x++; Q.add(new Ele(temp.x,temp.y)); // Move back to current cell temp.x--; } // Check left adjacent cell that if it can be rotten if (isValid(temp.x-1, temp.y) && arr[temp.x-1][temp.y] == 1) { if (!flag) { ans++; flag = true; } arr[temp.x-1][temp.y] = 2; temp.x--; Q.add(new Ele(temp.x,temp.y)); // push this cell to Queue temp.x++; } // Check top adjacent cell that if it can be rotten if (isValid(temp.x, temp.y+1) && arr[temp.x][temp.y+1] == 1) { if(!flag) { ans++; flag = true; } arr[temp.x][temp.y+1] = 2; temp.y++; Q.add(new Ele(temp.x,temp.y)); // Push this cell to Queue temp.y--; } // Check bottom adjacent cell if it can be rotten if (isValid(temp.x, temp.y-1) && arr[temp.x][temp.y-1] == 1) { if (!flag) { ans++; flag = true; } arr[temp.x][temp.y-1] = 2; temp.y--; Q.add(new Ele(temp.x,temp.y)); // push this cell to Queue } Q.remove(); } // Pop the delimiter Q.remove(); // If oranges were rotten in current frame than separate the // rotten oranges using delimiter for the next frame for processing. if (!Q.isEmpty()) { Q.add(new Ele(-1,-1)); } // If Queue was empty than no rotten oranges left to process so exit } // Return -1 if all arranges could not rot, otherwise ans return (checkAll(arr))? -1: ans; } // Driver program public static void main(String[] args) { int arr[][] = { {2, 1, 0, 2, 1}, {1, 0, 1, 2, 1}, {1, 0, 0, 2, 1}}; int ans = rotOranges(arr); if(ans == -1) System.out.println(\"All oranges cannot rot\"); else System.out.println(\"Time required for all oranges to rot = \" + ans); } }//This code is contributed by Sumit Ghosh", "e": 54482, "s": 48683, "text": null }, { "code": "# Python3 program to find minimum time required to make all# oranges rottenfrom collections import deque # function to check whether a cell is valid / invaliddef isvalid(i, j): return (i >= 0 and j >= 0 and i < 3 and j < 5) # Function to check whether the cell is delimiter# which is (-1, -1)def isdelim(temp): return (temp[0] == -1 and temp[1] == -1) # Function to check whether there is still a fresh# orange remainingdef checkall(arr): for i in range(3): for j in range(5): if (arr[i][j] == 1): return True return False # This function finds if it is# possible to rot all oranges or not.# If possible, then it returns# minimum time required to rot all,# otherwise returns -1def rotOranges(arr): # Create a queue of cells Q = deque() temp = [0, 0] ans = 1 # Store all the cells having # rotten orange in first time frame for i in range(3): for j in range(5): if (arr[i][j] == 2): temp[0]= i temp[1] = j Q.append([i, j]) # Separate these rotten oranges # from the oranges which will rotten # due the oranges in first time # frame using delimiter which is (-1, -1) temp[0] = -1 temp[1] = -1 Q.append([-1, -1]) # print(Q) # Process the grid while there are # rotten oranges in the Queue while False: # This flag is used to determine # whether even a single fresh # orange gets rotten due to rotten # oranges in current time # frame so we can increase # the count of the required time. flag = False print(len(Q)) # Process all the rotten # oranges in current time frame. while not isdelim(Q[0]): temp = Q[0] print(len(Q)) # Check right adjacent cell that if it can be rotten if (isvalid(temp[0] + 1, temp[1]) and arr[temp[0] + 1][temp[1]] == 1): # if this is the first orange to get rotten, increase # count and set the flag. if (not flag): ans, flag =ans + 1, True # Make the orange rotten arr[temp[0] + 1][temp[1]] = 2 # append the adjacent orange to Queue temp[0] += 1 Q.append(temp) temp[0] -= 1 # Move back to current cell # Check left adjacent cell that if it can be rotten if (isvalid(temp[0] - 1, temp[1]) and arr[temp[0] - 1][temp[1]] == 1): if (not flag): ans, flag =ans + 1, True arr[temp[0] - 1][temp[1]] = 2 temp[0] -= 1 Q.append(temp) # append this cell to Queue temp[0] += 1 # Check top adjacent cell that if it can be rotten if (isvalid(temp[0], temp[1] + 1) and arr[temp[0]][temp[1] + 1] == 1): if (not flag): ans, flag = ans + 1, True arr[temp[0]][temp[1] + 1] = 2 temp[1] += 1 Q.append(temp) # Push this cell to Queue temp[1] -= 1 # Check bottom adjacent cell if it can be rotten if (isvalid(temp[0], temp[1] - 1) and arr[temp[0]][temp[1] - 1] == 1): if (not flag): ans, flag = ans + 1, True arr[temp[0]][temp[1] - 1] = 2 temp[1] -= 1 Q.append(temp) # append this cell to Queue Q.popleft() # Pop the delimiter Q.popleft() # If oranges were rotten in # current frame than separate the # rotten oranges using delimiter # for the next frame for processing. if (len(Q) == 0): temp[0] = -1 temp[1] = -1 Q.append(temp) # If Queue was empty than no rotten oranges left to process so exit # Return -1 if all arranges could not rot, otherwise return ans. return ans + 1 if(checkall(arr)) else -1 # Driver programif __name__ == '__main__': arr = [[2, 1, 0, 2, 1], [1, 0, 1, 2, 1], [1, 0, 0, 2, 1]] ans = rotOranges(arr) if (ans == -1): print(\"All oranges cannot rotn\") else: print(\"Time required for all oranges to rot => \" , ans) # This code is contributed by mohit kumar 29", "e": 58826, "s": 54482, "text": null }, { "code": "// C# program to find minimum time// required to make all oranges rottenusing System;using System.Collections.Generic; class GFG{ public const int R = 3; public const int C = 5; // structure for storing // coordinates of the cell public class Ele { public int x = 0; public int y = 0; public Ele(int x, int y) { this.x = x; this.y = y; } } // function to check whether a cell // is valid / invalid public static bool isValid(int i, int j) { return (i >= 0 && j >= 0 && i < R && j < C); } // Function to check whether the cell // is delimiter which is (-1, -1) public static bool isDelim(Ele temp) { return (temp.x == -1 && temp.y == -1); } // Function to check whether there // is still a fresh orange remaining public static bool checkAll(int[][] arr) { for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { if (arr[i][j] == 1) { return true; } } } return false; } // This function finds if it is possible // to rot all oranges or not. If possible, // then it returns minimum time required // to rot all, otherwise returns -1 public static int rotOranges(int[][] arr) { // Create a queue of cells LinkedList<Ele> Q = new LinkedList<Ele>(); Ele temp; int ans = 0; // Store all the cells having rotten // orange in first time frame for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { if (arr[i][j] == 2) { Q.AddLast(new Ele(i, j)); } } } // Separate these rotten oranges from // the oranges which will rotten // due the oranges in first time frame // using delimiter which is (-1, -1) Q.AddLast(new Ele(-1,-1)); // Process the grid while there are // rotten oranges in the Queue while (Q.Count > 0) { // This flag is used to determine // whether even a single fresh // orange gets rotten due to rotten // oranges in current time frame so // we can increase the count of the // required time. bool flag = false; // Process all the rotten oranges // in current time frame. while (!isDelim(Q.First.Value)) { temp = Q.First.Value; // Check right adjacent cell that // if it can be rotten if (isValid(temp.x + 1, temp.y) && arr[temp.x + 1][temp.y] == 1) { if (!flag) { // if this is the first orange // to get rotten, increase // count and set the flag. ans++; flag = true; } // Make the orange rotten arr[temp.x + 1][temp.y] = 2; // push the adjacent orange to Queue temp.x++; Q.AddLast(new Ele(temp.x,temp.y)); // Move back to current cell temp.x--; } // Check left adjacent cell that // if it can be rotten if (isValid(temp.x - 1, temp.y) && arr[temp.x - 1][temp.y] == 1) { if (!flag) { ans++; flag = true; } arr[temp.x - 1][temp.y] = 2; temp.x--; // push this cell to Queue Q.AddLast(new Ele(temp.x,temp.y)); temp.x++; } // Check top adjacent cell that // if it can be rotten if (isValid(temp.x, temp.y + 1) && arr[temp.x][temp.y + 1] == 1) { if (!flag) { ans++; flag = true; } arr[temp.x][temp.y + 1] = 2; temp.y++; // Push this cell to Queue Q.AddLast(new Ele(temp.x,temp.y)); temp.y--; } // Check bottom adjacent cell // if it can be rotten if (isValid(temp.x, temp.y - 1) && arr[temp.x][temp.y - 1] == 1) { if (!flag) { ans++; flag = true; } arr[temp.x][temp.y - 1] = 2; temp.y--; // push this cell to Queue Q.AddLast(new Ele(temp.x,temp.y)); } Q.RemoveFirst(); } // Pop the delimiter Q.RemoveFirst(); // If oranges were rotten in current // frame than separate the rotten // oranges using delimiter for the // next frame for processing. if (Q.Count > 0) { Q.AddLast(new Ele(-1,-1)); } // If Queue was empty than no rotten // oranges left to process so exit } // Return -1 if all arranges could // not rot, otherwise ans return (checkAll(arr)) ? -1: ans; } // Driver Code public static void Main(string[] args) { int[][] arr = new int[][] { new int[] {2, 1, 0, 2, 1}, new int[] {1, 0, 1, 2, 1}, new int[] {1, 0, 0, 2, 1} }; int ans = rotOranges(arr); if (ans == -1) { Console.WriteLine(\"All oranges cannot rot\"); } else { Console.WriteLine(\"Time required for all \" + \"oranges to rot => \" + ans); } }} // This code is contributed by Shrikant13", "e": 65306, "s": 58826, "text": null }, { "code": null, "e": 65348, "s": 65306, "text": "Time required for all oranges to rot => 2" }, { "code": null, "e": 65649, "s": 65348, "text": "Complexity Analysis: Time Complexity: O( R *C). Each element of the matrix can be inserted into the queue only once so the upper bound of iteration is O(R*C), i.e. the number of elements. So time complexity is O(R *C).Space Complexity: O(R*C). To store the elements in a queue O(R*C) space is needed." }, { "code": null, "e": 65847, "s": 65649, "text": "Time Complexity: O( R *C). Each element of the matrix can be inserted into the queue only once so the upper bound of iteration is O(R*C), i.e. the number of elements. So time complexity is O(R *C)." }, { "code": null, "e": 65930, "s": 65847, "text": "Space Complexity: O(R*C). To store the elements in a queue O(R*C) space is needed." }, { "code": null, "e": 66114, "s": 65930, "text": "Thanks to Gaurav Ahirwar for suggesting the above solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 66126, "s": 66114, "text": "shrikanth13" }, { "code": null, "e": 66135, "s": 66126, "text": "arpitn30" }, { "code": null, "e": 66139, "s": 66135, "text": "gp6" }, { "code": null, "e": 66146, "s": 66139, "text": "md1844" }, { "code": null, "e": 66157, "s": 66146, "text": "andrew1234" }, { "code": null, "e": 66170, "s": 66157, "text": "Akanksha_Rai" }, { "code": null, "e": 66176, "s": 66170, "text": "ukasp" }, { "code": null, "e": 66189, "s": 66176, "text": "harshverma31" }, { "code": null, "e": 66207, "s": 66189, "text": "divyeshrabadiya07" }, { "code": null, "e": 66221, "s": 66207, "text": "divyesh072019" }, { "code": null, "e": 66236, "s": 66221, "text": "mohit kumar 29" }, { "code": null, "e": 66245, "s": 66236, "text": "mukesh07" }, { "code": null, "e": 66259, "s": 66245, "text": "bicky jaiswal" }, { "code": null, "e": 66276, "s": 66259, "text": "surinderdawra388" }, { "code": null, "e": 66285, "s": 66276, "text": "Accolite" }, { "code": null, "e": 66292, "s": 66285, "text": "Amazon" }, { "code": null, "e": 66296, "s": 66292, "text": "BFS" }, { "code": null, "e": 66307, "s": 66296, "text": "MakeMyTrip" }, { "code": null, "e": 66317, "s": 66307, "text": "Microsoft" }, { "code": null, "e": 66325, "s": 66317, "text": "Samsung" }, { "code": null, "e": 66331, "s": 66325, "text": "Graph" }, { "code": null, "e": 66338, "s": 66331, "text": "Matrix" }, { "code": null, "e": 66344, "s": 66338, "text": "Queue" }, { "code": null, "e": 66353, "s": 66344, "text": "Accolite" }, { "code": null, "e": 66360, "s": 66353, "text": "Amazon" }, { "code": null, "e": 66370, "s": 66360, "text": "Microsoft" }, { "code": null, "e": 66378, "s": 66370, "text": "Samsung" }, { "code": null, "e": 66389, "s": 66378, "text": "MakeMyTrip" }, { "code": null, "e": 66396, "s": 66389, "text": "Matrix" }, { "code": null, "e": 66402, "s": 66396, "text": "Graph" }, { "code": null, "e": 66408, "s": 66402, "text": "Queue" }, { "code": null, "e": 66412, "s": 66408, "text": "BFS" }, { "code": null, "e": 66510, "s": 66412, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 66568, "s": 66510, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 66588, "s": 66568, "text": "Topological Sorting" }, { "code": null, "e": 66619, "s": 66588, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 66652, "s": 66619, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 66685, "s": 66652, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 66720, "s": 66685, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 66764, "s": 66720, "text": "Program to find largest element in an array" }, { "code": null, "e": 66795, "s": 66764, "text": "Rat in a Maze | Backtracking-2" }, { "code": null, "e": 66831, "s": 66795, "text": "Print a given matrix in spiral form" } ]
CSS - Borders
The border properties allow you to specify how the border of the box representing an element should look. There are three properties of a border you can change βˆ’ The border-color specifies the color of a border. The border-color specifies the color of a border. The border-style specifies whether a border should be solid, dashed line, double line, or one of the other possible values. The border-style specifies whether a border should be solid, dashed line, double line, or one of the other possible values. The border-width specifies the width of a border. The border-width specifies the width of a border. Now, we will see how to use these properties with examples. The border-color property allows you to change the color of the border surrounding an element. You can individually change the color of the bottom, left, top and right sides of an element's border using the properties βˆ’ border-bottom-color changes the color of bottom border. border-bottom-color changes the color of bottom border. border-top-color changes the color of top border. border-top-color changes the color of top border. border-left-color changes the color of left border. border-left-color changes the color of left border. border-right-color changes the color of right border. border-right-color changes the color of right border. The following example shows the effect of all these properties βˆ’ <html> <head> <style type = "text/css"> p.example1 { border:1px solid; border-bottom-color:#009900; /* Green */ border-top-color:#FF0000; /* Red */ border-left-color:#330000; /* Black */ border-right-color:#0000CC; /* Blue */ } p.example2 { border:1px solid; border-color:#009900; /* Green */ } </style> </head> <body> <p class = "example1"> This example is showing all borders in different colors. </p> <p class = "example2"> This example is showing all borders in green color only. </p> </body> </html> It will produce the following result βˆ’ This example is showing all borders in different colors. This example is showing all borders in green color only. The border-style property allows you to select one of the following styles of border βˆ’ none βˆ’ No border. (Equivalent of border-width:0;) none βˆ’ No border. (Equivalent of border-width:0;) solid βˆ’ Border is a single solid line. solid βˆ’ Border is a single solid line. dotted βˆ’ Border is a series of dots. dotted βˆ’ Border is a series of dots. dashed βˆ’ Border is a series of short lines. dashed βˆ’ Border is a series of short lines. double βˆ’ Border is two solid lines. double βˆ’ Border is two solid lines. groove βˆ’ Border looks as though it is carved into the page. groove βˆ’ Border looks as though it is carved into the page. ridge βˆ’ Border looks the opposite of groove. ridge βˆ’ Border looks the opposite of groove. inset βˆ’ Border makes the box look like it is embedded in the page. inset βˆ’ Border makes the box look like it is embedded in the page. outset βˆ’ Border makes the box look like it is coming out of the canvas. outset βˆ’ Border makes the box look like it is coming out of the canvas. hidden βˆ’ Same as none, except in terms of border-conflict resolution for table elements. hidden βˆ’ Same as none, except in terms of border-conflict resolution for table elements. You can individually change the style of the bottom, left, top, and right borders of an element using the following properties βˆ’ border-bottom-style changes the style of bottom border. border-bottom-style changes the style of bottom border. border-top-style changes the style of top border. border-top-style changes the style of top border. border-left-style changes the style of left border. border-left-style changes the style of left border. border-right-style changes the style of right border. border-right-style changes the style of right border. The following example shows all these border styles βˆ’ <html> <head> </head> <body> <p style = "border-width:4px; border-style:none;"> This is a border with none width. </p> <p style = "border-width:4px; border-style:solid;"> This is a solid border. </p> <p style = "border-width:4px; border-style:dashed;"> This is a dashed border. </p> <p style = "border-width:4px; border-style:double;"> This is a double border. </p> <p style = "border-width:4px; border-style:groove;"> This is a groove border. </p> <p style = "border-width:4px; border-style:ridge"> This is a ridge border. </p> <p style = "border-width:4px; border-style:inset;"> This is a inset border. </p> <p style = "border-width:4px; border-style:outset;"> This is a outset border. </p> <p style = "border-width:4px; border-style:hidden;"> This is a hidden border. </p> <p style = "border-width:4px; border-top-style:solid; border-bottom-style:dashed; border-left-style:groove; border-right-style:double;"> This is a a border with four different styles. </p> </body> </html> It will produce the following result βˆ’ This is a border with none width. This is a solid border. This is a dahsed border. This is a double border. This is a groove border. This is aridge border. This is a inset border. This is a outset border. This is a hidden border. This is a a border with four different styles. The border-width property allows you to set the width of an element borders. The value of this property could be either a length in px, pt or cm or it should be set to thin, medium or thick. You can individually change the width of the bottom, top, left, and right borders of an element using the following properties βˆ’ border-bottom-width changes the width of bottom border. border-bottom-width changes the width of bottom border. border-top-width changes the width of top border. border-top-width changes the width of top border. border-left-width changes the width of left border. border-left-width changes the width of left border. border-right-width changes the width of right border. border-right-width changes the width of right border. The following example shows all these border width βˆ’ <html> <head> </head> <body> <p style = "border-width:4px; border-style:solid;"> This is a solid border whose width is 4px. </p> <p style = "border-width:4pt; border-style:solid;"> This is a solid border whose width is 4pt. </p> <p style = "border-width:thin; border-style:solid;"> This is a solid border whose width is thin. </p> <p style = "border-width:medium; border-style:solid;"> This is a solid border whose width is medium; </p> <p style = "border-width:thick; border-style:solid;"> This is a solid border whose width is thick. </p> <p style = "border-bottom-width:4px;border-top-width:10px; border-left-width: 2px;border-right-width:15px;border-style:solid;"> This is a a border with four different width. </p> </body> </html> It will produce the following result βˆ’ This is a solid border whose width is 4px. This is a solid border whose width is 4pt. This is a solid border whose width is thin. This is a solid border whose width is medium; This is a solid border whose width is thick. This is a a border with four different width. The border property allows you to specify color, style, and width of lines in one property βˆ’ The following example shows how to use all the three properties into a single property. This is the most frequently used property to set border around any element. <html> <head> </head> <body> <p style = "border:4px solid red;"> This example is showing shorthand property for border. </p> </body> </html> It will produce the following result βˆ’ This example is showing shorthand property for border. 33 Lectures 2.5 hours Anadi Sharma 26 Lectures 2.5 hours Frahaan Hussain 44 Lectures 4.5 hours DigiFisk (Programming Is Fun) 21 Lectures 2.5 hours DigiFisk (Programming Is Fun) 51 Lectures 7.5 hours DigiFisk (Programming Is Fun) 52 Lectures 4 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2788, "s": 2626, "text": "The border properties allow you to specify how the border of the box representing an element should look. There are three properties of a border you can change βˆ’" }, { "code": null, "e": 2838, "s": 2788, "text": "The border-color specifies the color of a border." }, { "code": null, "e": 2888, "s": 2838, "text": "The border-color specifies the color of a border." }, { "code": null, "e": 3012, "s": 2888, "text": "The border-style specifies whether a border should be solid, dashed line, double line, or one of the other possible values." }, { "code": null, "e": 3136, "s": 3012, "text": "The border-style specifies whether a border should be solid, dashed line, double line, or one of the other possible values." }, { "code": null, "e": 3186, "s": 3136, "text": "The border-width specifies the width of a border." }, { "code": null, "e": 3236, "s": 3186, "text": "The border-width specifies the width of a border." }, { "code": null, "e": 3296, "s": 3236, "text": "Now, we will see how to use these properties with examples." }, { "code": null, "e": 3516, "s": 3296, "text": "The border-color property allows you to change the color of the border surrounding an element. You can individually change the color of the bottom, left, top and right sides of an element's border using the properties βˆ’" }, { "code": null, "e": 3572, "s": 3516, "text": "border-bottom-color changes the color of bottom border." }, { "code": null, "e": 3628, "s": 3572, "text": "border-bottom-color changes the color of bottom border." }, { "code": null, "e": 3678, "s": 3628, "text": "border-top-color changes the color of top border." }, { "code": null, "e": 3728, "s": 3678, "text": "border-top-color changes the color of top border." }, { "code": null, "e": 3780, "s": 3728, "text": "border-left-color changes the color of left border." }, { "code": null, "e": 3832, "s": 3780, "text": "border-left-color changes the color of left border." }, { "code": null, "e": 3886, "s": 3832, "text": "border-right-color changes the color of right border." }, { "code": null, "e": 3940, "s": 3886, "text": "border-right-color changes the color of right border." }, { "code": null, "e": 4005, "s": 3940, "text": "The following example shows the effect of all these properties βˆ’" }, { "code": null, "e": 4718, "s": 4005, "text": "<html>\n <head>\n <style type = \"text/css\">\n p.example1 {\n border:1px solid;\n border-bottom-color:#009900; /* Green */\n border-top-color:#FF0000; /* Red */\n border-left-color:#330000; /* Black */\n border-right-color:#0000CC; /* Blue */\n }\n p.example2 {\n border:1px solid;\n border-color:#009900; /* Green */\n }\n </style>\n </head>\n\n <body>\n <p class = \"example1\">\n This example is showing all borders in different colors.\n </p>\n \n <p class = \"example2\">\n This example is showing all borders in green color only.\n </p>\n </body>\n</html> " }, { "code": null, "e": 4757, "s": 4718, "text": "It will produce the following result βˆ’" }, { "code": null, "e": 4819, "s": 4757, "text": "\n This example is showing all borders in different colors.\n" }, { "code": null, "e": 4881, "s": 4819, "text": "\n This example is showing all borders in green color only.\n" }, { "code": null, "e": 4968, "s": 4881, "text": "The border-style property allows you to select one of the following styles of border βˆ’" }, { "code": null, "e": 5018, "s": 4968, "text": "none βˆ’ No border. (Equivalent of border-width:0;)" }, { "code": null, "e": 5068, "s": 5018, "text": "none βˆ’ No border. (Equivalent of border-width:0;)" }, { "code": null, "e": 5107, "s": 5068, "text": "solid βˆ’ Border is a single solid line." }, { "code": null, "e": 5146, "s": 5107, "text": "solid βˆ’ Border is a single solid line." }, { "code": null, "e": 5183, "s": 5146, "text": "dotted βˆ’ Border is a series of dots." }, { "code": null, "e": 5220, "s": 5183, "text": "dotted βˆ’ Border is a series of dots." }, { "code": null, "e": 5264, "s": 5220, "text": "dashed βˆ’ Border is a series of short lines." }, { "code": null, "e": 5308, "s": 5264, "text": "dashed βˆ’ Border is a series of short lines." }, { "code": null, "e": 5344, "s": 5308, "text": "double βˆ’ Border is two solid lines." }, { "code": null, "e": 5380, "s": 5344, "text": "double βˆ’ Border is two solid lines." }, { "code": null, "e": 5440, "s": 5380, "text": "groove βˆ’ Border looks as though it is carved into the page." }, { "code": null, "e": 5500, "s": 5440, "text": "groove βˆ’ Border looks as though it is carved into the page." }, { "code": null, "e": 5545, "s": 5500, "text": "ridge βˆ’ Border looks the opposite of groove." }, { "code": null, "e": 5590, "s": 5545, "text": "ridge βˆ’ Border looks the opposite of groove." }, { "code": null, "e": 5657, "s": 5590, "text": "inset βˆ’ Border makes the box look like it is embedded in the page." }, { "code": null, "e": 5724, "s": 5657, "text": "inset βˆ’ Border makes the box look like it is embedded in the page." }, { "code": null, "e": 5796, "s": 5724, "text": "outset βˆ’ Border makes the box look like it is coming out of the canvas." }, { "code": null, "e": 5868, "s": 5796, "text": "outset βˆ’ Border makes the box look like it is coming out of the canvas." }, { "code": null, "e": 5957, "s": 5868, "text": "hidden βˆ’ Same as none, except in terms of border-conflict resolution for table elements." }, { "code": null, "e": 6046, "s": 5957, "text": "hidden βˆ’ Same as none, except in terms of border-conflict resolution for table elements." }, { "code": null, "e": 6175, "s": 6046, "text": "You can individually change the style of the bottom, left, top, and right borders of an element using the following properties βˆ’" }, { "code": null, "e": 6231, "s": 6175, "text": "border-bottom-style changes the style of bottom border." }, { "code": null, "e": 6287, "s": 6231, "text": "border-bottom-style changes the style of bottom border." }, { "code": null, "e": 6337, "s": 6287, "text": "border-top-style changes the style of top border." }, { "code": null, "e": 6387, "s": 6337, "text": "border-top-style changes the style of top border." }, { "code": null, "e": 6439, "s": 6387, "text": "border-left-style changes the style of left border." }, { "code": null, "e": 6491, "s": 6439, "text": "border-left-style changes the style of left border." }, { "code": null, "e": 6545, "s": 6491, "text": "border-right-style changes the style of right border." }, { "code": null, "e": 6599, "s": 6545, "text": "border-right-style changes the style of right border." }, { "code": null, "e": 6653, "s": 6599, "text": "The following example shows all these border styles βˆ’" }, { "code": null, "e": 7961, "s": 6653, "text": "<html>\n <head>\n </head>\n \n <body>\n <p style = \"border-width:4px; border-style:none;\">\n This is a border with none width.\n </p>\n \n <p style = \"border-width:4px; border-style:solid;\">\n This is a solid border.\n </p>\n \n <p style = \"border-width:4px; border-style:dashed;\">\n This is a dashed border.\n </p>\n \n <p style = \"border-width:4px; border-style:double;\">\n This is a double border.\n </p>\n \n <p style = \"border-width:4px; border-style:groove;\">\n This is a groove border.\n </p>\n \n <p style = \"border-width:4px; border-style:ridge\">\n This is a ridge border.\n </p>\n \n <p style = \"border-width:4px; border-style:inset;\">\n This is a inset border.\n </p>\n \n <p style = \"border-width:4px; border-style:outset;\">\n This is a outset border.\n </p>\n \n <p style = \"border-width:4px; border-style:hidden;\">\n This is a hidden border.\n </p>\n \n <p style = \"border-width:4px; \n border-top-style:solid;\n border-bottom-style:dashed;\n border-left-style:groove;\n border-right-style:double;\">\n This is a a border with four different styles.\n </p>\n </body>\n</html>" }, { "code": null, "e": 8000, "s": 7961, "text": "It will produce the following result βˆ’" }, { "code": null, "e": 8039, "s": 8000, "text": "\n This is a border with none width.\n" }, { "code": null, "e": 8068, "s": 8039, "text": "\n This is a solid border.\n" }, { "code": null, "e": 8098, "s": 8068, "text": "\n This is a dahsed border.\n" }, { "code": null, "e": 8128, "s": 8098, "text": "\n This is a double border.\n" }, { "code": null, "e": 8158, "s": 8128, "text": "\n This is a groove border.\n" }, { "code": null, "e": 8187, "s": 8158, "text": "\n This is aridge border.\n" }, { "code": null, "e": 8216, "s": 8187, "text": "\n This is a inset border.\n" }, { "code": null, "e": 8246, "s": 8216, "text": "\n This is a outset border.\n" }, { "code": null, "e": 8276, "s": 8246, "text": "\n This is a hidden border.\n" }, { "code": null, "e": 8328, "s": 8276, "text": "\n This is a a border with four different styles.\n" }, { "code": null, "e": 8519, "s": 8328, "text": "The border-width property allows you to set the width of an element borders. The value of this property could be either a length in px, pt or cm or it should be set to thin, medium or thick." }, { "code": null, "e": 8648, "s": 8519, "text": "You can individually change the width of the bottom, top, left, and right borders of an element using the following properties βˆ’" }, { "code": null, "e": 8704, "s": 8648, "text": "border-bottom-width changes the width of bottom border." }, { "code": null, "e": 8760, "s": 8704, "text": "border-bottom-width changes the width of bottom border." }, { "code": null, "e": 8810, "s": 8760, "text": "border-top-width changes the width of top border." }, { "code": null, "e": 8860, "s": 8810, "text": "border-top-width changes the width of top border." }, { "code": null, "e": 8912, "s": 8860, "text": "border-left-width changes the width of left border." }, { "code": null, "e": 8964, "s": 8912, "text": "border-left-width changes the width of left border." }, { "code": null, "e": 9018, "s": 8964, "text": "border-right-width changes the width of right border." }, { "code": null, "e": 9072, "s": 9018, "text": "border-right-width changes the width of right border." }, { "code": null, "e": 9125, "s": 9072, "text": "The following example shows all these border width βˆ’" }, { "code": null, "e": 10048, "s": 9125, "text": "<html>\n <head>\n </head>\n \n <body>\n <p style = \"border-width:4px; border-style:solid;\">\n This is a solid border whose width is 4px.\n </p>\n \n <p style = \"border-width:4pt; border-style:solid;\">\n This is a solid border whose width is 4pt.\n </p>\n \n <p style = \"border-width:thin; border-style:solid;\">\n This is a solid border whose width is thin.\n </p>\n \n <p style = \"border-width:medium; border-style:solid;\">\n This is a solid border whose width is medium;\n </p>\n \n <p style = \"border-width:thick; border-style:solid;\">\n This is a solid border whose width is thick.\n </p>\n \n <p style = \"border-bottom-width:4px;border-top-width:10px;\n border-left-width: 2px;border-right-width:15px;border-style:solid;\">\n This is a a border with four different width.\n </p>\n </body>\n</html> " }, { "code": null, "e": 10087, "s": 10048, "text": "It will produce the following result βˆ’" }, { "code": null, "e": 10135, "s": 10087, "text": "\n This is a solid border whose width is 4px.\n" }, { "code": null, "e": 10183, "s": 10135, "text": "\n This is a solid border whose width is 4pt.\n" }, { "code": null, "e": 10232, "s": 10183, "text": "\n This is a solid border whose width is thin.\n" }, { "code": null, "e": 10283, "s": 10232, "text": "\n This is a solid border whose width is medium;\n" }, { "code": null, "e": 10333, "s": 10283, "text": "\n This is a solid border whose width is thick.\n" }, { "code": null, "e": 10384, "s": 10333, "text": "\n This is a a border with four different width.\n" }, { "code": null, "e": 10477, "s": 10384, "text": "The border property allows you to specify color, style, and width of lines in one property βˆ’" }, { "code": null, "e": 10641, "s": 10477, "text": "The following example shows how to use all the three properties into a single property. This is the most frequently used property to set border around any element." }, { "code": null, "e": 10816, "s": 10641, "text": "<html>\n <head>\n </head>\n\n <body>\n <p style = \"border:4px solid red;\">\n This example is showing shorthand property for border.\n </p>\n </body>\n</html>" }, { "code": null, "e": 10855, "s": 10816, "text": "It will produce the following result βˆ’" }, { "code": null, "e": 10915, "s": 10855, "text": "\n This example is showing shorthand property for border.\n" }, { "code": null, "e": 10950, "s": 10915, "text": "\n 33 Lectures \n 2.5 hours \n" }, { "code": null, "e": 10964, "s": 10950, "text": " Anadi Sharma" }, { "code": null, "e": 10999, "s": 10964, "text": "\n 26 Lectures \n 2.5 hours \n" }, { "code": null, "e": 11016, "s": 10999, "text": " Frahaan Hussain" }, { "code": null, "e": 11051, "s": 11016, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11082, "s": 11051, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 11117, "s": 11082, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 11148, "s": 11117, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 11183, "s": 11148, "text": "\n 51 Lectures \n 7.5 hours \n" }, { "code": null, "e": 11214, "s": 11183, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 11247, "s": 11214, "text": "\n 52 Lectures \n 4 hours \n" }, { "code": null, "e": 11278, "s": 11247, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 11285, "s": 11278, "text": " Print" }, { "code": null, "e": 11296, "s": 11285, "text": " Add Notes" } ]
Multiple axes in Matplotlib with different scales
In the following code, we will see how to create a shared Y-axis. Create fig and ax variables using subplots method, where default nrows and ncols are 1. Create fig and ax variables using subplots method, where default nrows and ncols are 1. Plot line with lists passed in the argument of plot() method with color="red". Plot line with lists passed in the argument of plot() method with color="red". Create a twin of Axes with a shared X-axis but independent Y-axis. Create a twin of Axes with a shared X-axis but independent Y-axis. Plot the line on ax2 that is created in step 3. Plot the line on ax2 that is created in step 3. Adjust the padding between and around subplots. Adjust the padding between and around subplots. To show the figure use plt.show() method. To show the figure use plt.show() method. import matplotlib.pyplot as plt fig, ax1 = plt.subplots() ax1.plot([1, 2, 3, 4, 5], [3, 5, 7, 1, 9], color='red') ax2 = ax1.twinx() ax2.plot([11, 12, 31, 41, 15], [13, 51, 17, 11, 76], color='blue') fig.tight_layout() plt.show()
[ { "code": null, "e": 1128, "s": 1062, "text": "In the following code, we will see how to create a shared Y-axis." }, { "code": null, "e": 1216, "s": 1128, "text": "Create fig and ax variables using subplots method, where default nrows and ncols are 1." }, { "code": null, "e": 1304, "s": 1216, "text": "Create fig and ax variables using subplots method, where default nrows and ncols are 1." }, { "code": null, "e": 1383, "s": 1304, "text": "Plot line with lists passed in the argument of plot() method with color=\"red\"." }, { "code": null, "e": 1462, "s": 1383, "text": "Plot line with lists passed in the argument of plot() method with color=\"red\"." }, { "code": null, "e": 1529, "s": 1462, "text": "Create a twin of Axes with a shared X-axis but independent Y-axis." }, { "code": null, "e": 1596, "s": 1529, "text": "Create a twin of Axes with a shared X-axis but independent Y-axis." }, { "code": null, "e": 1644, "s": 1596, "text": "Plot the line on ax2 that is created in step 3." }, { "code": null, "e": 1692, "s": 1644, "text": "Plot the line on ax2 that is created in step 3." }, { "code": null, "e": 1740, "s": 1692, "text": "Adjust the padding between and around subplots." }, { "code": null, "e": 1788, "s": 1740, "text": "Adjust the padding between and around subplots." }, { "code": null, "e": 1830, "s": 1788, "text": "To show the figure use plt.show() method." }, { "code": null, "e": 1872, "s": 1830, "text": "To show the figure use plt.show() method." }, { "code": null, "e": 2101, "s": 1872, "text": "import matplotlib.pyplot as plt\nfig, ax1 = plt.subplots()\nax1.plot([1, 2, 3, 4, 5], [3, 5, 7, 1, 9], color='red')\nax2 = ax1.twinx()\nax2.plot([11, 12, 31, 41, 15], [13, 51, 17, 11, 76], color='blue')\nfig.tight_layout()\nplt.show()" } ]
Python time mktime() Method
Pythom time method mktime() is the inverse function of localtime(). Its argument is the struct_time or full 9-tuple and it returns a floating point number, for compatibility with time(). If the input value cannot be represented as a valid time, either OverflowError or ValueError will be raised. Following is the syntax for mktime() method βˆ’ time.mktime(t) t βˆ’ This is the struct_time or full 9-tuple. t βˆ’ This is the struct_time or full 9-tuple. This method returns a floating point number, for compatibility with time(). The following example shows the usage of mktime() method. #!/usr/bin/python import time t = (2009, 2, 17, 17, 3, 38, 1, 48, 0) secs = time.mktime( t ) print "time.mktime(t) : %f" % secs print "asctime(localtime(secs)): %s" % time.asctime(time.localtime(secs)) When we run above program, it produces following result βˆ’ time.mktime(t) : 1234915418.000000 asctime(localtime(secs)): Tue Feb 17 17:03:38 2009 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2431, "s": 2244, "text": "Pythom time method mktime() is the inverse function of localtime(). Its argument is the struct_time or full 9-tuple and it returns a floating point number, for compatibility with time()." }, { "code": null, "e": 2540, "s": 2431, "text": "If the input value cannot be represented as a valid time, either OverflowError or ValueError will be raised." }, { "code": null, "e": 2586, "s": 2540, "text": "Following is the syntax for mktime() method βˆ’" }, { "code": null, "e": 2602, "s": 2586, "text": "time.mktime(t)\n" }, { "code": null, "e": 2647, "s": 2602, "text": "t βˆ’ This is the struct_time or full 9-tuple." }, { "code": null, "e": 2692, "s": 2647, "text": "t βˆ’ This is the struct_time or full 9-tuple." }, { "code": null, "e": 2768, "s": 2692, "text": "This method returns a floating point number, for compatibility with time()." }, { "code": null, "e": 2826, "s": 2768, "text": "The following example shows the usage of mktime() method." }, { "code": null, "e": 3030, "s": 2826, "text": "#!/usr/bin/python\nimport time\n\nt = (2009, 2, 17, 17, 3, 38, 1, 48, 0)\nsecs = time.mktime( t )\nprint \"time.mktime(t) : %f\" % secs\nprint \"asctime(localtime(secs)): %s\" % time.asctime(time.localtime(secs))" }, { "code": null, "e": 3088, "s": 3030, "text": "When we run above program, it produces following result βˆ’" }, { "code": null, "e": 3175, "s": 3088, "text": "time.mktime(t) : 1234915418.000000\nasctime(localtime(secs)): Tue Feb 17 17:03:38 2009\n" }, { "code": null, "e": 3212, "s": 3175, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3228, "s": 3212, "text": " Malhar Lathkar" }, { "code": null, "e": 3261, "s": 3228, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3280, "s": 3261, "text": " Arnab Chakraborty" }, { "code": null, "e": 3315, "s": 3280, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3337, "s": 3315, "text": " In28Minutes Official" }, { "code": null, "e": 3371, "s": 3337, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3399, "s": 3371, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3434, "s": 3399, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3448, "s": 3434, "text": " Lets Kode It" }, { "code": null, "e": 3481, "s": 3448, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3498, "s": 3481, "text": " Abhilash Nelson" }, { "code": null, "e": 3505, "s": 3498, "text": " Print" }, { "code": null, "e": 3516, "s": 3505, "text": " Add Notes" } ]
Ansible - Roles
Roles provide a framework for fully independent, or interdependent collections of variables, tasks, files, templates, and modules. In Ansible, the role is the primary mechanism for breaking a playbook into multiple files. This simplifies writing complex playbooks, and it makes them easier to reuse. The breaking of playbook allows you to logically break the playbook into reusable components. Each role is basically limited to a particular functionality or desired output, with all the necessary steps to provide that result either within that role itself or in other roles listed as dependencies. Roles are not playbooks. Roles are small functionality which can be independently used but have to be used within playbooks. There is no way to directly execute a role. Roles have no explicit setting for which host the role will apply to. Top-level playbooks are the bridge holding the hosts from your inventory file to roles that should be applied to those hosts. The directory structure for roles is essential to create a new role. Roles have a structured layout on the file system. The default structure can be changed but for now let us stick to defaults. Each role is a directory tree in itself. The role name is the directory name within the /roles directory. $ ansible-galaxy -h ansible-galaxy [delete|import|info|init|install|list|login|remove|search|setup] [--help] [options] ... -h, --help βˆ’ Show this help message and exit. -h, --help βˆ’ Show this help message and exit. -v, --verbose βˆ’ Verbose mode (-vvv for more, -vvvv to enable connection debugging) -v, --verbose βˆ’ Verbose mode (-vvv for more, -vvvv to enable connection debugging) --version βˆ’ Show program's version number and exit. --version βˆ’ Show program's version number and exit. The above command has created the role directories. $ ansible-galaxy init vivekrole ERROR! The API server (https://galaxy.ansible.com/api/) is not responding, please try again later. $ ansible-galaxy init --force --offline vivekrole - vivekrole was created successfully $ tree vivekrole/ vivekrole/ β”œβ”€β”€ defaults β”‚ └── main.yml β”œβ”€β”€ files β”œβ”€β”€ handlers β”‚ └── main.yml β”œβ”€β”€ meta β”‚ └── main.yml β”œβ”€β”€ README.md β”œβ”€β”€ tasks β”‚ └── main.yml β”œβ”€β”€ templates β”œβ”€β”€ tests β”‚ β”œβ”€β”€ inventory β”‚ └── test.yml └── vars └── main.yml 8 directories, 8 files Not all the directories will be used in the example and we will show the use of some of them in the example. This is the code of the playbook we have written for demo purpose. This code is of the playbook vivek_orchestrate.yml. We have defined the hosts: tomcat-node and called the two roles – install-tomcat and start-tomcat. The problem statement is that we have a war which we need to deploy on a machine via Ansible. --- - hosts: tomcat-node roles: - {role: install-tomcat} - {role: start-tomcat} Contents of our directory structure from where we are running the playbook. $ ls ansible.cfg hosts roles vivek_orchestrate.retry vivek_orchestrate.yml There is a tasks directory under each directory and it contains a main.yml. The main.yml contents of install-tomcat are βˆ’ --- #Install vivek artifacts - block: - name: Install Tomcat artifacts action: > yum name = "demo-tomcat-1" state = present register: Output always: - debug: msg: - "Install Tomcat artifacts task ended with message: {{Output}}" - "Installed Tomcat artifacts - {{Output.changed}}" The contents of main.yml of the start tomcat are βˆ’ #Start Tomcat - block: - name: Start Tomcat command: <path of tomcat>/bin/startup.sh" register: output become: true always: - debug: msg: - "Start Tomcat task ended with message: {{output}}" - "Tomcat started - {{output.changed}}" The advantage of breaking the playbook into roles is that anyone who wants to use the Install tomcat feature can call the Install Tomcat role. If not for the roles, the content of the main.yml of the respective role can be copied in the playbook yml file. But to have modularity, roles were created. Any logical entity which can be reused as a reusable function, that entity can be moved to role. The example for this is shown above Ran the command to run the playbook. -vvv option for verbose output – verbose output $ cd vivek-playbook/ This is the command to run the playbook $ sudo ansible-playbook -i hosts vivek_orchestrate.yml –vvv ----------------------------------------------------------------- ----------------------------------------------------------------------- The generated output is as seen on the screen βˆ’ Using /users/demo/vivek-playbook/ansible.cfg as config file. PLAYBOOK: vivek_orchestrate.yml ********************************************************* *********************************************************** 1 plays in vivek_orchestrate.yml PLAY [tomcat-node] ********************************************************************** ******** ************************************************* TASK [Gathering Facts] ************************************************* ****************************** ********************************************* Tuesday 21 November 2017 13:02:05 +0530 (0:00:00.056) 0:00:00.056 ****** Using module file /usr/lib/python2.7/sitepackages/ansible/modules/system/setup.py <localhost> ESTABLISH LOCAL CONNECTION FOR USER: root <localhost> EXEC /bin/sh -c 'echo ~ && sleep 0' <localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /root/.ansible/tmp/ansible-tmp-1511249525.88-259535494116870 `" && echo ansible-tmp-1511249525.88-259535494116870="` echo /root/.ansible/tmp/ansibletmp-1511249525.88-259535494116870 `" ) && sleep 0' <localhost> PUT /tmp/tmpPEPrkd TO /root/.ansible/tmp/ansible-tmp-1511249525.88259535494116870/setup.py <localhost> EXEC /bin/sh -c 'chmod u+x /root/.ansible/tmp/ansible-tmp1511249525.88-259535494116870/ /root/.ansible/tmp/ansible-tmp-1511249525.88259535494116870/setup.py && sleep 0' <localhost> EXEC /bin/sh -c '/usr/bin/python /root/.ansible/tmp/ansible-tmp1511249525.88-259535494116870/setup.py; rm -rf "/root/.ansible/tmp/ansible-tmp1511249525.88-259535494116870/" > /dev/null 2>&1 && sleep 0' ok: [server1] META: ran handlers TASK [install-tomcat : Install Tomcat artifacts] *********************************** *************************************************************** task path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:5 Tuesday 21 November 2017 13:02:07 +0530 (0:00:01.515) 0:00:01.572 ****** Using module file /usr/lib/python2.7/sitepackages/ansible/modules/packaging/os/yum.py <localhost> ESTABLISH LOCAL CONNECTION FOR USER: root <localhost> EXEC /bin/sh -c 'echo ~ && sleep 0' <localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /root/.ansible/tmp/ansible-tmp-1511249527.34-40247177825302 `" && echo ansibletmp-1511249527.34-40247177825302="` echo /root/.ansible/tmp/ansible-tmp1511249527.34-40247177825302 `" ) && sleep 0' <localhost> PUT /tmp/tmpu83chg TO /root/.ansible/tmp/ansible-tmp-1511249527.3440247177825302/yum.py <localhost> EXEC /bin/sh -c 'chmod u+x /root/.ansible/tmp/ansible-tmp1511249527.34-40247177825302/ /root/.ansible/tmp/ansible-tmp-1511249527.3440247177825302/yum.py && sleep 0' <localhost> EXEC /bin/sh -c '/usr/bin/python /root/.ansible/tmp/ansible-tmp1511249527.34-40247177825302/yum.py; rm -rf "/root/.ansible/tmp/ansible-tmp1511249527.34-40247177825302/" > /dev/null 2> &1 && sleep 0' changed: [server1] => { "changed": true, "invocation": { "module_args": { "conf_file": null, "disable_gpg_check": false, "disablerepo": null, "enablerepo": null, "exclude": null, "install_repoquery": true, "installroot": "/", "list": null, "name": ["demo-tomcat-1"], "skip_broken": false, "state": "present", "update_cache": false, "validate_certs": true } }, "msg": "", "rc": 0, "results": [ "Loaded plugins: product-id, search-disabled-repos, subscriptionmanager\nThis system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.\nResolving Dependencies\n--> Running transaction check\n---> Package demo-tomcat-1.noarch 0:SNAPSHOT-1 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n \n================================================================================\n Package Arch Version Repository Size\n==================================================================\nInstalling:\n demo-tomcat-1 noarch SNAPSHOT-1 demo-repo1 7.1 M\n\nTransaction Summary\n==================================================================\nInstall 1 Package\n\nTotal download size: 7.1 M\nInstalled size: 7.9 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : demotomcat-1-SNAPSHOT-1.noarch 1/1 \n Verifying : demo-tomcat-1-SNAPSHOT-1.noarch 1/1 \n\nInstalled:\n demo-tomcat-1.noarch 0:SNAPSHOT-1 \n\nComplete!\n" ] } TASK [install-tomcat : debug] ********************************************************** *************************************************************************** task path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:11 Tuesday 21 November 2017 13:02:13 +0530 (0:00:06.757) 0:00:08.329 ****** ok: [server1] => { "changed": false, "msg": [ "Install Tomcat artifacts task ended with message: { u'msg': u'', u'changed': True, u'results': [u'Loaded plugins: product-id, search-disabledrepos, subscription-manager\\nThis system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.\\nResolving Dependencies\\n--> Running transaction check\\n---> Package demo-tomcat-1.noarch 0:SNAPSHOT-1 will be installed\\n--> Finished Dependency Resolution\\n \\nDependencies Resolved\\n\\n==================================================================\\n Package Arch Version Repository Size\\n======================================================================== =====\\nInstalling:\\n demo-tomcat-1 noarch SNAPSHOT-1 demo-repo1 7.1 M\\n\\nTransaction Summary\\n=========================================================\\nInstall 1 Package\\n\\nTotal download size: 7.1 M\\nInstalled size: 7.9 M\\nDownloading packages:\\nRunning transaction check\\nRunning transaction test\\nTransaction test succeeded\\nRunning transaction\\n Installing : demo-tomcat-1-SNAPSHOT-1.noarch 1/1 \\n Verifying : demo-tomcat-1-SNAPSHOT-1.noarch 1/1 \\n\\nInstalled:\\n demo-tomcat-1.noarch 0:SNAPSHOT-1 \\n\\nComplete!\\n'], u'rc': 0 }", "Installed Tomcat artifacts - True" ] } TASK [install-tomcat : Clean DEMO environment] **************************************** ************************************************************ task path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:19 Tuesday 21 November 2017 13:02:13 +0530 (0:00:00.057) 0:00:08.387 ****** [WARNING]: when statements should not include jinja2 templating delimiters such as {{ }} or {% %}. Found: {{installationOutput.changed}} Using module file /usr/lib/python2.7/sitepackages/ansible/modules/files/file.py <localhost> ESTABLISH LOCAL CONNECTION FOR USER: root <localhost> EXEC /bin/sh -c 'echo ~ && sleep 0' <localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /root/.ansible/tmp/ansible-tmp-1511249534.13-128345805983963 `" && echo ansible-tmp-1511249534.13-128345805983963="` echo /root/.ansible/tmp/ansibletmp-1511249534.13-128345805983963 `" ) && sleep 0' <localhost> PUT /tmp/tmp0aXel7 TO /root/.ansible/tmp/ansible-tmp-1511249534.13128345805983963/file.py <localhost> EXEC /bin/sh -c 'chmod u+x /root/.ansible/tmp/ansible-tmp1511249534.13-128345805983963/ /root/.ansible/tmp/ansible-tmp-1511249534.13128345805983963/file.py && sleep 0' <localhost> EXEC /bin/sh -c '/usr/bin/python /root/.ansible/tmp/ansible-tmp1511249534.13-128345805983963/file.py; rm -rf "/root/.ansible/tmp/ansible-tmp1511249534.13-128345805983963/" > /dev/null 2>&1 && sleep 0' changed: [server1] => { "changed": true, "diff": { "after": { "path": "/users/demo/DEMO", "state": "absent" }, "before": { "path": "/users/demo/DEMO", "state": "directory" } }, "invocation": { "module_args": { "attributes": null, "backup": null, "content": null, "delimiter": null, "diff_peek": null, "directory_mode": null, "follow": false, "force": false, "group": null, "mode": null, "original_basename": null, "owner": null, "path": "/users/demo/DEMO", "recurse": false, "regexp": null, "remote_src": null, "selevel": null, "serole": null, "setype": null, "seuser": null, "src": null, "state": "absent", "unsafe_writes": null, "validate": null } }, "path": "/users/demo/DEMO", "state": "absent" } TASK [install-tomcat : debug] ******************************************************** ************************************************************* task path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:29 Tuesday 21 November 2017 13:02:14 +0530 (0:00:00.257) 0:00:08.645 ****** ok: [server1] => { "changed": false, "msg": [ "Clean DEMO environment task ended with message:{u'diff': {u'after': {u'path': u'/users/demo/DEMO', u'state': u'absent'}, u'before': {u'path': u'/users/demo/DEMO', u'state': u'directory'}}, u'state': u'absent', u'changed': True, u'path': u'/users/demo/DEMO'}", "check value :True" ] } TASK [install-tomcat : Copy Tomcat to user home] ************************************* ******************************************************** task path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:37 Tuesday 21 November 2017 13:02:14 +0530 (0:00:00.055) 0:00:08.701 ****** [WARNING]: when statements should not include jinja2 templating delimiters such as {{ }} or {% %}. Found: {{installationOutput.changed}} Using module file /usr/lib/python2.7/sitepackages/ansible/modules/commands/command.py <localhost> ESTABLISH LOCAL CONNECTION FOR USER: root <localhost> EXEC /bin/sh -c 'echo ~ && sleep 0' <localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /root/.ansible/tmp/ansible-tmp-1511249534.43-41077200718443 `" && echo ansibletmp-1511249534.43-41077200718443="` echo /root/.ansible/tmp/ansible-tmp1511249534.43-41077200718443 `" ) && sleep 0' <localhost> PUT /tmp/tmp25deWs TO /root/.ansible/tmp/ansible-tmp-1511249534.4341077200718443/command.py <localhost> EXEC /bin/sh -c 'chmod u+x /root/.ansible/tmp/ansible-tmp1511249534.43-41077200718443/ /root/.ansible/tmp/ansible-tmp-1511249534.4341077200718443/command.py && sleep 0' <localhost> EXEC /bin/sh -c '/usr/bin/python /root/.ansible/tmp/ansible-tmp1511249534.43-41077200718443/command.py; rm -rf "/root/.ansible/tmp/ansibletmp-1511249534.43-41077200718443/" > /dev/null 2>&1 && sleep 0' changed: [server1] => { "changed": true, "cmd": [ "cp", "-r", "/opt/ansible/tomcat/demo", "/users/demo/DEMO/" ], "delta": "0:00:00.017923", "end": "2017-11-21 13:02:14.547633", "invocation": { "module_args": { "_raw_params": "cp -r /opt/ansible/tomcat/demo /users/demo/DEMO/", "_uses_shell": false, "chdir": null, "creates": null, "executable": null, "removes": null, "warn": true } }, "rc": 0, "start": "2017-11-21 13:02:14.529710", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": [] } TASK [install-tomcat : debug] ******************************************************** ********************************************************** task path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:47 Tuesday 21 November 2017 13:02:14 +0530 (0:00:00.260) 0:00:08.961 ****** ok: [server1] => { "changed": false, "msg": "Copy Tomcat to user home task ended with message { 'stderr_lines': [], u'changed': True, u'end': u'2017-11-21 13:02:14.547633', u'stdout': u'', u'cmd': [u'cp', u'-r', u'/opt/ansible/tomcat/demo', u'/users/demo/DEMO/'], u'rc': 0, u'start': u'2017-11-21 13:02:14.529710', u'stderr': u'', u'delta': u'0:00:00.017923', 'stdout_lines': []}" } TASK [start-tomcat : Start Tomcat] ************************************************** ********************************************************** task path: /users/demo/vivek-playbook/roles/start-tomcat/tasks/main.yml:5 Tuesday 21 November 2017 13:02:14 +0530 (0:00:00.044) 0:00:09.006 ****** Using module file /usr/lib/python2.7/sitepackages/ansible/modules/commands/command.py <localhost> ESTABLISH LOCAL CONNECTION FOR USER: root <localhost> EXEC /bin/sh -c 'echo ~ && sleep 0' <localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /root/.ansible/tmp/ansible-tmp-1511249534.63-46501211251197 `" && echo ansibletmp-1511249534.63-46501211251197="` echo /root/.ansible/tmp/ansible-tmp1511249534.63-46501211251197 `" ) && sleep 0' <localhost> PUT /tmp/tmp9f06MQ TO /root/.ansible/tmp/ansible-tmp-1511249534.6346501211251197/command.py <localhost> EXEC /bin/sh -c 'chmod u+x /root/.ansible/tmp/ansible-tmp1511249534.63-46501211251197/ /root/.ansible/tmp/ansible-tmp-1511249534.6346501211251197/command.py && sleep 0' <localhost> EXEC /bin/sh -c '/usr/bin/python /root/.ansible/tmp/ansible-tmp1511249534.63-46501211251197/command.py; rm -rf "/root/.ansible/tmp/ansibletmp-1511249534.63-46501211251197/" > /dev/null 2>&1 && sleep 0' changed: [server1] => { "changed": true, "cmd": [ "/users/demo/DEMO/bin/startup.sh" ], "delta": "0:00:00.020024", "end": "2017-11-21 13:02:14.741649", "invocation": { "module_args": { "_raw_params": "/users/demo/DEMO/bin/startup.sh", "_uses_shell": false, "chdir": null, "creates": null, "executable": null, "removes": null, "warn": true } }, "rc": 0, "start": "2017-11-21 13:02:14.721625", "stderr": "", "stderr_lines": [], "stdout": "Tomcat started.", "stdout_lines": [ "Tomcat started." ] } TASK [start-tomcat : debug] ************************************************* ********************************************************************** task path: /users/demo/vivek-playbook/roles/start-tomcat/tasks/main.yml:10 Tuesday 21 November 2017 13:02:14 +0530 (0:00:00.150) 0:00:09.156 ****** ok: [server1] => { "changed": false, "msg": [ "Start Tomcat task ended with message: {' stderr_lines': [], u'changed': True, u'end': u'2017-11-21 13:02:14.741649', u'stdout': u'Tomcat started.', u'cmd': [u'/users/demo/DEMO/bin/startup.sh'], u'rc': 0, u'start': u'2017-11-21 13:02:14.721625', u'stderr': u'', u'delta': u'0:00:00.020024', 'stdout_lines': [u'Tomcat started.']}", "Tomcat started - True" ] } META: ran handlers META: ran handlers PLAY RECAP ******************************************************************************* ********************************************************* server1 : ok = 9 changed = 4 unreachable = 0 failed = 0 Tuesday 21 November 2017 13:02:14 +0530 (0:00:00.042) 0:00:09.198 ****** =============================================================================== install-tomcat : Install Tomcat artifacts ------------------------------- 6.76s /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:5 -------------- Gathering Facts --------------------------------------------------------- 1.52s ------------------------------------------------------------------------------ install-tomcat : Copy Tomcat to user home ------------------------------- 0.26s /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:37 ------------- install-tomcat : Clean DEMO environment --------------------------------- 0.26s /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:19 ------------- start-tomcat : Start Tomcat --------------------------------------------- 0.15s /users/demo/vivek-playbook/roles/start-tomcat/tasks/main.yml:5 ---------------- install-tomcat : debug -------------------------------------------------- 0.06s /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:11 ------------- install-tomcat : debug -------------------------------------------------- 0.06s /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:29 ------------- install-tomcat : debug -------------------------------------------------- 0.04s /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:47 ------------- start-tomcat : debug ---------------------------------------------------- 0.04s /users/demo/vivek-playbook/roles/start-tomcat/tasks/main.yml:10 --------------- Hit the following URL and you will be directed to a page as shown below βˆ’ http://10.76.0.134:11677/HelloWorld/HelloWorld The deployed war just has a servlet which displays β€œHello World”. The detailed output shows the time taken by each and every task because of the entry added in ansible.cfg file βˆ’ [defaults] callback_whitelist = profile_tasks 41 Lectures 5 hours AR Shankar 11 Lectures 58 mins Musab Zayadneh 59 Lectures 15.5 hours Narendra P 11 Lectures 1 hours Sagar Mehta 39 Lectures 4 hours Vikas Yadav 4 Lectures 3.5 hours GreyCampus Inc. Print Add Notes Bookmark this page
[ { "code": null, "e": 1922, "s": 1791, "text": "Roles provide a framework for fully independent, or interdependent collections of variables, tasks, files, templates, and modules." }, { "code": null, "e": 2185, "s": 1922, "text": "In Ansible, the role is the primary mechanism for breaking a playbook into multiple files. This simplifies writing complex playbooks, and it makes them easier to reuse. The breaking of playbook allows you to logically break the playbook into reusable components." }, { "code": null, "e": 2390, "s": 2185, "text": "Each role is basically limited to a particular functionality or desired output, with all the necessary steps to provide that result either within that role itself or in other roles listed as dependencies." }, { "code": null, "e": 2629, "s": 2390, "text": "Roles are not playbooks. Roles are small functionality which can be independently used but have to be used within playbooks. There is no way to directly execute a role. Roles have no explicit setting for which host the role will apply to." }, { "code": null, "e": 2755, "s": 2629, "text": "Top-level playbooks are the bridge holding the hosts from your inventory file to roles that should be applied to those hosts." }, { "code": null, "e": 2824, "s": 2755, "text": "The directory structure for roles is essential to create a new role." }, { "code": null, "e": 2950, "s": 2824, "text": "Roles have a structured layout on the file system. The default structure can be changed but for now let us stick to defaults." }, { "code": null, "e": 3056, "s": 2950, "text": "Each role is a directory tree in itself. The role name is the directory name within the /roles directory." }, { "code": null, "e": 3078, "s": 3056, "text": "$ ansible-galaxy -h \n" }, { "code": null, "e": 3183, "s": 3078, "text": "ansible-galaxy [delete|import|info|init|install|list|login|remove|search|setup] [--help] [options] ... \n" }, { "code": null, "e": 3229, "s": 3183, "text": "-h, --help βˆ’ Show this help message and exit." }, { "code": null, "e": 3275, "s": 3229, "text": "-h, --help βˆ’ Show this help message and exit." }, { "code": null, "e": 3358, "s": 3275, "text": "-v, --verbose βˆ’ Verbose mode (-vvv for more, -vvvv to enable connection debugging)" }, { "code": null, "e": 3441, "s": 3358, "text": "-v, --verbose βˆ’ Verbose mode (-vvv for more, -vvvv to enable connection debugging)" }, { "code": null, "e": 3493, "s": 3441, "text": "--version βˆ’ Show program's version number and exit." }, { "code": null, "e": 3545, "s": 3493, "text": "--version βˆ’ Show program's version number and exit." }, { "code": null, "e": 3597, "s": 3545, "text": "The above command has created the role directories." }, { "code": null, "e": 4111, "s": 3597, "text": "$ ansible-galaxy init vivekrole \nERROR! The API server (https://galaxy.ansible.com/api/) is not responding, please try again later. \n\n$ ansible-galaxy init --force --offline vivekrole \n- vivekrole was created successfully \n\n$ tree vivekrole/ \nvivekrole/ \nβ”œβ”€β”€ defaults \nβ”‚ └── main.yml \nβ”œβ”€β”€ files β”œβ”€β”€ handlers \nβ”‚ └── main.yml \nβ”œβ”€β”€ meta \nβ”‚ └── main.yml \nβ”œβ”€β”€ README.md β”œβ”€β”€ tasks \nβ”‚ └── main.yml \nβ”œβ”€β”€ templates β”œβ”€β”€ tests β”‚ β”œβ”€β”€ inventory \nβ”‚ └── test.yml \n└── vars \n └── main.yml \n \n8 directories, 8 files" }, { "code": null, "e": 4220, "s": 4111, "text": "Not all the directories will be used in the example and we will show the use of some of them in the example." }, { "code": null, "e": 4438, "s": 4220, "text": "This is the code of the playbook we have written for demo purpose. This code is of the playbook vivek_orchestrate.yml. We have defined the hosts: tomcat-node and called the two roles – install-tomcat and start-tomcat." }, { "code": null, "e": 4532, "s": 4438, "text": "The problem statement is that we have a war which we need to deploy on a machine via Ansible." }, { "code": null, "e": 4623, "s": 4532, "text": "--- \n- hosts: tomcat-node \nroles: \n - {role: install-tomcat} \n - {role: start-tomcat} " }, { "code": null, "e": 4699, "s": 4623, "text": "Contents of our directory structure from where we are running the playbook." }, { "code": null, "e": 4780, "s": 4699, "text": "$ ls \nansible.cfg hosts roles vivek_orchestrate.retry vivek_orchestrate.yml \n" }, { "code": null, "e": 4902, "s": 4780, "text": "There is a tasks directory under each directory and it contains a main.yml. The main.yml contents of install-tomcat are βˆ’" }, { "code": null, "e": 5288, "s": 4902, "text": "--- \n#Install vivek artifacts \n- \n block: \n - name: Install Tomcat artifacts\n action: > \n yum name = \"demo-tomcat-1\" state = present \n register: Output \n \n always: \n - debug: \n msg: \n - \"Install Tomcat artifacts task ended with message: {{Output}}\" \n - \"Installed Tomcat artifacts - {{Output.changed}}\" \n" }, { "code": null, "e": 5339, "s": 5288, "text": "The contents of main.yml of the start tomcat are βˆ’" }, { "code": null, "e": 5666, "s": 5339, "text": "#Start Tomcat \n- \n block: \n - name: Start Tomcat \n command: <path of tomcat>/bin/startup.sh\" \n register: output \n become: true \n \n always: \n - debug: \n msg: \n - \"Start Tomcat task ended with message: {{output}}\" \n - \"Tomcat started - {{output.changed}}\" \n" }, { "code": null, "e": 5809, "s": 5666, "text": "The advantage of breaking the playbook into roles is that anyone who wants to use the Install tomcat feature can call the Install Tomcat role." }, { "code": null, "e": 5966, "s": 5809, "text": "If not for the roles, the content of the main.yml of the respective role can be copied in the playbook yml file. But to have modularity, roles were created." }, { "code": null, "e": 6099, "s": 5966, "text": "Any logical entity which can be reused as a reusable function, that entity can be moved to role. The example for this is shown above" }, { "code": null, "e": 6136, "s": 6099, "text": "Ran the command to run the playbook." }, { "code": null, "e": 6207, "s": 6136, "text": "-vvv option for verbose output – verbose output \n$ cd vivek-playbook/\n" }, { "code": null, "e": 6247, "s": 6207, "text": "This is the command to run the playbook" }, { "code": null, "e": 6448, "s": 6247, "text": "$ sudo ansible-playbook -i hosts vivek_orchestrate.yml –vvv \n-----------------------------------------------------------------\n----------------------------------------------------------------------- \n" }, { "code": null, "e": 6496, "s": 6448, "text": "The generated output is as seen on the screen βˆ’" }, { "code": null, "e": 6557, "s": 6496, "text": "Using /users/demo/vivek-playbook/ansible.cfg as config file." }, { "code": null, "e": 23702, "s": 6557, "text": "PLAYBOOK: vivek_orchestrate.yml *********************************************************\n*********************************************************** \n1 plays in vivek_orchestrate.yml \n\nPLAY [tomcat-node] **********************************************************************\n******** ************************************************* \n \nTASK [Gathering Facts] *************************************************\n****************************** ********************************************* \nTuesday 21 November 2017 13:02:05 +0530 (0:00:00.056) 0:00:00.056 ****** \nUsing module file /usr/lib/python2.7/sitepackages/ansible/modules/system/setup.py \n<localhost> ESTABLISH LOCAL CONNECTION FOR USER: root \n<localhost> EXEC /bin/sh -c 'echo ~ && sleep 0' \n<localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p \"` echo \n /root/.ansible/tmp/ansible-tmp-1511249525.88-259535494116870 `\" && \n echo ansible-tmp-1511249525.88-259535494116870=\"` \n echo /root/.ansible/tmp/ansibletmp-1511249525.88-259535494116870 `\" ) && sleep 0' \n<localhost> PUT /tmp/tmpPEPrkd TO \n /root/.ansible/tmp/ansible-tmp-1511249525.88259535494116870/setup.py \n<localhost> EXEC /bin/sh -c 'chmod u+x \n /root/.ansible/tmp/ansible-tmp1511249525.88-259535494116870/ \n /root/.ansible/tmp/ansible-tmp-1511249525.88259535494116870/setup.py && sleep 0' \n<localhost> EXEC /bin/sh -c '/usr/bin/python \n /root/.ansible/tmp/ansible-tmp1511249525.88-259535494116870/setup.py; rm -rf \n \"/root/.ansible/tmp/ansible-tmp1511249525.88-259535494116870/\" > /dev/null 2>&1 && sleep 0' \nok: [server1] \nMETA: ran handlers \n \nTASK [install-tomcat : Install Tomcat artifacts] ***********************************\n*************************************************************** \ntask path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:5 \nTuesday 21 November 2017 13:02:07 +0530 (0:00:01.515) 0:00:01.572 ****** \nUsing module file /usr/lib/python2.7/sitepackages/ansible/modules/packaging/os/yum.py \n<localhost> ESTABLISH LOCAL CONNECTION FOR USER: root \n<localhost> EXEC /bin/sh -c 'echo ~ && sleep 0' \n<localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p \"` echo \n /root/.ansible/tmp/ansible-tmp-1511249527.34-40247177825302 `\" && echo \n ansibletmp-1511249527.34-40247177825302=\"` echo \n /root/.ansible/tmp/ansible-tmp1511249527.34-40247177825302 `\" ) && sleep 0' \n<localhost> PUT /tmp/tmpu83chg TO \n /root/.ansible/tmp/ansible-tmp-1511249527.3440247177825302/yum.py \n<localhost> EXEC /bin/sh -c 'chmod u+x \n /root/.ansible/tmp/ansible-tmp1511249527.34-40247177825302/ \n /root/.ansible/tmp/ansible-tmp-1511249527.3440247177825302/yum.py && sleep 0' \n<localhost> EXEC /bin/sh -c '/usr/bin/python \n /root/.ansible/tmp/ansible-tmp1511249527.34-40247177825302/yum.py; rm -rf \n \"/root/.ansible/tmp/ansible-tmp1511249527.34-40247177825302/\" > /dev/null 2>\n &1 && sleep 0' \nchanged: [server1] => { \n \"changed\": true, \n \"invocation\": { \n \"module_args\": { \n \"conf_file\": null, \n \"disable_gpg_check\": false, \n \"disablerepo\": null, \n \"enablerepo\": null, \n \"exclude\": null, \n \"install_repoquery\": true, \n \"installroot\": \"/\", \n \"list\": null, \n \"name\": [\"demo-tomcat-1\"], \n \"skip_broken\": false, \n \"state\": \"present\", \n \"update_cache\": false, \n \"validate_certs\": true \n } \n }, \n \"msg\": \"\", \n \"rc\": 0, \n \"results\": [ \n \"Loaded plugins: product-id, \n search-disabled-repos, \n subscriptionmanager\\nThis system is not registered to Red Hat Subscription Management. \n You can use subscription-manager to register.\\nResolving Dependencies\\n--> \n Running transaction check\\n---> \n Package demo-tomcat-1.noarch 0:SNAPSHOT-1 will be installed\\n--> Finished Dependency \n Resolution\\n\\nDependencies Resolved\\n\n \\n================================================================================\\n \n Package Arch Version Repository \n Size\\n==================================================================\\nInstalling:\\n \n demo-tomcat-1 noarch SNAPSHOT-1 demo-repo1 7.1 M\\n\\nTransaction \n Summary\\n==================================================================\\nInstall 1 \n Package\\n\\nTotal download size: 7.1 M\\nInstalled size: 7.9 M\\nDownloading \n packages:\\nRunning transaction \n check\\nRunning transaction test\\nTransaction test succeeded\\nRunning transaction\\n Installing : \n demotomcat-1-SNAPSHOT-1.noarch 1/1 \\n Verifying : \n demo-tomcat-1-SNAPSHOT-1.noarch 1/1 \\n\\nInstalled:\\n \n demo-tomcat-1.noarch 0:SNAPSHOT-1 \\n\\nComplete!\\n\" \n ] \n} \n \nTASK [install-tomcat : debug] **********************************************************\n*************************************************************************** \ntask path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:11 \nTuesday 21 November 2017 13:02:13 +0530 (0:00:06.757) 0:00:08.329 ****** \nok: [server1] => { \n \"changed\": false, \n \"msg\": [ \n \"Install Tomcat artifacts task ended with message: {\n u'msg': u'', u'changed': True, u'results': \n [u'Loaded plugins: product-id, \n search-disabledrepos, \n subscription-manager\\\\nThis system is not registered to Red Hat Subscription Management. \n You can use subscription-manager to register.\\\\nResolving Dependencies\\\\n--> \n Running transaction check\\\\n---> \n Package demo-tomcat-1.noarch 0:SNAPSHOT-1 will be installed\\\\n--> \n Finished Dependency Resolution\\\\n\n \\\\nDependencies \n Resolved\\\\n\\\\n==================================================================\\\\n \n Package Arch Version Repository \n Size\\\\n======================================================================== \n =====\\\\nInstalling:\\\\n demo-tomcat-1 noarch SNAPSHOT-1 demo-repo1 7.1 M\\\\n\\\\nTransaction \n Summary\\\\n=========================================================\\\\nInstall 1 \n Package\\\\n\\\\nTotal download size: 7.1 M\\\\nInstalled size: 7.9 M\\\\nDownloading \n packages:\\\\nRunning \n transaction check\\\\nRunning transaction test\\\\nTransaction test succeeded\\\\nRunning \n transaction\\\\n \n Installing : demo-tomcat-1-SNAPSHOT-1.noarch 1/1 \\\\n Verifying : \n demo-tomcat-1-SNAPSHOT-1.noarch\n 1/1 \\\\n\\\\nInstalled:\\\\n demo-tomcat-1.noarch 0:SNAPSHOT-1 \\\\n\\\\nComplete!\\\\n'], u'rc': 0\n }\", \n \"Installed Tomcat artifacts - True\" \n ] \n} \n \nTASK [install-tomcat : Clean DEMO environment] ****************************************\n************************************************************ \ntask path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:19 \nTuesday 21 November 2017 13:02:13 +0530 (0:00:00.057) 0:00:08.387 ****** \n[WARNING]: when statements should not include jinja2 templating delimiters such as {{ }} or \n {% %}. Found: {{installationOutput.changed}} \n \nUsing module file /usr/lib/python2.7/sitepackages/ansible/modules/files/file.py \n<localhost> ESTABLISH LOCAL CONNECTION FOR USER: root \n<localhost> EXEC /bin/sh -c 'echo ~ && sleep 0' \n<localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p \"` echo \n /root/.ansible/tmp/ansible-tmp-1511249534.13-128345805983963 `\" && echo \n ansible-tmp-1511249534.13-128345805983963=\"` echo \n /root/.ansible/tmp/ansibletmp-1511249534.13-128345805983963 `\" ) && sleep 0' \n<localhost> PUT /tmp/tmp0aXel7 TO \n /root/.ansible/tmp/ansible-tmp-1511249534.13128345805983963/file.py \n<localhost> EXEC /bin/sh -c 'chmod u+x \n /root/.ansible/tmp/ansible-tmp1511249534.13-128345805983963/ \n /root/.ansible/tmp/ansible-tmp-1511249534.13128345805983963/file.py && sleep 0' \n<localhost> EXEC /bin/sh -c '/usr/bin/python \n /root/.ansible/tmp/ansible-tmp1511249534.13-128345805983963/file.py; rm -rf \n \"/root/.ansible/tmp/ansible-tmp1511249534.13-128345805983963/\" > /dev/null 2>&1 \n && sleep 0' \nchanged: [server1] => { \n \"changed\": true, \n \"diff\": { \n \"after\": { \n \"path\": \"/users/demo/DEMO\", \n \"state\": \"absent\" \n }, \n \"before\": { \n \"path\": \"/users/demo/DEMO\", \n \"state\": \"directory\" \n } \n },\n\n \"invocation\": { \n \"module_args\": { \n \"attributes\": null, \n \"backup\": null, \n \"content\": null, \n \"delimiter\": null, \n \"diff_peek\": null, \n \"directory_mode\": null, \n \"follow\": false, \n \"force\": false, \n \"group\": null, \n \"mode\": null, \n \"original_basename\": null, \n \"owner\": null, \n \"path\": \"/users/demo/DEMO\", \n \"recurse\": false, \n \"regexp\": null, \n \"remote_src\": null, \n \"selevel\": null, \n \"serole\": null, \n \"setype\": null, \n \"seuser\": null, \n \"src\": null, \n \"state\": \"absent\", \n \"unsafe_writes\": null, \n \"validate\": null \n } \n }, \n \"path\": \"/users/demo/DEMO\", \n \"state\": \"absent\" \n} \n \nTASK [install-tomcat : debug] ********************************************************\n************************************************************* \ntask path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:29 \nTuesday 21 November 2017 13:02:14 +0530 (0:00:00.257) 0:00:08.645 ****** \nok: [server1] => {\n \"changed\": false, \n \"msg\": [ \n \"Clean DEMO environment task ended with message:{u'diff': {u'after': {u'path': \n u'/users/demo/DEMO', u'state': u'absent'}, \n u'before': {u'path': u'/users/demo/DEMO', u'state': u'directory'}}, u'state': u'absent', \n u'changed': True, u'path': u'/users/demo/DEMO'}\", \n \"check value :True\" \n ] \n} \n \nTASK [install-tomcat : Copy Tomcat to user home] *************************************\n******************************************************** \ntask path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:37 \nTuesday 21 November 2017 13:02:14 +0530 (0:00:00.055) 0:00:08.701 ****** \n[WARNING]: when statements should not include jinja2 templating delimiters such as {{ }} or \n {% %}. Found: {{installationOutput.changed}} \n \nUsing module file /usr/lib/python2.7/sitepackages/ansible/modules/commands/command.py \n<localhost> ESTABLISH LOCAL CONNECTION FOR USER: root \n<localhost> EXEC /bin/sh -c 'echo ~ && sleep 0' \n<localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p \"` echo \n /root/.ansible/tmp/ansible-tmp-1511249534.43-41077200718443 `\" && echo \n ansibletmp-1511249534.43-41077200718443=\"` echo \n /root/.ansible/tmp/ansible-tmp1511249534.43-41077200718443 `\" ) && sleep 0' \n<localhost> PUT /tmp/tmp25deWs TO \n /root/.ansible/tmp/ansible-tmp-1511249534.4341077200718443/command.py \n<localhost> EXEC /bin/sh -c 'chmod u+x \n /root/.ansible/tmp/ansible-tmp1511249534.43-41077200718443/ \n /root/.ansible/tmp/ansible-tmp-1511249534.4341077200718443/command.py && sleep 0' \n<localhost> EXEC /bin/sh -c '/usr/bin/python \n /root/.ansible/tmp/ansible-tmp1511249534.43-41077200718443/command.py; rm -rf \n \"/root/.ansible/tmp/ansibletmp-1511249534.43-41077200718443/\" > /dev/null 2>&1 \n && sleep 0' \nchanged: [server1] => { \n \"changed\": true, \n \"cmd\": [ \n \"cp\", \n \"-r\", \n \"/opt/ansible/tomcat/demo\", \n \"/users/demo/DEMO/\" \n ],\n \"delta\": \"0:00:00.017923\", \n \"end\": \"2017-11-21 13:02:14.547633\", \n \"invocation\": { \n \"module_args\": { \n \"_raw_params\": \"cp -r /opt/ansible/tomcat/demo /users/demo/DEMO/\", \n \"_uses_shell\": false, \n \"chdir\": null, \n \"creates\": null, \n \"executable\": null, \n \"removes\": null, \n \"warn\": true \n } \n }, \n \"rc\": 0, \n \"start\": \"2017-11-21 13:02:14.529710\", \n \"stderr\": \"\", \n \"stderr_lines\": [], \n \"stdout\": \"\", \n \"stdout_lines\": [] \n} \n \nTASK [install-tomcat : debug] ********************************************************\n********************************************************** \ntask path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:47 \nTuesday 21 November 2017 13:02:14 +0530 (0:00:00.260) 0:00:08.961 ****** \nok: [server1] => { \n \"changed\": false, \n \"msg\": \"Copy Tomcat to user home task ended with message {\n 'stderr_lines': [], u'changed': True, u'end': u'2017-11-21 13:02:14.547633', u'stdout': \n u'', u'cmd': [u'cp', u'-r', u'/opt/ansible/tomcat/demo', u'/users/demo/DEMO/'], u'rc': 0, \n u'start': u'2017-11-21 13:02:14.529710', u'stderr': u'', u'delta': u'0:00:00.017923', \n 'stdout_lines': []}\" \n} \n \nTASK [start-tomcat : Start Tomcat] **************************************************\n********************************************************** \ntask path: /users/demo/vivek-playbook/roles/start-tomcat/tasks/main.yml:5 \nTuesday 21 November 2017 13:02:14 +0530 (0:00:00.044) 0:00:09.006 ****** \nUsing module file /usr/lib/python2.7/sitepackages/ansible/modules/commands/command.py \n<localhost> ESTABLISH LOCAL CONNECTION FOR USER: root \n<localhost> EXEC /bin/sh -c 'echo ~ && sleep 0' \n<localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p \"` echo \n /root/.ansible/tmp/ansible-tmp-1511249534.63-46501211251197 `\" && echo \n ansibletmp-1511249534.63-46501211251197=\"` echo \n /root/.ansible/tmp/ansible-tmp1511249534.63-46501211251197 `\" ) && sleep 0' \n<localhost> PUT /tmp/tmp9f06MQ TO \n /root/.ansible/tmp/ansible-tmp-1511249534.6346501211251197/command.py \n<localhost> EXEC /bin/sh -c 'chmod u+x \n /root/.ansible/tmp/ansible-tmp1511249534.63-46501211251197/ \n /root/.ansible/tmp/ansible-tmp-1511249534.6346501211251197/command.py && sleep 0' \n<localhost> EXEC /bin/sh -c '/usr/bin/python \n /root/.ansible/tmp/ansible-tmp1511249534.63-46501211251197/command.py; rm -rf \n \"/root/.ansible/tmp/ansibletmp-1511249534.63-46501211251197/\" > /dev/null 2>&1 \n && sleep 0' \nchanged: [server1] => { \n \"changed\": true, \n \"cmd\": [ \"/users/demo/DEMO/bin/startup.sh\" ], \n \"delta\": \"0:00:00.020024\", \n \"end\": \"2017-11-21 13:02:14.741649\", \n \"invocation\": { \n \"module_args\": { \n \"_raw_params\": \"/users/demo/DEMO/bin/startup.sh\", \n \"_uses_shell\": false, \n \"chdir\": null, \n \"creates\": null, \n \"executable\": null, \n \"removes\": null, \n \"warn\": true \n } \n }, \n \"rc\": 0, \n \"start\": \"2017-11-21 13:02:14.721625\", \n \"stderr\": \"\", \n \"stderr_lines\": [], \n \"stdout\": \"Tomcat started.\", \n \"stdout_lines\": [ \"Tomcat started.\" ] \n} \n \nTASK [start-tomcat : debug] *************************************************\n********************************************************************** \ntask path: /users/demo/vivek-playbook/roles/start-tomcat/tasks/main.yml:10 \nTuesday 21 November 2017 13:02:14 +0530 (0:00:00.150) 0:00:09.156 ****** \nok: [server1] => { \n \"changed\": false, \n \"msg\": [ \n \"Start Tomcat task ended with message: {'\n stderr_lines': [], u'changed': True, u'end': u'2017-11-21 13:02:14.741649', u'stdout': \n u'Tomcat started.', u'cmd': [u'/users/demo/DEMO/bin/startup.sh'], u'rc': 0, u'start': \n u'2017-11-21 13:02:14.721625', u'stderr': u'', u'delta': u'0:00:00.020024', \n 'stdout_lines': [u'Tomcat started.']}\", \n \"Tomcat started - True\" \n ] \n} \nMETA: ran handlers \nMETA: ran handlers \n \nPLAY RECAP ******************************************************************************* \n********************************************************* \nserver1 : ok = 9 changed = 4 unreachable = 0 failed = 0 \n \nTuesday 21 November 2017 13:02:14 +0530 (0:00:00.042) 0:00:09.198 ****** \n=============================================================================== \ninstall-tomcat : Install Tomcat artifacts ------------------------------- 6.76s \n/users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:5 -------------- \nGathering Facts --------------------------------------------------------- 1.52s \n ------------------------------------------------------------------------------ \ninstall-tomcat : Copy Tomcat to user home ------------------------------- 0.26s \n/users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:37 ------------- \n\ninstall-tomcat : Clean DEMO environment --------------------------------- 0.26s \n/users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:19 ------------- \n\nstart-tomcat : Start Tomcat --------------------------------------------- 0.15s \n/users/demo/vivek-playbook/roles/start-tomcat/tasks/main.yml:5 ----------------\n\ninstall-tomcat : debug -------------------------------------------------- 0.06s \n/users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:11 ------------- \n\ninstall-tomcat : debug -------------------------------------------------- 0.06s \n/users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:29 ------------- \n\ninstall-tomcat : debug -------------------------------------------------- 0.04s \n/users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:47 ------------- \n\nstart-tomcat : debug ---------------------------------------------------- 0.04s \n/users/demo/vivek-playbook/roles/start-tomcat/tasks/main.yml:10 --------------- \n" }, { "code": null, "e": 23824, "s": 23702, "text": "Hit the following URL and you will be directed to a page as shown below βˆ’ http://10.76.0.134:11677/HelloWorld/HelloWorld" }, { "code": null, "e": 24003, "s": 23824, "text": "The deployed war just has a servlet which displays β€œHello World”. The detailed output shows the time taken by each and every task because of the entry added in ansible.cfg file βˆ’" }, { "code": null, "e": 24052, "s": 24003, "text": "[defaults] \ncallback_whitelist = profile_tasks \n" }, { "code": null, "e": 24085, "s": 24052, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 24097, "s": 24085, "text": " AR Shankar" }, { "code": null, "e": 24129, "s": 24097, "text": "\n 11 Lectures \n 58 mins\n" }, { "code": null, "e": 24145, "s": 24129, "text": " Musab Zayadneh" }, { "code": null, "e": 24181, "s": 24145, "text": "\n 59 Lectures \n 15.5 hours \n" }, { "code": null, "e": 24193, "s": 24181, "text": " Narendra P" }, { "code": null, "e": 24226, "s": 24193, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 24239, "s": 24226, "text": " Sagar Mehta" }, { "code": null, "e": 24272, "s": 24239, "text": "\n 39 Lectures \n 4 hours \n" }, { "code": null, "e": 24285, "s": 24272, "text": " Vikas Yadav" }, { "code": null, "e": 24319, "s": 24285, "text": "\n 4 Lectures \n 3.5 hours \n" }, { "code": null, "e": 24336, "s": 24319, "text": " GreyCampus Inc." }, { "code": null, "e": 24343, "s": 24336, "text": " Print" }, { "code": null, "e": 24354, "s": 24343, "text": " Add Notes" } ]
Program to Print Alphabets from A to Z Using Loop - GeeksforGeeks
16 Jun, 2021 The task is to print the alphabets from A to Z using a loop. In the below program, for loop is used to print the alphabets from A to Z. A loop variable is taken to do this of type β€˜char’. The loop variable β€˜i’ is initialized with the first alphabet β€˜A’ and incremented by 1 on every iteration. In the loop, this character β€˜i’ is printed as the alphabet. Program: C++14 C Java Python3 C# Javascript // C++ program to find the print// Alphabets from A to Z#include <bits/stdc++.h>using namespace std; int main(){ // Declare the variables char i; // Display the alphabets cout << "The Alphabets from A to Z are: \n"; // Traverse each character // with the help of for loop for (i = 'A'; i <= 'Z'; i++) { // Print the alphabet cout << i <<" "; } return 0;} // This code is contributed by// Shubhamsingh10 // C program to find the print// Alphabets from A to Z #include <stdio.h> int main(){ // Declare the variables char i; // Display the alphabets printf("The Alphabets from A to Z are: \n"); // Traverse each character // with the help of for loop for (i = 'A'; i <= 'Z'; i++) { // Print the alphabet printf("%c ", i); } return 0;} // Java program to find the print// Alphabets from A to Zclass GFG{ public static void main(String[] args) { // Declare the variables char i; // Display the alphabets System.out.printf("The Alphabets from A to Z are: \n"); // Traverse each character // with the help of for loop for (i = 'A'; i <= 'Z'; i++) { // Print the alphabet System.out.printf("%c ", i); } }} /* This code contributed by PrinciRaj1992 */ # Python3 program to find the print# Alphabets from A to Z if __name__ == '__main__': # Declare the variables i = chr; # Display the alphabets print("The Alphabets from A to Z are: "); # Traverse each character # with the help of for loop for i in range(ord('A'), ord('Z') + 1): # Print the alphabet print(chr(i), end=" "); # This code is contributed by Rajput-Ji // C# program to find the print// Alphabets from A to Zusing System; class GFG{ public static void Main(String[] args) { // Declare the variables char i; // Display the alphabets Console.Write("The Alphabets from A to Z are: \n"); // Traverse each character // with the help of for loop for (i = 'A'; i <= 'Z'; i++) { // Print the alphabet Console.Write("{0} ", i); } }} // This code is contributed by Rajput-Ji <script> // Javascript program to find the print// Alphabets from A to Z // Declare the variableslet i; // Display the alphabetsdocument.write("The Alphabets from A" + " to Z are: " + "</br>"); // Traverse each character// with the help of for loopfor(i = 'A'.charCodeAt(); i <= 'Z'.charCodeAt(); i++){ // Print the alphabet document.write( String.fromCharCode(i) + " ");} // This code is contributed by decode2207 </script> Output: The Alphabets from A to Z are: 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 princiraj1992 Rajput-Ji SHUBHAMSINGH10 Code_Mech decode2207 school-programming C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C Program to read contents of Whole File Header files in C/C++ and its uses How to return multiple values from a function in C or C++? How to Append a Character to a String in C Program to print ASCII Value of a character C program to sort an array in ascending order time() function in C Flex (Fast Lexical Analyzer Generator ) C Program to Swap two Numbers Producer Consumer Problem in C
[ { "code": null, "e": 24148, "s": 24120, "text": "\n16 Jun, 2021" }, { "code": null, "e": 24209, "s": 24148, "text": "The task is to print the alphabets from A to Z using a loop." }, { "code": null, "e": 24502, "s": 24209, "text": "In the below program, for loop is used to print the alphabets from A to Z. A loop variable is taken to do this of type β€˜char’. The loop variable β€˜i’ is initialized with the first alphabet β€˜A’ and incremented by 1 on every iteration. In the loop, this character β€˜i’ is printed as the alphabet." }, { "code": null, "e": 24512, "s": 24502, "text": "Program: " }, { "code": null, "e": 24518, "s": 24512, "text": "C++14" }, { "code": null, "e": 24520, "s": 24518, "text": "C" }, { "code": null, "e": 24525, "s": 24520, "text": "Java" }, { "code": null, "e": 24533, "s": 24525, "text": "Python3" }, { "code": null, "e": 24536, "s": 24533, "text": "C#" }, { "code": null, "e": 24547, "s": 24536, "text": "Javascript" }, { "code": "// C++ program to find the print// Alphabets from A to Z#include <bits/stdc++.h>using namespace std; int main(){ // Declare the variables char i; // Display the alphabets cout << \"The Alphabets from A to Z are: \\n\"; // Traverse each character // with the help of for loop for (i = 'A'; i <= 'Z'; i++) { // Print the alphabet cout << i <<\" \"; } return 0;} // This code is contributed by// Shubhamsingh10", "e": 24998, "s": 24547, "text": null }, { "code": "// C program to find the print// Alphabets from A to Z #include <stdio.h> int main(){ // Declare the variables char i; // Display the alphabets printf(\"The Alphabets from A to Z are: \\n\"); // Traverse each character // with the help of for loop for (i = 'A'; i <= 'Z'; i++) { // Print the alphabet printf(\"%c \", i); } return 0;}", "e": 25372, "s": 24998, "text": null }, { "code": "// Java program to find the print// Alphabets from A to Zclass GFG{ public static void main(String[] args) { // Declare the variables char i; // Display the alphabets System.out.printf(\"The Alphabets from A to Z are: \\n\"); // Traverse each character // with the help of for loop for (i = 'A'; i <= 'Z'; i++) { // Print the alphabet System.out.printf(\"%c \", i); } }} /* This code contributed by PrinciRaj1992 */", "e": 25882, "s": 25372, "text": null }, { "code": "# Python3 program to find the print# Alphabets from A to Z if __name__ == '__main__': # Declare the variables i = chr; # Display the alphabets print(\"The Alphabets from A to Z are: \"); # Traverse each character # with the help of for loop for i in range(ord('A'), ord('Z') + 1): # Print the alphabet print(chr(i), end=\" \"); # This code is contributed by Rajput-Ji", "e": 26297, "s": 25882, "text": null }, { "code": "// C# program to find the print// Alphabets from A to Zusing System; class GFG{ public static void Main(String[] args) { // Declare the variables char i; // Display the alphabets Console.Write(\"The Alphabets from A to Z are: \\n\"); // Traverse each character // with the help of for loop for (i = 'A'; i <= 'Z'; i++) { // Print the alphabet Console.Write(\"{0} \", i); } }} // This code is contributed by Rajput-Ji", "e": 26808, "s": 26297, "text": null }, { "code": "<script> // Javascript program to find the print// Alphabets from A to Z // Declare the variableslet i; // Display the alphabetsdocument.write(\"The Alphabets from A\" + \" to Z are: \" + \"</br>\"); // Traverse each character// with the help of for loopfor(i = 'A'.charCodeAt(); i <= 'Z'.charCodeAt(); i++){ // Print the alphabet document.write( String.fromCharCode(i) + \" \");} // This code is contributed by decode2207 </script>", "e": 27269, "s": 26808, "text": null }, { "code": null, "e": 27278, "s": 27269, "text": "Output: " }, { "code": null, "e": 27363, "s": 27278, "text": "The Alphabets from A to Z are: \nA 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 " }, { "code": null, "e": 27379, "s": 27365, "text": "princiraj1992" }, { "code": null, "e": 27389, "s": 27379, "text": "Rajput-Ji" }, { "code": null, "e": 27404, "s": 27389, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 27414, "s": 27404, "text": "Code_Mech" }, { "code": null, "e": 27425, "s": 27414, "text": "decode2207" }, { "code": null, "e": 27444, "s": 27425, "text": "school-programming" }, { "code": null, "e": 27455, "s": 27444, "text": "C Programs" }, { "code": null, "e": 27553, "s": 27455, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27562, "s": 27553, "text": "Comments" }, { "code": null, "e": 27575, "s": 27562, "text": "Old Comments" }, { "code": null, "e": 27616, "s": 27575, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 27651, "s": 27616, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 27710, "s": 27651, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 27753, "s": 27710, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 27797, "s": 27753, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 27843, "s": 27797, "text": "C program to sort an array in ascending order" }, { "code": null, "e": 27864, "s": 27843, "text": "time() function in C" }, { "code": null, "e": 27904, "s": 27864, "text": "Flex (Fast Lexical Analyzer Generator )" }, { "code": null, "e": 27934, "s": 27904, "text": "C Program to Swap two Numbers" } ]