title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Introduction to Complex Objects and Composition - GeeksforGeeks
|
29 Jul, 2021
An object is a basic unit of Object-Oriented Programming and represents the real-life entities. Complex objects are the objects that are built from smaller or a collection of objects. For example, a mobile phone is made up of various objects like a camera, battery, screen, sensors, etc. In this article, we will understand the use and implementation of a complex object. In object-oriented programming languages, object composition is used for objects that have a βhas-aβ relationship with each other. For example, a mobile has-a battery, has-a sensor, has-a screen, etc. Therefore, the complex object is called the whole or a parent object whereas a simpler object is often referred to as a child object. In this case, all the objects or components are the child objects which together make up the complex object(mobile).
Classes that have data members of built-in type work really well for simple classes. However, in real-world programming, the product or software comprises of many different smaller objects and classes. In the above example, the mobile phone consisted of various different objects that on a whole made up a complete mobile phone. Since each of those objects performs a different task, they all are maintained in different classes. Therefore, this concept of complex objects is being used in most of the real-world scenarios. The advantages of using this concept are:
Each individual class can be simple and straightforward.
One class can focus on performing one specific task and obtain one behavior.
The class is easier to write, debug, understand, and usable by other programmers.
While simpler classes can perform all the operations, the complex class can be designed to coordinate the data flow between the simpler classes.
It lowers the overall complexity of the complex object because the main, task of the complex object would then be to delegate tasks to the sub-objects, who already know how to do them.
The most important advantage is if any changes have to be made in a child class, only the child class can be changed rather than changing the entire parent class.
For example, if we want to change the battery class in the mobile object, with the help of composition, the changes are only made in the battery class and the entire mobile object works fine with the updated changes.
Scope of Use: Although there are no well-defined rules to state when a programmer must use the composition, as a rule of thumb, each class should be built to accomplish a single task. The task should be to either perform some part of manipulation or be responsible for coordinating other classes but cannot perform both tasks. This immensely increases the maintenance of the code and future updations because, when we wish to update a feature or an object, only the class pertaining to that specific functionality needs to be updated. And also, itβs very easy to keep track of the errors in the program. For example:
C++
// C++ program to implement a// composition // A point classclass Point {private: int x; int y;}; // Every location has a point.// Every point has two coordinates.// The above class's functionality// is only to store the coordinates// in two variables. Any functionality// using the points is implemented// hereclass Location { Private : Point Source; Point Destination};
In the classes given here, Location uses objects of class Point as its data members. Hence, Location is a complex class which uses a simple class Point. Let us have a look at the program that makes use of the composition.
Below is the implementation of a composite class:
C++
// C++ program to implement a// composite classusing namespace std;#include <iostream> // Class with a private parameter// and the getters and settersclass One { // Private parameterprivate: int num; // Public setter and getterpublic: void set(int i) { num = i; } int get() { return num; }}; // Another classclass Two { // Public method and the object // of the previous classpublic: One O; void show() { cout << "\n Number = " << O.get(); }}; // Driver codeint main(){ // Creating the object of // class Two Two T; // Perform some operation using // the object of One in this class T.O.set(100); T.show();}
Number = 100
Explanation: Note that in the program, class Two has an object of class One. To access a member of One, we must use the object of Two as in T.O.set(100). Moreover, since num is a private member of One, we must use a public function to access its value.
ruhelaa48
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Queue in C++ Standard Template Library (STL)
Inline Functions in C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
|
[
{
"code": null,
"e": 25343,
"s": 25315,
"text": "\n29 Jul, 2021"
},
{
"code": null,
"e": 26168,
"s": 25343,
"text": "An object is a basic unit of Object-Oriented Programming and represents the real-life entities. Complex objects are the objects that are built from smaller or a collection of objects. For example, a mobile phone is made up of various objects like a camera, battery, screen, sensors, etc. In this article, we will understand the use and implementation of a complex object. In object-oriented programming languages, object composition is used for objects that have a βhas-aβ relationship with each other. For example, a mobile has-a battery, has-a sensor, has-a screen, etc. Therefore, the complex object is called the whole or a parent object whereas a simpler object is often referred to as a child object. In this case, all the objects or components are the child objects which together make up the complex object(mobile). "
},
{
"code": null,
"e": 26735,
"s": 26168,
"text": "Classes that have data members of built-in type work really well for simple classes. However, in real-world programming, the product or software comprises of many different smaller objects and classes. In the above example, the mobile phone consisted of various different objects that on a whole made up a complete mobile phone. Since each of those objects performs a different task, they all are maintained in different classes. Therefore, this concept of complex objects is being used in most of the real-world scenarios. The advantages of using this concept are: "
},
{
"code": null,
"e": 26792,
"s": 26735,
"text": "Each individual class can be simple and straightforward."
},
{
"code": null,
"e": 26869,
"s": 26792,
"text": "One class can focus on performing one specific task and obtain one behavior."
},
{
"code": null,
"e": 26951,
"s": 26869,
"text": "The class is easier to write, debug, understand, and usable by other programmers."
},
{
"code": null,
"e": 27096,
"s": 26951,
"text": "While simpler classes can perform all the operations, the complex class can be designed to coordinate the data flow between the simpler classes."
},
{
"code": null,
"e": 27281,
"s": 27096,
"text": "It lowers the overall complexity of the complex object because the main, task of the complex object would then be to delegate tasks to the sub-objects, who already know how to do them."
},
{
"code": null,
"e": 27444,
"s": 27281,
"text": "The most important advantage is if any changes have to be made in a child class, only the child class can be changed rather than changing the entire parent class."
},
{
"code": null,
"e": 27661,
"s": 27444,
"text": "For example, if we want to change the battery class in the mobile object, with the help of composition, the changes are only made in the battery class and the entire mobile object works fine with the updated changes."
},
{
"code": null,
"e": 28278,
"s": 27661,
"text": "Scope of Use: Although there are no well-defined rules to state when a programmer must use the composition, as a rule of thumb, each class should be built to accomplish a single task. The task should be to either perform some part of manipulation or be responsible for coordinating other classes but cannot perform both tasks. This immensely increases the maintenance of the code and future updations because, when we wish to update a feature or an object, only the class pertaining to that specific functionality needs to be updated. And also, itβs very easy to keep track of the errors in the program. For example:"
},
{
"code": null,
"e": 28282,
"s": 28278,
"text": "C++"
},
{
"code": "// C++ program to implement a// composition // A point classclass Point {private: int x; int y;}; // Every location has a point.// Every point has two coordinates.// The above class's functionality// is only to store the coordinates// in two variables. Any functionality// using the points is implemented// hereclass Location { Private : Point Source; Point Destination};",
"e": 28666,
"s": 28282,
"text": null
},
{
"code": null,
"e": 28888,
"s": 28666,
"text": "In the classes given here, Location uses objects of class Point as its data members. Hence, Location is a complex class which uses a simple class Point. Let us have a look at the program that makes use of the composition."
},
{
"code": null,
"e": 28938,
"s": 28888,
"text": "Below is the implementation of a composite class:"
},
{
"code": null,
"e": 28942,
"s": 28938,
"text": "C++"
},
{
"code": "// C++ program to implement a// composite classusing namespace std;#include <iostream> // Class with a private parameter// and the getters and settersclass One { // Private parameterprivate: int num; // Public setter and getterpublic: void set(int i) { num = i; } int get() { return num; }}; // Another classclass Two { // Public method and the object // of the previous classpublic: One O; void show() { cout << \"\\n Number = \" << O.get(); }}; // Driver codeint main(){ // Creating the object of // class Two Two T; // Perform some operation using // the object of One in this class T.O.set(100); T.show();}",
"e": 29653,
"s": 28942,
"text": null
},
{
"code": null,
"e": 29666,
"s": 29653,
"text": "Number = 100"
},
{
"code": null,
"e": 29922,
"s": 29668,
"text": "Explanation: Note that in the program, class Two has an object of class One. To access a member of One, we must use the object of Two as in T.O.set(100). Moreover, since num is a private member of One, we must use a public function to access its value. "
},
{
"code": null,
"e": 29932,
"s": 29922,
"text": "ruhelaa48"
},
{
"code": null,
"e": 29936,
"s": 29932,
"text": "C++"
},
{
"code": null,
"e": 29940,
"s": 29936,
"text": "CPP"
},
{
"code": null,
"e": 30038,
"s": 29940,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30066,
"s": 30038,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 30086,
"s": 30066,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 30110,
"s": 30086,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 30143,
"s": 30110,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 30187,
"s": 30143,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 30212,
"s": 30187,
"text": "std::string class in C++"
},
{
"code": null,
"e": 30257,
"s": 30212,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 30281,
"s": 30257,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 30334,
"s": 30281,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
}
] |
Python | Get first index values in tuple of strings
|
01 May, 2019
Yet another peculiar problem which might not be common, but can occur in python programming while playing with tuples. Since tuples are immutable, they are difficult to manipulate and hence knowledge of possible variation solutions always helps. This articles solves problem of extracting only the first index element of each string in tuple. Letβs discuss certain ways in which this problem can be solved.
Method #1 : Using list comprehension
Almost every problem can be solved using list comprehension as a shorthand to naive approach and this problem isnβt an exception. In this, we just iterate through each list picking just the 0th index element to build the resultant list.
# Python3 code to demonstrate# Get first index values in tuple of strings# using list comprehension # initializing tupletest_tuple = ('GfG', 'for', 'Geeks') # printing original tuple print("The original tuple : " + str(test_tuple)) # using list comprehsion# Get first index values in tuple of stringsres = list(sub[0] for sub in test_tuple) # print resultprint("The first index string character list : " + str(res))
The original tuple : ('GfG', 'for', 'Geeks')
The first index string character list : ['G', 'f', 'G']
Method #2 : Using next() + zip()
This particular task can also be performed using the combination of above two in more efficient way, using the iterators to do this task. The zip function can be used bind together the string elements.
# Python3 code to demonstrate# Get first index values in tuple of strings# using next() + zip() # initializing tupletest_tuple = ('GfG', 'for', 'Geeks') # printing original tuple print("The original tuple : " + str(test_tuple)) # using next() + zip()# Get first index values in tuple of stringsres = list(next(zip(*test_tuple))) # print resultprint("The first index string character list : " + str(res))
The original tuple : ('GfG', 'for', 'Geeks')
The first index string character list : ['G', 'f', 'G']
Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Split string into list of characters
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 May, 2019"
},
{
"code": null,
"e": 435,
"s": 28,
"text": "Yet another peculiar problem which might not be common, but can occur in python programming while playing with tuples. Since tuples are immutable, they are difficult to manipulate and hence knowledge of possible variation solutions always helps. This articles solves problem of extracting only the first index element of each string in tuple. Letβs discuss certain ways in which this problem can be solved."
},
{
"code": null,
"e": 472,
"s": 435,
"text": "Method #1 : Using list comprehension"
},
{
"code": null,
"e": 709,
"s": 472,
"text": "Almost every problem can be solved using list comprehension as a shorthand to naive approach and this problem isnβt an exception. In this, we just iterate through each list picking just the 0th index element to build the resultant list."
},
{
"code": "# Python3 code to demonstrate# Get first index values in tuple of strings# using list comprehension # initializing tupletest_tuple = ('GfG', 'for', 'Geeks') # printing original tuple print(\"The original tuple : \" + str(test_tuple)) # using list comprehsion# Get first index values in tuple of stringsres = list(sub[0] for sub in test_tuple) # print resultprint(\"The first index string character list : \" + str(res))",
"e": 1129,
"s": 709,
"text": null
},
{
"code": null,
"e": 1231,
"s": 1129,
"text": "The original tuple : ('GfG', 'for', 'Geeks')\nThe first index string character list : ['G', 'f', 'G']\n"
},
{
"code": null,
"e": 1266,
"s": 1233,
"text": "Method #2 : Using next() + zip()"
},
{
"code": null,
"e": 1468,
"s": 1266,
"text": "This particular task can also be performed using the combination of above two in more efficient way, using the iterators to do this task. The zip function can be used bind together the string elements."
},
{
"code": "# Python3 code to demonstrate# Get first index values in tuple of strings# using next() + zip() # initializing tupletest_tuple = ('GfG', 'for', 'Geeks') # printing original tuple print(\"The original tuple : \" + str(test_tuple)) # using next() + zip()# Get first index values in tuple of stringsres = list(next(zip(*test_tuple))) # print resultprint(\"The first index string character list : \" + str(res))",
"e": 1876,
"s": 1468,
"text": null
},
{
"code": null,
"e": 1978,
"s": 1876,
"text": "The original tuple : ('GfG', 'for', 'Geeks')\nThe first index string character list : ['G', 'f', 'G']\n"
},
{
"code": null,
"e": 1999,
"s": 1978,
"text": "Python list-programs"
},
{
"code": null,
"e": 2022,
"s": 1999,
"text": "Python string-programs"
},
{
"code": null,
"e": 2029,
"s": 2022,
"text": "Python"
},
{
"code": null,
"e": 2045,
"s": 2029,
"text": "Python Programs"
},
{
"code": null,
"e": 2143,
"s": 2045,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2175,
"s": 2143,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2202,
"s": 2175,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2223,
"s": 2202,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2246,
"s": 2223,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2302,
"s": 2246,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2324,
"s": 2302,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2363,
"s": 2324,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2401,
"s": 2363,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2438,
"s": 2401,
"text": "Python Program for Fibonacci numbers"
}
] |
jQuery | append() Method
|
19 Feb, 2019
This append() Method in jQuery is used to insert some content at the end of the selected elements.
Syntax:
$(selector).append( content, function(index, html) )
Parameters: This method accepts two parameters as mentioned above and described below:
content: It is required parameter and used to specify the content which is to be inserted at the end of selected elements. The possible value of contents are HTML elements, jQuery objects and DOM elements.
function(index, html): It is optional parameter and used to specify the function that will return the content to be inserted.index: It is used to return the index position of the element.html: It is used to return the current HTML of the selected element.
index: It is used to return the index position of the element.
html: It is used to return the current HTML of the selected element.
Example 1: This example append the content at the end of paragraph and list.
<!DOCTYPE html><html> <head> <title> jQuery append() Method </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- Script to append content --> <script> $(document).ready(function(){ $("#btn1").click(function(){ $("p").append(" <b>Append Geeks</b>."); }); $("#btn2").click(function(){ $("ol").append("<li>Append Gfg</li>"); }); }); </script></head> <body> <h1 style="margin-left: 150px;">Geeks</h1> <p>GeeksforGeeks</p> <p>Jquery</p> <ol> <li>Gfg 1</li> <li>Gfg 2</li> <li>Gfg 3</li> </ol> <button id="btn1">Append Geeks</button> <button id="btn2">Append Gfg</button></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2: This example append the content at the end of paragraph.
<!DOCTYPE html><html> <head> <title> jQuery append() Method </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- Script to append content --> <script> $(document).ready(function() { $("button").click(function() { $("p").append(function(n) { return "<b> Index of Element is " + n + ".</b>"; }); }); }); </script></head> <body> <h1 style="margin-left:150px;">Geeks</h1> <p>Geeks for Geeks</p> <p>Jquery_append</p> <button> Insertion using Append Method() </button></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
jQuery-HTML/CSS
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JQuery | Set the value of an input text field
How to change selected value of a drop-down list using jQuery?
Form validation using jQuery
How to add options to a select element using jQuery?
How to Dynamically Add/Remove Table Rows using jQuery ?
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": "\n19 Feb, 2019"
},
{
"code": null,
"e": 127,
"s": 28,
"text": "This append() Method in jQuery is used to insert some content at the end of the selected elements."
},
{
"code": null,
"e": 135,
"s": 127,
"text": "Syntax:"
},
{
"code": null,
"e": 188,
"s": 135,
"text": "$(selector).append( content, function(index, html) )"
},
{
"code": null,
"e": 275,
"s": 188,
"text": "Parameters: This method accepts two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 481,
"s": 275,
"text": "content: It is required parameter and used to specify the content which is to be inserted at the end of selected elements. The possible value of contents are HTML elements, jQuery objects and DOM elements."
},
{
"code": null,
"e": 737,
"s": 481,
"text": "function(index, html): It is optional parameter and used to specify the function that will return the content to be inserted.index: It is used to return the index position of the element.html: It is used to return the current HTML of the selected element."
},
{
"code": null,
"e": 800,
"s": 737,
"text": "index: It is used to return the index position of the element."
},
{
"code": null,
"e": 869,
"s": 800,
"text": "html: It is used to return the current HTML of the selected element."
},
{
"code": null,
"e": 946,
"s": 869,
"text": "Example 1: This example append the content at the end of paragraph and list."
},
{
"code": "<!DOCTYPE html><html> <head> <title> jQuery append() Method </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- Script to append content --> <script> $(document).ready(function(){ $(\"#btn1\").click(function(){ $(\"p\").append(\" <b>Append Geeks</b>.\"); }); $(\"#btn2\").click(function(){ $(\"ol\").append(\"<li>Append Gfg</li>\"); }); }); </script></head> <body> <h1 style=\"margin-left: 150px;\">Geeks</h1> <p>GeeksforGeeks</p> <p>Jquery</p> <ol> <li>Gfg 1</li> <li>Gfg 2</li> <li>Gfg 3</li> </ol> <button id=\"btn1\">Append Geeks</button> <button id=\"btn2\">Append Gfg</button></body> </html>",
"e": 1779,
"s": 946,
"text": null
},
{
"code": null,
"e": 1787,
"s": 1779,
"text": "Output:"
},
{
"code": null,
"e": 1818,
"s": 1787,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 1848,
"s": 1818,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 1916,
"s": 1848,
"text": "Example 2: This example append the content at the end of paragraph."
},
{
"code": "<!DOCTYPE html><html> <head> <title> jQuery append() Method </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- Script to append content --> <script> $(document).ready(function() { $(\"button\").click(function() { $(\"p\").append(function(n) { return \"<b> Index of Element is \" + n + \".</b>\"; }); }); }); </script></head> <body> <h1 style=\"margin-left:150px;\">Geeks</h1> <p>Geeks for Geeks</p> <p>Jquery_append</p> <button> Insertion using Append Method() </button></body> </html>",
"e": 2637,
"s": 1916,
"text": null
},
{
"code": null,
"e": 2645,
"s": 2637,
"text": "Output:"
},
{
"code": null,
"e": 2676,
"s": 2645,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 2706,
"s": 2676,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 2722,
"s": 2706,
"text": "jQuery-HTML/CSS"
},
{
"code": null,
"e": 2729,
"s": 2722,
"text": "Picked"
},
{
"code": null,
"e": 2736,
"s": 2729,
"text": "JQuery"
},
{
"code": null,
"e": 2753,
"s": 2736,
"text": "Web Technologies"
},
{
"code": null,
"e": 2851,
"s": 2753,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2897,
"s": 2851,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 2960,
"s": 2897,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 2989,
"s": 2960,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 3042,
"s": 2989,
"text": "How to add options to a select element using jQuery?"
},
{
"code": null,
"e": 3098,
"s": 3042,
"text": "How to Dynamically Add/Remove Table Rows using jQuery ?"
},
{
"code": null,
"e": 3131,
"s": 3098,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3193,
"s": 3131,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3254,
"s": 3193,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3304,
"s": 3254,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to capture multiple matches in the same line in Java regex
|
import java.util.regex.*;
class PatternMatcher {
public static void main(String args[]) {
int count = 0;
// String to be scanned to find the pattern.
String content = "aaa bb aaa";
String string = "aaa";
// Create a Pattern object
Pattern p = Pattern.compile(string);
// get a matcher object
Matcher m = p.matcher(content);
while(m.find()) {
count++;
System.out.println("Match no:"+count);
System.out.println("Found at: "+ m.start()+ " - " + m.end());
}
}
}
Match no:1
Found at: 0 - 3
Match no:2
Found at: 7 - 10
start() β This method used for getting the start index of a match that is being found using find() method.
start() β This method used for getting the start index of a match that is being found using find() method.
end() βThis method used for getting the end index of a match that is being found using find() method. It returns index of character next to last matching character.
end() βThis method used for getting the end index of a match that is being found using find() method. It returns index of character next to last matching character.
|
[
{
"code": null,
"e": 1741,
"s": 1187,
"text": "import java.util.regex.*;\nclass PatternMatcher {\n public static void main(String args[]) {\n int count = 0;\n // String to be scanned to find the pattern.\n String content = \"aaa bb aaa\";\n String string = \"aaa\";\n\n // Create a Pattern object\n Pattern p = Pattern.compile(string);\n\n // get a matcher object\n Matcher m = p.matcher(content);\n\n while(m.find()) {\n count++;\n System.out.println(\"Match no:\"+count);\n System.out.println(\"Found at: \"+ m.start()+ \" - \" + m.end());\n }\n }\n}"
},
{
"code": null,
"e": 1796,
"s": 1741,
"text": "Match no:1\nFound at: 0 - 3\nMatch no:2\nFound at: 7 - 10"
},
{
"code": null,
"e": 1903,
"s": 1796,
"text": "start() β This method used for getting the start index of a match that is being found using find() method."
},
{
"code": null,
"e": 2010,
"s": 1903,
"text": "start() β This method used for getting the start index of a match that is being found using find() method."
},
{
"code": null,
"e": 2175,
"s": 2010,
"text": "end() βThis method used for getting the end index of a match that is being found using find() method. It returns index of character next to last matching character."
},
{
"code": null,
"e": 2340,
"s": 2175,
"text": "end() βThis method used for getting the end index of a match that is being found using find() method. It returns index of character next to last matching character."
}
] |
Set Matplotlib colorbar size to match graph
|
08 Sep, 2021
Prerequisites: Matplotlib
Colorbar size that match graph or image is required to get good visualize effect. This can be achieved using any one of following approaches.
Fraction parameter in colorbar() is used to set the size of colorbar. Using this we can match colorbar size to graph as:
If vertical colorbar is used, then fraction=0.047 * (height_of_image / width_of_image)
If horizontal colorbar is used, then fraction=0.047 * (width_of_image / height_of_image)
Approach
Import module
Plot a graph
Set fraction parameter
Plot colorbar
Display plot
Example 1:
Python3
import matplotlib.pyplot as pltimport numpy as np # Plot an imagea = np.random.random((10, 20))plt.imshow(a, cmap='gray') # Calculate (height_of_image / width_of_image)im_ratio = a.shape[0]/a.shape[1] # Plot vertical colorbarplt.colorbar(fraction=0.047*im_ratio)plt.show()
Output:
Example 2:
Python3
import matplotlib.pyplot as pltimport numpy as np # Plot an imagea = np.random.random((10, 20))plt.imshow(a, cmap='gray') # Calculate (width_of_image/height_of_image)im_ratio = a.shape[1]/a.shape[0] # Plot horizontal colorbarplt.colorbar(orientation="horizontal", fraction=0.047*im_ratio)plt.show()
Output:
Axis_grid1 provides a helper function make_axes_locatable() which takes an existing axes instance and creates a divider for it. It provides append_axes() method that creates a new axes on the given side (βtopβ, βrightβ, βbottomβ and βleftβ) of the original axes.
Approach:
Import module
Plot image
Divide existing axes instance using make_axes_locatable()
Create new axes using append_axes()Use βtopβ or βbottomβ side for horizontal colorbarUse βleftβ or βrightβ side for vertical colorbar
Use βtopβ or βbottomβ side for horizontal colorbar
Use βleftβ or βrightβ side for vertical colorbar
Plot colorbar on created axis
Example 1:
Python3
import matplotlib.pyplot as pltfrom mpl_toolkits.axes_grid1 import make_axes_locatableimport numpy as np # Plot image on axes axax = plt.gca()img = np.random.random((10, 20))im = plt.imshow(img, cmap='gray') # Divide existing axes and create new axes# at bottom side of imagedivider = make_axes_locatable(ax)cax = divider.append_axes("bottom", size="5%", pad=0.25) # Plot horizontal colorbarplt.colorbar(im, orientation="horizontal", cax=cax)plt.show()
Output:
Example 2:
Python3
import matplotlib.pyplot as pltfrom mpl_toolkits.axes_grid1 import make_axes_locatableimport numpy as np # Plot image on axes axax = plt.gca()img = np.random.random((10, 20))im = plt.imshow(img, cmap='gray') # Divide existing axes and create# new axes at right side of imagedivider = make_axes_locatable(ax)cax = divider.append_axes("right", size="5%", pad=0.15) # Plot vertical colorbarplt.colorbar(im, cax=cax)plt.show()
Output:
Giving a colorbar its own axes using add_axes() method, can be an approach to get a colorbar matching given image.
Approach:
Plot a figure
Create axes using add_axes() method with position parameters:For vertical colorbar on right side of the image:left: Left point for colorbar=Right End position of imagebottom: Bottom point of colorbar= Bottom end position of imagewidth: Width of colorbarheight: Height of colorbar=Height of imageFor horizontal colorbar at bottom of the image:left: Left point for colorbar=Left End position of imagebottom: Bottom point of colorbar= Bottom end position of imagewidth: Width of colorbar =Width of imageheight: Height of colorbar
For vertical colorbar on right side of the image:left: Left point for colorbar=Right End position of imagebottom: Bottom point of colorbar= Bottom end position of imagewidth: Width of colorbarheight: Height of colorbar=Height of image
left: Left point for colorbar=Right End position of image
bottom: Bottom point of colorbar= Bottom end position of image
width: Width of colorbar
height: Height of colorbar=Height of image
For horizontal colorbar at bottom of the image:left: Left point for colorbar=Left End position of imagebottom: Bottom point of colorbar= Bottom end position of imagewidth: Width of colorbar =Width of imageheight: Height of colorbar
left: Left point for colorbar=Left End position of image
bottom: Bottom point of colorbar= Bottom end position of image
width: Width of colorbar =Width of image
height: Height of colorbar
Plot colorbar on created axes
Example 1 :
Python3
import matplotlib.pyplot as pltimport numpy as np # Plot imagefig = plt.figure()ax = plt.axes()img = np.random.random((10, 20))im = plt.imshow(img, cmap='gray') # Create new axes according to image positioncax = fig.add_axes([ax.get_position().x1+0.01, ax.get_position().y0, 0.02, ax.get_position().height]) # Plot vertical colorbarplt.colorbar(im, cax=cax)plt.show()
Output:
Example 2:
Python3
import matplotlib.pyplot as pltimport numpy as np # Plot an imagefig = plt.figure()ax = plt.axes()img = np.random.random((10, 20))im = plt.imshow(img, cmap='gray') # Create new axes according to image positioncax = fig.add_axes([ax.get_position().x0, ax.get_position().y0-0.08, ax.get_position().width, 0.02]) # Plot horizontal colorbar on created axesplt.colorbar(im, orientation="horizontal", cax=cax)plt.show()
Output:
anikakapoor
Picked
Python-matplotlib
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
Create a directory in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Sep, 2021"
},
{
"code": null,
"e": 54,
"s": 28,
"text": "Prerequisites: Matplotlib"
},
{
"code": null,
"e": 196,
"s": 54,
"text": "Colorbar size that match graph or image is required to get good visualize effect. This can be achieved using any one of following approaches."
},
{
"code": null,
"e": 317,
"s": 196,
"text": "Fraction parameter in colorbar() is used to set the size of colorbar. Using this we can match colorbar size to graph as:"
},
{
"code": null,
"e": 404,
"s": 317,
"text": "If vertical colorbar is used, then fraction=0.047 * (height_of_image / width_of_image)"
},
{
"code": null,
"e": 493,
"s": 404,
"text": "If horizontal colorbar is used, then fraction=0.047 * (width_of_image / height_of_image)"
},
{
"code": null,
"e": 502,
"s": 493,
"text": "Approach"
},
{
"code": null,
"e": 516,
"s": 502,
"text": "Import module"
},
{
"code": null,
"e": 529,
"s": 516,
"text": "Plot a graph"
},
{
"code": null,
"e": 552,
"s": 529,
"text": "Set fraction parameter"
},
{
"code": null,
"e": 566,
"s": 552,
"text": "Plot colorbar"
},
{
"code": null,
"e": 579,
"s": 566,
"text": "Display plot"
},
{
"code": null,
"e": 590,
"s": 579,
"text": "Example 1:"
},
{
"code": null,
"e": 598,
"s": 590,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltimport numpy as np # Plot an imagea = np.random.random((10, 20))plt.imshow(a, cmap='gray') # Calculate (height_of_image / width_of_image)im_ratio = a.shape[0]/a.shape[1] # Plot vertical colorbarplt.colorbar(fraction=0.047*im_ratio)plt.show()",
"e": 871,
"s": 598,
"text": null
},
{
"code": null,
"e": 879,
"s": 871,
"text": "Output:"
},
{
"code": null,
"e": 890,
"s": 879,
"text": "Example 2:"
},
{
"code": null,
"e": 898,
"s": 890,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltimport numpy as np # Plot an imagea = np.random.random((10, 20))plt.imshow(a, cmap='gray') # Calculate (width_of_image/height_of_image)im_ratio = a.shape[1]/a.shape[0] # Plot horizontal colorbarplt.colorbar(orientation=\"horizontal\", fraction=0.047*im_ratio)plt.show()",
"e": 1197,
"s": 898,
"text": null
},
{
"code": null,
"e": 1205,
"s": 1197,
"text": "Output:"
},
{
"code": null,
"e": 1469,
"s": 1205,
"text": "Axis_grid1 provides a helper function make_axes_locatable() which takes an existing axes instance and creates a divider for it. It provides append_axes() method that creates a new axes on the given side (βtopβ, βrightβ, βbottomβ and βleftβ) of the original axes. "
},
{
"code": null,
"e": 1479,
"s": 1469,
"text": "Approach:"
},
{
"code": null,
"e": 1493,
"s": 1479,
"text": "Import module"
},
{
"code": null,
"e": 1504,
"s": 1493,
"text": "Plot image"
},
{
"code": null,
"e": 1562,
"s": 1504,
"text": "Divide existing axes instance using make_axes_locatable()"
},
{
"code": null,
"e": 1696,
"s": 1562,
"text": "Create new axes using append_axes()Use βtopβ or βbottomβ side for horizontal colorbarUse βleftβ or βrightβ side for vertical colorbar"
},
{
"code": null,
"e": 1747,
"s": 1696,
"text": "Use βtopβ or βbottomβ side for horizontal colorbar"
},
{
"code": null,
"e": 1796,
"s": 1747,
"text": "Use βleftβ or βrightβ side for vertical colorbar"
},
{
"code": null,
"e": 1826,
"s": 1796,
"text": "Plot colorbar on created axis"
},
{
"code": null,
"e": 1837,
"s": 1826,
"text": "Example 1:"
},
{
"code": null,
"e": 1845,
"s": 1837,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltfrom mpl_toolkits.axes_grid1 import make_axes_locatableimport numpy as np # Plot image on axes axax = plt.gca()img = np.random.random((10, 20))im = plt.imshow(img, cmap='gray') # Divide existing axes and create new axes# at bottom side of imagedivider = make_axes_locatable(ax)cax = divider.append_axes(\"bottom\", size=\"5%\", pad=0.25) # Plot horizontal colorbarplt.colorbar(im, orientation=\"horizontal\", cax=cax)plt.show()",
"e": 2298,
"s": 1845,
"text": null
},
{
"code": null,
"e": 2306,
"s": 2298,
"text": "Output:"
},
{
"code": null,
"e": 2317,
"s": 2306,
"text": "Example 2:"
},
{
"code": null,
"e": 2325,
"s": 2317,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltfrom mpl_toolkits.axes_grid1 import make_axes_locatableimport numpy as np # Plot image on axes axax = plt.gca()img = np.random.random((10, 20))im = plt.imshow(img, cmap='gray') # Divide existing axes and create# new axes at right side of imagedivider = make_axes_locatable(ax)cax = divider.append_axes(\"right\", size=\"5%\", pad=0.15) # Plot vertical colorbarplt.colorbar(im, cax=cax)plt.show()",
"e": 2748,
"s": 2325,
"text": null
},
{
"code": null,
"e": 2756,
"s": 2748,
"text": "Output:"
},
{
"code": null,
"e": 2871,
"s": 2756,
"text": "Giving a colorbar its own axes using add_axes() method, can be an approach to get a colorbar matching given image."
},
{
"code": null,
"e": 2881,
"s": 2871,
"text": "Approach:"
},
{
"code": null,
"e": 2895,
"s": 2881,
"text": "Plot a figure"
},
{
"code": null,
"e": 3422,
"s": 2895,
"text": "Create axes using add_axes() method with position parameters:For vertical colorbar on right side of the image:left: Left point for colorbar=Right End position of imagebottom: Bottom point of colorbar= Bottom end position of imagewidth: Width of colorbarheight: Height of colorbar=Height of imageFor horizontal colorbar at bottom of the image:left: Left point for colorbar=Left End position of imagebottom: Bottom point of colorbar= Bottom end position of imagewidth: Width of colorbar =Width of imageheight: Height of colorbar"
},
{
"code": null,
"e": 3657,
"s": 3422,
"text": "For vertical colorbar on right side of the image:left: Left point for colorbar=Right End position of imagebottom: Bottom point of colorbar= Bottom end position of imagewidth: Width of colorbarheight: Height of colorbar=Height of image"
},
{
"code": null,
"e": 3715,
"s": 3657,
"text": "left: Left point for colorbar=Right End position of image"
},
{
"code": null,
"e": 3778,
"s": 3715,
"text": "bottom: Bottom point of colorbar= Bottom end position of image"
},
{
"code": null,
"e": 3803,
"s": 3778,
"text": "width: Width of colorbar"
},
{
"code": null,
"e": 3846,
"s": 3803,
"text": "height: Height of colorbar=Height of image"
},
{
"code": null,
"e": 4078,
"s": 3846,
"text": "For horizontal colorbar at bottom of the image:left: Left point for colorbar=Left End position of imagebottom: Bottom point of colorbar= Bottom end position of imagewidth: Width of colorbar =Width of imageheight: Height of colorbar"
},
{
"code": null,
"e": 4135,
"s": 4078,
"text": "left: Left point for colorbar=Left End position of image"
},
{
"code": null,
"e": 4198,
"s": 4135,
"text": "bottom: Bottom point of colorbar= Bottom end position of image"
},
{
"code": null,
"e": 4239,
"s": 4198,
"text": "width: Width of colorbar =Width of image"
},
{
"code": null,
"e": 4266,
"s": 4239,
"text": "height: Height of colorbar"
},
{
"code": null,
"e": 4296,
"s": 4266,
"text": "Plot colorbar on created axes"
},
{
"code": null,
"e": 4308,
"s": 4296,
"text": "Example 1 :"
},
{
"code": null,
"e": 4316,
"s": 4308,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltimport numpy as np # Plot imagefig = plt.figure()ax = plt.axes()img = np.random.random((10, 20))im = plt.imshow(img, cmap='gray') # Create new axes according to image positioncax = fig.add_axes([ax.get_position().x1+0.01, ax.get_position().y0, 0.02, ax.get_position().height]) # Plot vertical colorbarplt.colorbar(im, cax=cax)plt.show()",
"e": 4741,
"s": 4316,
"text": null
},
{
"code": null,
"e": 4749,
"s": 4741,
"text": "Output:"
},
{
"code": null,
"e": 4760,
"s": 4749,
"text": "Example 2:"
},
{
"code": null,
"e": 4768,
"s": 4760,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltimport numpy as np # Plot an imagefig = plt.figure()ax = plt.axes()img = np.random.random((10, 20))im = plt.imshow(img, cmap='gray') # Create new axes according to image positioncax = fig.add_axes([ax.get_position().x0, ax.get_position().y0-0.08, ax.get_position().width, 0.02]) # Plot horizontal colorbar on created axesplt.colorbar(im, orientation=\"horizontal\", cax=cax)plt.show()",
"e": 5239,
"s": 4768,
"text": null
},
{
"code": null,
"e": 5247,
"s": 5239,
"text": "Output:"
},
{
"code": null,
"e": 5259,
"s": 5247,
"text": "anikakapoor"
},
{
"code": null,
"e": 5266,
"s": 5259,
"text": "Picked"
},
{
"code": null,
"e": 5284,
"s": 5266,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 5291,
"s": 5284,
"text": "Python"
},
{
"code": null,
"e": 5389,
"s": 5291,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5421,
"s": 5389,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 5448,
"s": 5421,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 5469,
"s": 5448,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 5492,
"s": 5469,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 5548,
"s": 5492,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 5579,
"s": 5548,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 5621,
"s": 5579,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 5663,
"s": 5621,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 5702,
"s": 5663,
"text": "Python | Get unique values from a list"
}
] |
Python β Difference between sorted() and sort()
|
03 Jun, 2022
Sorting means rearranging a given sequence of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of the element in the respective data structure.For example: The below list of characters is sorted in increasing order of their ASCII values. That is, the character with lesser ASCII value will be placed first than the character with higher ASCII value.
In Python, sorting any sequence is very easy as it provides in-built methods for sorting. Two such methods are sorted() and sort(). These two methods are used for sorting but are quite different in their own way. Letβs have a look at them one by one.
sorted() method sorts the given sequence as well as set and dictionary(which is not a sequence) either in ascending order or in descending order(does unicode comparison for string char by char) and always returns the a sorted list. This method doesnβt effect the original sequence.
Syntax: sorted(iteraable, key, reverse=False)affectParameters: Iterable: sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other iterator that needs to be sorted. Key(optional): A function that would serve as a key or a basis of sort comparison. Reverse(optional): If set True, then the iterable would be sorted in reverse (descending) order, by default it is set as False.Return Type: Returns a sorted list.
Example 1:
Python3
# Python program to demonstrate# sorted() L = [1, 2, 3, 4, 5] print("Sorted list:")print(sorted(L)) print("\nReverse sorted list:")print(sorted(L, reverse = True)) print("\nOriginal list after sorting:")print(L)
Output:
Sorted list:
[1, 2, 3, 4, 5]
Reverse sorted list:
[5, 4, 3, 2, 1]
Original list after sorting:
[1, 2, 3, 4, 5]
Example 2: Sorting different data types
Python3
# Python program to demonstrate# sorted() # Listx = ['q', 'w', 'r', 'e', 't', 'y']print(sorted(x)) # Tuplex = ('q', 'w', 'e', 'r', 't', 'y')print(sorted(x)) # String-sorted based on ASCII translationsx = "python"print(sorted(x)) # Dictionaryx = {'q':1, 'w':2, 'e':3, 'r':4, 't':5, 'y':6}print(sorted(x)) # Setx = {'q', 'w', 'e', 'r', 't', 'y'}print(sorted(x))
Output:
['e', 'q', 'r', 't', 'w', 'y']
['e', 'q', 'r', 't', 'w', 'y']
['h', 'n', 'o', 'p', 't', 'y']
['e', 'q', 'r', 't', 'w', 'y']
['e', 'q', 'r', 't', 'w', 'y']
This optional parameter key takes a function as its value. This key function transforms each element before sorting, it takes the value and returns 1 value which is then used within sort instead of the original value.Example: Letβs suppose we want to sort a List of string according to its length. This can be done by passing the len() function as the value to the key parameter. Below is the implementation.
Python3
# Python program to demonstrate# sorted() L = ['aaaa', 'bbb', 'cc', 'd'] # sorted without key parameterprint(sorted(L))print() # sorted with key parameterprint(sorted(L, key = len))
Output:
['aaaa', 'bbb', 'cc', 'd']
['d', 'cc', 'bbb', 'aaaa']
sort() function is very similar to sorted() but unlike sorted it returns nothing and makes changes to the original sequence. Moreover, sort() is a method of list class and can only be used with lists.
Syntax: List_name.sort(key, reverse=False)Parameters: key: A function that serves as a key for the sort comparison. reverse: If true, the list is sorted in descending order.Return type: None
Example 1:
Python3
# Python program to demonstrate# sort() # List of Integersnumbers = [1, 3, 4, 2] # Sorting list of Integersnumbers.sort() print(numbers) # List of Floating point numbersdecimalnumber = [2.01, 2.00, 3.67, 3.28, 1.68] # Sorting list of Floating point numbersdecimalnumber.sort() print(decimalnumber) # List of stringswords = ["Geeks", "For", "Geeks"] # Sorting list of stringswords.sort() print(words)
Output:
[1, 2, 3, 4]
[1.68, 2.0, 2.01, 3.28, 3.67]
['For', 'Geeks', 'Geeks']
Example 2: Sorting in reverse order.
Python3
# Python program to demonstrate# sort() # List of Integersnumbers = [1, 3, 4, 2] # Sorting list of Integersnumbers.sort(reverse = True) print(numbers) # List of Floating point numbersdecimalnumber = [2.01, 2.00, 3.67, 3.28, 1.68] # Sorting list of Floating point numbersdecimalnumber.sort(reverse = True) print(decimalnumber) # List of stringswords = ["Geeks", "For", "Geeks"] # Sorting list of stringswords.sort(reverse = True) print(words)
Output:
[4, 3, 2, 1]
[3.67, 3.28, 2.01, 2.0, 1.68]
['Geeks', 'Geeks', 'For']
Example 3: Using key parameter.
Python3
# Python program to demonstrate sorting by user's# choice # function to return the second element of the# two elements passed as the parameterdef sortSecond(val): return val[1] # list1 to demonstrate the use of sorting # using second key list1 = [(1, 2), (3, 3), (1, 1)] # sorts the array in ascending according to # second elementlist1.sort(key = sortSecond) print(list1) # sorts the array in descending according to# second elementlist1.sort(key = sortSecond, reverse = True)print(list1)
Output:
[(1, 1), (1, 2), (3, 3)]
[(3, 3), (1, 2), (1, 1)]
Let us see the differences in a tabular form -:
Its syntax is :
sorted(iterable, key=key, reverse=reverse)
Its syntax is -:
list.sort(reverse=True|False, key=myFunc)
flashtoak
simranarora5sos
mayank007rawa
sweetyty
python-basics
Python-sort
Python-Sorted
Python
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()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Jun, 2022"
},
{
"code": null,
"e": 471,
"s": 52,
"text": "Sorting means rearranging a given sequence of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of the element in the respective data structure.For example: The below list of characters is sorted in increasing order of their ASCII values. That is, the character with lesser ASCII value will be placed first than the character with higher ASCII value. "
},
{
"code": null,
"e": 723,
"s": 471,
"text": "In Python, sorting any sequence is very easy as it provides in-built methods for sorting. Two such methods are sorted() and sort(). These two methods are used for sorting but are quite different in their own way. Letβs have a look at them one by one. "
},
{
"code": null,
"e": 1006,
"s": 723,
"text": "sorted() method sorts the given sequence as well as set and dictionary(which is not a sequence) either in ascending order or in descending order(does unicode comparison for string char by char) and always returns the a sorted list. This method doesnβt effect the original sequence. "
},
{
"code": null,
"e": 1448,
"s": 1006,
"text": "Syntax: sorted(iteraable, key, reverse=False)affectParameters: Iterable: sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other iterator that needs to be sorted. Key(optional): A function that would serve as a key or a basis of sort comparison. Reverse(optional): If set True, then the iterable would be sorted in reverse (descending) order, by default it is set as False.Return Type: Returns a sorted list. "
},
{
"code": null,
"e": 1460,
"s": 1448,
"text": "Example 1: "
},
{
"code": null,
"e": 1468,
"s": 1460,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# sorted() L = [1, 2, 3, 4, 5] print(\"Sorted list:\")print(sorted(L)) print(\"\\nReverse sorted list:\")print(sorted(L, reverse = True)) print(\"\\nOriginal list after sorting:\")print(L)",
"e": 1681,
"s": 1468,
"text": null
},
{
"code": null,
"e": 1690,
"s": 1681,
"text": "Output: "
},
{
"code": null,
"e": 1803,
"s": 1690,
"text": "Sorted list:\n[1, 2, 3, 4, 5]\n\nReverse sorted list:\n[5, 4, 3, 2, 1]\n\nOriginal list after sorting:\n[1, 2, 3, 4, 5]"
},
{
"code": null,
"e": 1844,
"s": 1803,
"text": "Example 2: Sorting different data types "
},
{
"code": null,
"e": 1852,
"s": 1844,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# sorted() # Listx = ['q', 'w', 'r', 'e', 't', 'y']print(sorted(x)) # Tuplex = ('q', 'w', 'e', 'r', 't', 'y')print(sorted(x)) # String-sorted based on ASCII translationsx = \"python\"print(sorted(x)) # Dictionaryx = {'q':1, 'w':2, 'e':3, 'r':4, 't':5, 'y':6}print(sorted(x)) # Setx = {'q', 'w', 'e', 'r', 't', 'y'}print(sorted(x))",
"e": 2219,
"s": 1852,
"text": null
},
{
"code": null,
"e": 2228,
"s": 2219,
"text": "Output: "
},
{
"code": null,
"e": 2383,
"s": 2228,
"text": "['e', 'q', 'r', 't', 'w', 'y']\n['e', 'q', 'r', 't', 'w', 'y']\n['h', 'n', 'o', 'p', 't', 'y']\n['e', 'q', 'r', 't', 'w', 'y']\n['e', 'q', 'r', 't', 'w', 'y']"
},
{
"code": null,
"e": 2795,
"s": 2385,
"text": "This optional parameter key takes a function as its value. This key function transforms each element before sorting, it takes the value and returns 1 value which is then used within sort instead of the original value.Example: Letβs suppose we want to sort a List of string according to its length. This can be done by passing the len() function as the value to the key parameter. Below is the implementation. "
},
{
"code": null,
"e": 2803,
"s": 2795,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# sorted() L = ['aaaa', 'bbb', 'cc', 'd'] # sorted without key parameterprint(sorted(L))print() # sorted with key parameterprint(sorted(L, key = len))",
"e": 2986,
"s": 2803,
"text": null
},
{
"code": null,
"e": 2995,
"s": 2986,
"text": "Output: "
},
{
"code": null,
"e": 3050,
"s": 2995,
"text": "['aaaa', 'bbb', 'cc', 'd']\n\n['d', 'cc', 'bbb', 'aaaa']"
},
{
"code": null,
"e": 3254,
"s": 3052,
"text": "sort() function is very similar to sorted() but unlike sorted it returns nothing and makes changes to the original sequence. Moreover, sort() is a method of list class and can only be used with lists. "
},
{
"code": null,
"e": 3447,
"s": 3254,
"text": "Syntax: List_name.sort(key, reverse=False)Parameters: key: A function that serves as a key for the sort comparison. reverse: If true, the list is sorted in descending order.Return type: None "
},
{
"code": null,
"e": 3459,
"s": 3447,
"text": "Example 1: "
},
{
"code": null,
"e": 3467,
"s": 3459,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# sort() # List of Integersnumbers = [1, 3, 4, 2] # Sorting list of Integersnumbers.sort() print(numbers) # List of Floating point numbersdecimalnumber = [2.01, 2.00, 3.67, 3.28, 1.68] # Sorting list of Floating point numbersdecimalnumber.sort() print(decimalnumber) # List of stringswords = [\"Geeks\", \"For\", \"Geeks\"] # Sorting list of stringswords.sort() print(words)",
"e": 3884,
"s": 3467,
"text": null
},
{
"code": null,
"e": 3893,
"s": 3884,
"text": "Output: "
},
{
"code": null,
"e": 3962,
"s": 3893,
"text": "[1, 2, 3, 4]\n[1.68, 2.0, 2.01, 3.28, 3.67]\n['For', 'Geeks', 'Geeks']"
},
{
"code": null,
"e": 4000,
"s": 3962,
"text": "Example 2: Sorting in reverse order. "
},
{
"code": null,
"e": 4008,
"s": 4000,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# sort() # List of Integersnumbers = [1, 3, 4, 2] # Sorting list of Integersnumbers.sort(reverse = True) print(numbers) # List of Floating point numbersdecimalnumber = [2.01, 2.00, 3.67, 3.28, 1.68] # Sorting list of Floating point numbersdecimalnumber.sort(reverse = True) print(decimalnumber) # List of stringswords = [\"Geeks\", \"For\", \"Geeks\"] # Sorting list of stringswords.sort(reverse = True) print(words)",
"e": 4467,
"s": 4008,
"text": null
},
{
"code": null,
"e": 4476,
"s": 4467,
"text": "Output: "
},
{
"code": null,
"e": 4545,
"s": 4476,
"text": "[4, 3, 2, 1]\n[3.67, 3.28, 2.01, 2.0, 1.68]\n['Geeks', 'Geeks', 'For']"
},
{
"code": null,
"e": 4578,
"s": 4545,
"text": "Example 3: Using key parameter. "
},
{
"code": null,
"e": 4586,
"s": 4578,
"text": "Python3"
},
{
"code": "# Python program to demonstrate sorting by user's# choice # function to return the second element of the# two elements passed as the parameterdef sortSecond(val): return val[1] # list1 to demonstrate the use of sorting # using second key list1 = [(1, 2), (3, 3), (1, 1)] # sorts the array in ascending according to # second elementlist1.sort(key = sortSecond) print(list1) # sorts the array in descending according to# second elementlist1.sort(key = sortSecond, reverse = True)print(list1)",
"e": 5089,
"s": 4586,
"text": null
},
{
"code": null,
"e": 5098,
"s": 5089,
"text": "Output: "
},
{
"code": null,
"e": 5148,
"s": 5098,
"text": "[(1, 1), (1, 2), (3, 3)]\n[(3, 3), (1, 2), (1, 1)]"
},
{
"code": null,
"e": 5197,
"s": 5148,
"text": " Let us see the differences in a tabular form -:"
},
{
"code": null,
"e": 5213,
"s": 5197,
"text": "Its syntax is :"
},
{
"code": null,
"e": 5256,
"s": 5213,
"text": "sorted(iterable, key=key, reverse=reverse)"
},
{
"code": null,
"e": 5273,
"s": 5256,
"text": "Its syntax is -:"
},
{
"code": null,
"e": 5315,
"s": 5273,
"text": "list.sort(reverse=True|False, key=myFunc)"
},
{
"code": null,
"e": 5325,
"s": 5315,
"text": "flashtoak"
},
{
"code": null,
"e": 5341,
"s": 5325,
"text": "simranarora5sos"
},
{
"code": null,
"e": 5355,
"s": 5341,
"text": "mayank007rawa"
},
{
"code": null,
"e": 5364,
"s": 5355,
"text": "sweetyty"
},
{
"code": null,
"e": 5378,
"s": 5364,
"text": "python-basics"
},
{
"code": null,
"e": 5390,
"s": 5378,
"text": "Python-sort"
},
{
"code": null,
"e": 5404,
"s": 5390,
"text": "Python-Sorted"
},
{
"code": null,
"e": 5411,
"s": 5404,
"text": "Python"
},
{
"code": null,
"e": 5509,
"s": 5411,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5527,
"s": 5509,
"text": "Python Dictionary"
},
{
"code": null,
"e": 5569,
"s": 5527,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 5591,
"s": 5569,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 5626,
"s": 5591,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 5652,
"s": 5626,
"text": "Python String | replace()"
},
{
"code": null,
"e": 5684,
"s": 5652,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 5713,
"s": 5684,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 5740,
"s": 5713,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 5770,
"s": 5740,
"text": "Iterate over a list in Python"
}
] |
Memory profiling in Python using memory_profiler
|
01 Aug, 2020
If you use Python a lot then you probably know that many people claim that Python takes up more time to execute. Well, you probably have seen approaches like the total time spent to execute a part of code or something like that but sometimes you need something more than that. What about RAM usage? Nobody really talks about that but itβs equally essential. This might look really insignificant but itβs actually pretty important while writing code for production.
We will be using memory-profiler from PyPi. We will also be needing requests to test the functionality. To do so, simply type the following in your terminal
pip3 install memory-profiler requests
Note: If you are working on windows or using a virtual env, then it will be pip instead of pip3
Now that everything is set up, rest is pretty easy and interesting obviously. Create a new file with the name word_extractor.py and add the code to it. Below is the implementation of the code. Everything is pretty well documented as in-line comments.
Python3
# importsfrom memory_profiler import profileimport requests class BaseExtractor: # decorator which specifies which # function to monitor @profile def parse_list(self, array): # create a file object f = open('words.txt', 'w') for word in array: # writing words to file f.writelines(word) # decorator which specifies which # function to monitor @profile def parse_url(self, url): # fetches the response response = requests.get(url).text with open('url.txt', 'w') as f: # writing response to file f.writelines(response)
Notice the @profile this is a decorator. Any function which is decorated by this decorator, that function will be tracked. Now, our main code is ready. Letβs write the driver code which will call this class functions. Now, create another file called run.py and insert the following code in it.
Python3
from word_extractor import BaseExtractor if __name__ == "__main__": # url for word list (huge) url = 'https://raw.githubusercontent.com/dwyl/english-words/master/words.txt' # word list in array array = ['one', 'two', 'three', 'four', 'five'] # initializing BaseExtractor object extractor = BaseExtractor() # calling parse_url function extractor.parse_url(url) # calling pasrse_list function extractor.parse_list(array)
So, basically now we are done. You will notice that parse_url() will consume more memory than parse_list() which is obvious because parse_url calls a URL and writes the response content to a text file. If you open the link, then you will find that the word list is huge. So, now to test your code, simply run the run.py file. You can do so by typing
python3 run.py
Note: If you are working on windows or using a virtual env, then it will be python instead of python3
If everything ran successfully, then you should see something like this
Memory Profiler Stats
An important thing to remember is that memory-profiler itself consumes a significant amount of memory. Use this only in development but avoid it in production.
python-modules
python-utility
Python
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
Python String | replace()
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 494,
"s": 28,
"text": "If you use Python a lot then you probably know that many people claim that Python takes up more time to execute. Well, you probably have seen approaches like the total time spent to execute a part of code or something like that but sometimes you need something more than that. What about RAM usage? Nobody really talks about that but itβs equally essential. This might look really insignificant but itβs actually pretty important while writing code for production. "
},
{
"code": null,
"e": 651,
"s": 494,
"text": "We will be using memory-profiler from PyPi. We will also be needing requests to test the functionality. To do so, simply type the following in your terminal"
},
{
"code": null,
"e": 689,
"s": 651,
"text": "pip3 install memory-profiler requests"
},
{
"code": null,
"e": 785,
"s": 689,
"text": "Note: If you are working on windows or using a virtual env, then it will be pip instead of pip3"
},
{
"code": null,
"e": 1037,
"s": 785,
"text": "Now that everything is set up, rest is pretty easy and interesting obviously. Create a new file with the name word_extractor.py and add the code to it. Below is the implementation of the code. Everything is pretty well documented as in-line comments."
},
{
"code": null,
"e": 1045,
"s": 1037,
"text": "Python3"
},
{
"code": "# importsfrom memory_profiler import profileimport requests class BaseExtractor: # decorator which specifies which # function to monitor @profile def parse_list(self, array): # create a file object f = open('words.txt', 'w') for word in array: # writing words to file f.writelines(word) # decorator which specifies which # function to monitor @profile def parse_url(self, url): # fetches the response response = requests.get(url).text with open('url.txt', 'w') as f: # writing response to file f.writelines(response)",
"e": 1726,
"s": 1045,
"text": null
},
{
"code": null,
"e": 2020,
"s": 1726,
"text": "Notice the @profile this is a decorator. Any function which is decorated by this decorator, that function will be tracked. Now, our main code is ready. Letβs write the driver code which will call this class functions. Now, create another file called run.py and insert the following code in it."
},
{
"code": null,
"e": 2028,
"s": 2020,
"text": "Python3"
},
{
"code": "from word_extractor import BaseExtractor if __name__ == \"__main__\": # url for word list (huge) url = 'https://raw.githubusercontent.com/dwyl/english-words/master/words.txt' # word list in array array = ['one', 'two', 'three', 'four', 'five'] # initializing BaseExtractor object extractor = BaseExtractor() # calling parse_url function extractor.parse_url(url) # calling pasrse_list function extractor.parse_list(array)",
"e": 2510,
"s": 2028,
"text": null
},
{
"code": null,
"e": 2862,
"s": 2510,
"text": "So, basically now we are done. You will notice that parse_url() will consume more memory than parse_list() which is obvious because parse_url calls a URL and writes the response content to a text file. If you open the link, then you will find that the word list is huge. So, now to test your code, simply run the run.py file. You can do so by typing "
},
{
"code": null,
"e": 2877,
"s": 2862,
"text": "python3 run.py"
},
{
"code": null,
"e": 2979,
"s": 2877,
"text": "Note: If you are working on windows or using a virtual env, then it will be python instead of python3"
},
{
"code": null,
"e": 3051,
"s": 2979,
"text": "If everything ran successfully, then you should see something like this"
},
{
"code": null,
"e": 3073,
"s": 3051,
"text": "Memory Profiler Stats"
},
{
"code": null,
"e": 3233,
"s": 3073,
"text": "An important thing to remember is that memory-profiler itself consumes a significant amount of memory. Use this only in development but avoid it in production."
},
{
"code": null,
"e": 3248,
"s": 3233,
"text": "python-modules"
},
{
"code": null,
"e": 3263,
"s": 3248,
"text": "python-utility"
},
{
"code": null,
"e": 3270,
"s": 3263,
"text": "Python"
},
{
"code": null,
"e": 3368,
"s": 3270,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3386,
"s": 3368,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3428,
"s": 3386,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3450,
"s": 3428,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3476,
"s": 3450,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3508,
"s": 3476,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3535,
"s": 3508,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3556,
"s": 3535,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3592,
"s": 3556,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 3615,
"s": 3592,
"text": "Introduction To PYTHON"
}
] |
Twitter Sentiment Analysis WebApp Using Flask
|
13 Jun, 2022
This is a web app made using Python and Flask Framework. It has a registration system and a dashboard. Users can enter keywords to retrieve live Twitter text based on the keyword, and analyze it for customer feelings and sentiments. This data can be visualized in a graph. This project, in particular, mines data using a popular βTweepyβ API. Tweepy API connects to Twitter in real-time and gathers metadata along with the text from the Twitter platform.
To help companies study the customer sentiment around a particular product.
To help system users analyze a huge amount of data, quickly and efficiently.
To segregate customer sentiment on a scale of -1 to 1, where -1 represents a strong negative sentimentality towards the keyword(s), and 1 represents a strongly positive reaction.
To visualize the collected data clearly and effectively.
HARDWARE:
4GB RAM
Windows 10
Google Chrome web browser for deployment
Internet connection to connect to Twitter
This project design is software-based, so the hardware design requirements include a 64-bit well-functioning PC with at least 4 Gigabits of RAM.
SOFTWARE:
Python- Python is an interpreted, high level, and general-purpose programming language. Python promotes code manageability and readability, making it one of the top applications for working with Machine Learning.
Flask web framework(works with python)- Flask is a web framework. This means flask provides us with tools, libraries, and technologies that will allow me to build a web application and web pages. Flask is a back-end micro-framework, and it makes data handling clean and simple.
Tweepy(Twitter API for Python)- Tweepy is an open-source Python package that gives you a very convenient way to access the Twitter API with Python. Tweepy includes a set of classes and methods that represent Twitterβs models and API endpoints, and it transparently handles various implementation details, such as Data encoding and decoding.
Apache SQL on Xampp server for windows- SQL server runs on phpMyAdmin inside the localhost. This database is used for storing, verifying, and retrieving a userβs login credentials.
Bootstrap- The UI is enhanced with the help of Bootstrap, which helps to build modern, intuitive, and responsive web pages.
JQuery- JQuery is used for sending and retrieving data back and forth from the Tweepy API, and displaying the results on the webpage.
HTML/CSS- HTML and CSS is the base for the website front-end design.
Machine Learning- Moderate
Programming skills
Python- Advanced.
HTML/CSS/JQUERY/BOOTSTRAP- Basic to moderate.
SQL/DBMS- Basic to moderate
Debugging/Deployment β Moderate
Ability to work with APIβs.
Follow the below steps to implement the project:
Step 1: Download and Install Xampp Server on your system.
Step 2: Start Apache Xampp and MySQL. Create a database in MySQL with 3 columns (username, email id, and password).
Step 3: Download and Install PyCharm. Click on Create-> New Project. Give a name to your project.
Step 4:Type the following code in Pycharm. For detailed project files and hierarchy, refer to this GitHub repository.
In this file, we first initialize our project. We establish a connection to our SQL database using the βconnβ object.
We set a user cookie variable, which checks if the user has logged in, before redirecting him/her to the home page. This script also handles the user input on the login/register pages.
Python3
from flask import Flask, render_template, request, redirect, sessionimport mysql.connectorfrom sentiments import secondimport os app = Flask(__name__) # initializing the user cookieapp.secret_key = os.urandom(24) # blueprint to call the second python file in the project.app.register_blueprint(second) # establishing a connection with mysql database made in xampptry: conn = mysql.connector.connect( host="localhost", user="root", password="", database="users") cursor = conn.cursor()except: print("An exception occurred") # call the login template when the url is http://localhost:5000/@app.route('/')def login(): return render_template('login.html') # call the register template when the url is http://localhost:5000/register@app.route('/register')def register(): return render_template('register.html') @app.route('/home')def home(): if 'user_id' in session: return render_template('home.html') else: return redirect('/') @app.route('/login_validation', methods=['POST'])def login_validation(): email = request.form.get('email') password = request.form.get('password') cursor.execute( """SELECT * from `users` WHERE `email` LIKE '{}' AND `password` LIKE '{}'""".format(email, password)) users = cursor.fetchall() # check if a user has already logged in if len(users) > 0: session['user_id'] = users[0][0] return redirect('/home') else: return redirect('/login') @app.route('/add_user', methods=['POST'])def add_user(): # get user login data and pass the data to database name = request.form.get('uname') email = request.form.get('uemail') password = request.form.get('upassword') cursor.execute("""INSERT INTO `users` (`name`,`email`,`password`) VALUES ('{}','{}','{}')""".format( name, email, password)) conn.commit() cursor.execute( """SELECT * from `users` WHERE `email` LIKE '{}'""".format(email)) myuser = cursor.fetchall() session['user_id'] = myuser[0][0] return redirect('/home') @app.route('/logout')def logout(): # close the session session.pop('user_id') return redirect('/') if __name__ == "__main__": app.run(debug=True)
This is the second python file in our project, which was registered as a blueprint in our βmain.pyβ file.
This code takes the user input from the HTML page, which specifies which keyword is to be searched, and the number of tweets to be looked at. It then connects to the Tweepy API, which retrieves the tweet text. This text is cleaned and then categorized into different sentiments( -1 is an angry/sad emotion, 1 is a happy emotion).
Based on this, a pie chart is created and saved as an image. This image is later called in other HTML pages.
Python3
from flask import Blueprint, render_template, requestimport matplotlib.pyplot as pltimport os import tweepyimport csvimport refrom textblob import TextBlobimport matplotlibmatplotlib.use('agg') # register this file as a blueprintsecond = Blueprint("second", __name__, static_folder="static", template_folder="template") # render page when url is called@second.route("/sentiment_analyzer")def sentiment_analyzer(): return render_template("sentiment_analyzer.html") # class with main logicclass SentimentAnalysis: def __init__(self): self.tweets = [] self.tweetText = [] # This function first connects to the Tweepy API using API keys def DownloadData(self, keyword, tweets): # authenticating consumerKey = '//get from Tweepy' consumerSecret = '//get from Tweepy' accessToken = '//insert your access token here' accessTokenSecret = '//Tweepy AccessToken secret here' auth = tweepy.OAuthHandler(consumerKey, consumerSecret) auth.set_access_token(accessToken, accessTokenSecret) api = tweepy.API(auth, wait_on_rate_limit=True) # input for term to be searched and how many tweets to search # searchTerm = input("Enter Keyword/Tag to search about: ") # NoOfTerms = int(input("Enter how many tweets to search: ")) tweets = int(tweets) # searching for tweets self.tweets = tweepy.Cursor( api.search, q=keyword, lang="en").items(tweets) # Open/create a file to append data to csvFile = open('result.csv', 'a') # Use csv writer csvWriter = csv.writer(csvFile) # creating some variables to store info polarity = 0 positive = 0 wpositive = 0 spositive = 0 negative = 0 wnegative = 0 snegative = 0 neutral = 0 # iterating through tweets fetched for tweet in self.tweets: # Append to temp so that we can store in csv later. I use encode UTF-8 self.tweetText.append(self.cleanTweet(tweet.text).encode('utf-8')) # print (tweet.text.translate(non_bmp_map)) #print tweet's text analysis = TextBlob(tweet.text) # print(analysis.sentiment) # print tweet's polarity # adding up polarities to find the average later polarity += analysis.sentiment.polarity # adding reaction of how people are reacting to find average later if (analysis.sentiment.polarity == 0): neutral += 1 elif (analysis.sentiment.polarity > 0 and analysis.sentiment.polarity <= 0.3): wpositive += 1 elif (analysis.sentiment.polarity > 0.3 and analysis.sentiment.polarity <= 0.6): positive += 1 elif (analysis.sentiment.polarity > 0.6 and analysis.sentiment.polarity <= 1): spositive += 1 elif (analysis.sentiment.polarity > -0.3 and analysis.sentiment.polarity <= 0): wnegative += 1 elif (analysis.sentiment.polarity > -0.6 and analysis.sentiment.polarity <= -0.3): negative += 1 elif (analysis.sentiment.polarity > -1 and analysis.sentiment.polarity <= -0.6): snegative += 1 # Write to csv and close csv file csvWriter.writerow(self.tweetText) csvFile.close() # finding average of how people are reacting positive = self.percentage(positive, tweets) wpositive = self.percentage(wpositive, tweets) spositive = self.percentage(spositive, tweets) negative = self.percentage(negative, tweets) wnegative = self.percentage(wnegative, tweets) snegative = self.percentage(snegative, tweets) neutral = self.percentage(neutral, tweets) # finding average reaction polarity = polarity / tweets # printing out data # print("How people are reacting on " + keyword + " by analyzing " + str(tweets) + " tweets.") # print() # print("General Report: ") if (polarity == 0): htmlpolarity = "Neutral" # print("Neutral") elif (polarity > 0 and polarity <= 0.3): htmlpolarity = "Weakly Positive" # print("Weakly Positive") elif (polarity > 0.3 and polarity <= 0.6): htmlpolarity = "Positive" elif (polarity > 0.6 and polarity <= 1): htmlpolarity = "Strongly Positive" elif (polarity > -0.3 and polarity <= 0): htmlpolarity = "Weakly Negative" elif (polarity > -0.6 and polarity <= -0.3): htmlpolarity = "Negative" elif (polarity > -1 and polarity <= -0.6): htmlpolarity = "strongly Negative" self.plotPieChart(positive, wpositive, spositive, negative, wnegative, snegative, neutral, keyword, tweets) print(polarity, htmlpolarity) return polarity, htmlpolarity, positive, wpositive, spositive, negative, wnegative, snegative, neutral, keyword, tweets def cleanTweet(self, tweet): # Remove Links, Special Characters etc from tweet return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t]) | (\w +:\ / \ / \S +)", " ", tweet).split()) # function to calculate percentage def percentage(self, part, whole): temp = 100 * float(part) / float(whole) return format(temp, '.2f') # function which sets and plots the pie chart. The chart is saved in an img file every time the project is run. # The previous image is overwritten. This image is called in the html page. def plotPieChart(self, positive, wpositive, spositive, negative, wnegative, snegative, neutral, keyword, tweets): fig = plt.figure() labels = ['Positive [' + str(positive) + '%]', 'Weakly Positive [' + str(wpositive) + '%]', 'Strongly Positive [' + str(spositive) + '%]', 'Neutral [' + str(neutral) + '%]', 'Negative [' + str(negative) + '%]', 'Weakly Negative [' + str(wnegative) + '%]', 'Strongly Negative [' + str(snegative) + '%]'] sizes = [positive, wpositive, spositive, neutral, negative, wnegative, snegative] colors = ['yellowgreen', 'lightgreen', 'darkgreen', 'gold', 'red', 'lightsalmon', 'darkred'] patches, texts = plt.pie(sizes, colors=colors, startangle=90) plt.legend(patches, labels, loc="best") plt.axis('equal') plt.tight_layout() strFile = r"C:\Users\LENOVO\PycharmProjects\SentimentAnalysis\static\images\plot1.png" if os.path.isfile(strFile): os.remove(strFile) # Opt.: os.system("rm "+strFile) plt.savefig(strFile) plt.show() @second.route('/sentiment_logic', methods=['POST', 'GET'])def sentiment_logic(): # get user input of keyword to search and number of tweets from html form. keyword = request.form.get('keyword') tweets = request.form.get('tweets') sa = SentimentAnalysis() # set variables which can be used in the jinja supported html page polarity, htmlpolarity, positive, wpositive, spositive, negative, wnegative, snegative, neutral, keyword1, tweet1 = sa.DownloadData( keyword, tweets) return render_template('sentiment_analyzer.html', polarity=polarity, htmlpolarity=htmlpolarity, positive=positive, wpositive=wpositive, spositive=spositive, negative=negative, wnegative=wnegative, snegative=snegative, neutral=neutral, keyword=keyword1, tweets=tweet1) @second.route('/visualize')def visualize(): return render_template('PieChart.html')
This template asks the users to enter a topic/word of their interest, and the number of tweets based on that topic that users would like to analyze.
Please note that Twitter has daily and hourly rate limits, which cannot be exceeded.
This form passes the data to second.py file, which calculates the output and sets βjinjaβ variables. (Jinja allows passing values between python and HTML).
These variables then display the output to users.
HTML
<!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/style.css') }}"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"></script> <title>Home</title> </head> <body class="bg-nav"> <!-- code for the navigation header bar--> <header style="height: 80px" class="navbar navbar-dark sticky-top bg-nav flex-md-nowrap p-0 shadow"> <a class="navbar-brand col-md-3 col-lg-2 me-0 px-3" style="font-size: 30px; font-weight: bold" href="#">Twitter Sentiment Analysis</a> <button class="navbar-toggler position-absolute d-md-none collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#sidebarMenu" aria-controls="sidebarMenu" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <nav class="d-inline-flex mt-2 mt-md-0 ms-md-auto"> <a class="me-3 py-2 text-decoration-none text-light" style="font-size: 20px" href="/sentiment_analyzer">Get started</a> <a class="me-3 py-2 text-light text-decoration-none" style="font-size: 20px" href="/home">Home</a> <a class="me-3 py-2 text-light text-decoration-none" style="font-size: 20px" href="/visualize">Visualize</a> <a class="py-2 text-light text-decoration-none" style="font-size: 20px" href="https://www.tweepy.org/">Help</a> </nav> <ul class="navbar-nav px-3"> <li class="nav-item text-nowrap"> <a class="nav-link text-dark card" style="font-size: 20px; padding: 3px" href="/logout">Sign out</a> </li> </ul> </header> <div class="container"> <div class="row"> <div class="card mt-100" style="margin-top: 50px"> <div class="card-body"> <form method="post" action="sentiment_logic"> <label> Enter your search keyword </label><br> <input type="text" class="form-control" name="keyword"> <br> <label> Enter your number of tweets to analyze </label><br> <input type="number" class="form-control" name="tweets"><br> <input type="submit" class="btn btn-primary btn-block btn-lg" value="Search"> </form> <br> <p> Need help? <a href="/register"> Click here </a></p> </div> </div> </div> </div> <!-- Optional JavaScript; choose one of the two! --> <!--output values--> <br> <br> <br> <h1 style="color: black">-----------------------------------------------------------------------------------</h1> <div style="text-align: center;"> <div > {% if polarity %} <h3 style="color: white; text-align: center;font-size:30px; border-radius: 25px; background-color: black">How are people reacting on {{keyword}} by analyzing {{tweets}} Tweets</h3> {% endif %} </div> </div> <!--parent div for reports--> <div class="row"> <div> <!--General sentiment report--> <div class="row"> <div class="mt-100"> <h1 style="color: white; text-align: center;font-size:50px">General Report</h1> <div class="alert alert-primary" role="alert" style="height:70px"> {% if polarity %} <h1 style="text-align: center;font-size:30px"> The Average Sentiment is {{htmlpolarity}} </h1> {%endif%} </div> </div> </div> <!--end of general report--> <!--start of polarity value--> <div class="row"> <div class="mt-100"> <h1 style="color: white; text-align: center;font-size:50px">Sentiment Polarity</h1> <div class="alert alert-primary" role="alert" style="height:70px"> {% if polarity %} <h1 style="text-align: center;font-size:30px"> The sentiment polarity is {{polarity}} </h1> {%endif%} </div> </div> </div> <!--end of polarity value--> </div> <!-- end of parent div for reports--> </div> <div style="margin-top: 50px"> <h1 style="color: white; text-align: center;font-size:50px">Detailed Report</h1> <div class="alert alert-primary" role="alert" style="height:400px"> {% if polarity %} <h2 class="report-text"> {{spositive}} "% people thought it was strongly positive"</h2> <h2 class="report-text"> {{positive}} "% people thought it was positive"</h2> <h2 class="report-text"> {{wpositive}} "% people thought it was weakly positive"</h2> <h2 class="report-text"> {{neutral}} "% people thought it was neutral"</h2> <h2 class="report-text"> {{negative}} "% people thought it was negative"</h2> <h2 class="report-text"> {{wnegative}} "% people thought it was weakly negative"</h2> <h2 class="report-text"> {{snegative}} "% people thought it was strongly negative"</h2> {%endif%} </div> </div> <!--end of report--> <a href="visualize" class="btn btn-primary btn-block btn-lg" style="background-color: crimson; font-size: 30px"> Generate Visualization</a> <br> <br> <!-- Option 1: Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script> <!-- Option 2: Separate Popper and Bootstrap JS --> <!-- <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.1/dist/umd/popper.min.js" integrity="sha384-SR1sx49pcuLnqZUnnPwx6FCym0wLsk5JZuNx2bPPENzswTNFaQU1RDvt3wT4gWFG" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.min.js" integrity="sha384-j0CNLUeiqtyaRmlzUHCPZ+Gy5fQu0dQ6eZ/xAww941Ai1SxSY+0EQqNXNE6DZiVc" crossorigin="anonymous"></script> --> </body></html>
HTML code for the page that displays the login form. The user enters a username and password, which has validations. Once the data is validated, these variables are passed to the main.py file, which connects to the SQL database to check if the login is valid.
HTML
<!doctype html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/style.css') }}"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href= "https://maxcdn.bootstrapcdn.com/bootstrap/ 4.0.0/css/bootstrap.min.css"> <!-- jQuery library --> <script src= "https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js"></script> <script src= "https://cdnjs.cloudflare.com/ajax/libs/ popper.js/1.12.9/umd/popper.min.js"></script> <title>Login</title> </head> <!-- navigation bar design --> <body class="bg-nav"> <nav class="navbar"> <a href="" class="navbar-brand text-light">Sentiment Analysis</a> </nav> <!-- login form outer design --> <div class="container"> <div class="row"> <div class="col-md-8"> <h1 class="text-light display-4 mt-100" style="font-size: 80px; font-weight: bold"> Welcome to this Twitter Sentiment Analysis! </h1> </div> <div class="col-md-4"> <div class="card mt-100"> <div class="card-body"> <!-- login form logic --> <form method="post" action="login_validation"> <div class="form_group"> <label> Email </label><br> <input type="email" class="form-control" name="email" id="email"> <br> <small id="emailvalid" class="form-text text-muted invalid-feedback"> Your email must be a valid email </small> </div> <div class="form_group"> <label> Password </label><br> <input type="password" class="form-control" name="password" id="password"><br> <h5 id="passcheck" style="color: red;"> **Please Fill the password </h5> </div> <input type="submit" class="btn btn-primary btn-block btn-lg" value="Login"> </form> <br> <p> Not a member? <a href="/register"> Create Account</a></p> </div> </div> </div> </div> </div> <script src="/static/app.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script> </body></html>
HTML code for the page that displays the registration form. The user enters a username and password, which has validations. Additionally, the userβs name becomes a value for the cookie that is set in the main.py file.
Once the data is validated, these variables are passed to the main.py file, which connects to the SQL database to check if the login is valid.
HTML
<!doctype html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/style.css') }}"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> <title>Registration</title> </head> <body class="bg-nav"> <nav class="navbar"> <a href="" class="navbar-brand text-light">Sentiment Analysis App</a> </nav> <div class="container"> <div class="row"> <div class="col-md-8"> <h1 class="text-light display-4 mt-100" style="font-size: 80px; font-weight: bold"> Welcome to this Twitter Sentiment Analysis! </h1> </div> <div class="col-md-4"> <div class="card mt-100"> <div class="card-body"> <form method="post" action="/add_user"> <label> Name </label><br> <input type="text" class="form-control" name="uname"> <br> <label> Email </label><br> <input type="email" class="form-control" name="uemail"> <br> <label> Password </label><br> <input type="password" class="form-control" name="upassword"><br> <input type="submit" class="btn btn-primary btn-block btn-lg" value="Login"> </form> <br> <p> Already a member? <a href="/"> Login </a></p> </div> </div> </div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script> </body></html>
HTML home page. The page has 2 main parts
Navigation bar- The navigation bar has links for all other pages, it retrieves the userβs name from the cookie and displays βWelcome Samβ [users name]. This bar also has a logout button.
Bootstrap carousel- This carousel is a customized version of the basic carousel which can be found here.
HTML
<!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/style.css') }}"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> <title>Home</title> </head> <body> <!-- code for the navigation header bar--> <header style="height: 80px" class="navbar navbar-dark sticky-top bg-nav flex-md-nowrap p-0 shadow"> <a class="navbar-brand col-md-3 col-lg-2 me-0 px-3" style="font-size: 30px; font-weight: bold" href="#"> {% if session['user_id'] %} <h3>Welcome {{session['user_id']}}</h3> {%endif%} </a> <button class="navbar-toggler position-absolute d-md-none collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#sidebarMenu" aria-controls="sidebarMenu" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <nav class="d-inline-flex mt-2 mt-md-0 ms-md-auto"> <a class="me-3 py-2 text-decoration-none text-light" style="font-size: 20px" href="/sentiment_analyzer">Get started</a> <a class="me-3 py-2 text-light text-decoration-none" style="font-size: 20px" href="/home">Home</a> <a class="me-3 py-2 text-light text-decoration-none" style="font-size: 20px" href="/visualize">Visualize</a> <a class="py-2 text-light text-decoration-none" style="font-size: 20px" href="https://www.tweepy.org/">Help</a> </nav> <ul class="navbar-nav px-3"> <li class="nav-item text-nowrap"> <a class="nav-link text-dark card" style="font-size: 20px; padding: 3px" href="/logout">Sign out</a> </li> </ul> </header> <style> .carousel-item { height: 34rem; background: black; color: white; position: relative; background-position: center; background-size: cover; } .carousel-caption{ position: absolute; bottom: 0; left: 0; right: 0; padding-bottom: 10px; } .overlay-image{ position: absolute; bottom: 0; left: 0; right: 0; padding-bottom: 0px; background-position: center; background-size: cover; opacity: 0.4; } </style> <!--This is the start of the image slider--> <div id="carouselExampleCaptions" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="1" aria-label="Slide 2"></button> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="2" aria-label="Slide 3"></button> </div> <div class="carousel-inner"> <div style="height: 100px"> <div class="carousel-item active" > <div class="overlay-image"> <img src="/static/images/slideone.jpg" style="width: 100%"> </div> <div class="carousel-caption" > <b> <h1 style="font-size: 100px">Let's get started!</h1> </b> <br> <a href="sentiment_analyzer" class="btn btn-primary btn-block btn-lg" style="background-color: crimson; font-size: 30px"> Click Here to Analyze Some Tweets</a> </div> </div> <div class="carousel-item"> <div class="overlay-image"> <img src="/static/images/slidetwo.jpg" style="width: 100%"> </div> <div class="carousel-caption" > <b> <h1 style="font-size: 100px"> How does this work? </h1> </b> <br> <a href="https://www.tweepy.org/" class="btn btn-primary btn-block btn-lg" style="background-color: crimson; font-size: 20px"> Click Here to know more about this project</a> </div> </div> <div class="carousel-item"> <div class="overlay-image"> <img src="/static/images/slidefour.jpg" style="width: 100%"> </div> <div class="carousel-caption" style="align-self: start; padding-top: 20px " > <b> <h1 style="font-size: 100px"> WorkFlow</h1> </b> <br> <div class="btn btn-primary btn-block btn-lg" style="background-color: #73AD21; color: black; font-weight: bold; font-size:30px;text-align: left; font-family: 'Franklin Gothic Book'"> Enter a keyword of your choice <br> Enter the no of tweets you want to search <br> Voila! See instant Results! <br> Click on Generate to View Detailed Data Visualization. </div> </div> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"></script> </body></html>
This HTML template simply displays an image file saved in our project. This image file is generated in the second.py file code. The image is a Pie Chart, which visually represents the results of sentiment analysis. The image is overwritten every time the code is run.
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title>Data Visualization</title> <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/style.css') }}"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> </head> <body> <header style="height: 80px" class="navbar navbar-dark sticky-top bg-nav flex-md-nowrap p-0 shadow"> <a class="navbar-brand col-md-3 col-lg-2 me-0 px-3" style="font-size: 30px; font-weight: bold" href="#">Twitter Sentiment Analysis</a> <button class="navbar-toggler position-absolute d-md-none collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#sidebarMenu" aria-controls="sidebarMenu" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <nav class="d-inline-flex mt-2 mt-md-0 ms-md-auto"> <a class="me-3 py-2 text-decoration-none text-light" style="font-size: 20px" href="/sentiment_analyzer">Get started</a> <a class="me-3 py-2 text-light text-decoration-none" style="font-size: 20px" href="/home">Home</a> <a class="me-3 py-2 text-light text-decoration-none" style="font-size: 20px" href="/visualize">Visualize</a> <a class="py-2 text-light text-decoration-none" style="font-size: 20px" href="https://www.tweepy.org/">Help</a> </nav> <ul class="navbar-nav px-3"> <li class="nav-item text-nowrap"> <a class="nav-link text-dark card" style="font-size: 20px; padding: 3px" href="/logout">Sign out</a> </li> </ul> </header> <div class="mt-100" style="padding-top: 100px; text-align: center"> <img src="/static/images/plot1.png" > </div> <small style="color: red"> ** Last generated visual. Press CTRL+ Refresh to reload</small><br> <a href="sentiment_analyzer" class="btn btn-primary btn-block btn-lg" style="background-color: crimson; font-size: 30px"> Back </a> <br> <br> </body></html>
The user creates a new account with all the required validations by clicking βCreate accountβ Registration page validations. URL Rewriting is prevented through the use of cookies.After successful registration/login, the user is directed to the home page.Home Page has a bootstrap carousel Slider. At the top left, the cookie is retrieved and displays the logged-in userβs name. This cookie also protects against website hijacking (No user can directly access the /home URL if they are not properly logged in).The Home Page welcomes the user with their registered name, using cookies,The user can navigate using the navigation bar at the top. Click βget startedβ to go to the main module screen.The user enters a keyword, and the number of tweets to analyze. Both fields need to be filled. The users click analyze. The system connects to Tweepy, fetches the latest tweets, analyzes them, and displays results in the respective fields.Users can click on the generate Visualization button at the bottom of the report. This generates a Pie Chart based on the report.When users click, βhow this project worksβ, they are redirected to tweepy documentation.Users can click βlogoutβ to log out and end their session.
The user creates a new account with all the required validations by clicking βCreate accountβ Registration page validations. URL Rewriting is prevented through the use of cookies.
After successful registration/login, the user is directed to the home page.
Home Page has a bootstrap carousel Slider. At the top left, the cookie is retrieved and displays the logged-in userβs name. This cookie also protects against website hijacking (No user can directly access the /home URL if they are not properly logged in).
The Home Page welcomes the user with their registered name, using cookies,
The user can navigate using the navigation bar at the top. Click βget startedβ to go to the main module screen.
The user enters a keyword, and the number of tweets to analyze. Both fields need to be filled. The users click analyze. The system connects to Tweepy, fetches the latest tweets, analyzes them, and displays results in the respective fields.
Users can click on the generate Visualization button at the bottom of the report. This generates a Pie Chart based on the report.
When users click, βhow this project worksβ, they are redirected to tweepy documentation.
Users can click βlogoutβ to log out and end their session.
Use Case Diagram
Twitter boasts 330 million monthly active users, which allows businesses to reach a broad audience and connect with customers without intermediaries. On the downside, thereβs so much information that itβs hard for brands to quickly detect negative social mentions that could harm their business.
Thatβs why sentiment analysis, which involves monitoring emotions in conversations on social media platforms, has become a key strategy in social media marketing. Listening to how customers feel on Twitter allows companies to understand their audience, keep on top of whatβs being said about their brand, and their competitors, and discover new trends in the industry. Companies can take action quickly. The idea can even be extended to ordinary users, where local keywords and hashtags can be used to analyze sentiments from the text on Twitter.
anikakapoor
surinderdawra388
Flask Projects
ProGeek 2021
Python Flask
Python-projects
ProGeek
Project
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Project Idea - A website acting as transaction between oxygen sellers and buyers
Online Schooling System - Python Project
Project Idea - Fintech
Project Idea β Healthcare App
Project Idea | Anonymous Message Prank Game in PHP
SDE SHEET - A Complete Guide for SDE Preparation
Implementing Web Scraping in Python with BeautifulSoup
Working with zip files in Python
XML parsing in Python
Python | Simple GUI calculator using Tkinter
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 511,
"s": 54,
"text": "This is a web app made using Python and Flask Framework. It has a registration system and a dashboard. Users can enter keywords to retrieve live Twitter text based on the keyword, and analyze it for customer feelings and sentiments. This data can be visualized in a graph. This project, in particular, mines data using a popular βTweepyβ API. Tweepy API connects to Twitter in real-time and gathers metadata along with the text from the Twitter platform. "
},
{
"code": null,
"e": 587,
"s": 511,
"text": "To help companies study the customer sentiment around a particular product."
},
{
"code": null,
"e": 664,
"s": 587,
"text": "To help system users analyze a huge amount of data, quickly and efficiently."
},
{
"code": null,
"e": 843,
"s": 664,
"text": "To segregate customer sentiment on a scale of -1 to 1, where -1 represents a strong negative sentimentality towards the keyword(s), and 1 represents a strongly positive reaction."
},
{
"code": null,
"e": 900,
"s": 843,
"text": "To visualize the collected data clearly and effectively."
},
{
"code": null,
"e": 910,
"s": 900,
"text": "HARDWARE:"
},
{
"code": null,
"e": 918,
"s": 910,
"text": "4GB RAM"
},
{
"code": null,
"e": 929,
"s": 918,
"text": "Windows 10"
},
{
"code": null,
"e": 970,
"s": 929,
"text": "Google Chrome web browser for deployment"
},
{
"code": null,
"e": 1012,
"s": 970,
"text": "Internet connection to connect to Twitter"
},
{
"code": null,
"e": 1159,
"s": 1012,
"text": "This project design is software-based, so the hardware design requirements include a 64-bit well-functioning PC with at least 4 Gigabits of RAM. "
},
{
"code": null,
"e": 1169,
"s": 1159,
"text": "SOFTWARE:"
},
{
"code": null,
"e": 1382,
"s": 1169,
"text": "Python- Python is an interpreted, high level, and general-purpose programming language. Python promotes code manageability and readability, making it one of the top applications for working with Machine Learning."
},
{
"code": null,
"e": 1660,
"s": 1382,
"text": "Flask web framework(works with python)- Flask is a web framework. This means flask provides us with tools, libraries, and technologies that will allow me to build a web application and web pages. Flask is a back-end micro-framework, and it makes data handling clean and simple."
},
{
"code": null,
"e": 2001,
"s": 1660,
"text": "Tweepy(Twitter API for Python)- Tweepy is an open-source Python package that gives you a very convenient way to access the Twitter API with Python. Tweepy includes a set of classes and methods that represent Twitterβs models and API endpoints, and it transparently handles various implementation details, such as Data encoding and decoding."
},
{
"code": null,
"e": 2182,
"s": 2001,
"text": "Apache SQL on Xampp server for windows- SQL server runs on phpMyAdmin inside the localhost. This database is used for storing, verifying, and retrieving a userβs login credentials."
},
{
"code": null,
"e": 2306,
"s": 2182,
"text": "Bootstrap- The UI is enhanced with the help of Bootstrap, which helps to build modern, intuitive, and responsive web pages."
},
{
"code": null,
"e": 2440,
"s": 2306,
"text": "JQuery- JQuery is used for sending and retrieving data back and forth from the Tweepy API, and displaying the results on the webpage."
},
{
"code": null,
"e": 2509,
"s": 2440,
"text": "HTML/CSS- HTML and CSS is the base for the website front-end design."
},
{
"code": null,
"e": 2536,
"s": 2509,
"text": "Machine Learning- Moderate"
},
{
"code": null,
"e": 2555,
"s": 2536,
"text": "Programming skills"
},
{
"code": null,
"e": 2573,
"s": 2555,
"text": "Python- Advanced."
},
{
"code": null,
"e": 2619,
"s": 2573,
"text": "HTML/CSS/JQUERY/BOOTSTRAP- Basic to moderate."
},
{
"code": null,
"e": 2647,
"s": 2619,
"text": "SQL/DBMS- Basic to moderate"
},
{
"code": null,
"e": 2679,
"s": 2647,
"text": "Debugging/Deployment β Moderate"
},
{
"code": null,
"e": 2707,
"s": 2679,
"text": "Ability to work with APIβs."
},
{
"code": null,
"e": 2756,
"s": 2707,
"text": "Follow the below steps to implement the project:"
},
{
"code": null,
"e": 2814,
"s": 2756,
"text": "Step 1: Download and Install Xampp Server on your system."
},
{
"code": null,
"e": 2930,
"s": 2814,
"text": "Step 2: Start Apache Xampp and MySQL. Create a database in MySQL with 3 columns (username, email id, and password)."
},
{
"code": null,
"e": 3029,
"s": 2930,
"text": "Step 3: Download and Install PyCharm. Click on Create-> New Project. Give a name to your project. "
},
{
"code": null,
"e": 3148,
"s": 3029,
"text": "Step 4:Type the following code in Pycharm. For detailed project files and hierarchy, refer to this GitHub repository. "
},
{
"code": null,
"e": 3268,
"s": 3148,
"text": "In this file, we first initialize our project. We establish a connection to our SQL database using the βconnβ object. "
},
{
"code": null,
"e": 3454,
"s": 3268,
"text": "We set a user cookie variable, which checks if the user has logged in, before redirecting him/her to the home page. This script also handles the user input on the login/register pages. "
},
{
"code": null,
"e": 3462,
"s": 3454,
"text": "Python3"
},
{
"code": "from flask import Flask, render_template, request, redirect, sessionimport mysql.connectorfrom sentiments import secondimport os app = Flask(__name__) # initializing the user cookieapp.secret_key = os.urandom(24) # blueprint to call the second python file in the project.app.register_blueprint(second) # establishing a connection with mysql database made in xampptry: conn = mysql.connector.connect( host=\"localhost\", user=\"root\", password=\"\", database=\"users\") cursor = conn.cursor()except: print(\"An exception occurred\") # call the login template when the url is http://localhost:5000/@app.route('/')def login(): return render_template('login.html') # call the register template when the url is http://localhost:5000/register@app.route('/register')def register(): return render_template('register.html') @app.route('/home')def home(): if 'user_id' in session: return render_template('home.html') else: return redirect('/') @app.route('/login_validation', methods=['POST'])def login_validation(): email = request.form.get('email') password = request.form.get('password') cursor.execute( \"\"\"SELECT * from `users` WHERE `email` LIKE '{}' AND `password` LIKE '{}'\"\"\".format(email, password)) users = cursor.fetchall() # check if a user has already logged in if len(users) > 0: session['user_id'] = users[0][0] return redirect('/home') else: return redirect('/login') @app.route('/add_user', methods=['POST'])def add_user(): # get user login data and pass the data to database name = request.form.get('uname') email = request.form.get('uemail') password = request.form.get('upassword') cursor.execute(\"\"\"INSERT INTO `users` (`name`,`email`,`password`) VALUES ('{}','{}','{}')\"\"\".format( name, email, password)) conn.commit() cursor.execute( \"\"\"SELECT * from `users` WHERE `email` LIKE '{}'\"\"\".format(email)) myuser = cursor.fetchall() session['user_id'] = myuser[0][0] return redirect('/home') @app.route('/logout')def logout(): # close the session session.pop('user_id') return redirect('/') if __name__ == \"__main__\": app.run(debug=True)",
"e": 5652,
"s": 3462,
"text": null
},
{
"code": null,
"e": 5758,
"s": 5652,
"text": "This is the second python file in our project, which was registered as a blueprint in our βmain.pyβ file."
},
{
"code": null,
"e": 6089,
"s": 5758,
"text": "This code takes the user input from the HTML page, which specifies which keyword is to be searched, and the number of tweets to be looked at. It then connects to the Tweepy API, which retrieves the tweet text. This text is cleaned and then categorized into different sentiments( -1 is an angry/sad emotion, 1 is a happy emotion). "
},
{
"code": null,
"e": 6198,
"s": 6089,
"text": "Based on this, a pie chart is created and saved as an image. This image is later called in other HTML pages."
},
{
"code": null,
"e": 6206,
"s": 6198,
"text": "Python3"
},
{
"code": "from flask import Blueprint, render_template, requestimport matplotlib.pyplot as pltimport os import tweepyimport csvimport refrom textblob import TextBlobimport matplotlibmatplotlib.use('agg') # register this file as a blueprintsecond = Blueprint(\"second\", __name__, static_folder=\"static\", template_folder=\"template\") # render page when url is called@second.route(\"/sentiment_analyzer\")def sentiment_analyzer(): return render_template(\"sentiment_analyzer.html\") # class with main logicclass SentimentAnalysis: def __init__(self): self.tweets = [] self.tweetText = [] # This function first connects to the Tweepy API using API keys def DownloadData(self, keyword, tweets): # authenticating consumerKey = '//get from Tweepy' consumerSecret = '//get from Tweepy' accessToken = '//insert your access token here' accessTokenSecret = '//Tweepy AccessToken secret here' auth = tweepy.OAuthHandler(consumerKey, consumerSecret) auth.set_access_token(accessToken, accessTokenSecret) api = tweepy.API(auth, wait_on_rate_limit=True) # input for term to be searched and how many tweets to search # searchTerm = input(\"Enter Keyword/Tag to search about: \") # NoOfTerms = int(input(\"Enter how many tweets to search: \")) tweets = int(tweets) # searching for tweets self.tweets = tweepy.Cursor( api.search, q=keyword, lang=\"en\").items(tweets) # Open/create a file to append data to csvFile = open('result.csv', 'a') # Use csv writer csvWriter = csv.writer(csvFile) # creating some variables to store info polarity = 0 positive = 0 wpositive = 0 spositive = 0 negative = 0 wnegative = 0 snegative = 0 neutral = 0 # iterating through tweets fetched for tweet in self.tweets: # Append to temp so that we can store in csv later. I use encode UTF-8 self.tweetText.append(self.cleanTweet(tweet.text).encode('utf-8')) # print (tweet.text.translate(non_bmp_map)) #print tweet's text analysis = TextBlob(tweet.text) # print(analysis.sentiment) # print tweet's polarity # adding up polarities to find the average later polarity += analysis.sentiment.polarity # adding reaction of how people are reacting to find average later if (analysis.sentiment.polarity == 0): neutral += 1 elif (analysis.sentiment.polarity > 0 and analysis.sentiment.polarity <= 0.3): wpositive += 1 elif (analysis.sentiment.polarity > 0.3 and analysis.sentiment.polarity <= 0.6): positive += 1 elif (analysis.sentiment.polarity > 0.6 and analysis.sentiment.polarity <= 1): spositive += 1 elif (analysis.sentiment.polarity > -0.3 and analysis.sentiment.polarity <= 0): wnegative += 1 elif (analysis.sentiment.polarity > -0.6 and analysis.sentiment.polarity <= -0.3): negative += 1 elif (analysis.sentiment.polarity > -1 and analysis.sentiment.polarity <= -0.6): snegative += 1 # Write to csv and close csv file csvWriter.writerow(self.tweetText) csvFile.close() # finding average of how people are reacting positive = self.percentage(positive, tweets) wpositive = self.percentage(wpositive, tweets) spositive = self.percentage(spositive, tweets) negative = self.percentage(negative, tweets) wnegative = self.percentage(wnegative, tweets) snegative = self.percentage(snegative, tweets) neutral = self.percentage(neutral, tweets) # finding average reaction polarity = polarity / tweets # printing out data # print(\"How people are reacting on \" + keyword + \" by analyzing \" + str(tweets) + \" tweets.\") # print() # print(\"General Report: \") if (polarity == 0): htmlpolarity = \"Neutral\" # print(\"Neutral\") elif (polarity > 0 and polarity <= 0.3): htmlpolarity = \"Weakly Positive\" # print(\"Weakly Positive\") elif (polarity > 0.3 and polarity <= 0.6): htmlpolarity = \"Positive\" elif (polarity > 0.6 and polarity <= 1): htmlpolarity = \"Strongly Positive\" elif (polarity > -0.3 and polarity <= 0): htmlpolarity = \"Weakly Negative\" elif (polarity > -0.6 and polarity <= -0.3): htmlpolarity = \"Negative\" elif (polarity > -1 and polarity <= -0.6): htmlpolarity = \"strongly Negative\" self.plotPieChart(positive, wpositive, spositive, negative, wnegative, snegative, neutral, keyword, tweets) print(polarity, htmlpolarity) return polarity, htmlpolarity, positive, wpositive, spositive, negative, wnegative, snegative, neutral, keyword, tweets def cleanTweet(self, tweet): # Remove Links, Special Characters etc from tweet return ' '.join(re.sub(\"(@[A-Za-z0-9]+)|([^0-9A-Za-z \\t]) | (\\w +:\\ / \\ / \\S +)\", \" \", tweet).split()) # function to calculate percentage def percentage(self, part, whole): temp = 100 * float(part) / float(whole) return format(temp, '.2f') # function which sets and plots the pie chart. The chart is saved in an img file every time the project is run. # The previous image is overwritten. This image is called in the html page. def plotPieChart(self, positive, wpositive, spositive, negative, wnegative, snegative, neutral, keyword, tweets): fig = plt.figure() labels = ['Positive [' + str(positive) + '%]', 'Weakly Positive [' + str(wpositive) + '%]', 'Strongly Positive [' + str(spositive) + '%]', 'Neutral [' + str(neutral) + '%]', 'Negative [' + str(negative) + '%]', 'Weakly Negative [' + str(wnegative) + '%]', 'Strongly Negative [' + str(snegative) + '%]'] sizes = [positive, wpositive, spositive, neutral, negative, wnegative, snegative] colors = ['yellowgreen', 'lightgreen', 'darkgreen', 'gold', 'red', 'lightsalmon', 'darkred'] patches, texts = plt.pie(sizes, colors=colors, startangle=90) plt.legend(patches, labels, loc=\"best\") plt.axis('equal') plt.tight_layout() strFile = r\"C:\\Users\\LENOVO\\PycharmProjects\\SentimentAnalysis\\static\\images\\plot1.png\" if os.path.isfile(strFile): os.remove(strFile) # Opt.: os.system(\"rm \"+strFile) plt.savefig(strFile) plt.show() @second.route('/sentiment_logic', methods=['POST', 'GET'])def sentiment_logic(): # get user input of keyword to search and number of tweets from html form. keyword = request.form.get('keyword') tweets = request.form.get('tweets') sa = SentimentAnalysis() # set variables which can be used in the jinja supported html page polarity, htmlpolarity, positive, wpositive, spositive, negative, wnegative, snegative, neutral, keyword1, tweet1 = sa.DownloadData( keyword, tweets) return render_template('sentiment_analyzer.html', polarity=polarity, htmlpolarity=htmlpolarity, positive=positive, wpositive=wpositive, spositive=spositive, negative=negative, wnegative=wnegative, snegative=snegative, neutral=neutral, keyword=keyword1, tweets=tweet1) @second.route('/visualize')def visualize(): return render_template('PieChart.html')",
"e": 13890,
"s": 6206,
"text": null
},
{
"code": null,
"e": 14040,
"s": 13890,
"text": "This template asks the users to enter a topic/word of their interest, and the number of tweets based on that topic that users would like to analyze. "
},
{
"code": null,
"e": 14126,
"s": 14040,
"text": "Please note that Twitter has daily and hourly rate limits, which cannot be exceeded. "
},
{
"code": null,
"e": 14282,
"s": 14126,
"text": "This form passes the data to second.py file, which calculates the output and sets βjinjaβ variables. (Jinja allows passing values between python and HTML)."
},
{
"code": null,
"e": 14333,
"s": 14282,
"text": "These variables then display the output to users. "
},
{
"code": null,
"e": 14338,
"s": 14333,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" type=\"text/css\" href=\"{{ url_for('static', filename='css/style.css') }}\"> <!-- Bootstrap CSS --> <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6\" crossorigin=\"anonymous\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"></script> <script src=\"https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css\"></script> <title>Home</title> </head> <body class=\"bg-nav\"> <!-- code for the navigation header bar--> <header style=\"height: 80px\" class=\"navbar navbar-dark sticky-top bg-nav flex-md-nowrap p-0 shadow\"> <a class=\"navbar-brand col-md-3 col-lg-2 me-0 px-3\" style=\"font-size: 30px; font-weight: bold\" href=\"#\">Twitter Sentiment Analysis</a> <button class=\"navbar-toggler position-absolute d-md-none collapsed\" type=\"button\" data-bs-toggle=\"collapse\" data-bs-target=\"#sidebarMenu\" aria-controls=\"sidebarMenu\" aria-expanded=\"false\" aria-label=\"Toggle navigation\"> <span class=\"navbar-toggler-icon\"></span> </button> <nav class=\"d-inline-flex mt-2 mt-md-0 ms-md-auto\"> <a class=\"me-3 py-2 text-decoration-none text-light\" style=\"font-size: 20px\" href=\"/sentiment_analyzer\">Get started</a> <a class=\"me-3 py-2 text-light text-decoration-none\" style=\"font-size: 20px\" href=\"/home\">Home</a> <a class=\"me-3 py-2 text-light text-decoration-none\" style=\"font-size: 20px\" href=\"/visualize\">Visualize</a> <a class=\"py-2 text-light text-decoration-none\" style=\"font-size: 20px\" href=\"https://www.tweepy.org/\">Help</a> </nav> <ul class=\"navbar-nav px-3\"> <li class=\"nav-item text-nowrap\"> <a class=\"nav-link text-dark card\" style=\"font-size: 20px; padding: 3px\" href=\"/logout\">Sign out</a> </li> </ul> </header> <div class=\"container\"> <div class=\"row\"> <div class=\"card mt-100\" style=\"margin-top: 50px\"> <div class=\"card-body\"> <form method=\"post\" action=\"sentiment_logic\"> <label> Enter your search keyword </label><br> <input type=\"text\" class=\"form-control\" name=\"keyword\"> <br> <label> Enter your number of tweets to analyze </label><br> <input type=\"number\" class=\"form-control\" name=\"tweets\"><br> <input type=\"submit\" class=\"btn btn-primary btn-block btn-lg\" value=\"Search\"> </form> <br> <p> Need help? <a href=\"/register\"> Click here </a></p> </div> </div> </div> </div> <!-- Optional JavaScript; choose one of the two! --> <!--output values--> <br> <br> <br> <h1 style=\"color: black\">-----------------------------------------------------------------------------------</h1> <div style=\"text-align: center;\"> <div > {% if polarity %} <h3 style=\"color: white; text-align: center;font-size:30px; border-radius: 25px; background-color: black\">How are people reacting on {{keyword}} by analyzing {{tweets}} Tweets</h3> {% endif %} </div> </div> <!--parent div for reports--> <div class=\"row\"> <div> <!--General sentiment report--> <div class=\"row\"> <div class=\"mt-100\"> <h1 style=\"color: white; text-align: center;font-size:50px\">General Report</h1> <div class=\"alert alert-primary\" role=\"alert\" style=\"height:70px\"> {% if polarity %} <h1 style=\"text-align: center;font-size:30px\"> The Average Sentiment is {{htmlpolarity}} </h1> {%endif%} </div> </div> </div> <!--end of general report--> <!--start of polarity value--> <div class=\"row\"> <div class=\"mt-100\"> <h1 style=\"color: white; text-align: center;font-size:50px\">Sentiment Polarity</h1> <div class=\"alert alert-primary\" role=\"alert\" style=\"height:70px\"> {% if polarity %} <h1 style=\"text-align: center;font-size:30px\"> The sentiment polarity is {{polarity}} </h1> {%endif%} </div> </div> </div> <!--end of polarity value--> </div> <!-- end of parent div for reports--> </div> <div style=\"margin-top: 50px\"> <h1 style=\"color: white; text-align: center;font-size:50px\">Detailed Report</h1> <div class=\"alert alert-primary\" role=\"alert\" style=\"height:400px\"> {% if polarity %} <h2 class=\"report-text\"> {{spositive}} \"% people thought it was strongly positive\"</h2> <h2 class=\"report-text\"> {{positive}} \"% people thought it was positive\"</h2> <h2 class=\"report-text\"> {{wpositive}} \"% people thought it was weakly positive\"</h2> <h2 class=\"report-text\"> {{neutral}} \"% people thought it was neutral\"</h2> <h2 class=\"report-text\"> {{negative}} \"% people thought it was negative\"</h2> <h2 class=\"report-text\"> {{wnegative}} \"% people thought it was weakly negative\"</h2> <h2 class=\"report-text\"> {{snegative}} \"% people thought it was strongly negative\"</h2> {%endif%} </div> </div> <!--end of report--> <a href=\"visualize\" class=\"btn btn-primary btn-block btn-lg\" style=\"background-color: crimson; font-size: 30px\"> Generate Visualization</a> <br> <br> <!-- Option 1: Bootstrap Bundle with Popper --> <script src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js\" integrity=\"sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf\" crossorigin=\"anonymous\"></script> <!-- Option 2: Separate Popper and Bootstrap JS --> <!-- <script src=\"https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.1/dist/umd/popper.min.js\" integrity=\"sha384-SR1sx49pcuLnqZUnnPwx6FCym0wLsk5JZuNx2bPPENzswTNFaQU1RDvt3wT4gWFG\" crossorigin=\"anonymous\"></script> <script src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.min.js\" integrity=\"sha384-j0CNLUeiqtyaRmlzUHCPZ+Gy5fQu0dQ6eZ/xAww941Ai1SxSY+0EQqNXNE6DZiVc\" crossorigin=\"anonymous\"></script> --> </body></html>",
"e": 21117,
"s": 14338,
"text": null
},
{
"code": null,
"e": 21379,
"s": 21117,
"text": "HTML code for the page that displays the login form. The user enters a username and password, which has validations. Once the data is validated, these variables are passed to the main.py file, which connects to the SQL database to check if the login is valid. "
},
{
"code": null,
"e": 21384,
"s": 21379,
"text": "HTML"
},
{
"code": "<!doctype html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" type=\"text/css\" href=\"{{ url_for('static', filename='css/style.css') }}\"> <!-- Bootstrap CSS --> <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6\" crossorigin=\"anonymous\"> <!-- Latest compiled and minified CSS --> <link rel=\"stylesheet\" href= \"https://maxcdn.bootstrapcdn.com/bootstrap/ 4.0.0/css/bootstrap.min.css\"> <!-- jQuery library --> <script src= \"https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js\"></script> <script src= \"https://cdnjs.cloudflare.com/ajax/libs/ popper.js/1.12.9/umd/popper.min.js\"></script> <title>Login</title> </head> <!-- navigation bar design --> <body class=\"bg-nav\"> <nav class=\"navbar\"> <a href=\"\" class=\"navbar-brand text-light\">Sentiment Analysis</a> </nav> <!-- login form outer design --> <div class=\"container\"> <div class=\"row\"> <div class=\"col-md-8\"> <h1 class=\"text-light display-4 mt-100\" style=\"font-size: 80px; font-weight: bold\"> Welcome to this Twitter Sentiment Analysis! </h1> </div> <div class=\"col-md-4\"> <div class=\"card mt-100\"> <div class=\"card-body\"> <!-- login form logic --> <form method=\"post\" action=\"login_validation\"> <div class=\"form_group\"> <label> Email </label><br> <input type=\"email\" class=\"form-control\" name=\"email\" id=\"email\"> <br> <small id=\"emailvalid\" class=\"form-text text-muted invalid-feedback\"> Your email must be a valid email </small> </div> <div class=\"form_group\"> <label> Password </label><br> <input type=\"password\" class=\"form-control\" name=\"password\" id=\"password\"><br> <h5 id=\"passcheck\" style=\"color: red;\"> **Please Fill the password </h5> </div> <input type=\"submit\" class=\"btn btn-primary btn-block btn-lg\" value=\"Login\"> </form> <br> <p> Not a member? <a href=\"/register\"> Create Account</a></p> </div> </div> </div> </div> </div> <script src=\"/static/app.js\"></script> <script src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js\" integrity=\"sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf\" crossorigin=\"anonymous\"></script> </body></html>",
"e": 24524,
"s": 21384,
"text": null
},
{
"code": null,
"e": 24743,
"s": 24524,
"text": "HTML code for the page that displays the registration form. The user enters a username and password, which has validations. Additionally, the userβs name becomes a value for the cookie that is set in the main.py file. "
},
{
"code": null,
"e": 24888,
"s": 24743,
"text": "Once the data is validated, these variables are passed to the main.py file, which connects to the SQL database to check if the login is valid. "
},
{
"code": null,
"e": 24893,
"s": 24888,
"text": "HTML"
},
{
"code": "<!doctype html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" type=\"text/css\" href=\"{{ url_for('static', filename='css/style.css') }}\"> <!-- Bootstrap CSS --> <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6\" crossorigin=\"anonymous\"> <title>Registration</title> </head> <body class=\"bg-nav\"> <nav class=\"navbar\"> <a href=\"\" class=\"navbar-brand text-light\">Sentiment Analysis App</a> </nav> <div class=\"container\"> <div class=\"row\"> <div class=\"col-md-8\"> <h1 class=\"text-light display-4 mt-100\" style=\"font-size: 80px; font-weight: bold\"> Welcome to this Twitter Sentiment Analysis! </h1> </div> <div class=\"col-md-4\"> <div class=\"card mt-100\"> <div class=\"card-body\"> <form method=\"post\" action=\"/add_user\"> <label> Name </label><br> <input type=\"text\" class=\"form-control\" name=\"uname\"> <br> <label> Email </label><br> <input type=\"email\" class=\"form-control\" name=\"uemail\"> <br> <label> Password </label><br> <input type=\"password\" class=\"form-control\" name=\"upassword\"><br> <input type=\"submit\" class=\"btn btn-primary btn-block btn-lg\" value=\"Login\"> </form> <br> <p> Already a member? <a href=\"/\"> Login </a></p> </div> </div> </div> </div> </div> <script src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js\" integrity=\"sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf\" crossorigin=\"anonymous\"></script> </body></html>",
"e": 26997,
"s": 24893,
"text": null
},
{
"code": null,
"e": 27040,
"s": 26997,
"text": "HTML home page. The page has 2 main parts "
},
{
"code": null,
"e": 27227,
"s": 27040,
"text": "Navigation bar- The navigation bar has links for all other pages, it retrieves the userβs name from the cookie and displays βWelcome Samβ [users name]. This bar also has a logout button."
},
{
"code": null,
"e": 27332,
"s": 27227,
"text": "Bootstrap carousel- This carousel is a customized version of the basic carousel which can be found here."
},
{
"code": null,
"e": 27337,
"s": 27332,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" type=\"text/css\" href=\"{{ url_for('static', filename='css/style.css') }}\"> <!-- Bootstrap CSS --> <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6\" crossorigin=\"anonymous\"> <title>Home</title> </head> <body> <!-- code for the navigation header bar--> <header style=\"height: 80px\" class=\"navbar navbar-dark sticky-top bg-nav flex-md-nowrap p-0 shadow\"> <a class=\"navbar-brand col-md-3 col-lg-2 me-0 px-3\" style=\"font-size: 30px; font-weight: bold\" href=\"#\"> {% if session['user_id'] %} <h3>Welcome {{session['user_id']}}</h3> {%endif%} </a> <button class=\"navbar-toggler position-absolute d-md-none collapsed\" type=\"button\" data-bs-toggle=\"collapse\" data-bs-target=\"#sidebarMenu\" aria-controls=\"sidebarMenu\" aria-expanded=\"false\" aria-label=\"Toggle navigation\"> <span class=\"navbar-toggler-icon\"></span> </button> <nav class=\"d-inline-flex mt-2 mt-md-0 ms-md-auto\"> <a class=\"me-3 py-2 text-decoration-none text-light\" style=\"font-size: 20px\" href=\"/sentiment_analyzer\">Get started</a> <a class=\"me-3 py-2 text-light text-decoration-none\" style=\"font-size: 20px\" href=\"/home\">Home</a> <a class=\"me-3 py-2 text-light text-decoration-none\" style=\"font-size: 20px\" href=\"/visualize\">Visualize</a> <a class=\"py-2 text-light text-decoration-none\" style=\"font-size: 20px\" href=\"https://www.tweepy.org/\">Help</a> </nav> <ul class=\"navbar-nav px-3\"> <li class=\"nav-item text-nowrap\"> <a class=\"nav-link text-dark card\" style=\"font-size: 20px; padding: 3px\" href=\"/logout\">Sign out</a> </li> </ul> </header> <style> .carousel-item { height: 34rem; background: black; color: white; position: relative; background-position: center; background-size: cover; } .carousel-caption{ position: absolute; bottom: 0; left: 0; right: 0; padding-bottom: 10px; } .overlay-image{ position: absolute; bottom: 0; left: 0; right: 0; padding-bottom: 0px; background-position: center; background-size: cover; opacity: 0.4; } </style> <!--This is the start of the image slider--> <div id=\"carouselExampleCaptions\" class=\"carousel slide\" data-bs-ride=\"carousel\"> <div class=\"carousel-indicators\"> <button type=\"button\" data-bs-target=\"#carouselExampleCaptions\" data-bs-slide-to=\"0\" class=\"active\" aria-current=\"true\" aria-label=\"Slide 1\"></button> <button type=\"button\" data-bs-target=\"#carouselExampleCaptions\" data-bs-slide-to=\"1\" aria-label=\"Slide 2\"></button> <button type=\"button\" data-bs-target=\"#carouselExampleCaptions\" data-bs-slide-to=\"2\" aria-label=\"Slide 3\"></button> </div> <div class=\"carousel-inner\"> <div style=\"height: 100px\"> <div class=\"carousel-item active\" > <div class=\"overlay-image\"> <img src=\"/static/images/slideone.jpg\" style=\"width: 100%\"> </div> <div class=\"carousel-caption\" > <b> <h1 style=\"font-size: 100px\">Let's get started!</h1> </b> <br> <a href=\"sentiment_analyzer\" class=\"btn btn-primary btn-block btn-lg\" style=\"background-color: crimson; font-size: 30px\"> Click Here to Analyze Some Tweets</a> </div> </div> <div class=\"carousel-item\"> <div class=\"overlay-image\"> <img src=\"/static/images/slidetwo.jpg\" style=\"width: 100%\"> </div> <div class=\"carousel-caption\" > <b> <h1 style=\"font-size: 100px\"> How does this work? </h1> </b> <br> <a href=\"https://www.tweepy.org/\" class=\"btn btn-primary btn-block btn-lg\" style=\"background-color: crimson; font-size: 20px\"> Click Here to know more about this project</a> </div> </div> <div class=\"carousel-item\"> <div class=\"overlay-image\"> <img src=\"/static/images/slidefour.jpg\" style=\"width: 100%\"> </div> <div class=\"carousel-caption\" style=\"align-self: start; padding-top: 20px \" > <b> <h1 style=\"font-size: 100px\"> WorkFlow</h1> </b> <br> <div class=\"btn btn-primary btn-block btn-lg\" style=\"background-color: #73AD21; color: black; font-weight: bold; font-size:30px;text-align: left; font-family: 'Franklin Gothic Book'\"> Enter a keyword of your choice <br> Enter the no of tweets you want to search <br> Voila! See instant Results! <br> Click on Generate to View Detailed Data Visualization. </div> </div> </div> </div> <button class=\"carousel-control-prev\" type=\"button\" data-bs-target=\"#carouselExampleCaptions\" data-bs-slide=\"prev\"> <span class=\"carousel-control-prev-icon\" aria-hidden=\"true\"></span> <span class=\"visually-hidden\">Previous</span> </button> <button class=\"carousel-control-next\" type=\"button\" data-bs-target=\"#carouselExampleCaptions\" data-bs-slide=\"next\"> <span class=\"carousel-control-next-icon\" aria-hidden=\"true\"></span> <span class=\"visually-hidden\">Next</span> </button> </div> </div> <script src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js\" integrity=\"sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf\" crossorigin=\"anonymous\"></script> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"></script> <script src=\"https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css\"></script> </body></html>",
"e": 33995,
"s": 27337,
"text": null
},
{
"code": null,
"e": 34264,
"s": 33995,
"text": "This HTML template simply displays an image file saved in our project. This image file is generated in the second.py file code. The image is a Pie Chart, which visually represents the results of sentiment analysis. The image is overwritten every time the code is run. "
},
{
"code": null,
"e": 34269,
"s": 34264,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title>Data Visualization</title> <link rel=\"stylesheet\" type=\"text/css\" href=\"{{ url_for('static', filename='css/style.css') }}\"> <!-- Bootstrap CSS --> <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6\" crossorigin=\"anonymous\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"></script> </head> </head> <body> <header style=\"height: 80px\" class=\"navbar navbar-dark sticky-top bg-nav flex-md-nowrap p-0 shadow\"> <a class=\"navbar-brand col-md-3 col-lg-2 me-0 px-3\" style=\"font-size: 30px; font-weight: bold\" href=\"#\">Twitter Sentiment Analysis</a> <button class=\"navbar-toggler position-absolute d-md-none collapsed\" type=\"button\" data-bs-toggle=\"collapse\" data-bs-target=\"#sidebarMenu\" aria-controls=\"sidebarMenu\" aria-expanded=\"false\" aria-label=\"Toggle navigation\"> <span class=\"navbar-toggler-icon\"></span> </button> <nav class=\"d-inline-flex mt-2 mt-md-0 ms-md-auto\"> <a class=\"me-3 py-2 text-decoration-none text-light\" style=\"font-size: 20px\" href=\"/sentiment_analyzer\">Get started</a> <a class=\"me-3 py-2 text-light text-decoration-none\" style=\"font-size: 20px\" href=\"/home\">Home</a> <a class=\"me-3 py-2 text-light text-decoration-none\" style=\"font-size: 20px\" href=\"/visualize\">Visualize</a> <a class=\"py-2 text-light text-decoration-none\" style=\"font-size: 20px\" href=\"https://www.tweepy.org/\">Help</a> </nav> <ul class=\"navbar-nav px-3\"> <li class=\"nav-item text-nowrap\"> <a class=\"nav-link text-dark card\" style=\"font-size: 20px; padding: 3px\" href=\"/logout\">Sign out</a> </li> </ul> </header> <div class=\"mt-100\" style=\"padding-top: 100px; text-align: center\"> <img src=\"/static/images/plot1.png\" > </div> <small style=\"color: red\"> ** Last generated visual. Press CTRL+ Refresh to reload</small><br> <a href=\"sentiment_analyzer\" class=\"btn btn-primary btn-block btn-lg\" style=\"background-color: crimson; font-size: 30px\"> Back </a> <br> <br> </body></html>",
"e": 36605,
"s": 34269,
"text": null
},
{
"code": null,
"e": 37817,
"s": 36608,
"text": "The user creates a new account with all the required validations by clicking βCreate accountβ Registration page validations. URL Rewriting is prevented through the use of cookies.After successful registration/login, the user is directed to the home page.Home Page has a bootstrap carousel Slider. At the top left, the cookie is retrieved and displays the logged-in userβs name. This cookie also protects against website hijacking (No user can directly access the /home URL if they are not properly logged in).The Home Page welcomes the user with their registered name, using cookies,The user can navigate using the navigation bar at the top. Click βget startedβ to go to the main module screen.The user enters a keyword, and the number of tweets to analyze. Both fields need to be filled. The users click analyze. The system connects to Tweepy, fetches the latest tweets, analyzes them, and displays results in the respective fields.Users can click on the generate Visualization button at the bottom of the report. This generates a Pie Chart based on the report.When users click, βhow this project worksβ, they are redirected to tweepy documentation.Users can click βlogoutβ to log out and end their session."
},
{
"code": null,
"e": 37997,
"s": 37817,
"text": "The user creates a new account with all the required validations by clicking βCreate accountβ Registration page validations. URL Rewriting is prevented through the use of cookies."
},
{
"code": null,
"e": 38073,
"s": 37997,
"text": "After successful registration/login, the user is directed to the home page."
},
{
"code": null,
"e": 38329,
"s": 38073,
"text": "Home Page has a bootstrap carousel Slider. At the top left, the cookie is retrieved and displays the logged-in userβs name. This cookie also protects against website hijacking (No user can directly access the /home URL if they are not properly logged in)."
},
{
"code": null,
"e": 38404,
"s": 38329,
"text": "The Home Page welcomes the user with their registered name, using cookies,"
},
{
"code": null,
"e": 38516,
"s": 38404,
"text": "The user can navigate using the navigation bar at the top. Click βget startedβ to go to the main module screen."
},
{
"code": null,
"e": 38756,
"s": 38516,
"text": "The user enters a keyword, and the number of tweets to analyze. Both fields need to be filled. The users click analyze. The system connects to Tweepy, fetches the latest tweets, analyzes them, and displays results in the respective fields."
},
{
"code": null,
"e": 38886,
"s": 38756,
"text": "Users can click on the generate Visualization button at the bottom of the report. This generates a Pie Chart based on the report."
},
{
"code": null,
"e": 38975,
"s": 38886,
"text": "When users click, βhow this project worksβ, they are redirected to tweepy documentation."
},
{
"code": null,
"e": 39034,
"s": 38975,
"text": "Users can click βlogoutβ to log out and end their session."
},
{
"code": null,
"e": 39051,
"s": 39034,
"text": "Use Case Diagram"
},
{
"code": null,
"e": 39347,
"s": 39051,
"text": "Twitter boasts 330 million monthly active users, which allows businesses to reach a broad audience and connect with customers without intermediaries. On the downside, thereβs so much information that itβs hard for brands to quickly detect negative social mentions that could harm their business."
},
{
"code": null,
"e": 39894,
"s": 39347,
"text": "Thatβs why sentiment analysis, which involves monitoring emotions in conversations on social media platforms, has become a key strategy in social media marketing. Listening to how customers feel on Twitter allows companies to understand their audience, keep on top of whatβs being said about their brand, and their competitors, and discover new trends in the industry. Companies can take action quickly. The idea can even be extended to ordinary users, where local keywords and hashtags can be used to analyze sentiments from the text on Twitter."
},
{
"code": null,
"e": 39908,
"s": 39896,
"text": "anikakapoor"
},
{
"code": null,
"e": 39925,
"s": 39908,
"text": "surinderdawra388"
},
{
"code": null,
"e": 39940,
"s": 39925,
"text": "Flask Projects"
},
{
"code": null,
"e": 39953,
"s": 39940,
"text": "ProGeek 2021"
},
{
"code": null,
"e": 39966,
"s": 39953,
"text": "Python Flask"
},
{
"code": null,
"e": 39982,
"s": 39966,
"text": "Python-projects"
},
{
"code": null,
"e": 39990,
"s": 39982,
"text": "ProGeek"
},
{
"code": null,
"e": 39998,
"s": 39990,
"text": "Project"
},
{
"code": null,
"e": 40005,
"s": 39998,
"text": "Python"
},
{
"code": null,
"e": 40103,
"s": 40005,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40184,
"s": 40103,
"text": "Project Idea - A website acting as transaction between oxygen sellers and buyers"
},
{
"code": null,
"e": 40225,
"s": 40184,
"text": "Online Schooling System - Python Project"
},
{
"code": null,
"e": 40248,
"s": 40225,
"text": "Project Idea - Fintech"
},
{
"code": null,
"e": 40278,
"s": 40248,
"text": "Project Idea β Healthcare App"
},
{
"code": null,
"e": 40329,
"s": 40278,
"text": "Project Idea | Anonymous Message Prank Game in PHP"
},
{
"code": null,
"e": 40378,
"s": 40329,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 40433,
"s": 40378,
"text": "Implementing Web Scraping in Python with BeautifulSoup"
},
{
"code": null,
"e": 40466,
"s": 40433,
"text": "Working with zip files in Python"
},
{
"code": null,
"e": 40488,
"s": 40466,
"text": "XML parsing in Python"
}
] |
G-Fact 19 (Logical and Bitwise Not Operators on Boolean)
|
01 Jun, 2022
Most of the languages including C, C++, Java and Python provide the boolean type that can be either set to False or True.Consider below programs that use Logical Not (or !) operator on boolean.
C++
Python
C#
Javascript
// A C++ program that uses Logical Not or ! on boolean#include <iostream>using namespace std; int main(){ // we are making variable store bool expression of false // and true, it can be also written as (1) for 'true' and // (0) for 'false' bool is_it_true = false; bool is_it_false = true; // This code below print first false (0) and then true // (1) cause of we have used 'not' (!) operator in second // case cout << is_it_true << endl; cout << !is_it_true << endl; // This code below print first true (1) and then false // (0) cause of we have used 'not' (!) operator in second // case cout << is_it_false << endl; cout << !is_it_false << endl; return 0;}
# A Python program that uses Logical Not or ! on booleana = not Trueb = not Falseprint aprint b# Output: False# True
// C# program that uses Logical// Not or ! on booleanusing System; class GFG{ public static void Main () { bool a = true, b = false; Console.WriteLine(!a); Console.WriteLine(!b); }}// Output: False// True // This code is contributed// by Rajput-Ji
<script>// A javascript program that uses Logical Not or ! on boolean var a = true, b = false; document.write(!a+"<br/>"); document.write(!b); // Output: False// True // This code contributed by gauravrajput1</script>
0
1
1
0
The outputs of above programs are as expected, but the outputs following programs may not be as expected if we have not used Bitwise Not (or ~) operator before.
Python
Java
# A Python program that uses Bitwise Not or ~ on booleana = Trueb = Falseprint ~aprint ~b
C/C++
// C/C++ program that uses Bitwise Not or ~ on boolean
#include <bits/stdc++.h>
using namespace std;
int main()
{
bool a = true, b = false;
cout << ~a << endl << ~b;
return 0;
}
// A Java program that uses Bitwise Not or ~ on booleanimport java.io.*; class GFG{ public static void main (String[] args) { boolean a = true, b = false; System.out.println(~a); System.out.println(~b); }}
Output:
6: error: bad operand type boolean for unary operator '~'
System.out.println(~a);
^
7: error: bad operand type boolean for unary operator '~'
System.out.println(~b);
^
2 errors
Conclusion: βLogical not or !β is meant for boolean values and βbitwise not or ~β is for integers. Languages like C/C++ and python do auto promotion of boolean to integer type when an integer operator is applied. But Java doesnβt do it.This article is contributed by Arpit Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Rajput-Ji
GauravRajput1
jhav365
GFacts
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between YOLO and SSD
How to Install and Configure MongoDB in Ubuntu?
Can C++ reference member be declared without being initialized with declaration?
What all is inherited from parent class in C++?
10 Web Development and Web Design Facts That You Should Know
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Jun, 2022"
},
{
"code": null,
"e": 248,
"s": 52,
"text": "Most of the languages including C, C++, Java and Python provide the boolean type that can be either set to False or True.Consider below programs that use Logical Not (or !) operator on boolean. "
},
{
"code": null,
"e": 252,
"s": 248,
"text": "C++"
},
{
"code": null,
"e": 259,
"s": 252,
"text": "Python"
},
{
"code": null,
"e": 262,
"s": 259,
"text": "C#"
},
{
"code": null,
"e": 273,
"s": 262,
"text": "Javascript"
},
{
"code": "// A C++ program that uses Logical Not or ! on boolean#include <iostream>using namespace std; int main(){ // we are making variable store bool expression of false // and true, it can be also written as (1) for 'true' and // (0) for 'false' bool is_it_true = false; bool is_it_false = true; // This code below print first false (0) and then true // (1) cause of we have used 'not' (!) operator in second // case cout << is_it_true << endl; cout << !is_it_true << endl; // This code below print first true (1) and then false // (0) cause of we have used 'not' (!) operator in second // case cout << is_it_false << endl; cout << !is_it_false << endl; return 0;}",
"e": 982,
"s": 273,
"text": null
},
{
"code": "# A Python program that uses Logical Not or ! on booleana = not Trueb = not Falseprint aprint b# Output: False# True",
"e": 1107,
"s": 982,
"text": null
},
{
"code": "// C# program that uses Logical// Not or ! on booleanusing System; class GFG{ public static void Main () { bool a = true, b = false; Console.WriteLine(!a); Console.WriteLine(!b); }}// Output: False// True // This code is contributed// by Rajput-Ji",
"e": 1393,
"s": 1107,
"text": null
},
{
"code": "<script>// A javascript program that uses Logical Not or ! on boolean var a = true, b = false; document.write(!a+\"<br/>\"); document.write(!b); // Output: False// True // This code contributed by gauravrajput1</script>",
"e": 1637,
"s": 1393,
"text": null
},
{
"code": null,
"e": 1646,
"s": 1637,
"text": "0\n1\n1\n0\n"
},
{
"code": null,
"e": 1808,
"s": 1646,
"text": "The outputs of above programs are as expected, but the outputs following programs may not be as expected if we have not used Bitwise Not (or ~) operator before. "
},
{
"code": null,
"e": 1815,
"s": 1808,
"text": "Python"
},
{
"code": null,
"e": 1820,
"s": 1815,
"text": "Java"
},
{
"code": "# A Python program that uses Bitwise Not or ~ on booleana = Trueb = Falseprint ~aprint ~b",
"e": 1910,
"s": 1820,
"text": null
},
{
"code": null,
"e": 1916,
"s": 1910,
"text": "C/C++"
},
{
"code": null,
"e": 2108,
"s": 1916,
"text": "\n// C/C++ program that uses Bitwise Not or ~ on boolean\n#include <bits/stdc++.h>\nusing namespace std;\nint main()\n{\n bool a = true, b = false;\n cout << ~a << endl << ~b;\n return 0;\n}\n"
},
{
"code": "// A Java program that uses Bitwise Not or ~ on booleanimport java.io.*; class GFG{ public static void main (String[] args) { boolean a = true, b = false; System.out.println(~a); System.out.println(~b); }}",
"e": 2344,
"s": 2108,
"text": null
},
{
"code": null,
"e": 2354,
"s": 2344,
"text": "Output: "
},
{
"code": null,
"e": 2601,
"s": 2354,
"text": "6: error: bad operand type boolean for unary operator '~'\n System.out.println(~a);\n ^\n7: error: bad operand type boolean for unary operator '~'\n System.out.println(~b);\n ^\n2 errors"
},
{
"code": null,
"e": 3229,
"s": 2601,
"text": "Conclusion: βLogical not or !β is meant for boolean values and βbitwise not or ~β is for integers. Languages like C/C++ and python do auto promotion of boolean to integer type when an integer operator is applied. But Java doesnβt do it.This article is contributed by Arpit Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 3239,
"s": 3229,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 3253,
"s": 3239,
"text": "GauravRajput1"
},
{
"code": null,
"e": 3261,
"s": 3253,
"text": "jhav365"
},
{
"code": null,
"e": 3268,
"s": 3261,
"text": "GFacts"
},
{
"code": null,
"e": 3275,
"s": 3268,
"text": "Python"
},
{
"code": null,
"e": 3373,
"s": 3275,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3405,
"s": 3373,
"text": "Difference between YOLO and SSD"
},
{
"code": null,
"e": 3453,
"s": 3405,
"text": "How to Install and Configure MongoDB in Ubuntu?"
},
{
"code": null,
"e": 3534,
"s": 3453,
"text": "Can C++ reference member be declared without being initialized with declaration?"
},
{
"code": null,
"e": 3582,
"s": 3534,
"text": "What all is inherited from parent class in C++?"
},
{
"code": null,
"e": 3643,
"s": 3582,
"text": "10 Web Development and Web Design Facts That You Should Know"
},
{
"code": null,
"e": 3671,
"s": 3643,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3721,
"s": 3671,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3743,
"s": 3721,
"text": "Python map() function"
},
{
"code": null,
"e": 3787,
"s": 3743,
"text": "How to get column names in Pandas dataframe"
}
] |
Python | Perform Sentence Segmentation Using Spacy
|
05 Sep, 2020
The process of deciding from where the sentences actually start or end in NLP or we can simply say that here we are dividing a paragraph based on sentences. This process is known as Sentence Segmentation. In Python, we implement this part of NLP using the spacy library.
Spacy is used for Natural Language Processing in Python.
To use this library in our python program we first need to install it.
Command to install this library:
pip install spacy
python -m spacy download en_core_web_sm
Here en_core_web_sm means core English Language available online of small size.
Example:
we have the following paragraph:
"I Love Coding. Geeks for Geeks helped me in this regard very much. I Love Geeks for Geeks."
here there are 3 sentences.
1. I Love Coding.
2. Geeks for Geeks helped me in this regard very much.
3. I Love Geeks for Geeks
In python, .sents is used for sentence segmentation which is present inside spacy. The output is given by .sents is a generator and we need to use the list if we want to print them randomly.
Code:
#import spacy libraryimport spacy #load core english librarynlp = spacy.load("en_core_web_sm") #take unicode string #here u stands for unicodedoc = nlp(u"I Love Coding. Geeks for Geeks helped me in this regard very much. I Love Geeks for Geeks.")#to print sentencesfor sent in doc.sents: print(sent)
Output:Now if we try to use doc.sents randomly then what happens:
Code: To overcome this error we first need to convert this generator into a list using list function.
#converting the generator object result in to listdoc1 = list(doc.sents) #Now we can use it randomly asdoc1[1]
Output:
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 299,
"s": 28,
"text": "The process of deciding from where the sentences actually start or end in NLP or we can simply say that here we are dividing a paragraph based on sentences. This process is known as Sentence Segmentation. In Python, we implement this part of NLP using the spacy library."
},
{
"code": null,
"e": 356,
"s": 299,
"text": "Spacy is used for Natural Language Processing in Python."
},
{
"code": null,
"e": 427,
"s": 356,
"text": "To use this library in our python program we first need to install it."
},
{
"code": null,
"e": 460,
"s": 427,
"text": "Command to install this library:"
},
{
"code": null,
"e": 599,
"s": 460,
"text": "pip install spacy\npython -m spacy download en_core_web_sm\nHere en_core_web_sm means core English Language available online of small size."
},
{
"code": null,
"e": 608,
"s": 599,
"text": "Example:"
},
{
"code": null,
"e": 861,
"s": 608,
"text": "we have the following paragraph:\n\"I Love Coding. Geeks for Geeks helped me in this regard very much. I Love Geeks for Geeks.\"\nhere there are 3 sentences.\n1. I Love Coding.\n2. Geeks for Geeks helped me in this regard very much.\n3. I Love Geeks for Geeks"
},
{
"code": null,
"e": 1052,
"s": 861,
"text": "In python, .sents is used for sentence segmentation which is present inside spacy. The output is given by .sents is a generator and we need to use the list if we want to print them randomly."
},
{
"code": null,
"e": 1058,
"s": 1052,
"text": "Code:"
},
{
"code": "#import spacy libraryimport spacy #load core english librarynlp = spacy.load(\"en_core_web_sm\") #take unicode string #here u stands for unicodedoc = nlp(u\"I Love Coding. Geeks for Geeks helped me in this regard very much. I Love Geeks for Geeks.\")#to print sentencesfor sent in doc.sents: print(sent)",
"e": 1362,
"s": 1058,
"text": null
},
{
"code": null,
"e": 1428,
"s": 1362,
"text": "Output:Now if we try to use doc.sents randomly then what happens:"
},
{
"code": null,
"e": 1530,
"s": 1428,
"text": "Code: To overcome this error we first need to convert this generator into a list using list function."
},
{
"code": "#converting the generator object result in to listdoc1 = list(doc.sents) #Now we can use it randomly asdoc1[1]",
"e": 1642,
"s": 1530,
"text": null
},
{
"code": null,
"e": 1650,
"s": 1642,
"text": "Output:"
},
{
"code": null,
"e": 1657,
"s": 1650,
"text": "Python"
}
] |
Ruby | Types of Variables
|
30 Jul, 2018
There are different types of variables in Ruby:
Local variables
Instance variables
Class variables
Global variables
Each variable in Ruby is declared by using a special character at the start of the variable name which is mentioned in the following table:
Local Variables: A local variable name always starts with a lowercase letter(a-z) or underscore (_). These variables are local to the code construct in which they are declared. A local variable is only accessible within the block of its initialization. Local variables are not available outside the method. There is no need to initialize the local variables.
Example:
age = 10
_Age = 20
Instance Variables: An instance variable name always starts with a @ sign. They are similar to Class variables but their values are local to specific instances of an object. Instance variables are available across methods for any specified instance or object i.e. instance variables can change from object to object. There is no need to initialize the instance variables and uninitialized instance variable always contains a nil value.
Example:
#!/usr/bin/ruby# Ruby program to illustrate # the Instance Variables class Customer def initialize(id, name, addr) # Instance Variables @cust_id = id @cust_name = name @cust_addr = addr end # displaying result def display_details() puts "Customer id #@cust_id" puts "Customer name #@cust_name" puts "Customer address #@cust_addr" endend # Create Objectscust1 = Customer.new("1", "John", "Wisdom Apartments, Ludhiya")cust2 = Customer.new("2", "Poul", "New Empire road, Khandala") # Call Methodscust1.display_details()cust2.display_details()
Output:
Customer id 1
Customer name John
Customer address Wisdom Apartments, Ludhiya
Customer id 2
Customer name Poul
Customer address New Empire road, Khandala
Class Variables: A class variable name always starts with @@ sign.It is available across different objects. A class variable belongs to the class and it is a characteristic of a class. They need to be initialized before use. Another way of thinking about class variables is as global variables within the context of a single class. A class variable is shared by all the descendants of the class. An uninitialized class variable will result in an error.
Example:
#!/usr/bin/ruby# Ruby program to illustrate # the Class Variables class Customer # class variable @@no_of_customers = 0 def initialize(id, name, addr) # An instance Variable @cust_id = id @cust_name = name @cust_addr = addr end # displaying result def display_details() puts "Customer id #@cust_id" puts "Customer name #@cust_name" puts "Customer address #@cust_addr" end def total_no_of_customers() # class variable @@no_of_customers += 1 puts "Total number of customers: #@@no_of_customers" endend # Create Objectscust1 = Customer.new("1", "John", "Wisdom Apartments, Ludhiya")cust2 = Customer.new("2", "Poul", "New Empire road, Khandala") # Call Methodscust1.display_details()cust1.total_no_of_customers()cust2.display_details()cust2.total_no_of_customers()
Output:
Customer id 1
Customer name John
Customer address Wisdom Apartments, Ludhiya
Total number of customers: 1
Customer id 2
Customer name Poul
Customer address New Empire road, Khandala
Total number of customers: 2
Global Variables: A global variable name always starts with $. Class variables are not available across classes. If you want to have a single variable, which is available across classes, you need to define a global variable. Its scope is global, means it can be accessed from anywhere in a program. By default, an uninitialized global variable has a nil value and its use can cause the programs to be cryptic and complex.
Example:
#!/usr/bin/ruby# Ruby program to illustrate # the Global Variables #!/usr/bin/ruby # global variable$global_variable = 10class Class1 def print_global puts "Global variable in Class1 is #$global_variable" endendclass Class2 def print_global puts "Global variable in Class2 is #$global_variable" endendclass1obj = Class1.newclass1obj.print_globalclass2obj = Class2.newclass2obj.print_global
Output:
Global variable in Class1 is 10
Global variable in Class2 is 10
Ruby-Basics
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Jul, 2018"
},
{
"code": null,
"e": 100,
"s": 52,
"text": "There are different types of variables in Ruby:"
},
{
"code": null,
"e": 116,
"s": 100,
"text": "Local variables"
},
{
"code": null,
"e": 135,
"s": 116,
"text": "Instance variables"
},
{
"code": null,
"e": 151,
"s": 135,
"text": "Class variables"
},
{
"code": null,
"e": 168,
"s": 151,
"text": "Global variables"
},
{
"code": null,
"e": 308,
"s": 168,
"text": "Each variable in Ruby is declared by using a special character at the start of the variable name which is mentioned in the following table:"
},
{
"code": null,
"e": 667,
"s": 308,
"text": "Local Variables: A local variable name always starts with a lowercase letter(a-z) or underscore (_). These variables are local to the code construct in which they are declared. A local variable is only accessible within the block of its initialization. Local variables are not available outside the method. There is no need to initialize the local variables."
},
{
"code": null,
"e": 676,
"s": 667,
"text": "Example:"
},
{
"code": null,
"e": 696,
"s": 676,
"text": "age = 10\n_Age = 20\n"
},
{
"code": null,
"e": 1132,
"s": 696,
"text": "Instance Variables: An instance variable name always starts with a @ sign. They are similar to Class variables but their values are local to specific instances of an object. Instance variables are available across methods for any specified instance or object i.e. instance variables can change from object to object. There is no need to initialize the instance variables and uninitialized instance variable always contains a nil value."
},
{
"code": null,
"e": 1141,
"s": 1132,
"text": "Example:"
},
{
"code": "#!/usr/bin/ruby# Ruby program to illustrate # the Instance Variables class Customer def initialize(id, name, addr) # Instance Variables @cust_id = id @cust_name = name @cust_addr = addr end # displaying result def display_details() puts \"Customer id #@cust_id\" puts \"Customer name #@cust_name\" puts \"Customer address #@cust_addr\" endend # Create Objectscust1 = Customer.new(\"1\", \"John\", \"Wisdom Apartments, Ludhiya\")cust2 = Customer.new(\"2\", \"Poul\", \"New Empire road, Khandala\") # Call Methodscust1.display_details()cust2.display_details()",
"e": 1704,
"s": 1141,
"text": null
},
{
"code": null,
"e": 1712,
"s": 1704,
"text": "Output:"
},
{
"code": null,
"e": 1865,
"s": 1712,
"text": "Customer id 1\nCustomer name John\nCustomer address Wisdom Apartments, Ludhiya\nCustomer id 2\nCustomer name Poul\nCustomer address New Empire road, Khandala"
},
{
"code": null,
"e": 2318,
"s": 1865,
"text": "Class Variables: A class variable name always starts with @@ sign.It is available across different objects. A class variable belongs to the class and it is a characteristic of a class. They need to be initialized before use. Another way of thinking about class variables is as global variables within the context of a single class. A class variable is shared by all the descendants of the class. An uninitialized class variable will result in an error."
},
{
"code": null,
"e": 2327,
"s": 2318,
"text": "Example:"
},
{
"code": "#!/usr/bin/ruby# Ruby program to illustrate # the Class Variables class Customer # class variable @@no_of_customers = 0 def initialize(id, name, addr) # An instance Variable @cust_id = id @cust_name = name @cust_addr = addr end # displaying result def display_details() puts \"Customer id #@cust_id\" puts \"Customer name #@cust_name\" puts \"Customer address #@cust_addr\" end def total_no_of_customers() # class variable @@no_of_customers += 1 puts \"Total number of customers: #@@no_of_customers\" endend # Create Objectscust1 = Customer.new(\"1\", \"John\", \"Wisdom Apartments, Ludhiya\")cust2 = Customer.new(\"2\", \"Poul\", \"New Empire road, Khandala\") # Call Methodscust1.display_details()cust1.total_no_of_customers()cust2.display_details()cust2.total_no_of_customers()",
"e": 3120,
"s": 2327,
"text": null
},
{
"code": null,
"e": 3128,
"s": 3120,
"text": "Output:"
},
{
"code": null,
"e": 3339,
"s": 3128,
"text": "Customer id 1\nCustomer name John\nCustomer address Wisdom Apartments, Ludhiya\nTotal number of customers: 1\nCustomer id 2\nCustomer name Poul\nCustomer address New Empire road, Khandala\nTotal number of customers: 2"
},
{
"code": null,
"e": 3761,
"s": 3339,
"text": "Global Variables: A global variable name always starts with $. Class variables are not available across classes. If you want to have a single variable, which is available across classes, you need to define a global variable. Its scope is global, means it can be accessed from anywhere in a program. By default, an uninitialized global variable has a nil value and its use can cause the programs to be cryptic and complex."
},
{
"code": null,
"e": 3770,
"s": 3761,
"text": "Example:"
},
{
"code": "#!/usr/bin/ruby# Ruby program to illustrate # the Global Variables #!/usr/bin/ruby # global variable$global_variable = 10class Class1 def print_global puts \"Global variable in Class1 is #$global_variable\" endendclass Class2 def print_global puts \"Global variable in Class2 is #$global_variable\" endendclass1obj = Class1.newclass1obj.print_globalclass2obj = Class2.newclass2obj.print_global",
"e": 4163,
"s": 3770,
"text": null
},
{
"code": null,
"e": 4171,
"s": 4163,
"text": "Output:"
},
{
"code": null,
"e": 4235,
"s": 4171,
"text": "Global variable in Class1 is 10\nGlobal variable in Class2 is 10"
},
{
"code": null,
"e": 4247,
"s": 4235,
"text": "Ruby-Basics"
},
{
"code": null,
"e": 4252,
"s": 4247,
"text": "Ruby"
}
] |
Reader ready() method in Java with Examples
|
07 Feb, 2019
The ready() method of Reader Class in Java is used to check whether this Reader is ready to be read or not. It returns a boolean which states if the reader is ready.
Syntax:
public void ready()
Parameters: This method does not accepts any parameters
Return Value: This method returns a boolean value which tells if this Reader is ready to be read or not. It return true if it is ready. Else it returns false.
Exception: This method throws IOException if some error occurs while input-output.
Below methods illustrates the working of ready() method:
Program 1:
// Java program to demonstrate// Reader ready() method import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { try { String str = "GeeksForGeeks"; // Create a Reader instance Reader reader = new StringReader(str); // Check if the Reader is // ready to be read using ready() System.out.println("Is Reader ready " + "to be read: " + reader.ready()); // Get the character // to be read from the stream int ch; // Read the first 5 characters // to this reader using read() method // This will put the str in the stream // till it is read by the reader for (int i = 0; i < 5; i++) { ch = reader.read(); System.out.println("\nInteger value " + "of character read: " + ch); System.out.println("Actual " + "character read: " + (char)ch); } reader.close(); } catch (Exception e) { System.out.println(e); } }}
Is Reader ready to be read: true
Integer value of character read: 71
Actual character read: G
Integer value of character read: 101
Actual character read: e
Integer value of character read: 101
Actual character read: e
Integer value of character read: 107
Actual character read: k
Integer value of character read: 115
Actual character read: s
Program 2:
// Java program to demonstrate// Reader ready() method import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { try { String str = "GeeksForGeeks"; // Create a Reader instance Reader reader = new StringReader(str); reader.close(); // Check if the Reader is // ready to be read using ready() System.out.println("Is Reader ready " + "to be read: " + reader.ready()); // Get the character // to be read from the stream int ch; // Read the first character // to this reader using read() method // This will put the str in the stream // till it is read by the reader ch = reader.read(); System.out.println("\nInteger value " + "of character read: " + ch); System.out.println("Actual " + "character read: " + (char)ch); reader.close(); } catch (Exception e) { System.out.println(e); } }}
java.io.IOException: Stream closed
Reference: https://docs.oracle.com/javase/9/docs/api/java/io/Reader.html#readyβ
Java-Functions
Java-IO package
Java-Reader
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Feb, 2019"
},
{
"code": null,
"e": 194,
"s": 28,
"text": "The ready() method of Reader Class in Java is used to check whether this Reader is ready to be read or not. It returns a boolean which states if the reader is ready."
},
{
"code": null,
"e": 202,
"s": 194,
"text": "Syntax:"
},
{
"code": null,
"e": 222,
"s": 202,
"text": "public void ready()"
},
{
"code": null,
"e": 278,
"s": 222,
"text": "Parameters: This method does not accepts any parameters"
},
{
"code": null,
"e": 437,
"s": 278,
"text": "Return Value: This method returns a boolean value which tells if this Reader is ready to be read or not. It return true if it is ready. Else it returns false."
},
{
"code": null,
"e": 520,
"s": 437,
"text": "Exception: This method throws IOException if some error occurs while input-output."
},
{
"code": null,
"e": 577,
"s": 520,
"text": "Below methods illustrates the working of ready() method:"
},
{
"code": null,
"e": 588,
"s": 577,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// Reader ready() method import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { try { String str = \"GeeksForGeeks\"; // Create a Reader instance Reader reader = new StringReader(str); // Check if the Reader is // ready to be read using ready() System.out.println(\"Is Reader ready \" + \"to be read: \" + reader.ready()); // Get the character // to be read from the stream int ch; // Read the first 5 characters // to this reader using read() method // This will put the str in the stream // till it is read by the reader for (int i = 0; i < 5; i++) { ch = reader.read(); System.out.println(\"\\nInteger value \" + \"of character read: \" + ch); System.out.println(\"Actual \" + \"character read: \" + (char)ch); } reader.close(); } catch (Exception e) { System.out.println(e); } }}",
"e": 1918,
"s": 588,
"text": null
},
{
"code": null,
"e": 2266,
"s": 1918,
"text": "Is Reader ready to be read: true\n\nInteger value of character read: 71\nActual character read: G\n\nInteger value of character read: 101\nActual character read: e\n\nInteger value of character read: 101\nActual character read: e\n\nInteger value of character read: 107\nActual character read: k\n\nInteger value of character read: 115\nActual character read: s\n"
},
{
"code": null,
"e": 2277,
"s": 2266,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// Reader ready() method import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { try { String str = \"GeeksForGeeks\"; // Create a Reader instance Reader reader = new StringReader(str); reader.close(); // Check if the Reader is // ready to be read using ready() System.out.println(\"Is Reader ready \" + \"to be read: \" + reader.ready()); // Get the character // to be read from the stream int ch; // Read the first character // to this reader using read() method // This will put the str in the stream // till it is read by the reader ch = reader.read(); System.out.println(\"\\nInteger value \" + \"of character read: \" + ch); System.out.println(\"Actual \" + \"character read: \" + (char)ch); reader.close(); } catch (Exception e) { System.out.println(e); } }}",
"e": 3549,
"s": 2277,
"text": null
},
{
"code": null,
"e": 3585,
"s": 3549,
"text": "java.io.IOException: Stream closed\n"
},
{
"code": null,
"e": 3665,
"s": 3585,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/io/Reader.html#readyβ"
},
{
"code": null,
"e": 3680,
"s": 3665,
"text": "Java-Functions"
},
{
"code": null,
"e": 3696,
"s": 3680,
"text": "Java-IO package"
},
{
"code": null,
"e": 3708,
"s": 3696,
"text": "Java-Reader"
},
{
"code": null,
"e": 3713,
"s": 3708,
"text": "Java"
},
{
"code": null,
"e": 3718,
"s": 3713,
"text": "Java"
},
{
"code": null,
"e": 3816,
"s": 3718,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3831,
"s": 3816,
"text": "Stream In Java"
},
{
"code": null,
"e": 3852,
"s": 3831,
"text": "Introduction to Java"
},
{
"code": null,
"e": 3873,
"s": 3852,
"text": "Constructors in Java"
},
{
"code": null,
"e": 3892,
"s": 3873,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 3909,
"s": 3892,
"text": "Generics in Java"
},
{
"code": null,
"e": 3939,
"s": 3909,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 3965,
"s": 3939,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 3981,
"s": 3965,
"text": "Strings in Java"
},
{
"code": null,
"e": 4018,
"s": 3981,
"text": "Differences between JDK, JRE and JVM"
}
] |
Palindrome String | Practice | GeeksforGeeks
|
Given a string S, check if it is palindrome or not.
Example 1:
Input: S = "abba"
Output: 1
Explanation: S is a palindrome
Example 2:
Input: S = "abc"
Output: 0
Explanation: S is not a palindrome
Your Task:
You don't need to read input or print anything. Complete the function isPlaindrome()which accepts string S and returns an integervalue 1 or 0.
Expected Time Complexity: O(Length of S)
Expected Auxiliary Space: O(1)
Constraints:
1 <= Length of S<= 105
0
1ashishchauhan2002in 6 hours
string p=S; reverse(p.begin(), p.end()); if(p==S) return 1; else return 0;
0
penchalaswamimannarapu22814 hours ago
class Solution:def isPalindrome(self, S): # code here w='' for i in S: w=i+w if w==S: return 1 else: return 0
0
parikshitgaikwad1721 day ago
int isPalindrome(string S)
{
int i=0,j=S.size()-1;
while(i<=j){
if(S[i]==S[j]){
i++;
j--;
continue;
}else{
return 0;
}
}
return 1;
// Your code goes here
}
0
mehtay0372 days ago
Python Solution:
class Solution:def isPalindrome(self, S): # code here if(S[::]==S[::-1]): return '1' else: return '0'
0
suprithsk20013 days ago
//easy cpp soln
string str=S; int s=0,e=str.length()-1; while(s<e){ swap(str[s],str[e]); s++; e--; } if(str==S){ return 1; } else{ return 0; }
0
visionsameer394 days ago
in pyhton
s1=S[0]
return s1[0]==S[::-1]
0
priyansh708905 days ago
Simple Solution -
int isPalindrome(string S){ // Your code goes here int start = 0; int end = S.length() - 1; string str = S; while(start < end) { swap(S[start++],S[end--]); } return S==str;}
0
singhvipnesh65 days ago
class Solution { int isPalindrome(String S) { int l=0; int r=S.length()-1; while(l<r) { if(S.charAt(l)!=S.charAt(r)){ return 0; } l++; r--; } return 1; }};
0
codewithshoaib196 days ago
int isPalindrome(String S) { // code here for(int i=0;i<S.length();i++){ if(S.charAt(i)!=S.charAt(S.length()-1-i)){ return 0; } } return 1; }
0
mayank180919996 days ago
int isPalindrome(string S)
{
// Your code goes here
string v;
for(int i=S.length()-1;i>=0;i--){
v.push_back(S[i]);
}
for(int i=0;i<S.length();i++){
if(S[i]!=v[i]){
return 0;
}
}
return 1;
}
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": 290,
"s": 238,
"text": "Given a string S, check if it is palindrome or not."
},
{
"code": null,
"e": 301,
"s": 290,
"text": "Example 1:"
},
{
"code": null,
"e": 360,
"s": 301,
"text": "Input: S = \"abba\"\nOutput: 1\nExplanation: S is a palindrome"
},
{
"code": null,
"e": 371,
"s": 360,
"text": "Example 2:"
},
{
"code": null,
"e": 434,
"s": 371,
"text": "Input: S = \"abc\" \nOutput: 0\nExplanation: S is not a palindrome"
},
{
"code": null,
"e": 591,
"s": 436,
"text": "Your Task: \nYou don't need to read input or print anything. Complete the function isPlaindrome()which accepts string S and returns an integervalue 1 or 0."
},
{
"code": null,
"e": 664,
"s": 591,
"text": "\nExpected Time Complexity: O(Length of S)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 701,
"s": 664,
"text": "\nConstraints:\n1 <= Length of S<= 105"
},
{
"code": null,
"e": 703,
"s": 701,
"text": "0"
},
{
"code": null,
"e": 732,
"s": 703,
"text": "1ashishchauhan2002in 6 hours"
},
{
"code": null,
"e": 817,
"s": 732,
"text": " string p=S; reverse(p.begin(), p.end()); if(p==S) return 1; else return 0;"
},
{
"code": null,
"e": 819,
"s": 817,
"text": "0"
},
{
"code": null,
"e": 857,
"s": 819,
"text": "penchalaswamimannarapu22814 hours ago"
},
{
"code": null,
"e": 984,
"s": 857,
"text": "class Solution:def isPalindrome(self, S): # code here w='' for i in S: w=i+w if w==S: return 1 else: return 0"
},
{
"code": null,
"e": 986,
"s": 984,
"text": "0"
},
{
"code": null,
"e": 1015,
"s": 986,
"text": "parikshitgaikwad1721 day ago"
},
{
"code": null,
"e": 1277,
"s": 1015,
"text": "int isPalindrome(string S)\n\t{\n\t int i=0,j=S.size()-1;\n\t while(i<=j){\n\t if(S[i]==S[j]){\n\t i++;\n\t j--;\n\t continue;\n\t }else{\n\t return 0;\n\t }\n\t }\n\t return 1;\n\t // Your code goes here\n\t}"
},
{
"code": null,
"e": 1279,
"s": 1277,
"text": "0"
},
{
"code": null,
"e": 1299,
"s": 1279,
"text": "mehtay0372 days ago"
},
{
"code": null,
"e": 1316,
"s": 1299,
"text": "Python Solution:"
},
{
"code": null,
"e": 1427,
"s": 1316,
"text": "class Solution:def isPalindrome(self, S): # code here if(S[::]==S[::-1]): return '1' else: return '0' "
},
{
"code": null,
"e": 1429,
"s": 1427,
"text": "0"
},
{
"code": null,
"e": 1453,
"s": 1429,
"text": "suprithsk20013 days ago"
},
{
"code": null,
"e": 1469,
"s": 1453,
"text": "//easy cpp soln"
},
{
"code": null,
"e": 1660,
"s": 1469,
"text": "string str=S; int s=0,e=str.length()-1; while(s<e){ swap(str[s],str[e]); s++; e--; } if(str==S){ return 1; } else{ return 0; }"
},
{
"code": null,
"e": 1662,
"s": 1660,
"text": "0"
},
{
"code": null,
"e": 1687,
"s": 1662,
"text": "visionsameer394 days ago"
},
{
"code": null,
"e": 1698,
"s": 1687,
"text": "in pyhton "
},
{
"code": null,
"e": 1706,
"s": 1698,
"text": "s1=S[0]"
},
{
"code": null,
"e": 1728,
"s": 1706,
"text": "return s1[0]==S[::-1]"
},
{
"code": null,
"e": 1730,
"s": 1728,
"text": "0"
},
{
"code": null,
"e": 1754,
"s": 1730,
"text": "priyansh708905 days ago"
},
{
"code": null,
"e": 1772,
"s": 1754,
"text": "Simple Solution -"
},
{
"code": null,
"e": 1978,
"s": 1772,
"text": " int isPalindrome(string S){ // Your code goes here int start = 0; int end = S.length() - 1; string str = S; while(start < end) { swap(S[start++],S[end--]); } return S==str;}"
},
{
"code": null,
"e": 1980,
"s": 1978,
"text": "0"
},
{
"code": null,
"e": 2004,
"s": 1980,
"text": "singhvipnesh65 days ago"
},
{
"code": null,
"e": 2251,
"s": 2004,
"text": "class Solution { int isPalindrome(String S) { int l=0; int r=S.length()-1; while(l<r) { if(S.charAt(l)!=S.charAt(r)){ return 0; } l++; r--; } return 1; }};"
},
{
"code": null,
"e": 2253,
"s": 2251,
"text": "0"
},
{
"code": null,
"e": 2280,
"s": 2253,
"text": "codewithshoaib196 days ago"
},
{
"code": null,
"e": 2483,
"s": 2280,
"text": " int isPalindrome(String S) { // code here for(int i=0;i<S.length();i++){ if(S.charAt(i)!=S.charAt(S.length()-1-i)){ return 0; } } return 1; }"
},
{
"code": null,
"e": 2485,
"s": 2483,
"text": "0"
},
{
"code": null,
"e": 2510,
"s": 2485,
"text": "mayank180919996 days ago"
},
{
"code": null,
"e": 2804,
"s": 2510,
"text": "\tint isPalindrome(string S)\n\t{\n\t // Your code goes here\n\t string v;\n for(int i=S.length()-1;i>=0;i--){\n v.push_back(S[i]);\n }\n for(int i=0;i<S.length();i++){\n if(S[i]!=v[i]){\n return 0;\n }\n }\n return 1;\n\t}"
},
{
"code": null,
"e": 2950,
"s": 2804,
"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": 2986,
"s": 2950,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 2996,
"s": 2986,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3006,
"s": 2996,
"text": "\nContest\n"
},
{
"code": null,
"e": 3069,
"s": 3006,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 3217,
"s": 3069,
"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": 3425,
"s": 3217,
"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": 3531,
"s": 3425,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
A Pancake Sorting Problem - GeeksforGeeks
|
17 Jan, 2022
We have discussed Pancake Sorting in the previous post. Following is a problem based on Pancake Sorting. Given an unsorted array, sort the given array. You are allowed to do only following operation on array.
flip(arr, i): Reverse array from 0 to i
Imagine a hypothetical machine where flip(i) always takes O(1) time. Write an efficient program for sorting a given array in O(nLogn) time on the given machine. If we apply the same algorithm here, the time taken will be O(n^2) because the algorithm calls findMax() in a loop and find findMax() takes O(n) time even on this hypothetical machine.We can use insertion sort that uses binary search. The idea is to run a loop from second element to last element (from i = 1 to n-1), and one by one insert arr[i] in arr[0..i-1] (like standard insertion sort algorithm). When we insert an element arr[i], we can use binary search to find position of arr[i] in O(Logi) time. Once we have the position, we can use some flip operations to put arr[i] at its new place. Following are abstract steps.
// Standard Insertion Sort Loop that starts from second element
for (i=1; i O(n)
{
int key = arr[i];
// Find index of ceiling of arr[i] in arr[0..i-1] using binary search
j = celiSearch(arr, key, 0, i-1); ----> O(logn) (See this)
// Apply some flip operations to put arr[i] at correct place
}
Since flip operation takes O(1) on given hypothetical machine, total running time of above algorithm is O(nlogn). Thanks to Kumar for suggesting above problem and algorithm.Let us see how does the above algorithm work. ceilSearch() actually returns the index of the smallest element which is greater than arr[i] in arr[0..i-1]. If there is no such element, it returns -1. Let the returned value be j. If j is -1, then we donβt need to do anything as arr[i] is already the greatest element among arr[0..i]. Otherwise we need to put arr[i] just before arr[j]. So how to apply flip operations to put arr[i] just before arr[j] using values of i and j. Let us take an example to understand this. Let i be 6 and current array be {12, 15, 18, 30, 35, 40, 20, 6, 90, 80}. To put 20 at its new place, the array should be changed to {12, 15, 18, 20, 30, 35, 40, 6, 90, 80}. We apply following steps to put 20 at its new place.1) Find j using ceilSearch (In the above example j is 3). 2) flip(arr, j-1) (array becomes {18, 15, 12, 30, 35, 40, 20, 6, 90, 80}) 3) flip(arr, i-1); (array becomes {40, 35, 30, 12, 15, 18, 20, 6, 90, 80}) 4) flip(arr, i); (array becomes {20, 18, 15, 12, 30, 35, 40, 6, 90, 80}) 5) flip(arr, j); (array becomes {12, 15, 18, 20, 30, 35, 40, 6, 90, 80})Following is the implementation of the above algorithm.
C++
C
Java
Python3
C#
Javascript
// C++ program of Pancake Sorting Problem#include<bits/stdc++.h>using namespace std; /* A Binary Search based function toget index of ceiling of x inarr[low..high] */int ceilSearch(int arr[], int low, int high, int x){ int mid; /* If x is smaller than or equal to the first element, then return the first element */ if(x <= arr[low]) return low; /* If x is greater than the last element, then return -1 */ if(x > arr[high]) return -1; /* get the index of middle element of arr[low..high]*/ mid = (low + high)/2; /* low + (high β low)/2 */ /* If x is same as middle element, then return mid */ if(arr[mid] == x) return mid; /* If x is greater than arr[mid], then either arr[mid + 1] is ceiling of x, or ceiling lies in arr[mid+1...high] */ if(arr[mid] < x) { if(mid + 1 <= high && x <= arr[mid+1]) return mid + 1; else return ceilSearch(arr, mid+1, high, x); } /* If x is smaller than arr[mid], then either arr[mid] is ceiling of x or ceiling lies in arr[mid-1...high] */ if (mid - 1 >= low && x > arr[mid-1]) return mid; else return ceilSearch(arr, low, mid - 1, x);} /* Reverses arr[0..i] */void flip(int arr[], int i){ int temp, start = 0; while (start < i) { temp = arr[start]; arr[start] = arr[i]; arr[i] = temp; start++; i--; }} /* Function to sort an array usinginsertion sort, binary search and flip */void insertionSort(int arr[], int size){ int i, j; // Start from the second element // and one by one insert arr[i] // in already sorted arr[0..i-1] for(i = 1; i < size; i++) { // Find the smallest element in arr[0..i-1] // which is also greater than // or equal to arr[i] int j = ceilSearch(arr, 0, i-1, arr[i]); // Check if there was no element // greater than arr[i] if (j != -1) { // Put arr[i] before arr[j] using // following four flip operations flip(arr, j-1); flip(arr, i-1); flip(arr, i); flip(arr, j); } }} /* A utility function to print an array of size n */void printArray(int arr[], int n){ int i; for (i = 0; i < n; ++i) cout<<arr[i]<<" ";} /* Driver code */int main(){ int arr[] = {18, 40, 35, 12, 30, 35, 20, 6, 90, 80}; int n = sizeof(arr)/sizeof(arr[0]); insertionSort(arr, n); printArray(arr, n); return 0;} // This code is contributed by rathbhupendra
// C program of Pancake Sorting Problem#include <stdlib.h>#include <stdio.h> /* A Binary Search based function to get index of ceiling of x in arr[low..high] */int ceilSearch(int arr[], int low, int high, int x){ int mid; /* If x is smaller than or equal to the first element, then return the first element */ if(x <= arr[low]) return low; /* If x is greater than the last element, then return -1 */ if(x > arr[high]) return -1; /* get the index of middle element of arr[low..high]*/ mid = (low + high)/2; /* low + (high β low)/2 */ /* If x is same as middle element, then return mid */ if(arr[mid] == x) return mid; /* If x is greater than arr[mid], then either arr[mid + 1] is ceiling of x, or ceiling lies in arr[mid+1...high] */ if(arr[mid] < x) { if(mid + 1 <= high && x <= arr[mid+1]) return mid + 1; else return ceilSearch(arr, mid+1, high, x); } /* If x is smaller than arr[mid], then either arr[mid] is ceiling of x or ceiling lies in arr[mid-1...high] */ if (mid - 1 >= low && x > arr[mid-1]) return mid; else return ceilSearch(arr, low, mid - 1, x);} /* Reverses arr[0..i] */void flip(int arr[], int i){ int temp, start = 0; while (start < i) { temp = arr[start]; arr[start] = arr[i]; arr[i] = temp; start++; i--; }} /* Function to sort an array using insertion sort, binary search and flip */void insertionSort(int arr[], int size){ int i, j; // Start from the second element and one by one insert arr[i] // in already sorted arr[0..i-1] for(i = 1; i < size; i++) { // Find the smallest element in arr[0..i-1] which is also greater than // or equal to arr[i] int j = ceilSearch(arr, 0, i-1, arr[i]); // Check if there was no element greater than arr[i] if (j != -1) { // Put arr[i] before arr[j] using following four flip operations flip(arr, j-1); flip(arr, i-1); flip(arr, i); flip(arr, j); } }} /* A utility function to print an array of size n */void printArray(int arr[], int n){ int i; for (i = 0; i < n; ++i) printf("%d ", arr[i]);} /* Driver program to test insertion sort */int main(){ int arr[] = {18, 40, 35, 12, 30, 35, 20, 6, 90, 80}; int n = sizeof(arr)/sizeof(arr[0]); insertionSort(arr, n); printArray(arr, n); return 0;}
// Java program of Pancake Sorting Problemclass GfG { /* A Binary Search based function to get index of ceiling of x inarr[low..high] */static int ceilSearch(int arr[], int low, int high, int x){ int mid; /* If x is smaller than or equal to the first element, then return the first element */ if(x <= arr[low]) return low; /* If x is greater than the last element, then return -1 */ if(x > arr[high]) return -1; /* get the index of middle element of arr[low..high]*/// low + (high - low)/2 mid = (low + high)/2; /* If x is same as middle element, then return mid */ if(arr[mid] == x) return mid; /* If x is greater than arr[mid], then either arr[mid + 1] is ceiling of x, or ceiling lies in arr[mid+1...high] */ if(arr[mid] < x) { if(mid + 1 <= high && x <= arr[mid+1]) return mid + 1; else return ceilSearch(arr, mid+1, high, x); } /* If x is smaller than arr[mid], then either arr[mid] is ceiling of x or ceiling lies in arr[mid-1...high] */ if (mid - 1 >= low && x > arr[mid-1]) return mid; else return ceilSearch(arr, low, mid - 1, x);} /* Reverses arr[0..i] */static void flip(int arr[], int i){ int temp, start = 0; while (start < i) { temp = arr[start]; arr[start] = arr[i]; arr[i] = temp; start++; i--; }} /* Function to sort an array using insertion sort, binary search and flip */static void insertionSort(int arr[], int size){ int i; // Start from the second element and one by one insert arr[i] // in already sorted arr[0..i-1] for(i = 1; i < size; i++) { // Find the smallest element in arr[0..i-1] which is also greater than // or equal to arr[i] int j = ceilSearch(arr, 0, i-1, arr[i]); // Check if there was no element greater than arr[i] if (j != -1) { // Put arr[i] before arr[j] using following four flip operations flip(arr, j-1); flip(arr, i-1); flip(arr, i); flip(arr, j); } }} /* A utility function to print an array of size n */static void printArray(int arr[], int n){ int i; for (i = 0; i < n; ++i) System.out.print(arr[i] + " ");} /* Driver program to test insertion sort */public static void main(String[] args){ int arr[] = {18, 40, 35, 12, 30, 35, 20, 6, 90, 80}; int n = arr.length; insertionSort(arr, n); printArray(arr, n);}}
# Python program of Pancake Sorting Problem#A Binary Search based function to get index of ceiling of x in arr[low..high] def ceilSearch(arr,low,high,x): #If x is smaller than or equal to the first element, #then return the first element if x <= arr[low]: return low #If x is greater than the last element, then return -1 if x > arr[high]: return -1 #get the index of middle element of arr[low..high] mid = (low + high)//2 #low + (high-low)/2 #If x is same as middle element, then return mid if(arr[mid] == x): return mid #If x is greater than arr[mid], then either arr[mid + 1] #is ceiling of x, or ceiling lies in arr[mid+1...high] if(arr[mid] < x): if(mid + 1 <= high and x <= arr[mid+1]): return mid + 1 else: return ceilSearch(arr, mid+1, high, x) #If x is smaller than arr[mid], then either arr[mid] #is ceiling of x or ceiling lies in arr[mid-1...high] if (mid - 1 >= low and x > arr[mid-1]): return mid else: return ceilSearch(arr, low, mid - 1, x) #Reverses arr[0..i] */def flip(arr,i): start = 0; while (start < i): temp = arr[start] arr[start] = arr[i] arr[i] = temp start+=1 i-=1 #Function to sort an array using insertion sort, binary search and flipdef insertionSort(arr): #Start from the second element and one by one insert arr[i] #in already sorted arr[0..i-1] for i in range(1,len(arr)): #Find the smallest element in arr[0..i-1] which is also greater than #or equal to arr[i] j = ceilSearch(arr, 0, i-1, arr[i]) #Check if there was no element greater than arr[i] if (j != -1): #Put arr[i] before arr[j] using following four flip operations flip(arr, j-1) flip(arr, i-1) flip(arr, i) flip(arr, j) # A utility function to print an array of size ndef printArray(arr): for i in range(0,len(arr)): print (arr[i],end=" ") #Driver function to test above functionarr=[18, 40, 35, 12, 30, 35, 20, 6, 90, 80]insertionSort(arr)printArray(arr) #This code is contributed by Devesh Agrawal
// C# program of Pancake Sorting Problemusing System; class GFG{ // A Binary Search based function to get// index of ceiling of x in arr[low..high]static int ceilSearch(int []arr, int low, int high, int x){ int mid; // If x is smaller than or equal to // the first element, // then return the first element if(x <= arr[low]) return low; // If x is greater than the last element, // then return -1 if(x > arr[high]) return -1; // get the index of middle element // of arr[low..high] // low + (high - low)/2 mid = (low + high) / 2; // If x is same as middle element, // then return mid if(arr[mid] == x) return mid; // If x is greater than arr[mid], // then either arr[mid + 1] is ceiling of x, // or ceiling lies in arr[mid+1...high] if(arr[mid] < x) { if(mid + 1 <= high && x <= arr[mid + 1]) return mid + 1; else return ceilSearch(arr, mid + 1, high, x); } // If x is smaller than arr[mid], // then either arr[mid] is ceiling of x // or ceiling lies in arr[mid-1...high] if (mid - 1 >= low && x > arr[mid - 1]) return mid; else return ceilSearch(arr, low, mid - 1, x);} // Reverses arr[0..i]static void flip(int []arr, int i){ int temp, start = 0; while (start < i) { temp = arr[start]; arr[start] = arr[i]; arr[i] = temp; start++; i--; }} // Function to sort an array using insertion sort,// binary search and flipstatic void insertionSort(int []arr, int size){ int i; // Start from the second element and // one by one insert arr[i] in // already sorted arr[0..i-1] for(i = 1; i < size; i++) { // Find the smallest element in arr[0..i-1] // which is also greater than or equal to arr[i] int j = ceilSearch(arr, 0, i - 1, arr[i]); // Check if there was no element greater than arr[i] if (j != -1) { // Put arr[i] before arr[j] using // following four flip operations flip(arr, j - 1); flip(arr, i - 1); flip(arr, i); flip(arr, j); } }} // A utility function to print an array of size nstatic void printArray(int []arr, int n){ int i; for (i = 0; i < n; ++i) Console.Write(arr[i] + " ");} // Driver Codepublic static void Main(String[] args){ int []arr = {18, 40, 35, 12, 30, 35, 20, 6, 90, 80}; int n = arr.Length; insertionSort(arr, n); printArray(arr, n);}} // This code is contributed by Princi Singh
<script>// Javascript program of Pancake Sorting Problem /* A Binary Search based function toget index of ceiling of x inarr[low..high] */function ceilSearch(arr, low, high, x){ var mid; /* If x is smaller than or equal to the first element, then return the first element */ if(x <= arr[low]) return low; /* If x is greater than the last element, then return -1 */ if(x > arr[high]) return -1; /* get the index of middle element of arr[low..high]*/ mid = parseInt((low + high)/2); /* low + (high β low)/2 */ /* If x is same as middle element, then return mid */ if(arr[mid] == x) return mid; /* If x is greater than arr[mid], then either arr[mid + 1] is ceiling of x, or ceiling lies in arr[mid+1...high] */ if(arr[mid] < x) { if(mid + 1 <= high && x <= arr[mid+1]) return mid + 1; else return ceilSearch(arr, mid+1, high, x); } /* If x is smaller than arr[mid], then either arr[mid] is ceiling of x or ceiling lies in arr[mid-1...high] */ if (mid - 1 >= low && x > arr[mid-1]) return mid; else return ceilSearch(arr, low, mid - 1, x);} /* Reverses arr[0..i] */function flip( arr, i){ var temp, start = 0; while (start < i) { temp = arr[start]; arr[start] = arr[i]; arr[i] = temp; start++; i--; }} /* Function to sort an array usinginsertion sort, binary search and flip */function insertionSort( arr, size){ var i, j; // Start from the second element // and one by one insert arr[i] // in already sorted arr[0..i-1] for(i = 1; i < size; i++) { // Find the smallest element in arr[0..i-1] // which is also greater than // or equal to arr[i] var j = ceilSearch(arr, 0, i-1, arr[i]); // Check if there was no element // greater than arr[i] if (j != -1) { // Put arr[i] before arr[j] using // following four flip operations flip(arr, j-1); flip(arr, i-1); flip(arr, i); flip(arr, j); } }} /* A utility function to print an array of size n */function printArray(arr, n){ var i; for (i = 0; i < n; ++i) document.write(arr[i]+" ");} var arr = [18, 40, 35, 12, 30, 35, 20, 6, 90, 80]; var n = arr.length; insertionSort(arr, n); printArray(arr, n); // This code is contributed by SoumikMondal</script>
Output:
6 12 18 20 30 35 35 40 80 90
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
prerna saini
rathbhupendra
Akanksha_Rai
princi singh
SoumikMondal
amartyaghoshgfg
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
std::sort() in C++ STL
Radix Sort
Time Complexities of all Sorting Algorithms
Python Program for QuickSort
Python List sort() method
Merge Sort for Linked Lists
sort() in Python
k largest(or smallest) elements in an array
Iterative Quick Sort
|
[
{
"code": null,
"e": 23253,
"s": 23225,
"text": "\n17 Jan, 2022"
},
{
"code": null,
"e": 23462,
"s": 23253,
"text": "We have discussed Pancake Sorting in the previous post. Following is a problem based on Pancake Sorting. Given an unsorted array, sort the given array. You are allowed to do only following operation on array."
},
{
"code": null,
"e": 23503,
"s": 23462,
"text": "flip(arr, i): Reverse array from 0 to i "
},
{
"code": null,
"e": 24293,
"s": 23503,
"text": "Imagine a hypothetical machine where flip(i) always takes O(1) time. Write an efficient program for sorting a given array in O(nLogn) time on the given machine. If we apply the same algorithm here, the time taken will be O(n^2) because the algorithm calls findMax() in a loop and find findMax() takes O(n) time even on this hypothetical machine.We can use insertion sort that uses binary search. The idea is to run a loop from second element to last element (from i = 1 to n-1), and one by one insert arr[i] in arr[0..i-1] (like standard insertion sort algorithm). When we insert an element arr[i], we can use binary search to find position of arr[i] in O(Logi) time. Once we have the position, we can use some flip operations to put arr[i] at its new place. Following are abstract steps. "
},
{
"code": null,
"e": 24602,
"s": 24293,
"text": "// Standard Insertion Sort Loop that starts from second element\nfor (i=1; i O(n)\n{\n int key = arr[i];\n\n // Find index of ceiling of arr[i] in arr[0..i-1] using binary search\n j = celiSearch(arr, key, 0, i-1); ----> O(logn) (See this)\n \n // Apply some flip operations to put arr[i] at correct place\n} "
},
{
"code": null,
"e": 25928,
"s": 24602,
"text": "Since flip operation takes O(1) on given hypothetical machine, total running time of above algorithm is O(nlogn). Thanks to Kumar for suggesting above problem and algorithm.Let us see how does the above algorithm work. ceilSearch() actually returns the index of the smallest element which is greater than arr[i] in arr[0..i-1]. If there is no such element, it returns -1. Let the returned value be j. If j is -1, then we donβt need to do anything as arr[i] is already the greatest element among arr[0..i]. Otherwise we need to put arr[i] just before arr[j]. So how to apply flip operations to put arr[i] just before arr[j] using values of i and j. Let us take an example to understand this. Let i be 6 and current array be {12, 15, 18, 30, 35, 40, 20, 6, 90, 80}. To put 20 at its new place, the array should be changed to {12, 15, 18, 20, 30, 35, 40, 6, 90, 80}. We apply following steps to put 20 at its new place.1) Find j using ceilSearch (In the above example j is 3). 2) flip(arr, j-1) (array becomes {18, 15, 12, 30, 35, 40, 20, 6, 90, 80}) 3) flip(arr, i-1); (array becomes {40, 35, 30, 12, 15, 18, 20, 6, 90, 80}) 4) flip(arr, i); (array becomes {20, 18, 15, 12, 30, 35, 40, 6, 90, 80}) 5) flip(arr, j); (array becomes {12, 15, 18, 20, 30, 35, 40, 6, 90, 80})Following is the implementation of the above algorithm. "
},
{
"code": null,
"e": 25932,
"s": 25928,
"text": "C++"
},
{
"code": null,
"e": 25934,
"s": 25932,
"text": "C"
},
{
"code": null,
"e": 25939,
"s": 25934,
"text": "Java"
},
{
"code": null,
"e": 25947,
"s": 25939,
"text": "Python3"
},
{
"code": null,
"e": 25950,
"s": 25947,
"text": "C#"
},
{
"code": null,
"e": 25961,
"s": 25950,
"text": "Javascript"
},
{
"code": "// C++ program of Pancake Sorting Problem#include<bits/stdc++.h>using namespace std; /* A Binary Search based function toget index of ceiling of x inarr[low..high] */int ceilSearch(int arr[], int low, int high, int x){ int mid; /* If x is smaller than or equal to the first element, then return the first element */ if(x <= arr[low]) return low; /* If x is greater than the last element, then return -1 */ if(x > arr[high]) return -1; /* get the index of middle element of arr[low..high]*/ mid = (low + high)/2; /* low + (high β low)/2 */ /* If x is same as middle element, then return mid */ if(arr[mid] == x) return mid; /* If x is greater than arr[mid], then either arr[mid + 1] is ceiling of x, or ceiling lies in arr[mid+1...high] */ if(arr[mid] < x) { if(mid + 1 <= high && x <= arr[mid+1]) return mid + 1; else return ceilSearch(arr, mid+1, high, x); } /* If x is smaller than arr[mid], then either arr[mid] is ceiling of x or ceiling lies in arr[mid-1...high] */ if (mid - 1 >= low && x > arr[mid-1]) return mid; else return ceilSearch(arr, low, mid - 1, x);} /* Reverses arr[0..i] */void flip(int arr[], int i){ int temp, start = 0; while (start < i) { temp = arr[start]; arr[start] = arr[i]; arr[i] = temp; start++; i--; }} /* Function to sort an array usinginsertion sort, binary search and flip */void insertionSort(int arr[], int size){ int i, j; // Start from the second element // and one by one insert arr[i] // in already sorted arr[0..i-1] for(i = 1; i < size; i++) { // Find the smallest element in arr[0..i-1] // which is also greater than // or equal to arr[i] int j = ceilSearch(arr, 0, i-1, arr[i]); // Check if there was no element // greater than arr[i] if (j != -1) { // Put arr[i] before arr[j] using // following four flip operations flip(arr, j-1); flip(arr, i-1); flip(arr, i); flip(arr, j); } }} /* A utility function to print an array of size n */void printArray(int arr[], int n){ int i; for (i = 0; i < n; ++i) cout<<arr[i]<<\" \";} /* Driver code */int main(){ int arr[] = {18, 40, 35, 12, 30, 35, 20, 6, 90, 80}; int n = sizeof(arr)/sizeof(arr[0]); insertionSort(arr, n); printArray(arr, n); return 0;} // This code is contributed by rathbhupendra",
"e": 28522,
"s": 25961,
"text": null
},
{
"code": "// C program of Pancake Sorting Problem#include <stdlib.h>#include <stdio.h> /* A Binary Search based function to get index of ceiling of x in arr[low..high] */int ceilSearch(int arr[], int low, int high, int x){ int mid; /* If x is smaller than or equal to the first element, then return the first element */ if(x <= arr[low]) return low; /* If x is greater than the last element, then return -1 */ if(x > arr[high]) return -1; /* get the index of middle element of arr[low..high]*/ mid = (low + high)/2; /* low + (high β low)/2 */ /* If x is same as middle element, then return mid */ if(arr[mid] == x) return mid; /* If x is greater than arr[mid], then either arr[mid + 1] is ceiling of x, or ceiling lies in arr[mid+1...high] */ if(arr[mid] < x) { if(mid + 1 <= high && x <= arr[mid+1]) return mid + 1; else return ceilSearch(arr, mid+1, high, x); } /* If x is smaller than arr[mid], then either arr[mid] is ceiling of x or ceiling lies in arr[mid-1...high] */ if (mid - 1 >= low && x > arr[mid-1]) return mid; else return ceilSearch(arr, low, mid - 1, x);} /* Reverses arr[0..i] */void flip(int arr[], int i){ int temp, start = 0; while (start < i) { temp = arr[start]; arr[start] = arr[i]; arr[i] = temp; start++; i--; }} /* Function to sort an array using insertion sort, binary search and flip */void insertionSort(int arr[], int size){ int i, j; // Start from the second element and one by one insert arr[i] // in already sorted arr[0..i-1] for(i = 1; i < size; i++) { // Find the smallest element in arr[0..i-1] which is also greater than // or equal to arr[i] int j = ceilSearch(arr, 0, i-1, arr[i]); // Check if there was no element greater than arr[i] if (j != -1) { // Put arr[i] before arr[j] using following four flip operations flip(arr, j-1); flip(arr, i-1); flip(arr, i); flip(arr, j); } }} /* A utility function to print an array of size n */void printArray(int arr[], int n){ int i; for (i = 0; i < n; ++i) printf(\"%d \", arr[i]);} /* Driver program to test insertion sort */int main(){ int arr[] = {18, 40, 35, 12, 30, 35, 20, 6, 90, 80}; int n = sizeof(arr)/sizeof(arr[0]); insertionSort(arr, n); printArray(arr, n); return 0;}",
"e": 31015,
"s": 28522,
"text": null
},
{
"code": "// Java program of Pancake Sorting Problemclass GfG { /* A Binary Search based function to get index of ceiling of x inarr[low..high] */static int ceilSearch(int arr[], int low, int high, int x){ int mid; /* If x is smaller than or equal to the first element, then return the first element */ if(x <= arr[low]) return low; /* If x is greater than the last element, then return -1 */ if(x > arr[high]) return -1; /* get the index of middle element of arr[low..high]*/// low + (high - low)/2 mid = (low + high)/2; /* If x is same as middle element, then return mid */ if(arr[mid] == x) return mid; /* If x is greater than arr[mid], then either arr[mid + 1] is ceiling of x, or ceiling lies in arr[mid+1...high] */ if(arr[mid] < x) { if(mid + 1 <= high && x <= arr[mid+1]) return mid + 1; else return ceilSearch(arr, mid+1, high, x); } /* If x is smaller than arr[mid], then either arr[mid] is ceiling of x or ceiling lies in arr[mid-1...high] */ if (mid - 1 >= low && x > arr[mid-1]) return mid; else return ceilSearch(arr, low, mid - 1, x);} /* Reverses arr[0..i] */static void flip(int arr[], int i){ int temp, start = 0; while (start < i) { temp = arr[start]; arr[start] = arr[i]; arr[i] = temp; start++; i--; }} /* Function to sort an array using insertion sort, binary search and flip */static void insertionSort(int arr[], int size){ int i; // Start from the second element and one by one insert arr[i] // in already sorted arr[0..i-1] for(i = 1; i < size; i++) { // Find the smallest element in arr[0..i-1] which is also greater than // or equal to arr[i] int j = ceilSearch(arr, 0, i-1, arr[i]); // Check if there was no element greater than arr[i] if (j != -1) { // Put arr[i] before arr[j] using following four flip operations flip(arr, j-1); flip(arr, i-1); flip(arr, i); flip(arr, j); } }} /* A utility function to print an array of size n */static void printArray(int arr[], int n){ int i; for (i = 0; i < n; ++i) System.out.print(arr[i] + \" \");} /* Driver program to test insertion sort */public static void main(String[] args){ int arr[] = {18, 40, 35, 12, 30, 35, 20, 6, 90, 80}; int n = arr.length; insertionSort(arr, n); printArray(arr, n);}}",
"e": 33508,
"s": 31015,
"text": null
},
{
"code": "# Python program of Pancake Sorting Problem#A Binary Search based function to get index of ceiling of x in arr[low..high] def ceilSearch(arr,low,high,x): #If x is smaller than or equal to the first element, #then return the first element if x <= arr[low]: return low #If x is greater than the last element, then return -1 if x > arr[high]: return -1 #get the index of middle element of arr[low..high] mid = (low + high)//2 #low + (high-low)/2 #If x is same as middle element, then return mid if(arr[mid] == x): return mid #If x is greater than arr[mid], then either arr[mid + 1] #is ceiling of x, or ceiling lies in arr[mid+1...high] if(arr[mid] < x): if(mid + 1 <= high and x <= arr[mid+1]): return mid + 1 else: return ceilSearch(arr, mid+1, high, x) #If x is smaller than arr[mid], then either arr[mid] #is ceiling of x or ceiling lies in arr[mid-1...high] if (mid - 1 >= low and x > arr[mid-1]): return mid else: return ceilSearch(arr, low, mid - 1, x) #Reverses arr[0..i] */def flip(arr,i): start = 0; while (start < i): temp = arr[start] arr[start] = arr[i] arr[i] = temp start+=1 i-=1 #Function to sort an array using insertion sort, binary search and flipdef insertionSort(arr): #Start from the second element and one by one insert arr[i] #in already sorted arr[0..i-1] for i in range(1,len(arr)): #Find the smallest element in arr[0..i-1] which is also greater than #or equal to arr[i] j = ceilSearch(arr, 0, i-1, arr[i]) #Check if there was no element greater than arr[i] if (j != -1): #Put arr[i] before arr[j] using following four flip operations flip(arr, j-1) flip(arr, i-1) flip(arr, i) flip(arr, j) # A utility function to print an array of size ndef printArray(arr): for i in range(0,len(arr)): print (arr[i],end=\" \") #Driver function to test above functionarr=[18, 40, 35, 12, 30, 35, 20, 6, 90, 80]insertionSort(arr)printArray(arr) #This code is contributed by Devesh Agrawal",
"e": 35738,
"s": 33508,
"text": null
},
{
"code": "// C# program of Pancake Sorting Problemusing System; class GFG{ // A Binary Search based function to get// index of ceiling of x in arr[low..high]static int ceilSearch(int []arr, int low, int high, int x){ int mid; // If x is smaller than or equal to // the first element, // then return the first element if(x <= arr[low]) return low; // If x is greater than the last element, // then return -1 if(x > arr[high]) return -1; // get the index of middle element // of arr[low..high] // low + (high - low)/2 mid = (low + high) / 2; // If x is same as middle element, // then return mid if(arr[mid] == x) return mid; // If x is greater than arr[mid], // then either arr[mid + 1] is ceiling of x, // or ceiling lies in arr[mid+1...high] if(arr[mid] < x) { if(mid + 1 <= high && x <= arr[mid + 1]) return mid + 1; else return ceilSearch(arr, mid + 1, high, x); } // If x is smaller than arr[mid], // then either arr[mid] is ceiling of x // or ceiling lies in arr[mid-1...high] if (mid - 1 >= low && x > arr[mid - 1]) return mid; else return ceilSearch(arr, low, mid - 1, x);} // Reverses arr[0..i]static void flip(int []arr, int i){ int temp, start = 0; while (start < i) { temp = arr[start]; arr[start] = arr[i]; arr[i] = temp; start++; i--; }} // Function to sort an array using insertion sort,// binary search and flipstatic void insertionSort(int []arr, int size){ int i; // Start from the second element and // one by one insert arr[i] in // already sorted arr[0..i-1] for(i = 1; i < size; i++) { // Find the smallest element in arr[0..i-1] // which is also greater than or equal to arr[i] int j = ceilSearch(arr, 0, i - 1, arr[i]); // Check if there was no element greater than arr[i] if (j != -1) { // Put arr[i] before arr[j] using // following four flip operations flip(arr, j - 1); flip(arr, i - 1); flip(arr, i); flip(arr, j); } }} // A utility function to print an array of size nstatic void printArray(int []arr, int n){ int i; for (i = 0; i < n; ++i) Console.Write(arr[i] + \" \");} // Driver Codepublic static void Main(String[] args){ int []arr = {18, 40, 35, 12, 30, 35, 20, 6, 90, 80}; int n = arr.Length; insertionSort(arr, n); printArray(arr, n);}} // This code is contributed by Princi Singh",
"e": 38346,
"s": 35738,
"text": null
},
{
"code": "<script>// Javascript program of Pancake Sorting Problem /* A Binary Search based function toget index of ceiling of x inarr[low..high] */function ceilSearch(arr, low, high, x){ var mid; /* If x is smaller than or equal to the first element, then return the first element */ if(x <= arr[low]) return low; /* If x is greater than the last element, then return -1 */ if(x > arr[high]) return -1; /* get the index of middle element of arr[low..high]*/ mid = parseInt((low + high)/2); /* low + (high β low)/2 */ /* If x is same as middle element, then return mid */ if(arr[mid] == x) return mid; /* If x is greater than arr[mid], then either arr[mid + 1] is ceiling of x, or ceiling lies in arr[mid+1...high] */ if(arr[mid] < x) { if(mid + 1 <= high && x <= arr[mid+1]) return mid + 1; else return ceilSearch(arr, mid+1, high, x); } /* If x is smaller than arr[mid], then either arr[mid] is ceiling of x or ceiling lies in arr[mid-1...high] */ if (mid - 1 >= low && x > arr[mid-1]) return mid; else return ceilSearch(arr, low, mid - 1, x);} /* Reverses arr[0..i] */function flip( arr, i){ var temp, start = 0; while (start < i) { temp = arr[start]; arr[start] = arr[i]; arr[i] = temp; start++; i--; }} /* Function to sort an array usinginsertion sort, binary search and flip */function insertionSort( arr, size){ var i, j; // Start from the second element // and one by one insert arr[i] // in already sorted arr[0..i-1] for(i = 1; i < size; i++) { // Find the smallest element in arr[0..i-1] // which is also greater than // or equal to arr[i] var j = ceilSearch(arr, 0, i-1, arr[i]); // Check if there was no element // greater than arr[i] if (j != -1) { // Put arr[i] before arr[j] using // following four flip operations flip(arr, j-1); flip(arr, i-1); flip(arr, i); flip(arr, j); } }} /* A utility function to print an array of size n */function printArray(arr, n){ var i; for (i = 0; i < n; ++i) document.write(arr[i]+\" \");} var arr = [18, 40, 35, 12, 30, 35, 20, 6, 90, 80]; var n = arr.length; insertionSort(arr, n); printArray(arr, n); // This code is contributed by SoumikMondal</script>",
"e": 40818,
"s": 38346,
"text": null
},
{
"code": null,
"e": 40827,
"s": 40818,
"text": "Output: "
},
{
"code": null,
"e": 40856,
"s": 40827,
"text": "6 12 18 20 30 35 35 40 80 90"
},
{
"code": null,
"e": 40982,
"s": 40856,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 40995,
"s": 40982,
"text": "prerna saini"
},
{
"code": null,
"e": 41009,
"s": 40995,
"text": "rathbhupendra"
},
{
"code": null,
"e": 41022,
"s": 41009,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 41035,
"s": 41022,
"text": "princi singh"
},
{
"code": null,
"e": 41048,
"s": 41035,
"text": "SoumikMondal"
},
{
"code": null,
"e": 41064,
"s": 41048,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 41072,
"s": 41064,
"text": "Sorting"
},
{
"code": null,
"e": 41080,
"s": 41072,
"text": "Sorting"
},
{
"code": null,
"e": 41178,
"s": 41080,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41187,
"s": 41178,
"text": "Comments"
},
{
"code": null,
"e": 41200,
"s": 41187,
"text": "Old Comments"
},
{
"code": null,
"e": 41223,
"s": 41200,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 41234,
"s": 41223,
"text": "Radix Sort"
},
{
"code": null,
"e": 41278,
"s": 41234,
"text": "Time Complexities of all Sorting Algorithms"
},
{
"code": null,
"e": 41307,
"s": 41278,
"text": "Python Program for QuickSort"
},
{
"code": null,
"e": 41333,
"s": 41307,
"text": "Python List sort() method"
},
{
"code": null,
"e": 41361,
"s": 41333,
"text": "Merge Sort for Linked Lists"
},
{
"code": null,
"e": 41378,
"s": 41361,
"text": "sort() in Python"
},
{
"code": null,
"e": 41422,
"s": 41378,
"text": "k largest(or smallest) elements in an array"
}
] |
numpy.inner()
|
This function returns the inner product of vectors for 1-D arrays. For higher dimensions, it returns the sum product over the last axes.
import numpy as np
print np.inner(np.array([1,2,3]),np.array([0,1,0]))
# Equates to 1*0+2*1+3*0
It will produce the following output β
2
# Multi-dimensional array example
import numpy as np
a = np.array([[1,2], [3,4]])
print 'Array a:'
print a
b = np.array([[11, 12], [13, 14]])
print 'Array b:'
print b
print 'Inner product:'
print np.inner(a,b)
It will produce the following output β
Array a:
[[1 2]
[3 4]]
Array b:
[[11 12]
[13 14]]
Inner product:
[[35 41]
[81 95]]
In the above case, the inner product is calculated as β
1*11+2*12, 1*13+2*14
3*11+4*12, 3*13+4*14
63 Lectures
6 hours
Abhilash Nelson
19 Lectures
8 hours
DATAhill Solutions Srinivas Reddy
12 Lectures
3 hours
DATAhill Solutions Srinivas Reddy
10 Lectures
2.5 hours
Akbar Khan
20 Lectures
2 hours
Pruthviraja L
63 Lectures
6 hours
Anmol
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2380,
"s": 2243,
"text": "This function returns the inner product of vectors for 1-D arrays. For higher dimensions, it returns the sum product over the last axes."
},
{
"code": null,
"e": 2478,
"s": 2380,
"text": "import numpy as np \nprint np.inner(np.array([1,2,3]),np.array([0,1,0])) \n# Equates to 1*0+2*1+3*0"
},
{
"code": null,
"e": 2517,
"s": 2478,
"text": "It will produce the following output β"
},
{
"code": null,
"e": 2520,
"s": 2517,
"text": "2\n"
},
{
"code": null,
"e": 2742,
"s": 2520,
"text": "# Multi-dimensional array example \nimport numpy as np \na = np.array([[1,2], [3,4]]) \n\nprint 'Array a:' \nprint a \nb = np.array([[11, 12], [13, 14]]) \n\nprint 'Array b:' \nprint b \n\nprint 'Inner product:' \nprint np.inner(a,b)"
},
{
"code": null,
"e": 2781,
"s": 2742,
"text": "It will produce the following output β"
},
{
"code": null,
"e": 2867,
"s": 2781,
"text": "Array a:\n[[1 2]\n[3 4]]\n\nArray b:\n[[11 12]\n[13 14]]\n\nInner product:\n[[35 41]\n[81 95]]\n"
},
{
"code": null,
"e": 2923,
"s": 2867,
"text": "In the above case, the inner product is calculated as β"
},
{
"code": null,
"e": 2968,
"s": 2923,
"text": "1*11+2*12, 1*13+2*14 \n3*11+4*12, 3*13+4*14 \n"
},
{
"code": null,
"e": 3001,
"s": 2968,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3018,
"s": 3001,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3051,
"s": 3018,
"text": "\n 19 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3086,
"s": 3051,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 3119,
"s": 3086,
"text": "\n 12 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3154,
"s": 3119,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 3189,
"s": 3154,
"text": "\n 10 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3201,
"s": 3189,
"text": " Akbar Khan"
},
{
"code": null,
"e": 3234,
"s": 3201,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3249,
"s": 3234,
"text": " Pruthviraja L"
},
{
"code": null,
"e": 3282,
"s": 3249,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3289,
"s": 3282,
"text": " Anmol"
},
{
"code": null,
"e": 3296,
"s": 3289,
"text": " Print"
},
{
"code": null,
"e": 3307,
"s": 3296,
"text": " Add Notes"
}
] |
Why Rectified Linear Unit (ReLU) in Deep Learning and the best practice to use it with TensorFlow | by B. Chen | Towards Data Science
|
The activation functions are at the very core of Deep Learning. They determine the output of a model, its accuracy, and computational efficiency. In some cases, activation functions have a major effect on the modelβs ability to converge and the convergence speed.
In this article, youβll learn why ReLU is used in Deep Learning and the best practice to use it with Keras and TensorFlow 2.
Problems with Sigmoid and Tanh activation functionsWhat is Rectified Linear Unit (ReLU)Training a deep neural network using ReLUBest practice to use ReLU with He initializationComparing to models with Sigmoid and TanhLimitations of ReLU
Problems with Sigmoid and Tanh activation functions
What is Rectified Linear Unit (ReLU)
Training a deep neural network using ReLU
Best practice to use ReLU with He initialization
Comparing to models with Sigmoid and Tanh
Limitations of ReLU
Please check out Notebook for the source code. More tutorials can be found from the Github repo.
Historically, the two most widely used nonlinear activations are the Sigmoid and Hyperbolic Tangent (Tanh) activations functions.
The Sigmoid activation function (also known as the Logistic function), is traditionally a very popular activation function for neural networks. The input to the function is transformed into a value between 0 and 1. For a long time, through the early 1990s, it was the default activation used on neural networks.
The Hyperbolic Tangent, also known as Tanh, is a similar shaped nonlinear activation function that outputs value range from -1.0 and 1.0 (instead of 0 to 1 in the case of Sigmoid function). In the later 1990s and through the 2000s, the Tanh function was preferred over the Sigmoid activation function as models that used it were easier to train and often had a better predictive performance.
A general problem with both the Sigmoid and Tanh functions is vanishing gradients. Looking at the function plot, you can see that when inputs become small or large, the Sigmoid function saturates at 0 or 1 and the Tanh function saturates at -1 and 1, with a derivative extremely close to 0. Thus it has almost no gradient to propagate back through the network, so there is almost nothing left for lower layers [2]. The problem prevents network models from learning effectively, especially in deep networks,
Another problem with both the Sigmoid and Tanh functions is that they have an exponential operation, which can be computationally expensive. In our case, a model trained with ReLU has got a 25% improvement in terms of the convergence speed (Check out this result from the section βComparing to models with Sigmoid and Tanhβ).
The Rectified Linear Unit (ReLU) is the most commonly used activation function in deep learning. The function returns 0 if the input is negative, but for any positive input, it returns that value back. The function is defined as:
The plot of the function and its derivative:
As we can see that:
Graphically, the ReLU function is composed of two linear pieces to account for non-linearities. A function is non-linear if the slope isnβt constant. So, the ReLU function is non-linear around 0, but the slope is always either 0 (for negative inputs) or 1 (for positive inputs).
The ReLU function is continuous, but it is not differentiable because its derivative is 0 for any negative input.
The output of ReLU does not have a maximum value (It is not saturated) and this helps Gradient Descent
The function is very fast to compute (Compare to Sigmoid and Tanh)
Itβs surprising that such a simple function works very well in deep neural networks.
For the demonstration purpose, we will build an image classifier to tackle Fashion MNIST, which is a dataset that has 70,000 grayscale images of 28-by-28 pixels with 10 classes.
Keras provides some utility functions to fetch and load common datasets, including Fashion MNIST. Letβs load Fashion MNIST
fashion_mnist = keras.datasets.fashion_mnist(X_train_full, y_train_full), (X_test, y_test) = fashion_mnist.load_data()
The dataset is already split into a training set and a test set. Here is the shape and data type of the training set:
>>> X_train_full.shape(60000, 28, 28)>>> X_train_full.dtypedtype('uint8')
We are going to train the neural network using Gradient Descent, we must scale the input feature down to the 0β1 range.
Now letβs build a deep neural network! There are 3 ways to create a machine learning model with Keras and TensorFlow 2.0. Since we are building a simple fully connected neural network and for simplicity, letβs use the easiest way: Sequential Model with Sequential(). Letβs create a deep neural network for Fashion MNIST with 50 hidden layers:
from tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense, Flattendef create_model(activation): model = keras.models.Sequential() model.add(Flatten(input_shape=[28, 28])) model.add(Dense(300, activation=activation)) for layer in range(49): model.add(Dense(100, activation=activation)) model.add(Dense(10, activation="softmax")) model.compile( optimizer='sgd', loss='sparse_categorical_crossentropy', metrics=['accuracy'] ) return model
Our model has the following specifications:
The first layer (also known as the input layer) has the input_shape to set the input size (28, 28) which matches the training data. The input layer is a Flatten layer whose role is simply to convert each input image into a 1D array.
And then it is followed by 50Dense layers, one with 300 units, and the other 49 with 100 units.
The output Dense layer has 10 units and the softmax activation function.
Letβs create a model with ReLU:
model_relu = create_model(activation = 'relu')
To fit the model to training data:
history_relu = model_relu.fit( X_train, y_train, epochs=10, validation_data=(X_valid, y_valid),)
If all runs smoothly, we should get an output like below.
Train on 55000 samples, validate on 5000 samplesEpoch 1/1055000/55000 [==============================] - 41s 751us/sample - loss: 2.3027 - accuracy: 0.0991 - val_loss: 2.3028 - val_accuracy: 0.0914Epoch 2/1055000/55000 [==============================] - 42s 771us/sample - loss: 2.3027 - accuracy: 0.0979 - val_loss: 2.3029 - val_accuracy: 0.0914............Epoch 10/1055000/55000 [==============================] - 39s 715us/sample - loss: 2.3027 - accuracy: 0.0993 - val_loss: 2.3028 - val_accuracy: 0.0914
In this case, we can see that performance is quite poor on both the train and validation sets achieving around 10% accuracy. This suggests that the model as configured could not learn the problem nor generalize a solution.
The line plots of model accuracy on the train and validation sets during training tell a similar story.
Isnβt ReLU the default activation function in deep learning? What else is causing the problem?
One of the hyperparameters on training a deep neural network is the weight initializers. In general, there are 3 common initializers:
Random initialization
Glorot (Also known as Xavier) initialization
He initialization
If you google a little bit, youβve likely also found out that one should use Glorot (Xavier) initialization if the activation function is a Tanh, and He initialization is recommended if the activation function is a ReLU. By default, Keras uses Glorot initialization and that was a problem with the previous model.
In addition, the learning rate is too high in the previous model because we have seen both the train and validation sets accuracy achieving around 10% during training. Letβs use a smaller learning rate.
To build layers with He initialization, we can simply set the argument kernel_initializer to 'he_normal'. To use a custom learning rate, we can set the argument optimizer to keras.optimizers.SGD(lr=1e-3).
def create_model(activation, k_init): model = keras.models.Sequential() model.add(Flatten(input_shape=[28, 28])) model.add(Dense(300, activation=activation, kernel_initializer=k_init)) for layer in range(49): model.add(Dense(100, activation=activation, kernel_initializer=k_init)) model.add(Dense(10, activation="softmax")) model.compile( optimizer=keras.optimizers.SGD(lr=1e-3), loss='sparse_categorical_crossentropy', metrics=['accuracy'] ) return modelmodel_with_he = create_model( activation = 'relu', k_init='he_normal')
Now, letβs fit the model to training data again:
history_relu_he = model_with_he.fit( X_train, y_train, epochs=10, validation_data=(X_valid, y_valid),)
This time you should get a much better output:
Train on 55000 samples, validate on 5000 samplesEpoch 1/1055000/55000 [==============================] - 38s 687us/sample - loss: 1.3974 - accuracy: 0.4666 - val_loss: 1.3329 - val_accuracy: 0.5898Epoch 2/1055000/55000 [==============================] - 38s 693us/sample - loss: 0.7728 - accuracy: 0.7079 - val_loss: 0.7561 - val_accuracy: 0.7154............Epoch 10/1055000/55000 [==============================] - 38s 687us/sample - loss: 0.4063 - accuracy: 0.8545 - val_loss: 0.4198 - val_accuracy: 0.8552
By plotting the model accuracy, we can see the model with He initialization shows a huge improvement to what we have seen before.
Now, letβs build 2 models, one with Sigmoid and the other with Tanh, fit them with the training data.
model_sigmoid = create_model(activation = 'sigmoid')model_tanh = create_model(activation = 'tanh')
After that, letβs compare the accuracy of all the models we have discussed:
In this case, the model trained with ReLU and He Initialization has the best performance, followed by the model trained with Tanh.
We can see that models with ReLU and Sigmoid are quite poor on both the train and validation sets achieving around 10% accuracy. This suggests that the two models as configured could not learn the problem nor generalize a solution.
In addition, we found the average execution time for the model trained with ReLU is about 33 seconds per epoch, comparing to the average 40 seconds per epoch for the model trained with Sigmoid or Tanh. It is a 25% improvement in terms of convergence speed. (Please check out log details from the Notebook)
ReLU works great in most applications, but it is not perfect. It suffers from a problem known as the dying ReLU.
During training, some neurons effectively die, meaning they stop outputting anything other than 0. In some cases, you may find that half of your networkβs neurons are dead, especially if you used a large learning rate. A neuron dies when its weights get tweaked in such a way that the weighted sum of its inputs are negative for all instances in the training set. When this happens, it just keeps outputting 0s, and gradient descent does not affect it anymore since the gradient of the ReLU function is 0 when its input is negative.
Hands-on Machine Learning [1], page 329
To solve this problem, you may want to use a variant of the ReLU function, such as Leaky ReLU, Parametric Leaky ReLU (PReLU), Exponential Linear Unit (ELU), or Scaled Exponential Linear Unit (SELU). Please check out their introduction from the following article:
towardsdatascience.com
In this article, we have gone through the reason behind using the ReLU activation function in Deep Learning and how to use it with Keras and TensorFlow.
I hope this article will help you to save time in building and tuning your own Deep Learning model. I recommend you to check out the Keras documentation for the activation functions 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.
7 popular activation functions you should know in Deep Learning
Building custom callbacks with Keras and TensorFlow 2
A practical introduction to Keras Callbacks in TensorFlow 2
Learning Rate Schedules in practice
The Googleβs 7 steps of Machine Learning in practice: a TensorFlow example for structured data
3 ways to create a Machine Learning Model with Keras and TensorFlow 2.0
Batch normalization in practice: an example with Keras and TensorFlow 2.0
Early stopping in Practice: an example with Keras and TensorFlow
More can be found from my Github
[1] Hands-on machine learning with Scikit-Learn and TensorFlow: concepts, tools, and techniques to build intelligent systems
|
[
{
"code": null,
"e": 436,
"s": 172,
"text": "The activation functions are at the very core of Deep Learning. They determine the output of a model, its accuracy, and computational efficiency. In some cases, activation functions have a major effect on the modelβs ability to converge and the convergence speed."
},
{
"code": null,
"e": 561,
"s": 436,
"text": "In this article, youβll learn why ReLU is used in Deep Learning and the best practice to use it with Keras and TensorFlow 2."
},
{
"code": null,
"e": 798,
"s": 561,
"text": "Problems with Sigmoid and Tanh activation functionsWhat is Rectified Linear Unit (ReLU)Training a deep neural network using ReLUBest practice to use ReLU with He initializationComparing to models with Sigmoid and TanhLimitations of ReLU"
},
{
"code": null,
"e": 850,
"s": 798,
"text": "Problems with Sigmoid and Tanh activation functions"
},
{
"code": null,
"e": 887,
"s": 850,
"text": "What is Rectified Linear Unit (ReLU)"
},
{
"code": null,
"e": 929,
"s": 887,
"text": "Training a deep neural network using ReLU"
},
{
"code": null,
"e": 978,
"s": 929,
"text": "Best practice to use ReLU with He initialization"
},
{
"code": null,
"e": 1020,
"s": 978,
"text": "Comparing to models with Sigmoid and Tanh"
},
{
"code": null,
"e": 1040,
"s": 1020,
"text": "Limitations of ReLU"
},
{
"code": null,
"e": 1137,
"s": 1040,
"text": "Please check out Notebook for the source code. More tutorials can be found from the Github repo."
},
{
"code": null,
"e": 1267,
"s": 1137,
"text": "Historically, the two most widely used nonlinear activations are the Sigmoid and Hyperbolic Tangent (Tanh) activations functions."
},
{
"code": null,
"e": 1579,
"s": 1267,
"text": "The Sigmoid activation function (also known as the Logistic function), is traditionally a very popular activation function for neural networks. The input to the function is transformed into a value between 0 and 1. For a long time, through the early 1990s, it was the default activation used on neural networks."
},
{
"code": null,
"e": 1971,
"s": 1579,
"text": "The Hyperbolic Tangent, also known as Tanh, is a similar shaped nonlinear activation function that outputs value range from -1.0 and 1.0 (instead of 0 to 1 in the case of Sigmoid function). In the later 1990s and through the 2000s, the Tanh function was preferred over the Sigmoid activation function as models that used it were easier to train and often had a better predictive performance."
},
{
"code": null,
"e": 2478,
"s": 1971,
"text": "A general problem with both the Sigmoid and Tanh functions is vanishing gradients. Looking at the function plot, you can see that when inputs become small or large, the Sigmoid function saturates at 0 or 1 and the Tanh function saturates at -1 and 1, with a derivative extremely close to 0. Thus it has almost no gradient to propagate back through the network, so there is almost nothing left for lower layers [2]. The problem prevents network models from learning effectively, especially in deep networks,"
},
{
"code": null,
"e": 2804,
"s": 2478,
"text": "Another problem with both the Sigmoid and Tanh functions is that they have an exponential operation, which can be computationally expensive. In our case, a model trained with ReLU has got a 25% improvement in terms of the convergence speed (Check out this result from the section βComparing to models with Sigmoid and Tanhβ)."
},
{
"code": null,
"e": 3034,
"s": 2804,
"text": "The Rectified Linear Unit (ReLU) is the most commonly used activation function in deep learning. The function returns 0 if the input is negative, but for any positive input, it returns that value back. The function is defined as:"
},
{
"code": null,
"e": 3079,
"s": 3034,
"text": "The plot of the function and its derivative:"
},
{
"code": null,
"e": 3099,
"s": 3079,
"text": "As we can see that:"
},
{
"code": null,
"e": 3378,
"s": 3099,
"text": "Graphically, the ReLU function is composed of two linear pieces to account for non-linearities. A function is non-linear if the slope isnβt constant. So, the ReLU function is non-linear around 0, but the slope is always either 0 (for negative inputs) or 1 (for positive inputs)."
},
{
"code": null,
"e": 3492,
"s": 3378,
"text": "The ReLU function is continuous, but it is not differentiable because its derivative is 0 for any negative input."
},
{
"code": null,
"e": 3595,
"s": 3492,
"text": "The output of ReLU does not have a maximum value (It is not saturated) and this helps Gradient Descent"
},
{
"code": null,
"e": 3662,
"s": 3595,
"text": "The function is very fast to compute (Compare to Sigmoid and Tanh)"
},
{
"code": null,
"e": 3747,
"s": 3662,
"text": "Itβs surprising that such a simple function works very well in deep neural networks."
},
{
"code": null,
"e": 3925,
"s": 3747,
"text": "For the demonstration purpose, we will build an image classifier to tackle Fashion MNIST, which is a dataset that has 70,000 grayscale images of 28-by-28 pixels with 10 classes."
},
{
"code": null,
"e": 4048,
"s": 3925,
"text": "Keras provides some utility functions to fetch and load common datasets, including Fashion MNIST. Letβs load Fashion MNIST"
},
{
"code": null,
"e": 4167,
"s": 4048,
"text": "fashion_mnist = keras.datasets.fashion_mnist(X_train_full, y_train_full), (X_test, y_test) = fashion_mnist.load_data()"
},
{
"code": null,
"e": 4285,
"s": 4167,
"text": "The dataset is already split into a training set and a test set. Here is the shape and data type of the training set:"
},
{
"code": null,
"e": 4359,
"s": 4285,
"text": ">>> X_train_full.shape(60000, 28, 28)>>> X_train_full.dtypedtype('uint8')"
},
{
"code": null,
"e": 4479,
"s": 4359,
"text": "We are going to train the neural network using Gradient Descent, we must scale the input feature down to the 0β1 range."
},
{
"code": null,
"e": 4822,
"s": 4479,
"text": "Now letβs build a deep neural network! There are 3 ways to create a machine learning model with Keras and TensorFlow 2.0. Since we are building a simple fully connected neural network and for simplicity, letβs use the easiest way: Sequential Model with Sequential(). Letβs create a deep neural network for Fashion MNIST with 50 hidden layers:"
},
{
"code": null,
"e": 5351,
"s": 4822,
"text": "from tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense, Flattendef create_model(activation): model = keras.models.Sequential() model.add(Flatten(input_shape=[28, 28])) model.add(Dense(300, activation=activation)) for layer in range(49): model.add(Dense(100, activation=activation)) model.add(Dense(10, activation=\"softmax\")) model.compile( optimizer='sgd', loss='sparse_categorical_crossentropy', metrics=['accuracy'] ) return model"
},
{
"code": null,
"e": 5395,
"s": 5351,
"text": "Our model has the following specifications:"
},
{
"code": null,
"e": 5628,
"s": 5395,
"text": "The first layer (also known as the input layer) has the input_shape to set the input size (28, 28) which matches the training data. The input layer is a Flatten layer whose role is simply to convert each input image into a 1D array."
},
{
"code": null,
"e": 5724,
"s": 5628,
"text": "And then it is followed by 50Dense layers, one with 300 units, and the other 49 with 100 units."
},
{
"code": null,
"e": 5797,
"s": 5724,
"text": "The output Dense layer has 10 units and the softmax activation function."
},
{
"code": null,
"e": 5829,
"s": 5797,
"text": "Letβs create a model with ReLU:"
},
{
"code": null,
"e": 5876,
"s": 5829,
"text": "model_relu = create_model(activation = 'relu')"
},
{
"code": null,
"e": 5911,
"s": 5876,
"text": "To fit the model to training data:"
},
{
"code": null,
"e": 6022,
"s": 5911,
"text": "history_relu = model_relu.fit( X_train, y_train, epochs=10, validation_data=(X_valid, y_valid),)"
},
{
"code": null,
"e": 6080,
"s": 6022,
"text": "If all runs smoothly, we should get an output like below."
},
{
"code": null,
"e": 6589,
"s": 6080,
"text": "Train on 55000 samples, validate on 5000 samplesEpoch 1/1055000/55000 [==============================] - 41s 751us/sample - loss: 2.3027 - accuracy: 0.0991 - val_loss: 2.3028 - val_accuracy: 0.0914Epoch 2/1055000/55000 [==============================] - 42s 771us/sample - loss: 2.3027 - accuracy: 0.0979 - val_loss: 2.3029 - val_accuracy: 0.0914............Epoch 10/1055000/55000 [==============================] - 39s 715us/sample - loss: 2.3027 - accuracy: 0.0993 - val_loss: 2.3028 - val_accuracy: 0.0914"
},
{
"code": null,
"e": 6812,
"s": 6589,
"text": "In this case, we can see that performance is quite poor on both the train and validation sets achieving around 10% accuracy. This suggests that the model as configured could not learn the problem nor generalize a solution."
},
{
"code": null,
"e": 6916,
"s": 6812,
"text": "The line plots of model accuracy on the train and validation sets during training tell a similar story."
},
{
"code": null,
"e": 7011,
"s": 6916,
"text": "Isnβt ReLU the default activation function in deep learning? What else is causing the problem?"
},
{
"code": null,
"e": 7145,
"s": 7011,
"text": "One of the hyperparameters on training a deep neural network is the weight initializers. In general, there are 3 common initializers:"
},
{
"code": null,
"e": 7167,
"s": 7145,
"text": "Random initialization"
},
{
"code": null,
"e": 7212,
"s": 7167,
"text": "Glorot (Also known as Xavier) initialization"
},
{
"code": null,
"e": 7230,
"s": 7212,
"text": "He initialization"
},
{
"code": null,
"e": 7544,
"s": 7230,
"text": "If you google a little bit, youβve likely also found out that one should use Glorot (Xavier) initialization if the activation function is a Tanh, and He initialization is recommended if the activation function is a ReLU. By default, Keras uses Glorot initialization and that was a problem with the previous model."
},
{
"code": null,
"e": 7747,
"s": 7544,
"text": "In addition, the learning rate is too high in the previous model because we have seen both the train and validation sets accuracy achieving around 10% during training. Letβs use a smaller learning rate."
},
{
"code": null,
"e": 7952,
"s": 7747,
"text": "To build layers with He initialization, we can simply set the argument kernel_initializer to 'he_normal'. To use a custom learning rate, we can set the argument optimizer to keras.optimizers.SGD(lr=1e-3)."
},
{
"code": null,
"e": 8548,
"s": 7952,
"text": "def create_model(activation, k_init): model = keras.models.Sequential() model.add(Flatten(input_shape=[28, 28])) model.add(Dense(300, activation=activation, kernel_initializer=k_init)) for layer in range(49): model.add(Dense(100, activation=activation, kernel_initializer=k_init)) model.add(Dense(10, activation=\"softmax\")) model.compile( optimizer=keras.optimizers.SGD(lr=1e-3), loss='sparse_categorical_crossentropy', metrics=['accuracy'] ) return modelmodel_with_he = create_model( activation = 'relu', k_init='he_normal')"
},
{
"code": null,
"e": 8597,
"s": 8548,
"text": "Now, letβs fit the model to training data again:"
},
{
"code": null,
"e": 8714,
"s": 8597,
"text": "history_relu_he = model_with_he.fit( X_train, y_train, epochs=10, validation_data=(X_valid, y_valid),)"
},
{
"code": null,
"e": 8761,
"s": 8714,
"text": "This time you should get a much better output:"
},
{
"code": null,
"e": 9270,
"s": 8761,
"text": "Train on 55000 samples, validate on 5000 samplesEpoch 1/1055000/55000 [==============================] - 38s 687us/sample - loss: 1.3974 - accuracy: 0.4666 - val_loss: 1.3329 - val_accuracy: 0.5898Epoch 2/1055000/55000 [==============================] - 38s 693us/sample - loss: 0.7728 - accuracy: 0.7079 - val_loss: 0.7561 - val_accuracy: 0.7154............Epoch 10/1055000/55000 [==============================] - 38s 687us/sample - loss: 0.4063 - accuracy: 0.8545 - val_loss: 0.4198 - val_accuracy: 0.8552"
},
{
"code": null,
"e": 9400,
"s": 9270,
"text": "By plotting the model accuracy, we can see the model with He initialization shows a huge improvement to what we have seen before."
},
{
"code": null,
"e": 9502,
"s": 9400,
"text": "Now, letβs build 2 models, one with Sigmoid and the other with Tanh, fit them with the training data."
},
{
"code": null,
"e": 9601,
"s": 9502,
"text": "model_sigmoid = create_model(activation = 'sigmoid')model_tanh = create_model(activation = 'tanh')"
},
{
"code": null,
"e": 9677,
"s": 9601,
"text": "After that, letβs compare the accuracy of all the models we have discussed:"
},
{
"code": null,
"e": 9808,
"s": 9677,
"text": "In this case, the model trained with ReLU and He Initialization has the best performance, followed by the model trained with Tanh."
},
{
"code": null,
"e": 10040,
"s": 9808,
"text": "We can see that models with ReLU and Sigmoid are quite poor on both the train and validation sets achieving around 10% accuracy. This suggests that the two models as configured could not learn the problem nor generalize a solution."
},
{
"code": null,
"e": 10346,
"s": 10040,
"text": "In addition, we found the average execution time for the model trained with ReLU is about 33 seconds per epoch, comparing to the average 40 seconds per epoch for the model trained with Sigmoid or Tanh. It is a 25% improvement in terms of convergence speed. (Please check out log details from the Notebook)"
},
{
"code": null,
"e": 10459,
"s": 10346,
"text": "ReLU works great in most applications, but it is not perfect. It suffers from a problem known as the dying ReLU."
},
{
"code": null,
"e": 10992,
"s": 10459,
"text": "During training, some neurons effectively die, meaning they stop outputting anything other than 0. In some cases, you may find that half of your networkβs neurons are dead, especially if you used a large learning rate. A neuron dies when its weights get tweaked in such a way that the weighted sum of its inputs are negative for all instances in the training set. When this happens, it just keeps outputting 0s, and gradient descent does not affect it anymore since the gradient of the ReLU function is 0 when its input is negative."
},
{
"code": null,
"e": 11032,
"s": 10992,
"text": "Hands-on Machine Learning [1], page 329"
},
{
"code": null,
"e": 11295,
"s": 11032,
"text": "To solve this problem, you may want to use a variant of the ReLU function, such as Leaky ReLU, Parametric Leaky ReLU (PReLU), Exponential Linear Unit (ELU), or Scaled Exponential Linear Unit (SELU). Please check out their introduction from the following article:"
},
{
"code": null,
"e": 11318,
"s": 11295,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 11471,
"s": 11318,
"text": "In this article, we have gone through the reason behind using the ReLU activation function in Deep Learning and how to use it with Keras and TensorFlow."
},
{
"code": null,
"e": 11696,
"s": 11471,
"text": "I hope this article will help you to save time in building and tuning your own Deep Learning model. I recommend you to check out the Keras documentation for the activation functions and to know about other things you can do."
},
{
"code": null,
"e": 11848,
"s": 11696,
"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": 11912,
"s": 11848,
"text": "7 popular activation functions you should know in Deep Learning"
},
{
"code": null,
"e": 11966,
"s": 11912,
"text": "Building custom callbacks with Keras and TensorFlow 2"
},
{
"code": null,
"e": 12026,
"s": 11966,
"text": "A practical introduction to Keras Callbacks in TensorFlow 2"
},
{
"code": null,
"e": 12062,
"s": 12026,
"text": "Learning Rate Schedules in practice"
},
{
"code": null,
"e": 12157,
"s": 12062,
"text": "The Googleβs 7 steps of Machine Learning in practice: a TensorFlow example for structured data"
},
{
"code": null,
"e": 12229,
"s": 12157,
"text": "3 ways to create a Machine Learning Model with Keras and TensorFlow 2.0"
},
{
"code": null,
"e": 12303,
"s": 12229,
"text": "Batch normalization in practice: an example with Keras and TensorFlow 2.0"
},
{
"code": null,
"e": 12368,
"s": 12303,
"text": "Early stopping in Practice: an example with Keras and TensorFlow"
},
{
"code": null,
"e": 12401,
"s": 12368,
"text": "More can be found from my Github"
}
] |
CUDA - Quick Guide
|
CUDA β Compute Unified Device Architecture. It is an extension of C programming, an API model for parallel computing created by Nvidia. Programs written using CUDA harness the power of GPU. Thus, increasing the computing performance.
Gordon Moore of Intel once famously stated a rule, which said that every passing year, the clock frequency of a semiconductor core doubles. This law held true until recent years. Now, as the clock frequencies of a single core reach saturation points (you will not find a single core CPU with a clock frequency of say, 5GHz, even after 2 years from now), the paradigm has shifted to multi-core and many-core processors.
In this chapter, we will study how parallelism is achieved in CPUs. This chapter is an essential foundation to studying GPUs (it helps in understanding the key differences between GPUs and CPUs).
Following are the five essential steps required for an instruction to finish β
Instruction fetch (IF)
Instruction decode (ID)
Instruction execute (Ex)
Memory access (Mem)
Register write-back (WB)
This is a basic five-stage RISC architecture.
There are multiple ways to achieve parallelism in the CPU. First, we will discuss about ILP (Instruction Level Parallelism), also known as pipelining.
A CPU pipeline is a series of instructions that a CPU can handle in parallel per clock. A basic CPU with no ILP will execute the above five steps sequentially. In fact, any CPU will do that. It will first fetch the instructions, decode them, execute them, then access the RAM, and then write-back to the registers. Thus, it needs at least five CPU cycles to execute an instruction. During this process, there are parts of the chip that are sitting idle, waiting for the current instruction to finish. This is highly inefficient and this is exactly what instruction pipelining tries to address. Instead now, in one clock cycle, there are many steps of different instructions that execute in parallel. Thus the name, Instruction Level Parallelism.
The following figure will help you understand how Instruction Level Parallelism works β
Using instruction pipelining, the instruction throughput has increased. Now, we can process many instructions in one-clock cycle. But for ILP, the resources of a chip would have been sitting idle.
In a pipe-lined chip, the instruction throughput increased. Initially, one instruction completed after every 5 cycles. Now, at the end of each cycle (from the 5th cycle onwards, considering each step takes 1 cycle), we get a completed instruction.
Note that in a non-pipelined chip, where it is assumed that the next instruction begins only when the current has finished, there is no data hazard. But since such is not the case with a pipelined chip, hazards may arise. Consider the situation below β
I1 β ADD 1 to R5
I2 β COPY R5 to R6
Now, in a pipeline processor, I1 starts at t1, and finishes at t5. I2 starts at t2 and finishes at t6. 1 is added to R5 at t5 (at the WB stage). The second instruction reads the value of R5 at its second step (at time t3). Thus, it will not fetch the update value, and this presents a hazard.
Modern compilers decode high-level code to low-level code, and take care of hazards.
ILP is also implemented by implementing a superscalar architecture. The primary difference between a superscalar and a pipelined processor is (a superscalar processor is also pipeline) that the former uses multiple execution units (on the same chip) to achieve ILP whereas the latter divides the EU in multiple phases to do that. This means that in superscalar, several instructions can simultaneously be in the same stage of the execution cycle. This is not possible in a simple pipelined chip. Superscalar microprocessors can execute two or more instructions at the same time. They typically have at least 2 ALUs.
Superscalar processors can dispatch multiple instructions in the same clock cycle. This means that multiple instructions can be started in the same clock cycle. If you look at the pipelines architecture above, you can observe that at any clock cycle, only one instruction is dispatched. This is not the case with superscalars. But we have only one instruction counter (in-flight, multiple instructions are tracked). This is still just one process.
Take the Intel i7 for instance. The processor boasts of 4 independent cores, each implementing the full x86 ISA. Each core is hyper-threaded with two hardware cores.
Hyper-threading is a dope technology, proprietary to Intel, using which the operating system see a single core as two virtual cores, for increasing the number of hardware instructions in the pipeline (note that not all operating systems support HT, and Intel recommends that in such cases, HT be disabled). So, the Intel i7 has a total of 8 hardware threads.
HT is just a technology to utilize a processor core better. Many a times, a processor core is utilizing only a fraction of its resources to execute instructions. What HT does is that it takes a few more CPU registers, and executes more instructions on the part of the core that is sitting idle. Thus, one core now appears as two core. It is to be considered that they are not completely independent. If both the βcoresβ need to access the CPU resource, one of them ends up waiting. That is the reason why we cannot replace a dual-core CPU with a hyper-threaded, single core CPU. A dual core CPU will have truly independent, out-of-order cores, each with its own resources. Also note that HT is Intelβs implementation of SMT (Simultaneous Multithreading). SPARC has a different implementation of SMT, with identical goals.
The pink box represents a single CPU core. The RAM contains instructions of 4 different programs, indicated by different colors. The CPU implements the SMT, using a technology similar to hyper-threading. Hence, it is able to run instructions of two different programs (red and yellow) simultaneously. White boxes represent pipeline stalls.
So, there are multi-core CPUs. One thing to notice is that they are designed to fasten-up sequential programs. A CPU is very good when it comes to executing a single instruction on a single datum, but not so much when it comes to processing a large chunk of data. A CPU has a larger instruction set than a GPU, a complex ALU, a better branch prediction logic, and a more sophisticated caching/pipeline schemes. The instruction cycles are also a lot faster.
The other paradigm is many-core processors that are designed to operate on large chunks of data, in which CPUs prove inefficient. A GPU comprises many cores (that almost double each passing year), and each core runs at a clock speed significantly slower than a CPUβs clock. GPUs focus on execution throughput of massively-parallel programs. For example, the Nvidia GeForce GTX 280 GPU has 240 cores, each of which is a heavily multithreaded, in-order, single-instruction issue processor (SIMD β single instruction, multiple-data) that shares its control and instruction cache with seven other cores. When it comes to the total Floating Point Operations per Second (FLOPS), GPUs have been leading the race for a long time now.
GPUs do not have virtual memory, interrupts, or means of addressing devices such as the keyboard and the mouse. They are terribly inefficient when we do not have SPMD (Single Program, Multiple Data). Such programs are best handled by CPUs, and may be that is the reason why they are still around. For example, a CPU can calculate a hash for a string much, much faster than a GPU, but when it comes to computing several thousand hashes, the GPU wins. As of data from 2009, the ratio b/w GPUs and multi-core CPUs for peak FLOP calculations is about 10:1. Such a large performance gap forces the developers to outsource their data-intensive applications to the GPU.
GPUs are designed for data intensive applications. This is emphasized-upon by the fact that the bandwidths of GPU DRAM has increased tremendously by each passing year, but not so much in case of CPUs. Why GPUs adopt such a design and CPUs do not? Well, because GPUs were originally designed for 3D rendering, which requires holding large amount of texture and polygon data. Caches cannot hold such large amount of data, and thus, the only design that would have increased rendering performance was to increase the bus width and the memory clock. For example, the Intel i7, which currently supports the largest memory bandwidth, has a memory bus of width 192b and a memory clock upto 800MHz. The GTX 285 had a bus width of 512b, and a memory clock of 1242 MHz.
CPUs also would not benefit greatly from an increased memory bandwidth. Sequential programs typically do not have a βworking setβ of data, and most of the required data can be stored in L1, L2 or L3 cache, which are faster than any RAM. Moreover, CPU programs generally have more random memory access patterns, unlike massively-parallel programs, that would not derive much benefit from having a wide memory bus.
Here is the architecture of a CUDA capable GPU β
There are 16 streaming multiprocessors (SMs) in the above diagram. Each SM has 8 streaming processors (SPs). That is, we get a total of 128 SPs. Now, each SP has a MAD unit (Multiply and Addition Unit) and an additional MU (Multiply Unit). The GT200 has 240 SPs, and exceeds 1 TFLOP of processing power.
Each SP is massively threaded, and can run thousands of threads per application. The G80 card supports 768 threads per SM (note: not per SP). Since each SM has 8 SPs, each SP supports a maximum of 96 threads. Total threads that can run: 128 * 96 = 12,228. This is why these processors are called βmassively parallelβ.
The G80 chips has a memory bandwidth of 86.4GB/s. It also has an 8GB/s communication channel with the CPU (4GB/s for uploading to the CPU RAM, and 4GB/s for downloading from the CPU RAM).
At this point, it becomes essential that we understand the difference between different types of memories.
DRAM stands for Dynamic RAM. It is the most common RAM found in systems today, and is also the slowest and the least expensive one. The RAM is named so because the information stored on it is lost, and the processor has to refresh it several times in a second to preserve data.
SRAMstands for Static RAM. This RAM does not need to be refreshed like DRAM, and it is significantly faster than DRAM (the difference in speeds comes from the design and the static nature of these RAMs). It is also called the microprocessor cache RAM.
So, if SRAM is faster than DRAM, why are DRAMs even used? The primary reason for this is that for the same amount of memory, SRAMs cost several times more than DRAMs. Therefore, processors do not have huge amount of cache memories. For example, the Intel 486 line microprocessor series has 8KB of internal SRAM cache (on-chip). This cache is used by the processor to store frequently used data, so that for each request, it does not have to access the much slower DRAM.
VRAM stands for Video RAM. It is quite similar to DRAM but with one major difference: it can be written to and read from simultaneously. This property is essential for better video performance. Using it, the video card can read data from VRAM and send it to the screen without having to wait for the CPU to finish writing it into the global memory. This property is of not much use in the rest of the computer, and therefore, VRAM are almost always used in video cards. Also, VRAMs are more expensive than DRAM, and this is one of the reasons why they have not replaced DRAMs yet.
This kind of hardware was popular from the early 1980s to the late 1990s. These were fixed-function pipelines that were configurable, but not programmable. Modern GPUs are shader-based and programmable.
The fixed-function pipeline does exactly what the name suggests; its functionality is fixed. So, for example, if the pipeline contains a list of methods to rasterize geometry and shade pixels, that is pretty much it. You cannot add any more methods. Although these pipelines were good at rendering scenes, they enshrine certain deficiencies. In broad terms, you can perform linear transformations and then rasterize by texturing, interpolate a color across a face by combinations and permutations of those things. But what when you wanted to perform things that the pipeline could not do?
In modern GPUs, all the pipelines are generic, and can run any type of GPU assembler code. In recent time, the number of functions of the pipeline are many - they do vertex mapping, and color calculation for each pixel, they also support geometry shader (tessellation), and even compute shaders (where the parallel processor is used to do a non-graphics job).
Fixed function pipelines are limited in their capabilities, but are easy to design. They are not used much in todayβs graphics systems. Instead, programmable pipelines using OpenGL or DirectX are the de-facto standards for modern GPUs.
The following image illustrates and describes a fixed-function Nvidia pipeline.
Let us understand the various stages of the pipeline now β
The CPU sends commands and data to the GPU host interface. Typically, the commands are given by application programs by calling an API function (from a list of many). A specialized Direct Memory Access (DMA) hardware is used by the host interface to fasten the transfer of bulk data to and fro the graphics pipeline.
In the GeForce pipeline, the surface of an object is drawn as a collection of triangles (the GeForce pipeline has been designed to render triangles). The finer the size of the triangle, the better the image quality (you can observe them in older games like the Tekken 3).
The vertex control stage receives parameterized triangle data from the host interface (which in-turn receives it from the CPU). Then comes the VT/T&;L stage. It stands for Vertex Shading, Transform and Lighting. This stage transforms vertices and assigns each vertex values for some parameters, such as colors, texture coordinates, normals and tangents. The pixel shader hardware does the shading (the vertex shader assigns a color value to each vertex, but coloring is done later).
The triangle setup stage is used to interpolate colors and other vertex parameters to those pixels that are touched by the triangle (the triangle setup stage actually determines the edge equations. It is the raster stage that interpolates).
The shader stage gives the pixel its final color. There are many methods to achieve this, apart form interpolations. Some of them include texture mapping, per-pixel lighting, reflections, etc.
It is basically assigning a color to each vertex of a triangle on the surface (represented by polygon meshes, in our case, the polygon is a triangle), and linearly interpolating for each pixel covered by the triangle. There are many varieties to this, such as flat shading, Gouraud shading and Phong shading.
Let us now see shading using Gouraud shading. The triangle count is poor, and hence the poor performance of the specular highlight.
The same image rendered with a high triangle count.
In this technique, illumination for each pixel is calculated. This results in a better quality image than an image that is shaded using interpolation. Most modern video games use this technique for increased realism and level of detail.
The ROP stage (Raster Operation) is used to perform the final rasterization steps on pixels. For example, it blends the color of overlapping objects for transparency and anti-aliasing effects. It also determines what pixels are occluded in a scene (a pixel is occluded when it is hidden by some other pixel in the image). Occluded pixels are simply discarded.
Reads and writes from the display buffer memory are managed by the last stage, that is, the frame buffer interface.
In this chapter, we will learn about a few key concepts related to CUDA. We will understand data parallelism, the program structure of CUDA and how a CUDA C Program is executed.
Modern applications process large amounts of data that incur significant execution time on sequential computers. An example of such an application is rendering pixels. For example, an application that converts sRGB pixels to grayscale. To process a 1920x1080 image, the application has to process 2073600 pixels.
Processing all those pixels on a traditional uniprocessor CPU will take a very long time since the execution will be done sequentially. (The time taken will be proportional to the number of pixels in the image). Further, it is very inefficient since the operation that is performed on each pixel is the same, but different on the data (SPMD). Since processing one pixel is independent of the processing of any other pixel, all the pixels can be processed in parallel. If we use 2073600 threads (βworkersβ) and each thread processes one pixel, the task can be reduced to constant time. Millions of such threads can be launched on modern GPUs.
As has already been explained in the previous chapters, GPU is traditionally used for rendering graphics. For example, per-pixel lighting is a highly parallel, and data-intensive task and a GPU is perfect for the job. We can map each pixel with a thread and they all can be processed in O(1) constant time.
Image processing and computer graphics are not the only areas in which we harness data parallelism to our advantage. Many high-performance algebra libraries today such as CU-BLAS harness the processing power of the modern GPU to perform data intensive algebra operations. One such operation, matrix multiplication has been explained in the later sections.
A typical CUDA program has code intended both for the GPU and the CPU. By default, a traditional C program is a CUDA program with only the host code. The CPU is referred to as the host, and the GPU is referred to as the device. Whereas the host code can be compiled by a traditional C compiler as the GCC, the device code needs a special compiler to understand the api functions that are used. For Nvidia GPUs, the compiler is called the NVCC (Nvidia C Compiler).
The device code runs on the GPU, and the host code runs on the CPU. The NVCC processes a CUDA program, and separates the host code from the device code. To accomplish this, special CUDA keywords are looked for. The code intended to run of the GPU (device code) is marked with special CUDA keywords for labelling data-parallel functions, called βKernelsβ. The device code is further compiled by the NVCC and executed on the GPU.
How does a CUDA program work? While writing a CUDA program, the programmer has explicit control on the number of threads that he wants to launch (this is a carefully decided-upon number). These threads collectively form a three-dimensional grid (threads are packed into blocks, and blocks are packed into grids). Each thread is given a unique identifier, which can be used to identify what data it is to be acted upon.
As has been explained in the previous chapter, a typical GPU comes with its own global memory (DRAM- Dynamic Random Access Memory). For example, the Nvidia GTX 480 has DRAM size equal to 4G. From now on, we will call this memory the device memory.
To execute a kernel on the GPU, the programmer needs to allocate separate memory on the GPU by writing code. The CUDA API provides specific functions for accomplishing this. Here is the flow sequence β
After allocating memory on the device, data has to be transferred from the host memory to the device memory.
After allocating memory on the device, data has to be transferred from the host memory to the device memory.
After the kernel is executed on the device, the result has to be transferred back from the device memory to the host memory.
After the kernel is executed on the device, the result has to be transferred back from the device memory to the host memory.
The allocated memory on the device has to be freed-up. The host can access the device memory and transfer data to and from it, but not the other way round.
The allocated memory on the device has to be freed-up. The host can access the device memory and transfer data to and from it, but not the other way round.
CUDA provides API functions to accomplish all these steps.
In this chapter, we will discuss the keywords and thread organisation in CUDA.
The following keywords are used while declaring a CUDA function. As an example, while declaring the kernel, we have to use the __global__ keyword. This provides a hint to the compiler that this function will be executed on the device and can be called from the host.
In this section, we will see a sample CUDA C Code.
void vecAdd(float* A, float* B, float* C,int N) {
int size=N*sizeOf(float);
float *d_A,*d_B,*d_C;
cudaMalloc((void**)&;d_A,size);
This helps in allocating memory on the device for storing vector A. When the function returns, we get a pointer to the starting location of the memory.
cudaMemcpy(d_A,A,size,cudaMemcpyHostToDevice);
Copy data from host to device. The host memory contains the contents of vector A. Now that we have allocated space on the device for storing vector A, we transfer the contents of vector A to the device. At this point, the GPU memory has vector A stored, ready to be operated upon.
cudaMalloc((void**)&;d_B,size);
cudaMemcpy(d_B,B,size,cudaMemcpyHostToDevice);
//Similar to A
cudaMalloc((void**)&;d_C,size);
This helps in allocating the memory on the GPU to store the result vector C. We will cover the Kernel launch statement later.
cudaMemcpy(C,d_C,size,cudaMemcpyDeviceToHost);
After all the threads have finished executing, the result is stored in d_C (d stands for device). The host copies the result back to vector C from d_C.
cudaFree(d_A);
cudaFree(d_B);
cudaFree(d_C);
This helps to free up the memory allocated on the device using cudaMalloc().
This is how the above program works β
The above program adds the corresponding elements of two vectors X and Y, and stores the final result in a vector Z.
The above program adds the corresponding elements of two vectors X and Y, and stores the final result in a vector Z.
The device memory is allocated for storing the input vectors (X and Y) and the result vector (Z).
The device memory is allocated for storing the input vectors (X and Y) and the result vector (Z).
cudaMalloc() β This method is used to allocate memory on the host. in two parameters, the address of a pointer to the allocated object, and the size of the allocated object in terms of bytes.
cudaMalloc() β This method is used to allocate memory on the host. in two parameters, the address of a pointer to the allocated object, and the size of the allocated object in terms of bytes.
cudaFree() β This method is used to release objects from device memory. It takes in the pointer to the freed object as parameter.
cudaFree() β This method is used to release objects from device memory. It takes in the pointer to the freed object as parameter.
cudaMemcpy() β This API function is used for memory data transfer. It requires four parameters as input: Pointer to the destination, pointer to the source, amount of data to be copied (in bytes), and the direction of transfer.
cudaMemcpy() β This API function is used for memory data transfer. It requires four parameters as input: Pointer to the destination, pointer to the source, amount of data to be copied (in bytes), and the direction of transfer.
Threads in a grid execute the same kernel function. They have specific coordinates to distinguish themselves from each other and identify the relevant portion of data to process. In CUDA, they are organized in a two-level hierarchy: a grid comprises blocks, and each block comprises threads.
For all threads in a block, the block index is the same. The block index parameter can be accessed using the blockIdx variable inside a kernel. Each thread also has an associated index, and it can be accessed by using threadIdx variable inside the kernel. Note that blockIdx and threadIdx are built-in CUDA variables that are only accessible from inside the kernel.
In a similar fashion, CUDA also has gridDim and blockDim variables that are also built-in. They return the dimensions of the grid and block along a particular axis respectively. As an example, blockDim. x can be used to find how many threads a particular block has along the x axis.
Let us consider an example to understand the concept explained above. Consider an image, which is 76 pixels along the x axis, and 62 pixels along the y axis. Our aim is to convert the image from sRGB to grayscale. We can calculate the total number of pixels by multiplying the number of pixels along the x axis with the total number along the y axis that comes out to be 4712 pixels. Since we are mapping each thread with each pixel, we need a minimum of 4712 pixels. Let us take number of threads in each direction to be a multiple of 4. So, along the x axis, we will need at least 80 threads, and along the y axis, we will need at least 64 threads to process the complete image. We will ensure that the extra threads are not assigned any work.
Thus, we are launching 5120 threads to process a 4712 pixels image. You may ask, why the extra threads? The answer to this question is that keeping the dimensions as multiple of 4 has many benefits that largely offsets any disadvantages that result from launching extra threads. This is explained in a later section).
Now, we have to divide these 5120 threads into grids and blocks. Let each block have 256 threads. If so, then one possibility that of the dimensions each block are: (16,16,1). This means, there are 16 threads in the x direction, 16 in the y direction, and 1 in the z direction. We will be needing 5 blocks in the x direction (since there are 80 threads in total along the x axis), and 4 blocks in y direction (64 threads along the y axis in total), and 1 block in z direction. So, in total, we need 20 blocks. In a nutshell, the grid dimensions are (5,4,1) and the block dimensions are (16,16,1). The programmer needs to specify these values in the program. This is shown in the figure above.
dim3 dimBlock(5,4,1) β To specify the grid dimensions
dim3 dimBlock(5,4,1) β To specify the grid dimensions
dim3 dimGrid(ceil(n/16.0),ceil(m/16.0),1) β To specify the block dimensions.
dim3 dimGrid(ceil(n/16.0),ceil(m/16.0),1) β To specify the block dimensions.
kernelName<<<dimGrid,dimBlock>>>(parameter1, parameter2, ...) β Launch the actual kernel.
kernelName<<<dimGrid,dimBlock>>>(parameter1, parameter2, ...) β Launch the actual kernel.
n is the number of pixels in the x direction, and m is the number of pixels in the y direction. βceilβ is the regular ceiling function. We use it because we never want to end up with less number of blocks than required. dim3 is a data structure, just like an int or a float. dimBlock and dimGrid are variables names. The third statement is the kernel launch statement. βkernelNameβ is the name of the kernel function, to which we pass the parameters: parameter1, parameter2, and so on. <<<>>> contain the dimensions of the grid and the block.
In this chapter, we will learn how to install CUDA.
For installing the CUDA toolkit on Windows, youβll need β
A CUDA enabled Nvidia GPU.
A supported version of Microsoft Windows.
A supported version of Visual Studio.
The latest CUDA toolkit.
Note that natively, CUDA allows only 64b applications. That is, you cannot develop 32b CUDA applications natively (exception: they can be developed only on the GeForce series GPUs). 32b applications can be developed on x86_64 using the cross-development capabilities of the CUDA toolkit. For compiling CUDA programs to 32b, follow these steps β
Step 1 β Add <installpath>\bin to your path.
Step 2 β Add -m32 to your nvcc options.
Step 3 β Link with the 32-bit libs in <installpath>\lib (instead of <installpath>\lib64).
You can download the latest CUDA toolkit from here.
As can be seen from the above tables, support for x86_32 is limited. Presently, only the GeForce series is supported for 32b CUDA applications. If you have a supported version of Windows and Visual Studio, then proceed. Otherwise, first install the required software.
Verifying if your system has a CUDA capable GPU β Open a RUN window and run the command β control /name Microsoft.DeviceManager, and verify from the given information. If you do not have a CUDA capable GPU, or a GPU, then halt.
In this section, we will see how to install the latest CUDA toolkit.
Step 1 β Visit β https://developer.nvidia.com and select the desired operating system.
Step 2 β Select the type of installation that you would like to perform. The network installer will initially be a very small executable, which will download the required files when run. The standalone installer will download each required file at once and wonβt require an Internet connection later to install.
Step 3 β Download the base installer.
The CUDA toolkit will also install the required GPU drivers, along with the required libraries and header files to develop CUDA applications. It will also install some sample code to help starters. If you run the executable by double-clicking on it, just follow the on-screen directions and the toolkit will be installed. This is the graphical way of installation, and the downside of this method is that you do not have control on what packages to install. This can be avoided if you install the toolkit using CLI. Here is a list of possible packages that you can control β
For example, to install only the compiler and the occupancy calculator, use the following command β
<PackageName>.exe -s nvcc_9.1 occupancy_calculator_9.1
Follow these steps to verify the installation β
Step 1 β Check the CUDA toolkit version by typing nvcc -V in the command prompt.
Step 2 β Run deviceQuery.cu located at: C:\ProgramData\NVIDIA Corporation\CUDA Samples\v9.1\bin\win64\Release to view your GPU card information. The output will look like β
Step 3 β Run the bandWidth test located at C:\ProgramData\NVIDIA Corporation\CUDA Samples\v9.1\bin\win64\Release. This ensures that the host and the device are able to communicate properly with each other. The output will look like β
If any of the above tests fail, it means the toolkit has not been installed properly. Re-install by following the above instructions.
CUDA can be uninstalled without any fuss from the βControl Panelβ of Windows.
At this point, the CUDA toolkit is installed. You can get started by running the sample programs provided in the toolkit.
For doing development work using CUDA on Visual Studio, it needs to be configured. To do this, go to β File β New | Project... NVIDIA β CUDA β. Now, select a template for your CUDA Toolkit version (We are using 9.1 in this tutorial). To specify a custom CUDA Toolkit location, under CUDA C/C++, select Common, and set the CUDA Toolkit Custom Directory.
We have learnt how threads are organized in CUDA and how they are mapped to multi-dimensional data. Let us go ahead and use our knowledge to do matrix-multiplication using CUDA. But before we delve into that, we need to understand how matrices are stored in the memory. The manner in which matrices are stored affect the performance by a great deal.
2D matrices can be stored in the computer memory using two layouts β row-major and column-major. Most of the modern languages, including C (and CUDA) use the row-major layout. Here is a visual representation of the same of both the layouts β
Actual organization in memory β
Actual organization in memory β
Actual organization in memory
Note that a 2D matrix is stored as a 1D array in memory in both the layouts. Some languages like FORTRAN follow the column-major layout.
In row-major layout, element(x,y) can be addressed as: x*width + y. In the above example, the width of the matrix is 4. For example, element (1,1) will be found at position β
1*4 + 1 = 5 in the 1D array.
We will be mapping each data element to a thread. The following mapping scheme is used to map data to thread. This gives each thread its unique identity.
row=blockIdx.x*blockDim.x+threadIdx.x;
col=blockIdx.y*blockDim.y+threadIdx.y;
We know that a grid is made-up of blocks, and that the blocks are made up of threads. All threads in the same block have the same block index. Each coloured chunk in the above figure represents a block (the yellow one is block 0, the red one is block 1, the blue one is block 2 and the green one is block 3). So, for each block, we have blockDim.x=4 and blockDim.y=1. Let us find the unique identity of thread M(0,2). Since it lies in the yellow array, blockIdx.x=0 and threadIdx.x=2. So, we get: 0*4+2=2.
In the previous chapter, we noted that we often launch more threads than actually needed. To ensure that the extra threads do not do any work, we use the following βifβ condition β
if(row<width && col<width) {
then do work
}
The above condition is written in the kernel. It ensures that extra threads do not do any work.
Matrix multiplication between a (IxJ) matrix d_M and (JxK) matrix d_N produces a matrix d_P with dimensions (IxK). The formula used to calculate elements of d_P is β
d_Px,y = Ξ£ d_Mx,,k*d_Nk,y, for k=0,1,2,....width
A d_P element calculated by a thread is in βblockIdx.y*blockDim.y+threadIdx.yβ row and βblockIdx.x*blockDim.x+threadIdx.xβ column. Here is the actual kernel that implements the above logic.
__global__ void simpleMatMulKernell(float* d_M, float* d_N, float* d_P, int width)
{
This helps to calculate row and col to address what element of d_P will be calculated by this thread.
int row = blockIdx.y*width+threadIdx.y;
int col = blockIdx.x*width+threadIdx.x;
This ensures that the extra threads do not do any work.
if(row<width && col <width) {
float product_val = 0
for(int k=0;k<width;k++) {
product_val += d_M[row*width+k]*d_N[k*width+col];
}
d_p[row*width+col] = product_val;
}
Let us now understand the above kernel with an example β
Let d_M be β
The above matrix will be stored as β
And let d_N be β
The above matrix will be stored as β
Since d_P will be a 3x3 matrix, we will be launching 9 threads, each of which will compute one element of d_P.
d_P matrix
Let us compute the (2,1) element of d_P by doing a dry-run of the kernel β
row=2;
col=1;
product_val = 0 + d_M[2*3+0] * d_N[0*3+1]
product_val = 0 + d_M[6]*d_N[1] = 0+7*8=56
product_val = 56 + d_M[2*3+1]*d_N[1*3+1]
product_val = 56 + d_M[7]*d_N[4] = 84
product_val = 84+d_M[2*3+2]*d_N[2*3+1]
product_val = 84+d_M[8]*d_N[7] = 129
Now, we have β
d_P[7] = 129
In this chapter, we will learn about the CUDA threads. To proceed, we need to first know how resources are assigned to blocks.
Execution resources are assigned to threads per block. Resources are organized into Streaming Multiprocessors (SM). Multiple blocks of threads can be assigned to a single SM. The number varies with CUDA device. For example, a CUDA device may allow up to 8 thread blocks to be assigned to an SM. This is the upper limit, and it is not necessary that for any configuration of threads, a SM will run 8 blocks.
For example, if the resources of a SM are not sufficient to run 8 blocks of threads, then the number of blocks that are assigned to it is dynamically reduced by the CUDA runtime. Reduction is done on block granularity. To reduce the amount of threads assigned to a SM, the number of threads is reduced by a block.
In recent CUDA devices, a SM can accommodate up to 1536 threads. The configuration depends upon the programmer. This can be in the form of 3 blocks of 512 threads each, 6 blocks of 256 threads each or 12 blocks of 128 threads each. The upper limit is on the number of threads, and not on the number of blocks.
Thus, the number of threads that can run parallel on a CUDA device is simply the number of SM multiplied by the maximum number of threads each SM can support. In this case, the value comes out to be SM x 1536.
The CUDA API has a method, __syncthreads() to synchronize threads. When the method is encountered in the kernel, all threads in a block will be blocked at the calling location until each of them reaches the location.
What is the need for it? It ensure phase synchronization. That is, all the threads of a block will now start executing their next phase only after they have finished the previous one. There are certain nuances to this method. For example, if a __syncthreads statement, is present in the kernel, it must be executed by all threads of a block. If it is present inside an if statement, then either all the threads in the block go through the if statement, or none of them does.
If an if-then-else statement is present inside the kernel, then either all the threads will take the if path, or all the threads will take the else path. This is implied. As all the threads of a block have to execute the sync method call, if threads took different paths, then they will be blocked forever.
It is the duty of the programmer to be wary of such conditions that may arise.
After a block of threads is assigned to a SM, it is divided into sets of 32 threads, each called a warp. However, the size of a warp depends upon the implementation. The CUDA specification does not specify it.
Here are some important properties of warps β
A warp is a unit of thread scheduling in SMs. That is, the granularity of thread scheduling is a warp. A block is divided into warps for scheduling purposes.
A warp is a unit of thread scheduling in SMs. That is, the granularity of thread scheduling is a warp. A block is divided into warps for scheduling purposes.
A SM is composed of many SPs (Streaming Processors). These are the actual CUDA cores. Normally, the number of CUDA cores in a SM is less than the total number of threads that are assigned to it. Thus the need for scheduling.
A SM is composed of many SPs (Streaming Processors). These are the actual CUDA cores. Normally, the number of CUDA cores in a SM is less than the total number of threads that are assigned to it. Thus the need for scheduling.
While a warp is waiting for the results of a previously executed long-latency operation (like data fetch from the RAM), a different warp that is not waiting and is ready to be assigned is selected for execution. This means that threads are always scheduled in a group.
While a warp is waiting for the results of a previously executed long-latency operation (like data fetch from the RAM), a different warp that is not waiting and is ready to be assigned is selected for execution. This means that threads are always scheduled in a group.
If more than one warps are on the ready queue, then some priority mechanism can be used for assignment. One such method is the round-robin.
If more than one warps are on the ready queue, then some priority mechanism can be used for assignment. One such method is the round-robin.
A warp consists of threads with consecutive threadIdx.x values. For example, threads of the first warp will have threads ids b/w 0 to 31. Threads of the second warp will have thread ids from 32-63.
A warp consists of threads with consecutive threadIdx.x values. For example, threads of the first warp will have threads ids b/w 0 to 31. Threads of the second warp will have thread ids from 32-63.
All threads in a warp follow the SIMD model. SIMD stands for βSingle Instruction, Multiple Dataβ. It is different when compared to SPMD. In SIMD, each thread is executing the same instruction of a kernel at any given time. But the data is always different.
All threads in a warp follow the SIMD model. SIMD stands for βSingle Instruction, Multiple Dataβ. It is different when compared to SPMD. In SIMD, each thread is executing the same instruction of a kernel at any given time. But the data is always different.
A lot of processor time goes waste if while a warp is waiting, another warp is not scheduled. This method of utilizing in the latency time of operations with work from other warps is called latency tolerance.
In this chapter, we will understand the performance considerations of CUDA.
A poorly written CUDA program can perform much worse than intended. Consider the following piece of code β
for(int k=0; k<width; k++) {
product_val += d_M[row*width+k] * d_N[k*width+col];
}
For every iteration of the loop, the global memory is accessed twice. That is, for two floating-point calculations, we access the global memory twice. One for fetching an element of d_M and one for fetching an element of d_N. Is it efficient? We know that accessing the global memory is terribly expensive β the processor is simply wasting that time. If we can reduce the number of memory fetches per iteration, then the performance will certainly go up.
The CGMA ratio of the above program is 1:1. CGMA stands for βCompute to Global Memory Accessβ ratio, and the higher it is, the better the kernel performs. Programmers should aim to increase this ratio as much as it possible. In the above kernel, there are two floating-point operations. One is MUL and the other is ADD.
Let the DRAM bandwidth be equal to 200G/s. Each single-precision floating-point value is 4B. Thus, in one second, no more than 50G single-precision floating-point values can be delivered. Since the CGMA ratio is 1:1, we can say that the maximum floating-point operations that the kernel will execute in 1 second is 50 GFLOPS (Giga Floating-point Operations per second). The peak performance of the Nvidia Titan X is 10157 GFLOPS for single-precision after boost. Compared to that 50GFLOPS is a minuscule number, and it is obvious that the above code will not harness the full potential of the card. Consider the kernel below β
__global__ void addNumToEachElement(float* M) {
int index = blockIdx.x * blockDim.x + threadIdx.x;
M[index] = M[index] + M[0];
}
The above kernel simply adds M[0] to each element of the array M. The number of global memory accesses for each thread is 3, while the total number of computations is 1 (ADD in the second instruction). The CGMA ratio is bad: 1β3. If we can eliminate the global memory access for M[0] for each thread, then the CGMA ratio will improve to 0.5. We will attain this by caching.
If the kernel does not have to fetch the value of M[0] from the global memory for every thread, then the CGMA ratio will increase. What actually happens is that the value of M[0] is cached aggressively by CUDA in the constant memory. The bandwidth is very high, and hence, fetching it from the constant memory is not a high-latency operation. Caching is used generously wherever possible by CUDA to improve performance.
Memory is often a bottleneck to achieving high performance in CUDA programs. No matter how fast the DRAM is, it cannot supply data at the rate at which the cores can consume it. It can be understood using the following analogy. Suppose that you are thirsty on a hot summer day, and someone offers you cold water, on the condition that you have to drink it using a straw. No matter how fast you try to suck the water in, only a specific quantity can enter your mouth per unit of time. In the case of GPUs, the cores are βthirstyβ, and the straw is the actual memory bandwidth. It limits the performance here.
Apart from the device DRAM, CUDA supports several additional types of memory that can be used to increase the CGMA ratio for a kernel. We know that accessing the DRAM is slow and expensive. To overcome this problem, several low-capacity, high-bandwidth memories, both on-chip and off-chip are present on a CUDA GPU. If some data is used frequently, then CUDA caches it in one of the low-level memories. Thus, the processor does not need to access the DRAM every time. The following figure illustrates the memory architecture supported by CUDA and typically found on Nvidia cards β
R/W per-thread registers
R/W per-thread local memory
R/W per-block shared memory
R/W per-grid global memory
Read only per-grid constant memory
This helps in transferring data to/from per grid global and constant memories.
The global memory is a high-latency memory (the slowest in the figure). To increase the arithmetic intensity of our kernel, we want to reduce as many accesses to the global memory as possible. One thing to note about global memory is that there is no limitation on what threads may access it. All the threads of any block can access it. There are no restrictions, like there are in the case of shared memory or registers.
The constant memory can be written into and read by the host. It is used for storing data that will not change over the course of kernel execution. It supports short-latency, high-bandwidth, read-only access by the device when all threads simultaneously access the same location. There is a total of 64K constant memory on a CUDA capable device. The constant memory is cached. For all threads of a half warp, reading from the constant cache, as long as all threads read the same address, is no slower than reading from a register. However, if threads of the half-warp access different memory locations, the access time scales linearly with the number of different addresses read by all threads within the half-warp.
For devices with CUDA capabilities 1.x, the following are the steps that are followed when a constant memory access is done by a warp β
The request is broken into two parts, one for each half-wrap. That is, two constant memory accesses will take place for a single request.
The request is broken into two parts, one for each half-wrap. That is, two constant memory accesses will take place for a single request.
The request for each half-warp is split into as many discrete requests as there are different memory addresses in the initial request, decreasing the throughput by a factor equal to the number of separate requests. The cost increases linearly. If there is just one memory address that is accessed, then the access is as fast as it is from a register.
The request for each half-warp is split into as many discrete requests as there are different memory addresses in the initial request, decreasing the throughput by a factor equal to the number of separate requests. The cost increases linearly. If there is just one memory address that is accessed, then the access is as fast as it is from a register.
If there is a cache hit, then the resulting data is serviced at the bandwidth of the cache.
If there is a cache hit, then the resulting data is serviced at the bandwidth of the cache.
In case of a cache miss, the resulting data is serviced at the bandwidth of the DRAM.
In case of a cache miss, the resulting data is serviced at the bandwidth of the DRAM.
The __constant__ keyword can be used to store a variable in constant memory. They are always declared as global variables.
Registers and shared-memory are on-chip memories. Variables that are stored in these memories are accessed at a very high speed in a highly parallel manner. A thread is allocated a set of registers, and it cannot access registers that are not parts of that set. A kernel generally stores frequently used variables that are private to each thread in registers. The cost of accessing variables from registers is less than that required to access variables from the global memory.
SM 2.0 GPUs support up to 63 registers per thread. If this limit is exceeded, the values will be spilled from local memory, supported by the cache hierarchy. SM 3.5 GPUs expand this to up to 255 registers per thread.
All threads of a block can access its shared memory. Shared memory can be used for inter-thread communication. Each block has its own shared-memory. Just like registers, shared memory is also on-chip, but they differ significantly in functionality and the respective access cost.
While accessing data from the shared memory, the processor needs to do a memory load operation, just like accessing data from the global memory. This makes them slower than registers, in which the LOAD operation is not required. Since it resides on-chip, shared memory has shorter latency and higher bandwidth than global memory. Shared memory is also called scratchpad memory in computer architecture parlance.
Lifetime of a variable tells the portion of the programβs execution duration when it is available for use. If a variableβs lifetime is within the kernel, then it will be available for use only by the kernel code. An important point to note here is that multiple invocations of the kernel do not maintain the value of the variable across them.
Automatic variables are those variables for which a copy exists for each thread. In the matrix multiplication example, row and col are automatic variables. A private copy of row and col exists for each thread, and once the thread finishes execution, its automatic variables are destroyed.
The following table summarizes the lifetime, scope and memory of different types of CUDA variables β
Constant variables are stored in the global memory (constant memory), but are cached for efficient access. They can be accessed in a highly-parallel manner at high-speeds. As their lifetime equals the lifetime of the application, and they are visible to all the threads, declaration of constant variables must be done outside any function.
Although shared memory and registers are high-speed memories with huge bandwidth, they are available in limited amounts in a CUDA device. A programmer should be careful not to overuse these limited resources. The limited amount of these resources also caps the number of threads that can actually execute in parallel in a SM for a given application. The more resources a thread requires, the less the number of threads that can simultaneously reside in the SM. It is simply because there is a dearth of resources.
Let us suppose that each SM can accommodate upto 1536 threads and has 16,384 registers. To accommodate 1536 threads, each thread can use no more than 16,384/1536 = 10 registers. If each threads requires 12 registers, the number of threads that can simultaneously reside in the SM is reduced. Such reduction is done per block. If each block contains 128 threads, the reduction of threads will be done by reducing 128 threads at a time.
Shared memory usage can also limit the number of threads assigned to each SM. Suppose that a CUDA GPU has 16k/SM of shared memory. Suppose that each SM can support upto 8 blocks. To reach the maximum, each block must use no more than 2k of shared memory. If each block uses 5k of shared memory, then no more than 3 blocks can live in a SM.
As we already know, CUDA applications process large chunks of data from the global memory in a short span of time. Hence, more often than not, limited memory bandwidth is a bottleneck to optimal performance.
In this chapter, we will discuss memory coalescing. It is one of the most important things that are taken into account while writing CUDA applications. Coalesced memory accesses improve the performance of your applications drastically.
Data bits in DRAM cells are stored in very weak capacitors that hold charge to distinguish between 1 and 0. A charge capacitor contains 1, and it shares its charge with a sensor that determines if it was sufficiently charged to represent a 1. This process is slow, and accessing a bit like this would be very inefficient. Instead, what actually happens is that many consecutive cells transfer their charges in parallel to increase bandwidth. There are multiple sensors present that detect charges on these cell in parallel. Whenever a location is accessed in the DRAM, data at locations adjacent to it are also accessed and supplied. Now, if that data were actually needed, then it is used and bandwidth is saved. Otherwise, it goes to waste.
We already know that threads in a warp execute the same instruction at any point in time. Let the instruction be LOAD (LD). If it so happens that the threads are accessing consecutive memory locations in the DRAM, then their individual requests can be coalesced into one. This is detected by the hardware dynamically, and saves a lot of DRAM bandwidth. When all threads of a warp access consecutive memory locations, it is the most optimal access pattern. For example, if thread 0 of the warp accesses location 0 of the DRAM, thread 1 accesses location 1, and so on, their requests will be merged into one. Such access patterns enable the DRAM to supply data close to their peak bandwidth.
Let us take our example of matrix-multiplication and see how the row-major layout gives rise to coalesced access pattern, ultimately leading to improved performance. Consider the matrix given below β
Let us take the threads of a warp. Let each thread process a row. In the 0th iteration, all of them will be accessing the 0th element of each row. In the 1st iteration, the 1st element of each row, and in the 2nd iteration, the 2nd element. Now, since CUDA stores its matrices in row major layout, let us see the access pattern β
Elements accessed β M(0,0), M(1,0), M(2,0) and so on.
Elements accessed β M(0,0), M(1,0), M(2,0) and so on.
Elements accessed β M(0,1), M(1,1), M(2,1) and so on.
Elements accessed β M(0,1), M(1,1), M(2,1) and so on.
As you can see, the memory locations that are accessed in each loop are not consecutive. Hence, coalesced memory access will not be of much help here and optimal bandwidth is not achieved.
Let each thread now access the 0th element of each column. Let us see the access pattern now β
Elements accessed β M(0,0), M(0,1), M(0,2) and M(0,3) and so on.
Elements accessed β M(0,0), M(0,1), M(0,2) and M(0,3) and so on.
Elements accessed β M(1,0), M(1,1), M(1,2) and M(1,3) and so on.
Elements accessed β M(1,0), M(1,1), M(1,2) and M(1,3) and so on.
As you can see that in each iteration, consecutive memory locations are accessed, and hence, all these requests can be coalesced into a single one. This increases the kernel performance.
It may so happen that data are to be accessed in a non-favourable pattern. For example, while doing matrix multiplication, one of the matrices has to be read in a non-coalesced manner. The programmer has no choice here. So, what can instead be done is that one of the matrices can be loaded into the shared memory in a coalesced manner, and then it can be read in any pattern (row major or column major). Performance will not be affected much since the shared memory is an intrinsically high-speed memory that resides on-chip.
Here is a tiled kernel for matrix multiplication β
__global__ void MatrixMulTiled(float *Md, float *Nd, float *Pd, int width) {
__shared__ float Mds[width_tile][width_tile];
__shared__ float Nds[width_tile][width_tile];
int bx = blockIdx.x;
int by = blockIdx.y;
int tx = threadIdx.x;
int ty = threadIdx.y;
//identify what pd element to work on
int row = by * width_tile + ty;
int col = bx * width_tile + tx;
float product_val = 0;
for(int m = 0; m < width/width_tile; m++) {
//load the tiles
Mds[ty][tx] = Md[row*width + (m*width_tile + tx)];
Nds[ty][tx] = Nd[col*width + (m*width_tile + ty)];
_syncthreads();
for(int k=0; k < width_tile; k++) {
product_val += Mds[ty][k] * Nds[k][tx];
}
pd[row][col] = product_val;
}
}
Resources in SM are dynamically partitioned and assigned to threads to support their execution. As has been explained in the previous chapter, the number of resources in SM are limited, and the higher the demands of a thread, the lower the number of threads that can actually run parallel inside the SM. Execution resources of SM include registers, shared memory, thread block slots and thread slots.
In the previous chapter, It has already been discussed that the current generation of CUDA devices support upto 1536 thread slots. That is, each SM can support no more than 1536 threads that can run in parallel. It has to be remembered that there is no capping on the number of thread blocks that can occupy a SM. They can be as many as would keep the total number of threads less than or equal to 1536 per SM. For example, there may be 3 blocks of 512 threads each, or 6 blocks of 256 threads each, or 12 blocks of 128 threads each.
This ability of CUDA to dynamically partition SM resources into thread blocks makes it the real deal. Fixed partitioning methods, in which each thread block receives a fixed number of execution resources regardless of its need leads to wasting of execution resources, which is not desired, as they are already at a premium. Dynamics partition has its own nuances. For example, suppose each thread block has 128 threads. This way, each SM will have 12 blocks. But we know that the current generation of CUDA devices support no more than 8 thread block slots per SM. Thus, out of 12, only 8 blocks will be allowed. This means that out of 1536 threads, only 1024 will be allocated to the SM. Thus, to fully utilize the available resources, we need to have at least 256 threads in each block.
In the matrix-multiplication example, consider that each SM has 16384 registers and each thread requires 10 registers. If we have 16x16 thread blocks, how many registers can run on each SM? The total number of registers needed per thread block = 256x10 = 2560 registers. This means that a maximum of 6 thread blocks (that need 15360 registers) can execute in a SM.
Thus, each SM can have a maximum of 6 x 256=1536 threads run on each SM. What if the number of registers required by each thread is 12? In that case, a thread block requires 256 x 12 = 3072 registers. Thus, we can have 5 blocks at maximum. This concludes that the maximum number of threads that can be allocated to a SM are 5 x 256 =1280.
It is to be noted that by using just two registers per thread extra, the warp parallelism reduces by 1/6.This is known as performance cliff and refers to a situation in which increasing the resource usage per thread even slightly leads to a large reduction in performance. The CUDA occupancy calculator (a program from Nvidia) can calculate the occupancy of each SM.
Let us consider an example of matrix-matrix multiplication once again. Our aim is to reduce the number of accesses to global memory to increase arithmetic intensity of the kernel. Let d_N and d_M be of dimensions 4 x 4 and let each block be of dimensions 2 x 2. This implies that, each block is made up of 4 threads, and we require 4 blocks to compute all the elements of d_P.
The following table shows us the memory access pattern of block (0,0) in our previous kernel.
From the above figure, we see that both thread (0,0) and thread (1,0) access N1,0. Similarly, both thread (0,0) and thread (0,1) access element M0,0. In fact, each d_M and d_N element is accessed twice during the execution of block (0,0). Accessing the global memory twice for fetching the same data is inefficient. Is it possible to somehow make a thread collaborate with others so that they donβt access previously fetched elements? It was explained in the previous chapter that shared memory can be used for inter-thread communication.
It is an algorithm for matrix multiplication in which threads collaborate to reduce global memory traffic. Using this algorithm, multiple accesses to the global memory for fetching the same data is avoided.
Threads collaboratively load M and N elements into shared memory before using them in calculations.
Threads collaboratively load M and N elements into shared memory before using them in calculations.
d_M and d_N are divided into small tiles. Let the tile dimension be equal to the block dimension. In our example, each time has dimensions 2 x 2.
d_M and d_N are divided into small tiles. Let the tile dimension be equal to the block dimension. In our example, each time has dimensions 2 x 2.
The dot product done by each thread is divided into multiple phases. During each phase, all threads in a block collaboratively load two tiles into the shared memory. Let us call these tiles Mds and Nds.
The dot product done by each thread is divided into multiple phases. During each phase, all threads in a block collaboratively load two tiles into the shared memory. Let us call these tiles Mds and Nds.
The following figure illustrates the above mentioned points β
The following figure illustrates the above mentioned points β
In the above figure, in phase one, threads of block (0,0) (other blocks will have similar behaviour) load two tiles, Mds and Nds into the shared memory. Each tile is of size 2 x 2. After the values are loaded into the shared memory, they are used in the calculation of dot product.
In the above figure, in phase one, threads of block (0,0) (other blocks will have similar behaviour) load two tiles, Mds and Nds into the shared memory. Each tile is of size 2 x 2. After the values are loaded into the shared memory, they are used in the calculation of dot product.
The calculation of dot product is done in two phases (P1 and P2 in the above diagram). After phase 2 is over, we get the final value of each element of d_P.
The calculation of dot product is done in two phases (P1 and P2 in the above diagram). After phase 2 is over, we get the final value of each element of d_P.
The number of phases required to calculate d_P is equal to N/tile_width, where N is the width of the input matrices. Mds and Nds are reused in each phase.
The number of phases required to calculate d_P is equal to N/tile_width, where N is the width of the input matrices. Mds and Nds are reused in each phase.
It should be noted that each value in the shared memory is read twice. In this way, we reduce the number of access to global memory by half. As a rule, for a tile of size N x N, the number of access to the global memory is reduced by a factor of N.
It should be noted that each value in the shared memory is read twice. In this way, we reduce the number of access to global memory by half. As a rule, for a tile of size N x N, the number of access to the global memory is reduced by a factor of N.
__global__ void MatrixMulKernel(float* d_M, float* d_N, float* d_P, int Width) {
__shared__ float Mds[TILE_WIDTH][TILE_WIDTH];
__shared__ float Nds[TILE_WIDTH][TILE_WIDTH];
int bx = blockIdx.x;
int by = blockIdx.y;
int tx = threadIdx.x;
int ty = threadIdx.y;
int Row = by * TILE_WIDTH + ty;
int Col = bx * TILE_WIDTH + tx;
float Pvalue = 0;
for (int m = 0; m < Width/TILE_WIDTH;m++) {
Mds[ty][tx] = d_M[Row*Width + m*TILE_WIDTH + tx];
Nds[ty][tx] = d_N[(m*TILE_WIDTH + ty)*Width + Col];
__syncthreads(); //Wait till all the threads have finished loading elements into the tiles.
for (int k = 0; k < TILE_WIDTH;k++) {
Pvalue += Mds[ty][k] * Nds[k][tx];
__syncthreads();
}
d_P[Row*Width + Col] = Pvalue;
}
}
As we know already, the increase in DRAM bandwidth has not kept up with the increase in processor speed. DRAM is made up of capacitors, that need to be refreshed several times per second, and this process is slow. One of the workarounds is to use a SRAM instead of DRAM. SRAMs are static in nature, and hence, need not be refreshed. They are much faster than DRAMs, but also much more expensive than them. Modern GPUs have 2-4G of DRAM on average. Using SRAM to build memories of that size would increase the cost manifolds.
So, instead, what architecture designers did was they used small memories made up of SRAM that lay very close to the processor. These memories are called caches, and they can transmit data to the processor at a much higher rate than DRAM. But they are typically small in size. The modern GPU contains three levels of caching β L1, L2 and L3. The L1 cache has higher bandwidth compared to other L2 and L3 caches. As we go farther from the cores, the size of the memory increases and its bandwidth decreases.
Caches have been around because of the following attributes of most of the computer programs β
Temporal locality β Programs tend to use data that they have used recently.
Temporal locality β Programs tend to use data that they have used recently.
Spatial locality β Programs tend to access data residing in addresses similar to recently referenced data.
Spatial locality β Programs tend to access data residing in addresses similar to recently referenced data.
Computer programs have something called as a working set. The working set of a program can be defined as the set of data a program needs during a certain interval of time to do a certain task. If the working set can be stored in a cache, then the program wonβt have to go to the higher levels of memory to fetch data.
One important thing to note is that caches are completely transparent to the operating system. That is, the OS does not have any knowledge if the working set of the program is cached. The CPU still generates the same address. Why is it so? Why doesnβt the OS know about caches? It is simply because that would defeat the very purpose of caches; they are meant to decrease the time the CPU wastes waiting for data. Kernel calls are very expensive, and if the OS takes into account the presence of caches, the increase in the time required to generate an address would offset any benefits that caches offer.
Now, we know that the CPU still generates the same address (it addresses the RAM directly). So, to access caches, we somehow need to map the generated addresses with the cached addresses. In caches, data are stored in blocks (also called lines). A block is a unit of replacement - that is, if some new data comes to be cached, a block of data would be evicted. What block is evicted is a matter of policy (one such policy is the LRU policy). The least recently used block is evicted (takes advantage of temporal locality).
In this section, we will learn about the different types of caches β
This is a simple cache. Blocks of the RAM map the cache size to their respective address module. On a conflict, it evicts a block. The advantage is that it is really simple to implement, and is very fast. The downside is that due to a simple hash function, many conflicts may arise.
In associative caches, we have a set of associated blocks in them. Now, blocks from the RAM may map to any block in a particular set. They are of many types β 2-way, 4-way, 8-way. If the cache is an n-way associative cache, then it can eliminate conflicts; if at max n blocks in the RAM map to the same block in the cache concurrently. These types of caches are hard to implement than direct mapped caches. The access time is slower and the hardware required is expensive. Their advantage is that they can eliminate conflicts completely.
In these caches, any block of the RAM can block to any block in the cache. Conflicts are eliminated completely, and it is the most expensive to implement.
Caches have 4 kinds of misses β
Compulsory misses
Conflict misses
Capacity misses
Coherence misses (in distributed caches)
When the cache is empty initially, and data come to it for caching. There is not much that can be done about it. One thing that can be done is prefetching. That is, while you are fetching some data from the RAM into the cache, also ensure that the data you will be requiring next are present in the same block. This would prevent a cache miss the next time.
These type of misses happen when data need to be fetched again from the RAM as another block mapped to the same cache line and the data were evicted. It should be noted here that fully-associative caches have no conflict misses, whereas direct mapped caches have the most conflict misses.
These misses occur when the working set of the program is larger than the size of the cache itself. It is simply because some blocks of data are discarded as they cannot fit into the cache. The solution is that the working set of a program should be made smaller.
These happen in distributed caches where there is in-consistent data in the same distributed cache.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2126,
"s": 1892,
"text": "CUDA β Compute Unified Device Architecture. It is an extension of C programming, an API model for parallel computing created by Nvidia. Programs written using CUDA harness the power of GPU. Thus, increasing the computing performance."
},
{
"code": null,
"e": 2545,
"s": 2126,
"text": "Gordon Moore of Intel once famously stated a rule, which said that every passing year, the clock frequency of a semiconductor core doubles. This law held true until recent years. Now, as the clock frequencies of a single core reach saturation points (you will not find a single core CPU with a clock frequency of say, 5GHz, even after 2 years from now), the paradigm has shifted to multi-core and many-core processors."
},
{
"code": null,
"e": 2741,
"s": 2545,
"text": "In this chapter, we will study how parallelism is achieved in CPUs. This chapter is an essential foundation to studying GPUs (it helps in understanding the key differences between GPUs and CPUs)."
},
{
"code": null,
"e": 2820,
"s": 2741,
"text": "Following are the five essential steps required for an instruction to finish β"
},
{
"code": null,
"e": 2843,
"s": 2820,
"text": "Instruction fetch (IF)"
},
{
"code": null,
"e": 2867,
"s": 2843,
"text": "Instruction decode (ID)"
},
{
"code": null,
"e": 2892,
"s": 2867,
"text": "Instruction execute (Ex)"
},
{
"code": null,
"e": 2912,
"s": 2892,
"text": "Memory access (Mem)"
},
{
"code": null,
"e": 2937,
"s": 2912,
"text": "Register write-back (WB)"
},
{
"code": null,
"e": 2983,
"s": 2937,
"text": "This is a basic five-stage RISC architecture."
},
{
"code": null,
"e": 3134,
"s": 2983,
"text": "There are multiple ways to achieve parallelism in the CPU. First, we will discuss about ILP (Instruction Level Parallelism), also known as pipelining."
},
{
"code": null,
"e": 3880,
"s": 3134,
"text": "A CPU pipeline is a series of instructions that a CPU can handle in parallel per clock. A basic CPU with no ILP will execute the above five steps sequentially. In fact, any CPU will do that. It will first fetch the instructions, decode them, execute them, then access the RAM, and then write-back to the registers. Thus, it needs at least five CPU cycles to execute an instruction. During this process, there are parts of the chip that are sitting idle, waiting for the current instruction to finish. This is highly inefficient and this is exactly what instruction pipelining tries to address. Instead now, in one clock cycle, there are many steps of different instructions that execute in parallel. Thus the name, Instruction Level Parallelism."
},
{
"code": null,
"e": 3968,
"s": 3880,
"text": "The following figure will help you understand how Instruction Level Parallelism works β"
},
{
"code": null,
"e": 4165,
"s": 3968,
"text": "Using instruction pipelining, the instruction throughput has increased. Now, we can process many instructions in one-clock cycle. But for ILP, the resources of a chip would have been sitting idle."
},
{
"code": null,
"e": 4413,
"s": 4165,
"text": "In a pipe-lined chip, the instruction throughput increased. Initially, one instruction completed after every 5 cycles. Now, at the end of each cycle (from the 5th cycle onwards, considering each step takes 1 cycle), we get a completed instruction."
},
{
"code": null,
"e": 4666,
"s": 4413,
"text": "Note that in a non-pipelined chip, where it is assumed that the next instruction begins only when the current has finished, there is no data hazard. But since such is not the case with a pipelined chip, hazards may arise. Consider the situation below β"
},
{
"code": null,
"e": 4683,
"s": 4666,
"text": "I1 β ADD 1 to R5"
},
{
"code": null,
"e": 4702,
"s": 4683,
"text": "I2 β COPY R5 to R6"
},
{
"code": null,
"e": 4995,
"s": 4702,
"text": "Now, in a pipeline processor, I1 starts at t1, and finishes at t5. I2 starts at t2 and finishes at t6. 1 is added to R5 at t5 (at the WB stage). The second instruction reads the value of R5 at its second step (at time t3). Thus, it will not fetch the update value, and this presents a hazard."
},
{
"code": null,
"e": 5080,
"s": 4995,
"text": "Modern compilers decode high-level code to low-level code, and take care of hazards."
},
{
"code": null,
"e": 5696,
"s": 5080,
"text": "ILP is also implemented by implementing a superscalar architecture. The primary difference between a superscalar and a pipelined processor is (a superscalar processor is also pipeline) that the former uses multiple execution units (on the same chip) to achieve ILP whereas the latter divides the EU in multiple phases to do that. This means that in superscalar, several instructions can simultaneously be in the same stage of the execution cycle. This is not possible in a simple pipelined chip. Superscalar microprocessors can execute two or more instructions at the same time. They typically have at least 2 ALUs."
},
{
"code": null,
"e": 6144,
"s": 5696,
"text": "Superscalar processors can dispatch multiple instructions in the same clock cycle. This means that multiple instructions can be started in the same clock cycle. If you look at the pipelines architecture above, you can observe that at any clock cycle, only one instruction is dispatched. This is not the case with superscalars. But we have only one instruction counter (in-flight, multiple instructions are tracked). This is still just one process."
},
{
"code": null,
"e": 6310,
"s": 6144,
"text": "Take the Intel i7 for instance. The processor boasts of 4 independent cores, each implementing the full x86 ISA. Each core is hyper-threaded with two hardware cores."
},
{
"code": null,
"e": 6669,
"s": 6310,
"text": "Hyper-threading is a dope technology, proprietary to Intel, using which the operating system see a single core as two virtual cores, for increasing the number of hardware instructions in the pipeline (note that not all operating systems support HT, and Intel recommends that in such cases, HT be disabled). So, the Intel i7 has a total of 8 hardware threads."
},
{
"code": null,
"e": 7491,
"s": 6669,
"text": "HT is just a technology to utilize a processor core better. Many a times, a processor core is utilizing only a fraction of its resources to execute instructions. What HT does is that it takes a few more CPU registers, and executes more instructions on the part of the core that is sitting idle. Thus, one core now appears as two core. It is to be considered that they are not completely independent. If both the βcoresβ need to access the CPU resource, one of them ends up waiting. That is the reason why we cannot replace a dual-core CPU with a hyper-threaded, single core CPU. A dual core CPU will have truly independent, out-of-order cores, each with its own resources. Also note that HT is Intelβs implementation of SMT (Simultaneous Multithreading). SPARC has a different implementation of SMT, with identical goals."
},
{
"code": null,
"e": 7831,
"s": 7491,
"text": "The pink box represents a single CPU core. The RAM contains instructions of 4 different programs, indicated by different colors. The CPU implements the SMT, using a technology similar to hyper-threading. Hence, it is able to run instructions of two different programs (red and yellow) simultaneously. White boxes represent pipeline stalls."
},
{
"code": null,
"e": 8288,
"s": 7831,
"text": "So, there are multi-core CPUs. One thing to notice is that they are designed to fasten-up sequential programs. A CPU is very good when it comes to executing a single instruction on a single datum, but not so much when it comes to processing a large chunk of data. A CPU has a larger instruction set than a GPU, a complex ALU, a better branch prediction logic, and a more sophisticated caching/pipeline schemes. The instruction cycles are also a lot faster."
},
{
"code": null,
"e": 9015,
"s": 8288,
"text": "The other paradigm is many-core processors that are designed to operate on large chunks of data, in which CPUs prove inefficient. A GPU comprises many cores (that almost double each passing year), and each core runs at a clock speed significantly slower than a CPUβs clock. GPUs focus on execution throughput of massively-parallel programs. For example, the Nvidia GeForce GTX 280 GPU has 240 cores, each of which is a heavily multithreaded, in-order, single-instruction issue processor (SIMD β single instruction, multiple-data) that shares its control and instruction cache with seven other cores. When it comes to the total Floating Point Operations per Second (FLOPS), GPUs have been leading the race for a long time now."
},
{
"code": null,
"e": 9678,
"s": 9015,
"text": "GPUs do not have virtual memory, interrupts, or means of addressing devices such as the keyboard and the mouse. They are terribly inefficient when we do not have SPMD (Single Program, Multiple Data). Such programs are best handled by CPUs, and may be that is the reason why they are still around. For example, a CPU can calculate a hash for a string much, much faster than a GPU, but when it comes to computing several thousand hashes, the GPU wins. As of data from 2009, the ratio b/w GPUs and multi-core CPUs for peak FLOP calculations is about 10:1. Such a large performance gap forces the developers to outsource their data-intensive applications to the GPU."
},
{
"code": null,
"e": 10438,
"s": 9678,
"text": "GPUs are designed for data intensive applications. This is emphasized-upon by the fact that the bandwidths of GPU DRAM has increased tremendously by each passing year, but not so much in case of CPUs. Why GPUs adopt such a design and CPUs do not? Well, because GPUs were originally designed for 3D rendering, which requires holding large amount of texture and polygon data. Caches cannot hold such large amount of data, and thus, the only design that would have increased rendering performance was to increase the bus width and the memory clock. For example, the Intel i7, which currently supports the largest memory bandwidth, has a memory bus of width 192b and a memory clock upto 800MHz. The GTX 285 had a bus width of 512b, and a memory clock of 1242 MHz."
},
{
"code": null,
"e": 10851,
"s": 10438,
"text": "CPUs also would not benefit greatly from an increased memory bandwidth. Sequential programs typically do not have a βworking setβ of data, and most of the required data can be stored in L1, L2 or L3 cache, which are faster than any RAM. Moreover, CPU programs generally have more random memory access patterns, unlike massively-parallel programs, that would not derive much benefit from having a wide memory bus."
},
{
"code": null,
"e": 10900,
"s": 10851,
"text": "Here is the architecture of a CUDA capable GPU β"
},
{
"code": null,
"e": 11204,
"s": 10900,
"text": "There are 16 streaming multiprocessors (SMs) in the above diagram. Each SM has 8 streaming processors (SPs). That is, we get a total of 128 SPs. Now, each SP has a MAD unit (Multiply and Addition Unit) and an additional MU (Multiply Unit). The GT200 has 240 SPs, and exceeds 1 TFLOP of processing power."
},
{
"code": null,
"e": 11522,
"s": 11204,
"text": "Each SP is massively threaded, and can run thousands of threads per application. The G80 card supports 768 threads per SM (note: not per SP). Since each SM has 8 SPs, each SP supports a maximum of 96 threads. Total threads that can run: 128 * 96 = 12,228. This is why these processors are called βmassively parallelβ."
},
{
"code": null,
"e": 11710,
"s": 11522,
"text": "The G80 chips has a memory bandwidth of 86.4GB/s. It also has an 8GB/s communication channel with the CPU (4GB/s for uploading to the CPU RAM, and 4GB/s for downloading from the CPU RAM)."
},
{
"code": null,
"e": 11817,
"s": 11710,
"text": "At this point, it becomes essential that we understand the difference between different types of memories."
},
{
"code": null,
"e": 12095,
"s": 11817,
"text": "DRAM stands for Dynamic RAM. It is the most common RAM found in systems today, and is also the slowest and the least expensive one. The RAM is named so because the information stored on it is lost, and the processor has to refresh it several times in a second to preserve data."
},
{
"code": null,
"e": 12347,
"s": 12095,
"text": "SRAMstands for Static RAM. This RAM does not need to be refreshed like DRAM, and it is significantly faster than DRAM (the difference in speeds comes from the design and the static nature of these RAMs). It is also called the microprocessor cache RAM."
},
{
"code": null,
"e": 12817,
"s": 12347,
"text": "So, if SRAM is faster than DRAM, why are DRAMs even used? The primary reason for this is that for the same amount of memory, SRAMs cost several times more than DRAMs. Therefore, processors do not have huge amount of cache memories. For example, the Intel 486 line microprocessor series has 8KB of internal SRAM cache (on-chip). This cache is used by the processor to store frequently used data, so that for each request, it does not have to access the much slower DRAM."
},
{
"code": null,
"e": 13398,
"s": 12817,
"text": "VRAM stands for Video RAM. It is quite similar to DRAM but with one major difference: it can be written to and read from simultaneously. This property is essential for better video performance. Using it, the video card can read data from VRAM and send it to the screen without having to wait for the CPU to finish writing it into the global memory. This property is of not much use in the rest of the computer, and therefore, VRAM are almost always used in video cards. Also, VRAMs are more expensive than DRAM, and this is one of the reasons why they have not replaced DRAMs yet."
},
{
"code": null,
"e": 13601,
"s": 13398,
"text": "This kind of hardware was popular from the early 1980s to the late 1990s. These were fixed-function pipelines that were configurable, but not programmable. Modern GPUs are shader-based and programmable."
},
{
"code": null,
"e": 14190,
"s": 13601,
"text": "The fixed-function pipeline does exactly what the name suggests; its functionality is fixed. So, for example, if the pipeline contains a list of methods to rasterize geometry and shade pixels, that is pretty much it. You cannot add any more methods. Although these pipelines were good at rendering scenes, they enshrine certain deficiencies. In broad terms, you can perform linear transformations and then rasterize by texturing, interpolate a color across a face by combinations and permutations of those things. But what when you wanted to perform things that the pipeline could not do?"
},
{
"code": null,
"e": 14550,
"s": 14190,
"text": "In modern GPUs, all the pipelines are generic, and can run any type of GPU assembler code. In recent time, the number of functions of the pipeline are many - they do vertex mapping, and color calculation for each pixel, they also support geometry shader (tessellation), and even compute shaders (where the parallel processor is used to do a non-graphics job)."
},
{
"code": null,
"e": 14786,
"s": 14550,
"text": "Fixed function pipelines are limited in their capabilities, but are easy to design. They are not used much in todayβs graphics systems. Instead, programmable pipelines using OpenGL or DirectX are the de-facto standards for modern GPUs."
},
{
"code": null,
"e": 14866,
"s": 14786,
"text": "The following image illustrates and describes a fixed-function Nvidia pipeline."
},
{
"code": null,
"e": 14925,
"s": 14866,
"text": "Let us understand the various stages of the pipeline now β"
},
{
"code": null,
"e": 15242,
"s": 14925,
"text": "The CPU sends commands and data to the GPU host interface. Typically, the commands are given by application programs by calling an API function (from a list of many). A specialized Direct Memory Access (DMA) hardware is used by the host interface to fasten the transfer of bulk data to and fro the graphics pipeline."
},
{
"code": null,
"e": 15514,
"s": 15242,
"text": "In the GeForce pipeline, the surface of an object is drawn as a collection of triangles (the GeForce pipeline has been designed to render triangles). The finer the size of the triangle, the better the image quality (you can observe them in older games like the Tekken 3)."
},
{
"code": null,
"e": 15997,
"s": 15514,
"text": "The vertex control stage receives parameterized triangle data from the host interface (which in-turn receives it from the CPU). Then comes the VT/T&;L stage. It stands for Vertex Shading, Transform and Lighting. This stage transforms vertices and assigns each vertex values for some parameters, such as colors, texture coordinates, normals and tangents. The pixel shader hardware does the shading (the vertex shader assigns a color value to each vertex, but coloring is done later)."
},
{
"code": null,
"e": 16238,
"s": 15997,
"text": "The triangle setup stage is used to interpolate colors and other vertex parameters to those pixels that are touched by the triangle (the triangle setup stage actually determines the edge equations. It is the raster stage that interpolates)."
},
{
"code": null,
"e": 16431,
"s": 16238,
"text": "The shader stage gives the pixel its final color. There are many methods to achieve this, apart form interpolations. Some of them include texture mapping, per-pixel lighting, reflections, etc."
},
{
"code": null,
"e": 16740,
"s": 16431,
"text": "It is basically assigning a color to each vertex of a triangle on the surface (represented by polygon meshes, in our case, the polygon is a triangle), and linearly interpolating for each pixel covered by the triangle. There are many varieties to this, such as flat shading, Gouraud shading and Phong shading."
},
{
"code": null,
"e": 16872,
"s": 16740,
"text": "Let us now see shading using Gouraud shading. The triangle count is poor, and hence the poor performance of the specular highlight."
},
{
"code": null,
"e": 16924,
"s": 16872,
"text": "The same image rendered with a high triangle count."
},
{
"code": null,
"e": 17161,
"s": 16924,
"text": "In this technique, illumination for each pixel is calculated. This results in a better quality image than an image that is shaded using interpolation. Most modern video games use this technique for increased realism and level of detail."
},
{
"code": null,
"e": 17521,
"s": 17161,
"text": "The ROP stage (Raster Operation) is used to perform the final rasterization steps on pixels. For example, it blends the color of overlapping objects for transparency and anti-aliasing effects. It also determines what pixels are occluded in a scene (a pixel is occluded when it is hidden by some other pixel in the image). Occluded pixels are simply discarded."
},
{
"code": null,
"e": 17637,
"s": 17521,
"text": "Reads and writes from the display buffer memory are managed by the last stage, that is, the frame buffer interface."
},
{
"code": null,
"e": 17815,
"s": 17637,
"text": "In this chapter, we will learn about a few key concepts related to CUDA. We will understand data parallelism, the program structure of CUDA and how a CUDA C Program is executed."
},
{
"code": null,
"e": 18128,
"s": 17815,
"text": "Modern applications process large amounts of data that incur significant execution time on sequential computers. An example of such an application is rendering pixels. For example, an application that converts sRGB pixels to grayscale. To process a 1920x1080 image, the application has to process 2073600 pixels."
},
{
"code": null,
"e": 18770,
"s": 18128,
"text": "Processing all those pixels on a traditional uniprocessor CPU will take a very long time since the execution will be done sequentially. (The time taken will be proportional to the number of pixels in the image). Further, it is very inefficient since the operation that is performed on each pixel is the same, but different on the data (SPMD). Since processing one pixel is independent of the processing of any other pixel, all the pixels can be processed in parallel. If we use 2073600 threads (βworkersβ) and each thread processes one pixel, the task can be reduced to constant time. Millions of such threads can be launched on modern GPUs."
},
{
"code": null,
"e": 19077,
"s": 18770,
"text": "As has already been explained in the previous chapters, GPU is traditionally used for rendering graphics. For example, per-pixel lighting is a highly parallel, and data-intensive task and a GPU is perfect for the job. We can map each pixel with a thread and they all can be processed in O(1) constant time."
},
{
"code": null,
"e": 19433,
"s": 19077,
"text": "Image processing and computer graphics are not the only areas in which we harness data parallelism to our advantage. Many high-performance algebra libraries today such as CU-BLAS harness the processing power of the modern GPU to perform data intensive algebra operations. One such operation, matrix multiplication has been explained in the later sections."
},
{
"code": null,
"e": 19897,
"s": 19433,
"text": "A typical CUDA program has code intended both for the GPU and the CPU. By default, a traditional C program is a CUDA program with only the host code. The CPU is referred to as the host, and the GPU is referred to as the device. Whereas the host code can be compiled by a traditional C compiler as the GCC, the device code needs a special compiler to understand the api functions that are used. For Nvidia GPUs, the compiler is called the NVCC (Nvidia C Compiler)."
},
{
"code": null,
"e": 20325,
"s": 19897,
"text": "The device code runs on the GPU, and the host code runs on the CPU. The NVCC processes a CUDA program, and separates the host code from the device code. To accomplish this, special CUDA keywords are looked for. The code intended to run of the GPU (device code) is marked with special CUDA keywords for labelling data-parallel functions, called βKernelsβ. The device code is further compiled by the NVCC and executed on the GPU."
},
{
"code": null,
"e": 20744,
"s": 20325,
"text": "How does a CUDA program work? While writing a CUDA program, the programmer has explicit control on the number of threads that he wants to launch (this is a carefully decided-upon number). These threads collectively form a three-dimensional grid (threads are packed into blocks, and blocks are packed into grids). Each thread is given a unique identifier, which can be used to identify what data it is to be acted upon."
},
{
"code": null,
"e": 20992,
"s": 20744,
"text": "As has been explained in the previous chapter, a typical GPU comes with its own global memory (DRAM- Dynamic Random Access Memory). For example, the Nvidia GTX 480 has DRAM size equal to 4G. From now on, we will call this memory the device memory."
},
{
"code": null,
"e": 21194,
"s": 20992,
"text": "To execute a kernel on the GPU, the programmer needs to allocate separate memory on the GPU by writing code. The CUDA API provides specific functions for accomplishing this. Here is the flow sequence β"
},
{
"code": null,
"e": 21303,
"s": 21194,
"text": "After allocating memory on the device, data has to be transferred from the host memory to the device memory."
},
{
"code": null,
"e": 21412,
"s": 21303,
"text": "After allocating memory on the device, data has to be transferred from the host memory to the device memory."
},
{
"code": null,
"e": 21537,
"s": 21412,
"text": "After the kernel is executed on the device, the result has to be transferred back from the device memory to the host memory."
},
{
"code": null,
"e": 21662,
"s": 21537,
"text": "After the kernel is executed on the device, the result has to be transferred back from the device memory to the host memory."
},
{
"code": null,
"e": 21818,
"s": 21662,
"text": "The allocated memory on the device has to be freed-up. The host can access the device memory and transfer data to and from it, but not the other way round."
},
{
"code": null,
"e": 21974,
"s": 21818,
"text": "The allocated memory on the device has to be freed-up. The host can access the device memory and transfer data to and from it, but not the other way round."
},
{
"code": null,
"e": 22033,
"s": 21974,
"text": "CUDA provides API functions to accomplish all these steps."
},
{
"code": null,
"e": 22112,
"s": 22033,
"text": "In this chapter, we will discuss the keywords and thread organisation in CUDA."
},
{
"code": null,
"e": 22379,
"s": 22112,
"text": "The following keywords are used while declaring a CUDA function. As an example, while declaring the kernel, we have to use the __global__ keyword. This provides a hint to the compiler that this function will be executed on the device and can be called from the host."
},
{
"code": null,
"e": 22430,
"s": 22379,
"text": "In this section, we will see a sample CUDA C Code."
},
{
"code": null,
"e": 22569,
"s": 22430,
"text": "void vecAdd(float* A, float* B, float* C,int N) {\n int size=N*sizeOf(float);\n float *d_A,*d_B,*d_C;\n cudaMalloc((void**)&;d_A,size);"
},
{
"code": null,
"e": 22721,
"s": 22569,
"text": "This helps in allocating memory on the device for storing vector A. When the function returns, we get a pointer to the starting location of the memory."
},
{
"code": null,
"e": 22769,
"s": 22721,
"text": "cudaMemcpy(d_A,A,size,cudaMemcpyHostToDevice);\n"
},
{
"code": null,
"e": 23050,
"s": 22769,
"text": "Copy data from host to device. The host memory contains the contents of vector A. Now that we have allocated space on the device for storing vector A, we transfer the contents of vector A to the device. At this point, the GPU memory has vector A stored, ready to be operated upon."
},
{
"code": null,
"e": 23177,
"s": 23050,
"text": "cudaMalloc((void**)&;d_B,size);\ncudaMemcpy(d_B,B,size,cudaMemcpyHostToDevice);\n\n//Similar to A\ncudaMalloc((void**)&;d_C,size);"
},
{
"code": null,
"e": 23303,
"s": 23177,
"text": "This helps in allocating the memory on the GPU to store the result vector C. We will cover the Kernel launch statement later."
},
{
"code": null,
"e": 23351,
"s": 23303,
"text": "cudaMemcpy(C,d_C,size,cudaMemcpyDeviceToHost);\n"
},
{
"code": null,
"e": 23503,
"s": 23351,
"text": "After all the threads have finished executing, the result is stored in d_C (d stands for device). The host copies the result back to vector C from d_C."
},
{
"code": null,
"e": 23549,
"s": 23503,
"text": "cudaFree(d_A);\ncudaFree(d_B);\ncudaFree(d_C);\n"
},
{
"code": null,
"e": 23626,
"s": 23549,
"text": "This helps to free up the memory allocated on the device using cudaMalloc()."
},
{
"code": null,
"e": 23664,
"s": 23626,
"text": "This is how the above program works β"
},
{
"code": null,
"e": 23781,
"s": 23664,
"text": "The above program adds the corresponding elements of two vectors X and Y, and stores the final result in a vector Z."
},
{
"code": null,
"e": 23898,
"s": 23781,
"text": "The above program adds the corresponding elements of two vectors X and Y, and stores the final result in a vector Z."
},
{
"code": null,
"e": 23996,
"s": 23898,
"text": "The device memory is allocated for storing the input vectors (X and Y) and the result vector (Z)."
},
{
"code": null,
"e": 24094,
"s": 23996,
"text": "The device memory is allocated for storing the input vectors (X and Y) and the result vector (Z)."
},
{
"code": null,
"e": 24286,
"s": 24094,
"text": "cudaMalloc() β This method is used to allocate memory on the host. in two parameters, the address of a pointer to the allocated object, and the size of the allocated object in terms of bytes."
},
{
"code": null,
"e": 24478,
"s": 24286,
"text": "cudaMalloc() β This method is used to allocate memory on the host. in two parameters, the address of a pointer to the allocated object, and the size of the allocated object in terms of bytes."
},
{
"code": null,
"e": 24608,
"s": 24478,
"text": "cudaFree() β This method is used to release objects from device memory. It takes in the pointer to the freed object as parameter."
},
{
"code": null,
"e": 24738,
"s": 24608,
"text": "cudaFree() β This method is used to release objects from device memory. It takes in the pointer to the freed object as parameter."
},
{
"code": null,
"e": 24965,
"s": 24738,
"text": "cudaMemcpy() β This API function is used for memory data transfer. It requires four parameters as input: Pointer to the destination, pointer to the source, amount of data to be copied (in bytes), and the direction of transfer."
},
{
"code": null,
"e": 25192,
"s": 24965,
"text": "cudaMemcpy() β This API function is used for memory data transfer. It requires four parameters as input: Pointer to the destination, pointer to the source, amount of data to be copied (in bytes), and the direction of transfer."
},
{
"code": null,
"e": 25484,
"s": 25192,
"text": "Threads in a grid execute the same kernel function. They have specific coordinates to distinguish themselves from each other and identify the relevant portion of data to process. In CUDA, they are organized in a two-level hierarchy: a grid comprises blocks, and each block comprises threads."
},
{
"code": null,
"e": 25851,
"s": 25484,
"text": "For all threads in a block, the block index is the same. The block index parameter can be accessed using the blockIdx variable inside a kernel. Each thread also has an associated index, and it can be accessed by using threadIdx variable inside the kernel. Note that blockIdx and threadIdx are built-in CUDA variables that are only accessible from inside the kernel."
},
{
"code": null,
"e": 26134,
"s": 25851,
"text": "In a similar fashion, CUDA also has gridDim and blockDim variables that are also built-in. They return the dimensions of the grid and block along a particular axis respectively. As an example, blockDim. x can be used to find how many threads a particular block has along the x axis."
},
{
"code": null,
"e": 26880,
"s": 26134,
"text": "Let us consider an example to understand the concept explained above. Consider an image, which is 76 pixels along the x axis, and 62 pixels along the y axis. Our aim is to convert the image from sRGB to grayscale. We can calculate the total number of pixels by multiplying the number of pixels along the x axis with the total number along the y axis that comes out to be 4712 pixels. Since we are mapping each thread with each pixel, we need a minimum of 4712 pixels. Let us take number of threads in each direction to be a multiple of 4. So, along the x axis, we will need at least 80 threads, and along the y axis, we will need at least 64 threads to process the complete image. We will ensure that the extra threads are not assigned any work."
},
{
"code": null,
"e": 27198,
"s": 26880,
"text": "Thus, we are launching 5120 threads to process a 4712 pixels image. You may ask, why the extra threads? The answer to this question is that keeping the dimensions as multiple of 4 has many benefits that largely offsets any disadvantages that result from launching extra threads. This is explained in a later section)."
},
{
"code": null,
"e": 27891,
"s": 27198,
"text": "Now, we have to divide these 5120 threads into grids and blocks. Let each block have 256 threads. If so, then one possibility that of the dimensions each block are: (16,16,1). This means, there are 16 threads in the x direction, 16 in the y direction, and 1 in the z direction. We will be needing 5 blocks in the x direction (since there are 80 threads in total along the x axis), and 4 blocks in y direction (64 threads along the y axis in total), and 1 block in z direction. So, in total, we need 20 blocks. In a nutshell, the grid dimensions are (5,4,1) and the block dimensions are (16,16,1). The programmer needs to specify these values in the program. This is shown in the figure above."
},
{
"code": null,
"e": 27945,
"s": 27891,
"text": "dim3 dimBlock(5,4,1) β To specify the grid dimensions"
},
{
"code": null,
"e": 27999,
"s": 27945,
"text": "dim3 dimBlock(5,4,1) β To specify the grid dimensions"
},
{
"code": null,
"e": 28076,
"s": 27999,
"text": "dim3 dimGrid(ceil(n/16.0),ceil(m/16.0),1) β To specify the block dimensions."
},
{
"code": null,
"e": 28153,
"s": 28076,
"text": "dim3 dimGrid(ceil(n/16.0),ceil(m/16.0),1) β To specify the block dimensions."
},
{
"code": null,
"e": 28243,
"s": 28153,
"text": "kernelName<<<dimGrid,dimBlock>>>(parameter1, parameter2, ...) β Launch the actual kernel."
},
{
"code": null,
"e": 28333,
"s": 28243,
"text": "kernelName<<<dimGrid,dimBlock>>>(parameter1, parameter2, ...) β Launch the actual kernel."
},
{
"code": null,
"e": 28876,
"s": 28333,
"text": "n is the number of pixels in the x direction, and m is the number of pixels in the y direction. βceilβ is the regular ceiling function. We use it because we never want to end up with less number of blocks than required. dim3 is a data structure, just like an int or a float. dimBlock and dimGrid are variables names. The third statement is the kernel launch statement. βkernelNameβ is the name of the kernel function, to which we pass the parameters: parameter1, parameter2, and so on. <<<>>> contain the dimensions of the grid and the block."
},
{
"code": null,
"e": 28928,
"s": 28876,
"text": "In this chapter, we will learn how to install CUDA."
},
{
"code": null,
"e": 28986,
"s": 28928,
"text": "For installing the CUDA toolkit on Windows, youβll need β"
},
{
"code": null,
"e": 29013,
"s": 28986,
"text": "A CUDA enabled Nvidia GPU."
},
{
"code": null,
"e": 29055,
"s": 29013,
"text": "A supported version of Microsoft Windows."
},
{
"code": null,
"e": 29093,
"s": 29055,
"text": "A supported version of Visual Studio."
},
{
"code": null,
"e": 29118,
"s": 29093,
"text": "The latest CUDA toolkit."
},
{
"code": null,
"e": 29463,
"s": 29118,
"text": "Note that natively, CUDA allows only 64b applications. That is, you cannot develop 32b CUDA applications natively (exception: they can be developed only on the GeForce series GPUs). 32b applications can be developed on x86_64 using the cross-development capabilities of the CUDA toolkit. For compiling CUDA programs to 32b, follow these steps β"
},
{
"code": null,
"e": 29508,
"s": 29463,
"text": "Step 1 β Add <installpath>\\bin to your path."
},
{
"code": null,
"e": 29548,
"s": 29508,
"text": "Step 2 β Add -m32 to your nvcc options."
},
{
"code": null,
"e": 29638,
"s": 29548,
"text": "Step 3 β Link with the 32-bit libs in <installpath>\\lib (instead of <installpath>\\lib64)."
},
{
"code": null,
"e": 29690,
"s": 29638,
"text": "You can download the latest CUDA toolkit from here."
},
{
"code": null,
"e": 29958,
"s": 29690,
"text": "As can be seen from the above tables, support for x86_32 is limited. Presently, only the GeForce series is supported for 32b CUDA applications. If you have a supported version of Windows and Visual Studio, then proceed. Otherwise, first install the required software."
},
{
"code": null,
"e": 30187,
"s": 29958,
"text": "Verifying if your system has a CUDA capable GPU β Open a RUN window and run the command β control /name Microsoft.DeviceManager, and verify from the given information. If you do not have a CUDA capable GPU, or a GPU, then halt."
},
{
"code": null,
"e": 30256,
"s": 30187,
"text": "In this section, we will see how to install the latest CUDA toolkit."
},
{
"code": null,
"e": 30343,
"s": 30256,
"text": "Step 1 β Visit β https://developer.nvidia.com and select the desired operating system."
},
{
"code": null,
"e": 30655,
"s": 30343,
"text": "Step 2 β Select the type of installation that you would like to perform. The network installer will initially be a very small executable, which will download the required files when run. The standalone installer will download each required file at once and wonβt require an Internet connection later to install."
},
{
"code": null,
"e": 30693,
"s": 30655,
"text": "Step 3 β Download the base installer."
},
{
"code": null,
"e": 31268,
"s": 30693,
"text": "The CUDA toolkit will also install the required GPU drivers, along with the required libraries and header files to develop CUDA applications. It will also install some sample code to help starters. If you run the executable by double-clicking on it, just follow the on-screen directions and the toolkit will be installed. This is the graphical way of installation, and the downside of this method is that you do not have control on what packages to install. This can be avoided if you install the toolkit using CLI. Here is a list of possible packages that you can control β"
},
{
"code": null,
"e": 31368,
"s": 31268,
"text": "For example, to install only the compiler and the occupancy calculator, use the following command β"
},
{
"code": null,
"e": 31424,
"s": 31368,
"text": "<PackageName>.exe -s nvcc_9.1 occupancy_calculator_9.1\n"
},
{
"code": null,
"e": 31472,
"s": 31424,
"text": "Follow these steps to verify the installation β"
},
{
"code": null,
"e": 31553,
"s": 31472,
"text": "Step 1 β Check the CUDA toolkit version by typing nvcc -V in the command prompt."
},
{
"code": null,
"e": 31726,
"s": 31553,
"text": "Step 2 β Run deviceQuery.cu located at: C:\\ProgramData\\NVIDIA Corporation\\CUDA Samples\\v9.1\\bin\\win64\\Release to view your GPU card information. The output will look like β"
},
{
"code": null,
"e": 31960,
"s": 31726,
"text": "Step 3 β Run the bandWidth test located at C:\\ProgramData\\NVIDIA Corporation\\CUDA Samples\\v9.1\\bin\\win64\\Release. This ensures that the host and the device are able to communicate properly with each other. The output will look like β"
},
{
"code": null,
"e": 32094,
"s": 31960,
"text": "If any of the above tests fail, it means the toolkit has not been installed properly. Re-install by following the above instructions."
},
{
"code": null,
"e": 32172,
"s": 32094,
"text": "CUDA can be uninstalled without any fuss from the βControl Panelβ of Windows."
},
{
"code": null,
"e": 32294,
"s": 32172,
"text": "At this point, the CUDA toolkit is installed. You can get started by running the sample programs provided in the toolkit."
},
{
"code": null,
"e": 32647,
"s": 32294,
"text": "For doing development work using CUDA on Visual Studio, it needs to be configured. To do this, go to β File β New | Project... NVIDIA β CUDA β. Now, select a template for your CUDA Toolkit version (We are using 9.1 in this tutorial). To specify a custom CUDA Toolkit location, under CUDA C/C++, select Common, and set the CUDA Toolkit Custom Directory."
},
{
"code": null,
"e": 32997,
"s": 32647,
"text": "We have learnt how threads are organized in CUDA and how they are mapped to multi-dimensional data. Let us go ahead and use our knowledge to do matrix-multiplication using CUDA. But before we delve into that, we need to understand how matrices are stored in the memory. The manner in which matrices are stored affect the performance by a great deal."
},
{
"code": null,
"e": 33239,
"s": 32997,
"text": "2D matrices can be stored in the computer memory using two layouts β row-major and column-major. Most of the modern languages, including C (and CUDA) use the row-major layout. Here is a visual representation of the same of both the layouts β"
},
{
"code": null,
"e": 33271,
"s": 33239,
"text": "Actual organization in memory β"
},
{
"code": null,
"e": 33303,
"s": 33271,
"text": "Actual organization in memory β"
},
{
"code": null,
"e": 33333,
"s": 33303,
"text": "Actual organization in memory"
},
{
"code": null,
"e": 33470,
"s": 33333,
"text": "Note that a 2D matrix is stored as a 1D array in memory in both the layouts. Some languages like FORTRAN follow the column-major layout."
},
{
"code": null,
"e": 33645,
"s": 33470,
"text": "In row-major layout, element(x,y) can be addressed as: x*width + y. In the above example, the width of the matrix is 4. For example, element (1,1) will be found at position β"
},
{
"code": null,
"e": 33674,
"s": 33645,
"text": "1*4 + 1 = 5 in the 1D array."
},
{
"code": null,
"e": 33828,
"s": 33674,
"text": "We will be mapping each data element to a thread. The following mapping scheme is used to map data to thread. This gives each thread its unique identity."
},
{
"code": null,
"e": 33906,
"s": 33828,
"text": "row=blockIdx.x*blockDim.x+threadIdx.x;\ncol=blockIdx.y*blockDim.y+threadIdx.y;"
},
{
"code": null,
"e": 34412,
"s": 33906,
"text": "We know that a grid is made-up of blocks, and that the blocks are made up of threads. All threads in the same block have the same block index. Each coloured chunk in the above figure represents a block (the yellow one is block 0, the red one is block 1, the blue one is block 2 and the green one is block 3). So, for each block, we have blockDim.x=4 and blockDim.y=1. Let us find the unique identity of thread M(0,2). Since it lies in the yellow array, blockIdx.x=0 and threadIdx.x=2. So, we get: 0*4+2=2."
},
{
"code": null,
"e": 34593,
"s": 34412,
"text": "In the previous chapter, we noted that we often launch more threads than actually needed. To ensure that the extra threads do not do any work, we use the following βifβ condition β"
},
{
"code": null,
"e": 34640,
"s": 34593,
"text": "if(row<width && col<width) {\n then do work\n}"
},
{
"code": null,
"e": 34736,
"s": 34640,
"text": "The above condition is written in the kernel. It ensures that extra threads do not do any work."
},
{
"code": null,
"e": 34902,
"s": 34736,
"text": "Matrix multiplication between a (IxJ) matrix d_M and (JxK) matrix d_N produces a matrix d_P with dimensions (IxK). The formula used to calculate elements of d_P is β"
},
{
"code": null,
"e": 34952,
"s": 34902,
"text": "d_Px,y = Ξ£ d_Mx,,k*d_Nk,y, for k=0,1,2,....width\n"
},
{
"code": null,
"e": 35142,
"s": 34952,
"text": "A d_P element calculated by a thread is in βblockIdx.y*blockDim.y+threadIdx.yβ row and βblockIdx.x*blockDim.x+threadIdx.xβ column. Here is the actual kernel that implements the above logic."
},
{
"code": null,
"e": 35227,
"s": 35142,
"text": "__global__ void simpleMatMulKernell(float* d_M, float* d_N, float* d_P, int width)\n{"
},
{
"code": null,
"e": 35329,
"s": 35227,
"text": "This helps to calculate row and col to address what element of d_P will be calculated by this thread."
},
{
"code": null,
"e": 35409,
"s": 35329,
"text": "int row = blockIdx.y*width+threadIdx.y;\nint col = blockIdx.x*width+threadIdx.x;"
},
{
"code": null,
"e": 35465,
"s": 35409,
"text": "This ensures that the extra threads do not do any work."
},
{
"code": null,
"e": 35650,
"s": 35465,
"text": "if(row<width && col <width) {\n float product_val = 0\n for(int k=0;k<width;k++) {\n product_val += d_M[row*width+k]*d_N[k*width+col];\n }\n d_p[row*width+col] = product_val;\n}"
},
{
"code": null,
"e": 35707,
"s": 35650,
"text": "Let us now understand the above kernel with an example β"
},
{
"code": null,
"e": 35720,
"s": 35707,
"text": "Let d_M be β"
},
{
"code": null,
"e": 35757,
"s": 35720,
"text": "The above matrix will be stored as β"
},
{
"code": null,
"e": 35774,
"s": 35757,
"text": "And let d_N be β"
},
{
"code": null,
"e": 35811,
"s": 35774,
"text": "The above matrix will be stored as β"
},
{
"code": null,
"e": 35922,
"s": 35811,
"text": "Since d_P will be a 3x3 matrix, we will be launching 9 threads, each of which will compute one element of d_P."
},
{
"code": null,
"e": 35933,
"s": 35922,
"text": "d_P matrix"
},
{
"code": null,
"e": 36008,
"s": 35933,
"text": "Let us compute the (2,1) element of d_P by doing a dry-run of the kernel β"
},
{
"code": null,
"e": 36023,
"s": 36008,
"text": "row=2;\ncol=1;\n"
},
{
"code": null,
"e": 36108,
"s": 36023,
"text": "product_val = 0 + d_M[2*3+0] * d_N[0*3+1]\nproduct_val = 0 + d_M[6]*d_N[1] = 0+7*8=56"
},
{
"code": null,
"e": 36187,
"s": 36108,
"text": "product_val = 56 + d_M[2*3+1]*d_N[1*3+1]\nproduct_val = 56 + d_M[7]*d_N[4] = 84"
},
{
"code": null,
"e": 36263,
"s": 36187,
"text": "product_val = 84+d_M[2*3+2]*d_N[2*3+1]\nproduct_val = 84+d_M[8]*d_N[7] = 129"
},
{
"code": null,
"e": 36278,
"s": 36263,
"text": "Now, we have β"
},
{
"code": null,
"e": 36292,
"s": 36278,
"text": "d_P[7] = 129\n"
},
{
"code": null,
"e": 36419,
"s": 36292,
"text": "In this chapter, we will learn about the CUDA threads. To proceed, we need to first know how resources are assigned to blocks."
},
{
"code": null,
"e": 36826,
"s": 36419,
"text": "Execution resources are assigned to threads per block. Resources are organized into Streaming Multiprocessors (SM). Multiple blocks of threads can be assigned to a single SM. The number varies with CUDA device. For example, a CUDA device may allow up to 8 thread blocks to be assigned to an SM. This is the upper limit, and it is not necessary that for any configuration of threads, a SM will run 8 blocks."
},
{
"code": null,
"e": 37140,
"s": 36826,
"text": "For example, if the resources of a SM are not sufficient to run 8 blocks of threads, then the number of blocks that are assigned to it is dynamically reduced by the CUDA runtime. Reduction is done on block granularity. To reduce the amount of threads assigned to a SM, the number of threads is reduced by a block."
},
{
"code": null,
"e": 37450,
"s": 37140,
"text": "In recent CUDA devices, a SM can accommodate up to 1536 threads. The configuration depends upon the programmer. This can be in the form of 3 blocks of 512 threads each, 6 blocks of 256 threads each or 12 blocks of 128 threads each. The upper limit is on the number of threads, and not on the number of blocks."
},
{
"code": null,
"e": 37660,
"s": 37450,
"text": "Thus, the number of threads that can run parallel on a CUDA device is simply the number of SM multiplied by the maximum number of threads each SM can support. In this case, the value comes out to be SM x 1536."
},
{
"code": null,
"e": 37877,
"s": 37660,
"text": "The CUDA API has a method, __syncthreads() to synchronize threads. When the method is encountered in the kernel, all threads in a block will be blocked at the calling location until each of them reaches the location."
},
{
"code": null,
"e": 38352,
"s": 37877,
"text": "What is the need for it? It ensure phase synchronization. That is, all the threads of a block will now start executing their next phase only after they have finished the previous one. There are certain nuances to this method. For example, if a __syncthreads statement, is present in the kernel, it must be executed by all threads of a block. If it is present inside an if statement, then either all the threads in the block go through the if statement, or none of them does."
},
{
"code": null,
"e": 38659,
"s": 38352,
"text": "If an if-then-else statement is present inside the kernel, then either all the threads will take the if path, or all the threads will take the else path. This is implied. As all the threads of a block have to execute the sync method call, if threads took different paths, then they will be blocked forever."
},
{
"code": null,
"e": 38738,
"s": 38659,
"text": "It is the duty of the programmer to be wary of such conditions that may arise."
},
{
"code": null,
"e": 38948,
"s": 38738,
"text": "After a block of threads is assigned to a SM, it is divided into sets of 32 threads, each called a warp. However, the size of a warp depends upon the implementation. The CUDA specification does not specify it."
},
{
"code": null,
"e": 38994,
"s": 38948,
"text": "Here are some important properties of warps β"
},
{
"code": null,
"e": 39152,
"s": 38994,
"text": "A warp is a unit of thread scheduling in SMs. That is, the granularity of thread scheduling is a warp. A block is divided into warps for scheduling purposes."
},
{
"code": null,
"e": 39310,
"s": 39152,
"text": "A warp is a unit of thread scheduling in SMs. That is, the granularity of thread scheduling is a warp. A block is divided into warps for scheduling purposes."
},
{
"code": null,
"e": 39535,
"s": 39310,
"text": "A SM is composed of many SPs (Streaming Processors). These are the actual CUDA cores. Normally, the number of CUDA cores in a SM is less than the total number of threads that are assigned to it. Thus the need for scheduling."
},
{
"code": null,
"e": 39760,
"s": 39535,
"text": "A SM is composed of many SPs (Streaming Processors). These are the actual CUDA cores. Normally, the number of CUDA cores in a SM is less than the total number of threads that are assigned to it. Thus the need for scheduling."
},
{
"code": null,
"e": 40029,
"s": 39760,
"text": "While a warp is waiting for the results of a previously executed long-latency operation (like data fetch from the RAM), a different warp that is not waiting and is ready to be assigned is selected for execution. This means that threads are always scheduled in a group."
},
{
"code": null,
"e": 40298,
"s": 40029,
"text": "While a warp is waiting for the results of a previously executed long-latency operation (like data fetch from the RAM), a different warp that is not waiting and is ready to be assigned is selected for execution. This means that threads are always scheduled in a group."
},
{
"code": null,
"e": 40438,
"s": 40298,
"text": "If more than one warps are on the ready queue, then some priority mechanism can be used for assignment. One such method is the round-robin."
},
{
"code": null,
"e": 40578,
"s": 40438,
"text": "If more than one warps are on the ready queue, then some priority mechanism can be used for assignment. One such method is the round-robin."
},
{
"code": null,
"e": 40776,
"s": 40578,
"text": "A warp consists of threads with consecutive threadIdx.x values. For example, threads of the first warp will have threads ids b/w 0 to 31. Threads of the second warp will have thread ids from 32-63."
},
{
"code": null,
"e": 40974,
"s": 40776,
"text": "A warp consists of threads with consecutive threadIdx.x values. For example, threads of the first warp will have threads ids b/w 0 to 31. Threads of the second warp will have thread ids from 32-63."
},
{
"code": null,
"e": 41231,
"s": 40974,
"text": "All threads in a warp follow the SIMD model. SIMD stands for βSingle Instruction, Multiple Dataβ. It is different when compared to SPMD. In SIMD, each thread is executing the same instruction of a kernel at any given time. But the data is always different."
},
{
"code": null,
"e": 41488,
"s": 41231,
"text": "All threads in a warp follow the SIMD model. SIMD stands for βSingle Instruction, Multiple Dataβ. It is different when compared to SPMD. In SIMD, each thread is executing the same instruction of a kernel at any given time. But the data is always different."
},
{
"code": null,
"e": 41697,
"s": 41488,
"text": "A lot of processor time goes waste if while a warp is waiting, another warp is not scheduled. This method of utilizing in the latency time of operations with work from other warps is called latency tolerance."
},
{
"code": null,
"e": 41773,
"s": 41697,
"text": "In this chapter, we will understand the performance considerations of CUDA."
},
{
"code": null,
"e": 41880,
"s": 41773,
"text": "A poorly written CUDA program can perform much worse than intended. Consider the following piece of code β"
},
{
"code": null,
"e": 41966,
"s": 41880,
"text": "for(int k=0; k<width; k++) {\n product_val += d_M[row*width+k] * d_N[k*width+col];\n}"
},
{
"code": null,
"e": 42421,
"s": 41966,
"text": "For every iteration of the loop, the global memory is accessed twice. That is, for two floating-point calculations, we access the global memory twice. One for fetching an element of d_M and one for fetching an element of d_N. Is it efficient? We know that accessing the global memory is terribly expensive β the processor is simply wasting that time. If we can reduce the number of memory fetches per iteration, then the performance will certainly go up."
},
{
"code": null,
"e": 42741,
"s": 42421,
"text": "The CGMA ratio of the above program is 1:1. CGMA stands for βCompute to Global Memory Accessβ ratio, and the higher it is, the better the kernel performs. Programmers should aim to increase this ratio as much as it possible. In the above kernel, there are two floating-point operations. One is MUL and the other is ADD."
},
{
"code": null,
"e": 43368,
"s": 42741,
"text": "Let the DRAM bandwidth be equal to 200G/s. Each single-precision floating-point value is 4B. Thus, in one second, no more than 50G single-precision floating-point values can be delivered. Since the CGMA ratio is 1:1, we can say that the maximum floating-point operations that the kernel will execute in 1 second is 50 GFLOPS (Giga Floating-point Operations per second). The peak performance of the Nvidia Titan X is 10157 GFLOPS for single-precision after boost. Compared to that 50GFLOPS is a minuscule number, and it is obvious that the above code will not harness the full potential of the card. Consider the kernel below β"
},
{
"code": null,
"e": 43503,
"s": 43368,
"text": "__global__ void addNumToEachElement(float* M) {\n int index = blockIdx.x * blockDim.x + threadIdx.x;\n M[index] = M[index] + M[0];\n}"
},
{
"code": null,
"e": 43877,
"s": 43503,
"text": "The above kernel simply adds M[0] to each element of the array M. The number of global memory accesses for each thread is 3, while the total number of computations is 1 (ADD in the second instruction). The CGMA ratio is bad: 1β3. If we can eliminate the global memory access for M[0] for each thread, then the CGMA ratio will improve to 0.5. We will attain this by caching."
},
{
"code": null,
"e": 44297,
"s": 43877,
"text": "If the kernel does not have to fetch the value of M[0] from the global memory for every thread, then the CGMA ratio will increase. What actually happens is that the value of M[0] is cached aggressively by CUDA in the constant memory. The bandwidth is very high, and hence, fetching it from the constant memory is not a high-latency operation. Caching is used generously wherever possible by CUDA to improve performance."
},
{
"code": null,
"e": 44905,
"s": 44297,
"text": "Memory is often a bottleneck to achieving high performance in CUDA programs. No matter how fast the DRAM is, it cannot supply data at the rate at which the cores can consume it. It can be understood using the following analogy. Suppose that you are thirsty on a hot summer day, and someone offers you cold water, on the condition that you have to drink it using a straw. No matter how fast you try to suck the water in, only a specific quantity can enter your mouth per unit of time. In the case of GPUs, the cores are βthirstyβ, and the straw is the actual memory bandwidth. It limits the performance here."
},
{
"code": null,
"e": 45486,
"s": 44905,
"text": "Apart from the device DRAM, CUDA supports several additional types of memory that can be used to increase the CGMA ratio for a kernel. We know that accessing the DRAM is slow and expensive. To overcome this problem, several low-capacity, high-bandwidth memories, both on-chip and off-chip are present on a CUDA GPU. If some data is used frequently, then CUDA caches it in one of the low-level memories. Thus, the processor does not need to access the DRAM every time. The following figure illustrates the memory architecture supported by CUDA and typically found on Nvidia cards β"
},
{
"code": null,
"e": 45511,
"s": 45486,
"text": "R/W per-thread registers"
},
{
"code": null,
"e": 45539,
"s": 45511,
"text": "R/W per-thread local memory"
},
{
"code": null,
"e": 45567,
"s": 45539,
"text": "R/W per-block shared memory"
},
{
"code": null,
"e": 45594,
"s": 45567,
"text": "R/W per-grid global memory"
},
{
"code": null,
"e": 45629,
"s": 45594,
"text": "Read only per-grid constant memory"
},
{
"code": null,
"e": 45708,
"s": 45629,
"text": "This helps in transferring data to/from per grid global and constant memories."
},
{
"code": null,
"e": 46130,
"s": 45708,
"text": "The global memory is a high-latency memory (the slowest in the figure). To increase the arithmetic intensity of our kernel, we want to reduce as many accesses to the global memory as possible. One thing to note about global memory is that there is no limitation on what threads may access it. All the threads of any block can access it. There are no restrictions, like there are in the case of shared memory or registers."
},
{
"code": null,
"e": 46846,
"s": 46130,
"text": "The constant memory can be written into and read by the host. It is used for storing data that will not change over the course of kernel execution. It supports short-latency, high-bandwidth, read-only access by the device when all threads simultaneously access the same location. There is a total of 64K constant memory on a CUDA capable device. The constant memory is cached. For all threads of a half warp, reading from the constant cache, as long as all threads read the same address, is no slower than reading from a register. However, if threads of the half-warp access different memory locations, the access time scales linearly with the number of different addresses read by all threads within the half-warp."
},
{
"code": null,
"e": 46982,
"s": 46846,
"text": "For devices with CUDA capabilities 1.x, the following are the steps that are followed when a constant memory access is done by a warp β"
},
{
"code": null,
"e": 47120,
"s": 46982,
"text": "The request is broken into two parts, one for each half-wrap. That is, two constant memory accesses will take place for a single request."
},
{
"code": null,
"e": 47258,
"s": 47120,
"text": "The request is broken into two parts, one for each half-wrap. That is, two constant memory accesses will take place for a single request."
},
{
"code": null,
"e": 47609,
"s": 47258,
"text": "The request for each half-warp is split into as many discrete requests as there are different memory addresses in the initial request, decreasing the throughput by a factor equal to the number of separate requests. The cost increases linearly. If there is just one memory address that is accessed, then the access is as fast as it is from a register."
},
{
"code": null,
"e": 47960,
"s": 47609,
"text": "The request for each half-warp is split into as many discrete requests as there are different memory addresses in the initial request, decreasing the throughput by a factor equal to the number of separate requests. The cost increases linearly. If there is just one memory address that is accessed, then the access is as fast as it is from a register."
},
{
"code": null,
"e": 48052,
"s": 47960,
"text": "If there is a cache hit, then the resulting data is serviced at the bandwidth of the cache."
},
{
"code": null,
"e": 48144,
"s": 48052,
"text": "If there is a cache hit, then the resulting data is serviced at the bandwidth of the cache."
},
{
"code": null,
"e": 48230,
"s": 48144,
"text": "In case of a cache miss, the resulting data is serviced at the bandwidth of the DRAM."
},
{
"code": null,
"e": 48316,
"s": 48230,
"text": "In case of a cache miss, the resulting data is serviced at the bandwidth of the DRAM."
},
{
"code": null,
"e": 48439,
"s": 48316,
"text": "The __constant__ keyword can be used to store a variable in constant memory. They are always declared as global variables."
},
{
"code": null,
"e": 48917,
"s": 48439,
"text": "Registers and shared-memory are on-chip memories. Variables that are stored in these memories are accessed at a very high speed in a highly parallel manner. A thread is allocated a set of registers, and it cannot access registers that are not parts of that set. A kernel generally stores frequently used variables that are private to each thread in registers. The cost of accessing variables from registers is less than that required to access variables from the global memory."
},
{
"code": null,
"e": 49134,
"s": 48917,
"text": "SM 2.0 GPUs support up to 63 registers per thread. If this limit is exceeded, the values will be spilled from local memory, supported by the cache hierarchy. SM 3.5 GPUs expand this to up to 255 registers per thread."
},
{
"code": null,
"e": 49414,
"s": 49134,
"text": "All threads of a block can access its shared memory. Shared memory can be used for inter-thread communication. Each block has its own shared-memory. Just like registers, shared memory is also on-chip, but they differ significantly in functionality and the respective access cost."
},
{
"code": null,
"e": 49826,
"s": 49414,
"text": "While accessing data from the shared memory, the processor needs to do a memory load operation, just like accessing data from the global memory. This makes them slower than registers, in which the LOAD operation is not required. Since it resides on-chip, shared memory has shorter latency and higher bandwidth than global memory. Shared memory is also called scratchpad memory in computer architecture parlance."
},
{
"code": null,
"e": 50169,
"s": 49826,
"text": "Lifetime of a variable tells the portion of the programβs execution duration when it is available for use. If a variableβs lifetime is within the kernel, then it will be available for use only by the kernel code. An important point to note here is that multiple invocations of the kernel do not maintain the value of the variable across them."
},
{
"code": null,
"e": 50458,
"s": 50169,
"text": "Automatic variables are those variables for which a copy exists for each thread. In the matrix multiplication example, row and col are automatic variables. A private copy of row and col exists for each thread, and once the thread finishes execution, its automatic variables are destroyed."
},
{
"code": null,
"e": 50559,
"s": 50458,
"text": "The following table summarizes the lifetime, scope and memory of different types of CUDA variables β"
},
{
"code": null,
"e": 50899,
"s": 50559,
"text": "Constant variables are stored in the global memory (constant memory), but are cached for efficient access. They can be accessed in a highly-parallel manner at high-speeds. As their lifetime equals the lifetime of the application, and they are visible to all the threads, declaration of constant variables must be done outside any function."
},
{
"code": null,
"e": 51413,
"s": 50899,
"text": "Although shared memory and registers are high-speed memories with huge bandwidth, they are available in limited amounts in a CUDA device. A programmer should be careful not to overuse these limited resources. The limited amount of these resources also caps the number of threads that can actually execute in parallel in a SM for a given application. The more resources a thread requires, the less the number of threads that can simultaneously reside in the SM. It is simply because there is a dearth of resources."
},
{
"code": null,
"e": 51848,
"s": 51413,
"text": "Let us suppose that each SM can accommodate upto 1536 threads and has 16,384 registers. To accommodate 1536 threads, each thread can use no more than 16,384/1536 = 10 registers. If each threads requires 12 registers, the number of threads that can simultaneously reside in the SM is reduced. Such reduction is done per block. If each block contains 128 threads, the reduction of threads will be done by reducing 128 threads at a time."
},
{
"code": null,
"e": 52188,
"s": 51848,
"text": "Shared memory usage can also limit the number of threads assigned to each SM. Suppose that a CUDA GPU has 16k/SM of shared memory. Suppose that each SM can support upto 8 blocks. To reach the maximum, each block must use no more than 2k of shared memory. If each block uses 5k of shared memory, then no more than 3 blocks can live in a SM."
},
{
"code": null,
"e": 52396,
"s": 52188,
"text": "As we already know, CUDA applications process large chunks of data from the global memory in a short span of time. Hence, more often than not, limited memory bandwidth is a bottleneck to optimal performance."
},
{
"code": null,
"e": 52632,
"s": 52396,
"text": "In this chapter, we will discuss memory coalescing. It is one of the most important things that are taken into account while writing CUDA applications. Coalesced memory accesses improve the performance of your applications drastically."
},
{
"code": null,
"e": 53375,
"s": 52632,
"text": "Data bits in DRAM cells are stored in very weak capacitors that hold charge to distinguish between 1 and 0. A charge capacitor contains 1, and it shares its charge with a sensor that determines if it was sufficiently charged to represent a 1. This process is slow, and accessing a bit like this would be very inefficient. Instead, what actually happens is that many consecutive cells transfer their charges in parallel to increase bandwidth. There are multiple sensors present that detect charges on these cell in parallel. Whenever a location is accessed in the DRAM, data at locations adjacent to it are also accessed and supplied. Now, if that data were actually needed, then it is used and bandwidth is saved. Otherwise, it goes to waste."
},
{
"code": null,
"e": 54065,
"s": 53375,
"text": "We already know that threads in a warp execute the same instruction at any point in time. Let the instruction be LOAD (LD). If it so happens that the threads are accessing consecutive memory locations in the DRAM, then their individual requests can be coalesced into one. This is detected by the hardware dynamically, and saves a lot of DRAM bandwidth. When all threads of a warp access consecutive memory locations, it is the most optimal access pattern. For example, if thread 0 of the warp accesses location 0 of the DRAM, thread 1 accesses location 1, and so on, their requests will be merged into one. Such access patterns enable the DRAM to supply data close to their peak bandwidth."
},
{
"code": null,
"e": 54265,
"s": 54065,
"text": "Let us take our example of matrix-multiplication and see how the row-major layout gives rise to coalesced access pattern, ultimately leading to improved performance. Consider the matrix given below β"
},
{
"code": null,
"e": 54595,
"s": 54265,
"text": "Let us take the threads of a warp. Let each thread process a row. In the 0th iteration, all of them will be accessing the 0th element of each row. In the 1st iteration, the 1st element of each row, and in the 2nd iteration, the 2nd element. Now, since CUDA stores its matrices in row major layout, let us see the access pattern β"
},
{
"code": null,
"e": 54649,
"s": 54595,
"text": "Elements accessed β M(0,0), M(1,0), M(2,0) and so on."
},
{
"code": null,
"e": 54703,
"s": 54649,
"text": "Elements accessed β M(0,0), M(1,0), M(2,0) and so on."
},
{
"code": null,
"e": 54757,
"s": 54703,
"text": "Elements accessed β M(0,1), M(1,1), M(2,1) and so on."
},
{
"code": null,
"e": 54811,
"s": 54757,
"text": "Elements accessed β M(0,1), M(1,1), M(2,1) and so on."
},
{
"code": null,
"e": 55000,
"s": 54811,
"text": "As you can see, the memory locations that are accessed in each loop are not consecutive. Hence, coalesced memory access will not be of much help here and optimal bandwidth is not achieved."
},
{
"code": null,
"e": 55095,
"s": 55000,
"text": "Let each thread now access the 0th element of each column. Let us see the access pattern now β"
},
{
"code": null,
"e": 55160,
"s": 55095,
"text": "Elements accessed β M(0,0), M(0,1), M(0,2) and M(0,3) and so on."
},
{
"code": null,
"e": 55225,
"s": 55160,
"text": "Elements accessed β M(0,0), M(0,1), M(0,2) and M(0,3) and so on."
},
{
"code": null,
"e": 55290,
"s": 55225,
"text": "Elements accessed β M(1,0), M(1,1), M(1,2) and M(1,3) and so on."
},
{
"code": null,
"e": 55355,
"s": 55290,
"text": "Elements accessed β M(1,0), M(1,1), M(1,2) and M(1,3) and so on."
},
{
"code": null,
"e": 55542,
"s": 55355,
"text": "As you can see that in each iteration, consecutive memory locations are accessed, and hence, all these requests can be coalesced into a single one. This increases the kernel performance."
},
{
"code": null,
"e": 56069,
"s": 55542,
"text": "It may so happen that data are to be accessed in a non-favourable pattern. For example, while doing matrix multiplication, one of the matrices has to be read in a non-coalesced manner. The programmer has no choice here. So, what can instead be done is that one of the matrices can be loaded into the shared memory in a coalesced manner, and then it can be read in any pattern (row major or column major). Performance will not be affected much since the shared memory is an intrinsically high-speed memory that resides on-chip."
},
{
"code": null,
"e": 56120,
"s": 56069,
"text": "Here is a tiled kernel for matrix multiplication β"
},
{
"code": null,
"e": 56880,
"s": 56120,
"text": "__global__ void MatrixMulTiled(float *Md, float *Nd, float *Pd, int width) {\n __shared__ float Mds[width_tile][width_tile];\n __shared__ float Nds[width_tile][width_tile];\n int bx = blockIdx.x;\n int by = blockIdx.y;\n int tx = threadIdx.x;\n int ty = threadIdx.y;\n\t\n //identify what pd element to work on\n int row = by * width_tile + ty;\n int col = bx * width_tile + tx;\n float product_val = 0;\n for(int m = 0; m < width/width_tile; m++) {\n\t\n //load the tiles\n Mds[ty][tx] = Md[row*width + (m*width_tile + tx)];\n Nds[ty][tx] = Nd[col*width + (m*width_tile + ty)];\n _syncthreads();\n for(int k=0; k < width_tile; k++) {\n product_val += Mds[ty][k] * Nds[k][tx];\n }\n pd[row][col] = product_val;\n }\n}"
},
{
"code": null,
"e": 57281,
"s": 56880,
"text": "Resources in SM are dynamically partitioned and assigned to threads to support their execution. As has been explained in the previous chapter, the number of resources in SM are limited, and the higher the demands of a thread, the lower the number of threads that can actually run parallel inside the SM. Execution resources of SM include registers, shared memory, thread block slots and thread slots."
},
{
"code": null,
"e": 57815,
"s": 57281,
"text": "In the previous chapter, It has already been discussed that the current generation of CUDA devices support upto 1536 thread slots. That is, each SM can support no more than 1536 threads that can run in parallel. It has to be remembered that there is no capping on the number of thread blocks that can occupy a SM. They can be as many as would keep the total number of threads less than or equal to 1536 per SM. For example, there may be 3 blocks of 512 threads each, or 6 blocks of 256 threads each, or 12 blocks of 128 threads each."
},
{
"code": null,
"e": 58604,
"s": 57815,
"text": "This ability of CUDA to dynamically partition SM resources into thread blocks makes it the real deal. Fixed partitioning methods, in which each thread block receives a fixed number of execution resources regardless of its need leads to wasting of execution resources, which is not desired, as they are already at a premium. Dynamics partition has its own nuances. For example, suppose each thread block has 128 threads. This way, each SM will have 12 blocks. But we know that the current generation of CUDA devices support no more than 8 thread block slots per SM. Thus, out of 12, only 8 blocks will be allowed. This means that out of 1536 threads, only 1024 will be allocated to the SM. Thus, to fully utilize the available resources, we need to have at least 256 threads in each block."
},
{
"code": null,
"e": 58969,
"s": 58604,
"text": "In the matrix-multiplication example, consider that each SM has 16384 registers and each thread requires 10 registers. If we have 16x16 thread blocks, how many registers can run on each SM? The total number of registers needed per thread block = 256x10 = 2560 registers. This means that a maximum of 6 thread blocks (that need 15360 registers) can execute in a SM."
},
{
"code": null,
"e": 59308,
"s": 58969,
"text": "Thus, each SM can have a maximum of 6 x 256=1536 threads run on each SM. What if the number of registers required by each thread is 12? In that case, a thread block requires 256 x 12 = 3072 registers. Thus, we can have 5 blocks at maximum. This concludes that the maximum number of threads that can be allocated to a SM are 5 x 256 =1280."
},
{
"code": null,
"e": 59675,
"s": 59308,
"text": "It is to be noted that by using just two registers per thread extra, the warp parallelism reduces by 1/6.This is known as performance cliff and refers to a situation in which increasing the resource usage per thread even slightly leads to a large reduction in performance. The CUDA occupancy calculator (a program from Nvidia) can calculate the occupancy of each SM."
},
{
"code": null,
"e": 60052,
"s": 59675,
"text": "Let us consider an example of matrix-matrix multiplication once again. Our aim is to reduce the number of accesses to global memory to increase arithmetic intensity of the kernel. Let d_N and d_M be of dimensions 4 x 4 and let each block be of dimensions 2 x 2. This implies that, each block is made up of 4 threads, and we require 4 blocks to compute all the elements of d_P."
},
{
"code": null,
"e": 60146,
"s": 60052,
"text": "The following table shows us the memory access pattern of block (0,0) in our previous kernel."
},
{
"code": null,
"e": 60685,
"s": 60146,
"text": "From the above figure, we see that both thread (0,0) and thread (1,0) access N1,0. Similarly, both thread (0,0) and thread (0,1) access element M0,0. In fact, each d_M and d_N element is accessed twice during the execution of block (0,0). Accessing the global memory twice for fetching the same data is inefficient. Is it possible to somehow make a thread collaborate with others so that they donβt access previously fetched elements? It was explained in the previous chapter that shared memory can be used for inter-thread communication."
},
{
"code": null,
"e": 60892,
"s": 60685,
"text": "It is an algorithm for matrix multiplication in which threads collaborate to reduce global memory traffic. Using this algorithm, multiple accesses to the global memory for fetching the same data is avoided."
},
{
"code": null,
"e": 60992,
"s": 60892,
"text": "Threads collaboratively load M and N elements into shared memory before using them in calculations."
},
{
"code": null,
"e": 61092,
"s": 60992,
"text": "Threads collaboratively load M and N elements into shared memory before using them in calculations."
},
{
"code": null,
"e": 61238,
"s": 61092,
"text": "d_M and d_N are divided into small tiles. Let the tile dimension be equal to the block dimension. In our example, each time has dimensions 2 x 2."
},
{
"code": null,
"e": 61384,
"s": 61238,
"text": "d_M and d_N are divided into small tiles. Let the tile dimension be equal to the block dimension. In our example, each time has dimensions 2 x 2."
},
{
"code": null,
"e": 61587,
"s": 61384,
"text": "The dot product done by each thread is divided into multiple phases. During each phase, all threads in a block collaboratively load two tiles into the shared memory. Let us call these tiles Mds and Nds."
},
{
"code": null,
"e": 61790,
"s": 61587,
"text": "The dot product done by each thread is divided into multiple phases. During each phase, all threads in a block collaboratively load two tiles into the shared memory. Let us call these tiles Mds and Nds."
},
{
"code": null,
"e": 61852,
"s": 61790,
"text": "The following figure illustrates the above mentioned points β"
},
{
"code": null,
"e": 61914,
"s": 61852,
"text": "The following figure illustrates the above mentioned points β"
},
{
"code": null,
"e": 62196,
"s": 61914,
"text": "In the above figure, in phase one, threads of block (0,0) (other blocks will have similar behaviour) load two tiles, Mds and Nds into the shared memory. Each tile is of size 2 x 2. After the values are loaded into the shared memory, they are used in the calculation of dot product."
},
{
"code": null,
"e": 62478,
"s": 62196,
"text": "In the above figure, in phase one, threads of block (0,0) (other blocks will have similar behaviour) load two tiles, Mds and Nds into the shared memory. Each tile is of size 2 x 2. After the values are loaded into the shared memory, they are used in the calculation of dot product."
},
{
"code": null,
"e": 62635,
"s": 62478,
"text": "The calculation of dot product is done in two phases (P1 and P2 in the above diagram). After phase 2 is over, we get the final value of each element of d_P."
},
{
"code": null,
"e": 62792,
"s": 62635,
"text": "The calculation of dot product is done in two phases (P1 and P2 in the above diagram). After phase 2 is over, we get the final value of each element of d_P."
},
{
"code": null,
"e": 62947,
"s": 62792,
"text": "The number of phases required to calculate d_P is equal to N/tile_width, where N is the width of the input matrices. Mds and Nds are reused in each phase."
},
{
"code": null,
"e": 63102,
"s": 62947,
"text": "The number of phases required to calculate d_P is equal to N/tile_width, where N is the width of the input matrices. Mds and Nds are reused in each phase."
},
{
"code": null,
"e": 63351,
"s": 63102,
"text": "It should be noted that each value in the shared memory is read twice. In this way, we reduce the number of access to global memory by half. As a rule, for a tile of size N x N, the number of access to the global memory is reduced by a factor of N."
},
{
"code": null,
"e": 63600,
"s": 63351,
"text": "It should be noted that each value in the shared memory is read twice. In this way, we reduce the number of access to global memory by half. As a rule, for a tile of size N x N, the number of access to the global memory is reduced by a factor of N."
},
{
"code": null,
"e": 64406,
"s": 63600,
"text": "__global__ void MatrixMulKernel(float* d_M, float* d_N, float* d_P, int Width) {\n __shared__ float Mds[TILE_WIDTH][TILE_WIDTH];\n __shared__ float Nds[TILE_WIDTH][TILE_WIDTH];\n int bx = blockIdx.x;\n int by = blockIdx.y;\n int tx = threadIdx.x;\n int ty = threadIdx.y;\n\t\n int Row = by * TILE_WIDTH + ty;\n int Col = bx * TILE_WIDTH + tx;\n\t\n float Pvalue = 0;\n\t\n for (int m = 0; m < Width/TILE_WIDTH;m++) {\n Mds[ty][tx] = d_M[Row*Width + m*TILE_WIDTH + tx];\n Nds[ty][tx] = d_N[(m*TILE_WIDTH + ty)*Width + Col];\n __syncthreads(); //Wait till all the threads have finished loading elements into the tiles.\n\t\t\n for (int k = 0; k < TILE_WIDTH;k++) {\n Pvalue += Mds[ty][k] * Nds[k][tx];\n __syncthreads();\n }\n\t\t\n d_P[Row*Width + Col] = Pvalue;\n }\n}\t"
},
{
"code": null,
"e": 64931,
"s": 64406,
"text": "As we know already, the increase in DRAM bandwidth has not kept up with the increase in processor speed. DRAM is made up of capacitors, that need to be refreshed several times per second, and this process is slow. One of the workarounds is to use a SRAM instead of DRAM. SRAMs are static in nature, and hence, need not be refreshed. They are much faster than DRAMs, but also much more expensive than them. Modern GPUs have 2-4G of DRAM on average. Using SRAM to build memories of that size would increase the cost manifolds."
},
{
"code": null,
"e": 65438,
"s": 64931,
"text": "So, instead, what architecture designers did was they used small memories made up of SRAM that lay very close to the processor. These memories are called caches, and they can transmit data to the processor at a much higher rate than DRAM. But they are typically small in size. The modern GPU contains three levels of caching β L1, L2 and L3. The L1 cache has higher bandwidth compared to other L2 and L3 caches. As we go farther from the cores, the size of the memory increases and its bandwidth decreases."
},
{
"code": null,
"e": 65533,
"s": 65438,
"text": "Caches have been around because of the following attributes of most of the computer programs β"
},
{
"code": null,
"e": 65609,
"s": 65533,
"text": "Temporal locality β Programs tend to use data that they have used recently."
},
{
"code": null,
"e": 65685,
"s": 65609,
"text": "Temporal locality β Programs tend to use data that they have used recently."
},
{
"code": null,
"e": 65792,
"s": 65685,
"text": "Spatial locality β Programs tend to access data residing in addresses similar to recently referenced data."
},
{
"code": null,
"e": 65899,
"s": 65792,
"text": "Spatial locality β Programs tend to access data residing in addresses similar to recently referenced data."
},
{
"code": null,
"e": 66217,
"s": 65899,
"text": "Computer programs have something called as a working set. The working set of a program can be defined as the set of data a program needs during a certain interval of time to do a certain task. If the working set can be stored in a cache, then the program wonβt have to go to the higher levels of memory to fetch data."
},
{
"code": null,
"e": 66823,
"s": 66217,
"text": "One important thing to note is that caches are completely transparent to the operating system. That is, the OS does not have any knowledge if the working set of the program is cached. The CPU still generates the same address. Why is it so? Why doesnβt the OS know about caches? It is simply because that would defeat the very purpose of caches; they are meant to decrease the time the CPU wastes waiting for data. Kernel calls are very expensive, and if the OS takes into account the presence of caches, the increase in the time required to generate an address would offset any benefits that caches offer."
},
{
"code": null,
"e": 67346,
"s": 66823,
"text": "Now, we know that the CPU still generates the same address (it addresses the RAM directly). So, to access caches, we somehow need to map the generated addresses with the cached addresses. In caches, data are stored in blocks (also called lines). A block is a unit of replacement - that is, if some new data comes to be cached, a block of data would be evicted. What block is evicted is a matter of policy (one such policy is the LRU policy). The least recently used block is evicted (takes advantage of temporal locality)."
},
{
"code": null,
"e": 67415,
"s": 67346,
"text": "In this section, we will learn about the different types of caches β"
},
{
"code": null,
"e": 67698,
"s": 67415,
"text": "This is a simple cache. Blocks of the RAM map the cache size to their respective address module. On a conflict, it evicts a block. The advantage is that it is really simple to implement, and is very fast. The downside is that due to a simple hash function, many conflicts may arise."
},
{
"code": null,
"e": 68236,
"s": 67698,
"text": "In associative caches, we have a set of associated blocks in them. Now, blocks from the RAM may map to any block in a particular set. They are of many types β 2-way, 4-way, 8-way. If the cache is an n-way associative cache, then it can eliminate conflicts; if at max n blocks in the RAM map to the same block in the cache concurrently. These types of caches are hard to implement than direct mapped caches. The access time is slower and the hardware required is expensive. Their advantage is that they can eliminate conflicts completely."
},
{
"code": null,
"e": 68391,
"s": 68236,
"text": "In these caches, any block of the RAM can block to any block in the cache. Conflicts are eliminated completely, and it is the most expensive to implement."
},
{
"code": null,
"e": 68423,
"s": 68391,
"text": "Caches have 4 kinds of misses β"
},
{
"code": null,
"e": 68441,
"s": 68423,
"text": "Compulsory misses"
},
{
"code": null,
"e": 68457,
"s": 68441,
"text": "Conflict misses"
},
{
"code": null,
"e": 68473,
"s": 68457,
"text": "Capacity misses"
},
{
"code": null,
"e": 68514,
"s": 68473,
"text": "Coherence misses (in distributed caches)"
},
{
"code": null,
"e": 68872,
"s": 68514,
"text": "When the cache is empty initially, and data come to it for caching. There is not much that can be done about it. One thing that can be done is prefetching. That is, while you are fetching some data from the RAM into the cache, also ensure that the data you will be requiring next are present in the same block. This would prevent a cache miss the next time."
},
{
"code": null,
"e": 69161,
"s": 68872,
"text": "These type of misses happen when data need to be fetched again from the RAM as another block mapped to the same cache line and the data were evicted. It should be noted here that fully-associative caches have no conflict misses, whereas direct mapped caches have the most conflict misses."
},
{
"code": null,
"e": 69425,
"s": 69161,
"text": "These misses occur when the working set of the program is larger than the size of the cache itself. It is simply because some blocks of data are discarded as they cannot fit into the cache. The solution is that the working set of a program should be made smaller."
},
{
"code": null,
"e": 69525,
"s": 69425,
"text": "These happen in distributed caches where there is in-consistent data in the same distributed cache."
},
{
"code": null,
"e": 69532,
"s": 69525,
"text": " Print"
},
{
"code": null,
"e": 69543,
"s": 69532,
"text": " Add Notes"
}
] |
Program to count substrings with all 1s in binary string in Python
|
Suppose we have a binary string s. We have to find the number of substrings that contain only "1"s. If the answer is too large, mod the result by 10^9+7.
So, if the input is like s = "100111", then the output will be 7, because the substrings containing only "1"s are ["1", "1", "1", "1", "11", "11" and "111"]
To solve this, we will follow these steps β
a := 0
count := 0
for i in range 0 to size of s - 1, doif s[i] is same as "0", thena := 0otherwise,a := a + 1count := count + a
if s[i] is same as "0", thena := 0
a := 0
otherwise,a := a + 1count := count + a
a := a + 1
count := count + a
return count
Let us see the following implementation to get better understanding β
def solve(s):
a = 0
count = 0
for i in range(len(s)):
if s[i] == "0":
a = 0
else:
a += 1
count += a
return count
s = "100111"
print(solve(s))
"100111"
7
|
[
{
"code": null,
"e": 1216,
"s": 1062,
"text": "Suppose we have a binary string s. We have to find the number of substrings that contain only \"1\"s. If the answer is too large, mod the result by 10^9+7."
},
{
"code": null,
"e": 1373,
"s": 1216,
"text": "So, if the input is like s = \"100111\", then the output will be 7, because the substrings containing only \"1\"s are [\"1\", \"1\", \"1\", \"1\", \"11\", \"11\" and \"111\"]"
},
{
"code": null,
"e": 1417,
"s": 1373,
"text": "To solve this, we will follow these steps β"
},
{
"code": null,
"e": 1424,
"s": 1417,
"text": "a := 0"
},
{
"code": null,
"e": 1435,
"s": 1424,
"text": "count := 0"
},
{
"code": null,
"e": 1545,
"s": 1435,
"text": "for i in range 0 to size of s - 1, doif s[i] is same as \"0\", thena := 0otherwise,a := a + 1count := count + a"
},
{
"code": null,
"e": 1580,
"s": 1545,
"text": "if s[i] is same as \"0\", thena := 0"
},
{
"code": null,
"e": 1587,
"s": 1580,
"text": "a := 0"
},
{
"code": null,
"e": 1626,
"s": 1587,
"text": "otherwise,a := a + 1count := count + a"
},
{
"code": null,
"e": 1637,
"s": 1626,
"text": "a := a + 1"
},
{
"code": null,
"e": 1656,
"s": 1637,
"text": "count := count + a"
},
{
"code": null,
"e": 1669,
"s": 1656,
"text": "return count"
},
{
"code": null,
"e": 1739,
"s": 1669,
"text": "Let us see the following implementation to get better understanding β"
},
{
"code": null,
"e": 1933,
"s": 1739,
"text": "def solve(s):\n a = 0\n count = 0\n for i in range(len(s)):\n if s[i] == \"0\":\n a = 0\n else:\n a += 1\n count += a\n return count\n\ns = \"100111\"\nprint(solve(s))"
},
{
"code": null,
"e": 1942,
"s": 1933,
"text": "\"100111\""
},
{
"code": null,
"e": 1944,
"s": 1942,
"text": "7"
}
] |
Dynamic program vs integer program: which one is better for the knapsack problem? | by Wei Xia | Towards Data Science
|
The field of optimization encompasses many different fields of models and algorithms. You can classify the field base on many different criteria: Linear vs nonlinear, convex vs non-convex, continuous vs discrete, etc. Often times, one problem could be solved with multiple different approaches, and this is where different underlying solution philosophies meet each other, which I find very interesting. In this article, we are going to dive deeper into the difference between dynamic programming and integer programming with the interesting and well-studied problem of knapsack problem.
Knapsack problem is perhaps widely-known as one of the medium level Leetcode problem. But even before Leetcode, knapsack was covered in the introduction of integer programming classes and perhaps higher level computer science classes, due to its recursive nature and easy problem setup. As an optimization person, knapsack problem is one of the first problems you learn in integer programming class. Whatβs more, knapsack problem is in fact a NP-hard problem! However, it is one of the NP hard problem we can solve pretty efficiently. The more reason we want to start with it!
Letβs recap what the knapsack problem is. Suppose you are going on a trip, and you have a list of n items you would like to carry with you in your backpack (or knapsack, if you will). Each item has a weight and an utility score. You would like to find the subset of items, the total weight of which is below a threshold W and the total utility score of which is maximized.
From the description, the problem sounds simple enough. One caveat is that each item can be either selected or not selected, but it can not be half selected or fractionally selected. This is a good distinction between the 0β1 knapsack problem where each item is a whole, and the fractional knapsack problem where a fractional part of an item can be selected. In real life, the 0β1 knapsack problem can be seen as deciding if a flashlight should be selected, whereas the fractional problem might be considering how much of the 1 gallon of water should be selected.
The main tradeoff of the knapsack problem is between getting as much utility score as possible while satisfying the constrained weight limit. A natural idea is to calculate a utility/weight ratio for each item, then try to fit the items that has higher utility score per unit weight until hitting the weight threshold. This algorithm is a greedy algorithm, and is actually the solution to the fractional knapsack problem. However, this does not guarantee an optimal solution to the 0β1 knapsack problem, as demonstrated by the following counter example.
Suppose the specs of the items are given in the following table:
The weight threshold is 50. Using the greedy heuristic, we will select item 1 and 2, with a total utility of 160 and total weight of 30. Clearly, this is not the optimal solution, which is choosing item 2 and 3, where the total utility is 220, and total weight is exactly 50. The insight is that, ranking with a relative ratio is good, but it does not take into consideration of the absolute weight value and items can not be selected in a fractional manner.
As a matter of fact, one can exploit this weakness and create instances of the knapsack problem which makes the solution of the greedy heuristic arbitrarily bad.
Consider the following knapsack problem with weight threshold X
The greedy algorithm solution will only select item 1, with total utility 1, rather than the optimal solution of selecting item 2 with utility score X-1. As we make X arbitrarily large, the greedy algorithm will perform arbitrarily bad compared to the optimal solution.
Dynamic programming is based on the idea that, in the optimal solution, a given item i is either in the selected subset or not. This property defines the recursive nature of the algorithm. Let I be the set of items, ui, wi be the utility and weight of item i respectively, W be the weight threshold, and knapsack(I,W) be the optimal solution of knapsack problem with item set I and weight threshold W. In mathematical term, the recursion can be defined as
where I\{i} represents the set of items I without item i.
The first term in the max statement is the case where item i is not in the optimal solution, so the optimal solution is the same as the optimal solution to the knapsack problem with same weight threshold and same items except item i.
The second term is the case where item i is in the optimal solution, and to choose the rest of the items in the optimal solution, it requires solving a new knapsack problem, where the set of items is I\{i}, and the weight threshold is W-wi.
With this recursive definition, we can build a table to keep track of the optimal solution of each knapsack problem, starting from 0 items and weight threshold 0 to all items in set I and weight threshold W. Then whenever we are computing the solution of knapsack(I\{i}, W-wi), we can just look up the solution in the table.
Here is a python implementation of the dynamic programming algorithm:
def knapSack(weight_threshold, weight_list, util_list): """ A Dynamic Programming algorithm that solves the 0-1 Knapsack problem. Args: weight_threshold: Weight threshold weight_list: List of weights for each item in item set I util_list: utility score of each item i Returns: The optimal utility score of the knapsack problem """ n = len(util_list) lookup_table = [[0 for x in range(weight_threshold+1)] for x in range(n+1)] # Build table K[][] in bottom up manner for i in range(n+1): for w in range(weight_threshold+1): if i==0 or w==0: lookup_table[i][w] = 0 elif weight_list[i-1] <= w: lookup_table[i][w] = ( max(util_list[i-1] + lookup_table[i-1][w-weight_list[i-1]], lookup_table[i-1][w])) else: lookup_table[i][w] = ( lookup_table[i-1][weight_threshold]) return lookup_table[n][weight_threshold]
Note that here i stands for the number of items available to consider from set I. For example, i = 2 means we can only select from the set of item 1 and 2. As w iterates through all possible weight, and K[i][w] represent the optimal utility score of the knapsack problem with weight threshold j and has items 1, 2, ... , i.
Letβs see the DP algorithm in action with the following problem with weight threshold 5:
The table K would look like the table below when the algorithm terminates with the optimal solution:
where the optimal solution can be found at K[3][5] = 20 and item 2 and 3 are selected.
Another approach is the integer programming approach. Integer programming is a mathematical optimization program in which some or all of the variables are restricted to be integers. Integer programming is NP-complete, so it is not surprising that the knapsack problem, which can be posed as an integer programming problem, is NP-hard as well. When using the Integer programming approach, one usually models the decisions as discrete decision variables, and feasible decisions are described by a set of constraints. The resulting model can be solved by special integer programming algorithm to obtain an optimal solution. In this case, the discrete decision is whether an item should be selected or not. We introduce xi where item i is from set I to represent the decision of item i being selected or not. If xi = 1, then item i is selected, otherwise xi = 0 and item i is not selected.
The integer programming model can be formulated as the following:
The term
is the objective function we want to maximize. In this case, the objective is to maximize the total utility score of the selected subset of items.
The inequality
is the knapsack constraint, which enforces the selected itemsβ total weight does not exceed W.
The model is the classic knapsack problem modeled as integer program. To solve the above model, one can utilize any integer programming solvers. A good option is Google ORtools which is an open source tools for writing and solving optimization models.
Below is the python code that uses ORtools and CBC integer programming solver to model and solve the knapsack problem:
def mip(weight_threshold, weight_list, util_list): """ A Integer Programming model that solves the 0-1 Knapsack problem. Args: weight_threshold: Weight threshold weight_list: List of weights for each item in item set I util_list: utility score of each item i Returns: The optimal utility score of the knapsack problem """ n = len(weight_list) # initialize the integer programming model with the open source CBC solver solver = pywraplp.Solver('simple_mip_program', pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING) # Declare binary variable x for each item from 1 to n x_dict = {} for i in range(n): x_dict[i] = solver.IntVar(0, 1, f'x_{i}') # Add constraint on total weight of items selected cannot exceed weight threshold solver.Add(solver.Sum([weight_list[i]*x_dict[i] for i in range(n)]) <= weight_threshold) # Maximize total utility score solver.Maximize(solver.Sum([util_list[i]*x_dict[i] for i in range(n)])) # Solve! status = solver.Solve() # Uncomment the section below to print solution details # if status == pywraplp.Solver.OPTIMAL: # print('Solution:') # print('Objective value =', solver.Objective().Value()) # print('Problem solved in %f milliseconds' % solver.wall_time()) # for i in x_dict: # print(f'{x_dict[i]} = {x_dict[i].solution_value()}') return solver.Objective().Value()
The standard method to solve an integer programming is called Branch-and-Bound. This is a divide-and-conquer approach which partitions the solution space repetitively until a solution is found and proven to be optimal.
As the name suggests, branch-and-bound consists of two main action:
Bound: Given a solution set, get an upper/lower bound estimate of the best solution that can be found in the solution set. For example, one can find an upper bound for a 0β1 knapsack problem by solving its corresponding fractional knapsack problem. Since fractional knapsack problem allows selecting a fraction of an item while 0β1 knapsack problem does not, fractional knapsack problem will always yield a equal or better objective value, which can be seen as an upper bound on the objective of the 0β1 knapsack problem.
Branch: While computing bounds on the solution set, we encounter solutions which satisfies all constraints of the problem, but yet is not feasible because the solution values are not integer. In this case we can branch on one of the fractional value variables β splitting the current solution space into two: (in the binary variable case) one that enforces the fractional value variables to be 0, and the other enforces the fractional value variable to be 1. For example, solving the fractional knapsack problem may yield a solution that takes 50% of item 2. One can then branch on item 2βs variable by splitting the solution space to either include item 2 or not include item 2.
Letβs walk through solving the example problem we used with dynamic programming, and hopefully that can clear things up.
We start with the original problem of knapsack(I, W), which in branch-and-bound is referred to as the βmaster problemβ. We first solve a relaxation of the master problem. In integer programming, a relaxation usually refers to linear relaxation, where instead of requiring each binary variable xi to be binary, we relax this constraint, and enforce each xi to be between [0, 1]. This results in a linear program, hence the name βlinear relaxationβ. Interestingly, in the knapsack problem case, the linear relaxation is just the fractional knapsack problem. So we can solve it with the heuristic and obtain the optimal solution. For more general integer programsβ relaxations, solving a linear program is required.
After solving the relaxation of knapsack(I, W), we get (x_1, x_2, x_3) = (1, 1, 0.67) and an objective of 22.67. This solution gives us two pieces of information:
A global upper bound of 22.67 on the objective, since the solution space of 0β1 knapsack problem is a subset of the fractional knapsack problem, the best objective of the 0β1 knapsack can not do better than 22.67. As a matter of fact, it cannot be better than 22, since all coefficients in the 0β1 knapsack problem are integers.
The only fractional variable is x3, which is perfect for branching on.
Next, we branch on variable x3 by adding a constraint, and we obtain two subproblems:
a) knapsack(I, W) with constraint x3 = 0
b) knapsack(I, W) with constraint x3 = 1
where each subproblem is a new knapsack problem, and we repeat the same steps and solve each subproblemβs relaxation.
For subproblem a), solving its relaxation yields a solution of (x1, x2, x3) = (1, 1, 0) and objective of 16. This is a feasible solution, which can be used as a lower bound. In other words, now we have found a candidate solution with objective 16, we are only looking for solutions that has a better objective than 16. Any other solution with a worse objective can be discarded.
For subproblem b), the solution to its relaxation gives the solution of (x1, x2, x3) = (1, 0.5, 1), and an objective of 21. As the subproblem a) already attained a best objective of 16, the global upper bound can be updated from 22 to 21, since the only chance of finding a better solution is on subproblem b)βs solution space, and the best it can get is 21. But since x2 is now fractional, we further branch on x2, and form problems b1) and b2).
b1) knapsack(I, W) with constraint x2 = 0, x3 = 1
b2) knapsack(I, W) with constraint x2 = 1, x3 = 1
Solving subproblem b1), we obtain solution (x1, x2, x3) = (1, 0, 1) with objective 16. We can safely discard this branch, as the best objective it can attain is 16, which is already found on subproblem a). In this case, since the solution is also integral, we will stop anyway as there are no other solutions left to investigate on problem b1) that can potentially yield a better objective.
Solving subproblem b2), we get (x1, x2, x3) = (0, 1, 1) with objective 20. Since the solution is integral and is larger than the previous lower bound of 16, this is the new lower bound. And as this is the last branch that we need to explore, we can claim this is the optimal solution to the original problem. Another certificate that shows the optimality of the solution is that the global upper bound is 21, and there is no combination of items that will yield a total utility score of 21, thus the solution of objective 20 is optimal.
Below is a flowchart that summarizes the steps above:
Letβs come back and look at both approaches. Both approaches are using some kind of recursive scheme: dynamic programming exploit the problem structure and builds towards the optimal solution from smaller problems recursively, while integer programming recursively partitions the problem space to smaller trunks, and use estimated bounds to discard uninteresting solution partitions to accelerate the search. Dynamic programming is like a super smart enumeration, and it avoids unnecessary computations by always building upon simpler problemβs optimal solutions. Integer programming does not necessarily work exclusively within the solution set. Rather, it uses the information gained from solving the relaxations to refine the lower and upper bounds, and work towards closing the gap between the bounds. The bounds can help eliminate parts of the solution space that does not contain better solutions, which is why branch-and-bound can be very efficient. Dynamic programming is great when the problem structure is nice, and the solution set is moderate. Integer programming can be very efficient if you have efficient ways to compute quality lower and upper bounds on the solutions.
In the end, which one should we use for knapsack problem? To answer this question, we run two sets of experiments:
Run both algorithms on varying sizes of randomly generated knapsack problems to see the impact of size on performanceRun both algorithms on randomly generated knapsack problems with varying tightness of the knapsack constraints to see the effect of constraint tightness on performance.
Run both algorithms on varying sizes of randomly generated knapsack problems to see the impact of size on performance
Run both algorithms on randomly generated knapsack problems with varying tightness of the knapsack constraints to see the effect of constraint tightness on performance.
The problem size is an usual factor to consider as larger problems usually take longer time to solve. We generate instances of knapsack problem with number of items ranging from 100 to 1000. The weight and utility scores are randomly generated integers between 0 and 100. The weight threshold is a fixed number of 100. We run both algorithms on each instances 7 times, and record the average solution time in terms of seconds. The results can be summarized in the following plot:
From the above plot, it can be observed that for small to moderate size problems, dynamic programming approach is very competitive against integer programming approach. As the size of problem increase, the solution time of both algorithms increases. With the experiment setup, it seems there is no clear advantage of one algorithm to the other.
Another factor we look at is the tightness of the knapsack constraint. A tight constraint means most of the items will not be selected, where a loose constraint means most of the items will end up being selected. This directly affects the lookup table size for dynamic programming. We generate random instances of knapsack problems with 100 items which has random weight and utility scores in the range of 0 to 100. We run each algorithm 7 times on each different weight threshold, which ranges from 50 to 950, and record the average solution time in seconds. The results can be seen from the table below:
From the plot one can see that, as the weight threshold increase, the solution time increases with the dynamic programming approach, while integer programming seems to not be affected as much. This is because dynamic programmingβs table size and number of iteration is directly proportional to the weight threshold, while integer programming is more directly affected by the number of integer variables and constraints, so in this case the constraint tightness does not have a huge impact on the solution time of integer programming.
From the experiments we can see that, for tightly constraint knapsack problems, dynamic programming can be a solid choice, as its efficiency is competitive against integer programming, but does not require a model set up and calling an external solver. Plus dynamic programming has the bonus of the lookup table, which contains optimal solutions of the knapsack problem with different parameters.
On the other hand, the integer programming approach is better if the problem size is large and the knapsack constraint is not very tight. Integer program is not affected as much when the tightness of the knapsack constraint changes. Dynamic programming does have the drawback of not being scale invariant, which means if we multiply the weights and the weight threshold all by the same factor, the solution time will increase as well since the lookup table size is weight threshold * number of items. As a side note, integer program solvers also has more weapons in its arsenal for finding a feasible solution faster and refining the bounds more efficiently. One example is a lot of solvers has builtin heuristics that searches for feasible solutions, and builtin cuts which tightens the bounds.
Hopefully this answers the question of when should we use which approach. If you are familiar with the column generation approach in the field of optimization, you will know that knapsack problem is often a subproblem that we need to solve efficiently. In the literatures, the knapsack problem is always solved with dynamic programming, which has always made me wonder. With all the analysis, I think the choice is due to the fact that the knapsack problem is usually smaller in size and tightly constrained. Hopefully this attracts more people who is interested in optimization, and provided good insights on how each algorithm works to find the optimal solution.
For readers who are interested in the knapsack problem, Google ORtools has more discussions here, and there is also a great book on the same topic.
|
[
{
"code": null,
"e": 760,
"s": 172,
"text": "The field of optimization encompasses many different fields of models and algorithms. You can classify the field base on many different criteria: Linear vs nonlinear, convex vs non-convex, continuous vs discrete, etc. Often times, one problem could be solved with multiple different approaches, and this is where different underlying solution philosophies meet each other, which I find very interesting. In this article, we are going to dive deeper into the difference between dynamic programming and integer programming with the interesting and well-studied problem of knapsack problem."
},
{
"code": null,
"e": 1337,
"s": 760,
"text": "Knapsack problem is perhaps widely-known as one of the medium level Leetcode problem. But even before Leetcode, knapsack was covered in the introduction of integer programming classes and perhaps higher level computer science classes, due to its recursive nature and easy problem setup. As an optimization person, knapsack problem is one of the first problems you learn in integer programming class. Whatβs more, knapsack problem is in fact a NP-hard problem! However, it is one of the NP hard problem we can solve pretty efficiently. The more reason we want to start with it!"
},
{
"code": null,
"e": 1710,
"s": 1337,
"text": "Letβs recap what the knapsack problem is. Suppose you are going on a trip, and you have a list of n items you would like to carry with you in your backpack (or knapsack, if you will). Each item has a weight and an utility score. You would like to find the subset of items, the total weight of which is below a threshold W and the total utility score of which is maximized."
},
{
"code": null,
"e": 2274,
"s": 1710,
"text": "From the description, the problem sounds simple enough. One caveat is that each item can be either selected or not selected, but it can not be half selected or fractionally selected. This is a good distinction between the 0β1 knapsack problem where each item is a whole, and the fractional knapsack problem where a fractional part of an item can be selected. In real life, the 0β1 knapsack problem can be seen as deciding if a flashlight should be selected, whereas the fractional problem might be considering how much of the 1 gallon of water should be selected."
},
{
"code": null,
"e": 2828,
"s": 2274,
"text": "The main tradeoff of the knapsack problem is between getting as much utility score as possible while satisfying the constrained weight limit. A natural idea is to calculate a utility/weight ratio for each item, then try to fit the items that has higher utility score per unit weight until hitting the weight threshold. This algorithm is a greedy algorithm, and is actually the solution to the fractional knapsack problem. However, this does not guarantee an optimal solution to the 0β1 knapsack problem, as demonstrated by the following counter example."
},
{
"code": null,
"e": 2893,
"s": 2828,
"text": "Suppose the specs of the items are given in the following table:"
},
{
"code": null,
"e": 3352,
"s": 2893,
"text": "The weight threshold is 50. Using the greedy heuristic, we will select item 1 and 2, with a total utility of 160 and total weight of 30. Clearly, this is not the optimal solution, which is choosing item 2 and 3, where the total utility is 220, and total weight is exactly 50. The insight is that, ranking with a relative ratio is good, but it does not take into consideration of the absolute weight value and items can not be selected in a fractional manner."
},
{
"code": null,
"e": 3514,
"s": 3352,
"text": "As a matter of fact, one can exploit this weakness and create instances of the knapsack problem which makes the solution of the greedy heuristic arbitrarily bad."
},
{
"code": null,
"e": 3578,
"s": 3514,
"text": "Consider the following knapsack problem with weight threshold X"
},
{
"code": null,
"e": 3848,
"s": 3578,
"text": "The greedy algorithm solution will only select item 1, with total utility 1, rather than the optimal solution of selecting item 2 with utility score X-1. As we make X arbitrarily large, the greedy algorithm will perform arbitrarily bad compared to the optimal solution."
},
{
"code": null,
"e": 4304,
"s": 3848,
"text": "Dynamic programming is based on the idea that, in the optimal solution, a given item i is either in the selected subset or not. This property defines the recursive nature of the algorithm. Let I be the set of items, ui, wi be the utility and weight of item i respectively, W be the weight threshold, and knapsack(I,W) be the optimal solution of knapsack problem with item set I and weight threshold W. In mathematical term, the recursion can be defined as"
},
{
"code": null,
"e": 4362,
"s": 4304,
"text": "where I\\{i} represents the set of items I without item i."
},
{
"code": null,
"e": 4596,
"s": 4362,
"text": "The first term in the max statement is the case where item i is not in the optimal solution, so the optimal solution is the same as the optimal solution to the knapsack problem with same weight threshold and same items except item i."
},
{
"code": null,
"e": 4837,
"s": 4596,
"text": "The second term is the case where item i is in the optimal solution, and to choose the rest of the items in the optimal solution, it requires solving a new knapsack problem, where the set of items is I\\{i}, and the weight threshold is W-wi."
},
{
"code": null,
"e": 5162,
"s": 4837,
"text": "With this recursive definition, we can build a table to keep track of the optimal solution of each knapsack problem, starting from 0 items and weight threshold 0 to all items in set I and weight threshold W. Then whenever we are computing the solution of knapsack(I\\{i}, W-wi), we can just look up the solution in the table."
},
{
"code": null,
"e": 5232,
"s": 5162,
"text": "Here is a python implementation of the dynamic programming algorithm:"
},
{
"code": null,
"e": 6297,
"s": 5232,
"text": "def knapSack(weight_threshold, weight_list, util_list): \"\"\" A Dynamic Programming algorithm that solves the 0-1 Knapsack problem. Args: weight_threshold: Weight threshold weight_list: List of weights for each item in item set I util_list: utility score of each item i Returns: The optimal utility score of the knapsack problem \"\"\" n = len(util_list) lookup_table = [[0 for x in range(weight_threshold+1)] for x in range(n+1)] # Build table K[][] in bottom up manner for i in range(n+1): for w in range(weight_threshold+1): if i==0 or w==0: lookup_table[i][w] = 0 elif weight_list[i-1] <= w: lookup_table[i][w] = ( max(util_list[i-1] + lookup_table[i-1][w-weight_list[i-1]], lookup_table[i-1][w])) else: lookup_table[i][w] = ( lookup_table[i-1][weight_threshold]) return lookup_table[n][weight_threshold]"
},
{
"code": null,
"e": 6621,
"s": 6297,
"text": "Note that here i stands for the number of items available to consider from set I. For example, i = 2 means we can only select from the set of item 1 and 2. As w iterates through all possible weight, and K[i][w] represent the optimal utility score of the knapsack problem with weight threshold j and has items 1, 2, ... , i."
},
{
"code": null,
"e": 6710,
"s": 6621,
"text": "Letβs see the DP algorithm in action with the following problem with weight threshold 5:"
},
{
"code": null,
"e": 6811,
"s": 6710,
"text": "The table K would look like the table below when the algorithm terminates with the optimal solution:"
},
{
"code": null,
"e": 6898,
"s": 6811,
"text": "where the optimal solution can be found at K[3][5] = 20 and item 2 and 3 are selected."
},
{
"code": null,
"e": 7784,
"s": 6898,
"text": "Another approach is the integer programming approach. Integer programming is a mathematical optimization program in which some or all of the variables are restricted to be integers. Integer programming is NP-complete, so it is not surprising that the knapsack problem, which can be posed as an integer programming problem, is NP-hard as well. When using the Integer programming approach, one usually models the decisions as discrete decision variables, and feasible decisions are described by a set of constraints. The resulting model can be solved by special integer programming algorithm to obtain an optimal solution. In this case, the discrete decision is whether an item should be selected or not. We introduce xi where item i is from set I to represent the decision of item i being selected or not. If xi = 1, then item i is selected, otherwise xi = 0 and item i is not selected."
},
{
"code": null,
"e": 7850,
"s": 7784,
"text": "The integer programming model can be formulated as the following:"
},
{
"code": null,
"e": 7859,
"s": 7850,
"text": "The term"
},
{
"code": null,
"e": 8006,
"s": 7859,
"text": "is the objective function we want to maximize. In this case, the objective is to maximize the total utility score of the selected subset of items."
},
{
"code": null,
"e": 8021,
"s": 8006,
"text": "The inequality"
},
{
"code": null,
"e": 8116,
"s": 8021,
"text": "is the knapsack constraint, which enforces the selected itemsβ total weight does not exceed W."
},
{
"code": null,
"e": 8368,
"s": 8116,
"text": "The model is the classic knapsack problem modeled as integer program. To solve the above model, one can utilize any integer programming solvers. A good option is Google ORtools which is an open source tools for writing and solving optimization models."
},
{
"code": null,
"e": 8487,
"s": 8368,
"text": "Below is the python code that uses ORtools and CBC integer programming solver to model and solve the knapsack problem:"
},
{
"code": null,
"e": 9947,
"s": 8487,
"text": "def mip(weight_threshold, weight_list, util_list): \"\"\" A Integer Programming model that solves the 0-1 Knapsack problem. Args: weight_threshold: Weight threshold weight_list: List of weights for each item in item set I util_list: utility score of each item i Returns: The optimal utility score of the knapsack problem \"\"\" n = len(weight_list) # initialize the integer programming model with the open source CBC solver solver = pywraplp.Solver('simple_mip_program', pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING) # Declare binary variable x for each item from 1 to n x_dict = {} for i in range(n): x_dict[i] = solver.IntVar(0, 1, f'x_{i}') # Add constraint on total weight of items selected cannot exceed weight threshold solver.Add(solver.Sum([weight_list[i]*x_dict[i] for i in range(n)]) <= weight_threshold) # Maximize total utility score solver.Maximize(solver.Sum([util_list[i]*x_dict[i] for i in range(n)])) # Solve! status = solver.Solve() # Uncomment the section below to print solution details # if status == pywraplp.Solver.OPTIMAL: # print('Solution:') # print('Objective value =', solver.Objective().Value()) # print('Problem solved in %f milliseconds' % solver.wall_time()) # for i in x_dict: # print(f'{x_dict[i]} = {x_dict[i].solution_value()}') return solver.Objective().Value()"
},
{
"code": null,
"e": 10166,
"s": 9947,
"text": "The standard method to solve an integer programming is called Branch-and-Bound. This is a divide-and-conquer approach which partitions the solution space repetitively until a solution is found and proven to be optimal."
},
{
"code": null,
"e": 10234,
"s": 10166,
"text": "As the name suggests, branch-and-bound consists of two main action:"
},
{
"code": null,
"e": 10756,
"s": 10234,
"text": "Bound: Given a solution set, get an upper/lower bound estimate of the best solution that can be found in the solution set. For example, one can find an upper bound for a 0β1 knapsack problem by solving its corresponding fractional knapsack problem. Since fractional knapsack problem allows selecting a fraction of an item while 0β1 knapsack problem does not, fractional knapsack problem will always yield a equal or better objective value, which can be seen as an upper bound on the objective of the 0β1 knapsack problem."
},
{
"code": null,
"e": 11436,
"s": 10756,
"text": "Branch: While computing bounds on the solution set, we encounter solutions which satisfies all constraints of the problem, but yet is not feasible because the solution values are not integer. In this case we can branch on one of the fractional value variables β splitting the current solution space into two: (in the binary variable case) one that enforces the fractional value variables to be 0, and the other enforces the fractional value variable to be 1. For example, solving the fractional knapsack problem may yield a solution that takes 50% of item 2. One can then branch on item 2βs variable by splitting the solution space to either include item 2 or not include item 2."
},
{
"code": null,
"e": 11557,
"s": 11436,
"text": "Letβs walk through solving the example problem we used with dynamic programming, and hopefully that can clear things up."
},
{
"code": null,
"e": 12270,
"s": 11557,
"text": "We start with the original problem of knapsack(I, W), which in branch-and-bound is referred to as the βmaster problemβ. We first solve a relaxation of the master problem. In integer programming, a relaxation usually refers to linear relaxation, where instead of requiring each binary variable xi to be binary, we relax this constraint, and enforce each xi to be between [0, 1]. This results in a linear program, hence the name βlinear relaxationβ. Interestingly, in the knapsack problem case, the linear relaxation is just the fractional knapsack problem. So we can solve it with the heuristic and obtain the optimal solution. For more general integer programsβ relaxations, solving a linear program is required."
},
{
"code": null,
"e": 12433,
"s": 12270,
"text": "After solving the relaxation of knapsack(I, W), we get (x_1, x_2, x_3) = (1, 1, 0.67) and an objective of 22.67. This solution gives us two pieces of information:"
},
{
"code": null,
"e": 12762,
"s": 12433,
"text": "A global upper bound of 22.67 on the objective, since the solution space of 0β1 knapsack problem is a subset of the fractional knapsack problem, the best objective of the 0β1 knapsack can not do better than 22.67. As a matter of fact, it cannot be better than 22, since all coefficients in the 0β1 knapsack problem are integers."
},
{
"code": null,
"e": 12833,
"s": 12762,
"text": "The only fractional variable is x3, which is perfect for branching on."
},
{
"code": null,
"e": 12919,
"s": 12833,
"text": "Next, we branch on variable x3 by adding a constraint, and we obtain two subproblems:"
},
{
"code": null,
"e": 12960,
"s": 12919,
"text": "a) knapsack(I, W) with constraint x3 = 0"
},
{
"code": null,
"e": 13001,
"s": 12960,
"text": "b) knapsack(I, W) with constraint x3 = 1"
},
{
"code": null,
"e": 13119,
"s": 13001,
"text": "where each subproblem is a new knapsack problem, and we repeat the same steps and solve each subproblemβs relaxation."
},
{
"code": null,
"e": 13498,
"s": 13119,
"text": "For subproblem a), solving its relaxation yields a solution of (x1, x2, x3) = (1, 1, 0) and objective of 16. This is a feasible solution, which can be used as a lower bound. In other words, now we have found a candidate solution with objective 16, we are only looking for solutions that has a better objective than 16. Any other solution with a worse objective can be discarded."
},
{
"code": null,
"e": 13945,
"s": 13498,
"text": "For subproblem b), the solution to its relaxation gives the solution of (x1, x2, x3) = (1, 0.5, 1), and an objective of 21. As the subproblem a) already attained a best objective of 16, the global upper bound can be updated from 22 to 21, since the only chance of finding a better solution is on subproblem b)βs solution space, and the best it can get is 21. But since x2 is now fractional, we further branch on x2, and form problems b1) and b2)."
},
{
"code": null,
"e": 13995,
"s": 13945,
"text": "b1) knapsack(I, W) with constraint x2 = 0, x3 = 1"
},
{
"code": null,
"e": 14045,
"s": 13995,
"text": "b2) knapsack(I, W) with constraint x2 = 1, x3 = 1"
},
{
"code": null,
"e": 14436,
"s": 14045,
"text": "Solving subproblem b1), we obtain solution (x1, x2, x3) = (1, 0, 1) with objective 16. We can safely discard this branch, as the best objective it can attain is 16, which is already found on subproblem a). In this case, since the solution is also integral, we will stop anyway as there are no other solutions left to investigate on problem b1) that can potentially yield a better objective."
},
{
"code": null,
"e": 14973,
"s": 14436,
"text": "Solving subproblem b2), we get (x1, x2, x3) = (0, 1, 1) with objective 20. Since the solution is integral and is larger than the previous lower bound of 16, this is the new lower bound. And as this is the last branch that we need to explore, we can claim this is the optimal solution to the original problem. Another certificate that shows the optimality of the solution is that the global upper bound is 21, and there is no combination of items that will yield a total utility score of 21, thus the solution of objective 20 is optimal."
},
{
"code": null,
"e": 15027,
"s": 14973,
"text": "Below is a flowchart that summarizes the steps above:"
},
{
"code": null,
"e": 16212,
"s": 15027,
"text": "Letβs come back and look at both approaches. Both approaches are using some kind of recursive scheme: dynamic programming exploit the problem structure and builds towards the optimal solution from smaller problems recursively, while integer programming recursively partitions the problem space to smaller trunks, and use estimated bounds to discard uninteresting solution partitions to accelerate the search. Dynamic programming is like a super smart enumeration, and it avoids unnecessary computations by always building upon simpler problemβs optimal solutions. Integer programming does not necessarily work exclusively within the solution set. Rather, it uses the information gained from solving the relaxations to refine the lower and upper bounds, and work towards closing the gap between the bounds. The bounds can help eliminate parts of the solution space that does not contain better solutions, which is why branch-and-bound can be very efficient. Dynamic programming is great when the problem structure is nice, and the solution set is moderate. Integer programming can be very efficient if you have efficient ways to compute quality lower and upper bounds on the solutions."
},
{
"code": null,
"e": 16327,
"s": 16212,
"text": "In the end, which one should we use for knapsack problem? To answer this question, we run two sets of experiments:"
},
{
"code": null,
"e": 16613,
"s": 16327,
"text": "Run both algorithms on varying sizes of randomly generated knapsack problems to see the impact of size on performanceRun both algorithms on randomly generated knapsack problems with varying tightness of the knapsack constraints to see the effect of constraint tightness on performance."
},
{
"code": null,
"e": 16731,
"s": 16613,
"text": "Run both algorithms on varying sizes of randomly generated knapsack problems to see the impact of size on performance"
},
{
"code": null,
"e": 16900,
"s": 16731,
"text": "Run both algorithms on randomly generated knapsack problems with varying tightness of the knapsack constraints to see the effect of constraint tightness on performance."
},
{
"code": null,
"e": 17380,
"s": 16900,
"text": "The problem size is an usual factor to consider as larger problems usually take longer time to solve. We generate instances of knapsack problem with number of items ranging from 100 to 1000. The weight and utility scores are randomly generated integers between 0 and 100. The weight threshold is a fixed number of 100. We run both algorithms on each instances 7 times, and record the average solution time in terms of seconds. The results can be summarized in the following plot:"
},
{
"code": null,
"e": 17725,
"s": 17380,
"text": "From the above plot, it can be observed that for small to moderate size problems, dynamic programming approach is very competitive against integer programming approach. As the size of problem increase, the solution time of both algorithms increases. With the experiment setup, it seems there is no clear advantage of one algorithm to the other."
},
{
"code": null,
"e": 18331,
"s": 17725,
"text": "Another factor we look at is the tightness of the knapsack constraint. A tight constraint means most of the items will not be selected, where a loose constraint means most of the items will end up being selected. This directly affects the lookup table size for dynamic programming. We generate random instances of knapsack problems with 100 items which has random weight and utility scores in the range of 0 to 100. We run each algorithm 7 times on each different weight threshold, which ranges from 50 to 950, and record the average solution time in seconds. The results can be seen from the table below:"
},
{
"code": null,
"e": 18865,
"s": 18331,
"text": "From the plot one can see that, as the weight threshold increase, the solution time increases with the dynamic programming approach, while integer programming seems to not be affected as much. This is because dynamic programmingβs table size and number of iteration is directly proportional to the weight threshold, while integer programming is more directly affected by the number of integer variables and constraints, so in this case the constraint tightness does not have a huge impact on the solution time of integer programming."
},
{
"code": null,
"e": 19262,
"s": 18865,
"text": "From the experiments we can see that, for tightly constraint knapsack problems, dynamic programming can be a solid choice, as its efficiency is competitive against integer programming, but does not require a model set up and calling an external solver. Plus dynamic programming has the bonus of the lookup table, which contains optimal solutions of the knapsack problem with different parameters."
},
{
"code": null,
"e": 20058,
"s": 19262,
"text": "On the other hand, the integer programming approach is better if the problem size is large and the knapsack constraint is not very tight. Integer program is not affected as much when the tightness of the knapsack constraint changes. Dynamic programming does have the drawback of not being scale invariant, which means if we multiply the weights and the weight threshold all by the same factor, the solution time will increase as well since the lookup table size is weight threshold * number of items. As a side note, integer program solvers also has more weapons in its arsenal for finding a feasible solution faster and refining the bounds more efficiently. One example is a lot of solvers has builtin heuristics that searches for feasible solutions, and builtin cuts which tightens the bounds."
},
{
"code": null,
"e": 20723,
"s": 20058,
"text": "Hopefully this answers the question of when should we use which approach. If you are familiar with the column generation approach in the field of optimization, you will know that knapsack problem is often a subproblem that we need to solve efficiently. In the literatures, the knapsack problem is always solved with dynamic programming, which has always made me wonder. With all the analysis, I think the choice is due to the fact that the knapsack problem is usually smaller in size and tightly constrained. Hopefully this attracts more people who is interested in optimization, and provided good insights on how each algorithm works to find the optimal solution."
}
] |
Mockito - Spying
|
Mockito provides option to create spy on real objects. When spy is called, then actual method of real object is called.
//create a spy on actual object
calcService = spy(calculator);
//perform operation on real object
//test the add functionality
Assert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0);
Step 1 β Create an interface called CalculatorService to provide mathematical functions
File: CalculatorService.java
public interface CalculatorService {
public double add(double input1, double input2);
public double subtract(double input1, double input2);
public double multiply(double input1, double input2);
public double divide(double input1, double input2);
}
Step 2 β Create a JAVA class to represent MathApplication
File: MathApplication.java
public class MathApplication {
private CalculatorService calcService;
public void setCalculatorService(CalculatorService calcService){
this.calcService = calcService;
}
public double add(double input1, double input2){
return calcService.add(input1, input2);
}
public double subtract(double input1, double input2){
return calcService.subtract(input1, input2);
}
public double multiply(double input1, double input2){
return calcService.multiply(input1, input2);
}
public double divide(double input1, double input2){
return calcService.divide(input1, input2);
}
}
Step 3 β Test the MathApplication class
Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by Mockito.
Here we've added one mock method calls, add() to the mock object via when(). However during testing, we've called subtract() before calling add(). When we create a mock object using Mockito.createStrictMock(), the order of execution of the method does matter.
File: MathApplicationTester.java
import static org.mockito.Mockito.spy;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
// @RunWith attaches a runner with the test class to initialize the test data
@RunWith(MockitoJUnitRunner.class)
public class MathApplicationTester {
private MathApplication mathApplication;
private CalculatorService calcService;
@Before
public void setUp(){
mathApplication = new MathApplication();
Calculator calculator = new Calculator();
calcService = spy(calculator);
mathApplication.setCalculatorService(calcService);
}
@Test
public void testAdd(){
//perform operation on real object
//test the add functionality
Assert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0);
}
class Calculator implements CalculatorService {
@Override
public double add(double input1, double input2) {
return input1 + input2;
}
@Override
public double subtract(double input1, double input2) {
throw new UnsupportedOperationException("Method not implemented yet!");
}
@Override
public double multiply(double input1, double input2) {
throw new UnsupportedOperationException("Method not implemented yet!");
}
@Override
public double divide(double input1, double input2) {
throw new UnsupportedOperationException("Method not implemented yet!");
}
}
}
Step 4 β Execute test cases
Create a java class file named TestRunner in C:\> Mockito_WORKSPACE to execute Test case(s).
File: TestRunner.java
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(MathApplicationTester.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Step 5 β Verify the Result
Compile the classes using javac compiler as follows β
C:\Mockito_WORKSPACE>javac CalculatorService.java MathApplication.
java MathApplicationTester.java TestRunner.java
Now run the Test Runner to see the result β
C:\Mockito_WORKSPACE>java TestRunner
Verify the output.
true
31 Lectures
43 mins
Abhinav Manchanda
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2100,
"s": 1980,
"text": "Mockito provides option to create spy on real objects. When spy is called, then actual method of real object is called."
},
{
"code": null,
"e": 2290,
"s": 2100,
"text": "//create a spy on actual object\ncalcService = spy(calculator);\n\n//perform operation on real object\n//test the add functionality\nAssert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0);\n"
},
{
"code": null,
"e": 2378,
"s": 2290,
"text": "Step 1 β Create an interface called CalculatorService to provide mathematical functions"
},
{
"code": null,
"e": 2407,
"s": 2378,
"text": "File: CalculatorService.java"
},
{
"code": null,
"e": 2667,
"s": 2407,
"text": "public interface CalculatorService {\n public double add(double input1, double input2);\n public double subtract(double input1, double input2);\n public double multiply(double input1, double input2);\n public double divide(double input1, double input2);\n}"
},
{
"code": null,
"e": 2725,
"s": 2667,
"text": "Step 2 β Create a JAVA class to represent MathApplication"
},
{
"code": null,
"e": 2752,
"s": 2725,
"text": "File: MathApplication.java"
},
{
"code": null,
"e": 3395,
"s": 2752,
"text": "public class MathApplication {\n private CalculatorService calcService;\n\n public void setCalculatorService(CalculatorService calcService){\n this.calcService = calcService;\n }\n \n public double add(double input1, double input2){\n return calcService.add(input1, input2);\t\t\n }\n \n public double subtract(double input1, double input2){\n return calcService.subtract(input1, input2);\n }\n \n public double multiply(double input1, double input2){\n return calcService.multiply(input1, input2);\n }\n \n public double divide(double input1, double input2){\n return calcService.divide(input1, input2);\n }\n}"
},
{
"code": null,
"e": 3435,
"s": 3395,
"text": "Step 3 β Test the MathApplication class"
},
{
"code": null,
"e": 3554,
"s": 3435,
"text": "Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by Mockito."
},
{
"code": null,
"e": 3814,
"s": 3554,
"text": "Here we've added one mock method calls, add() to the mock object via when(). However during testing, we've called subtract() before calling add(). When we create a mock object using Mockito.createStrictMock(), the order of execution of the method does matter."
},
{
"code": null,
"e": 3847,
"s": 3814,
"text": "File: MathApplicationTester.java"
},
{
"code": null,
"e": 5371,
"s": 3847,
"text": "import static org.mockito.Mockito.spy;\n\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.runners.MockitoJUnitRunner;\n\n// @RunWith attaches a runner with the test class to initialize the test data\n@RunWith(MockitoJUnitRunner.class)\npublic class MathApplicationTester {\n\t\n private MathApplication mathApplication;\n private CalculatorService calcService;\n\n @Before\n public void setUp(){\n mathApplication = new MathApplication();\n Calculator calculator = new Calculator();\n calcService = spy(calculator);\n mathApplication.setCalculatorService(calcService);\t \n }\n\n @Test\n public void testAdd(){\n\n //perform operation on real object\n //test the add functionality\n Assert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0);\n }\n\n class Calculator implements CalculatorService {\n @Override\n public double add(double input1, double input2) {\n return input1 + input2;\n }\n\n @Override\n public double subtract(double input1, double input2) {\n throw new UnsupportedOperationException(\"Method not implemented yet!\");\n }\n\n @Override\n public double multiply(double input1, double input2) {\n throw new UnsupportedOperationException(\"Method not implemented yet!\");\n }\n\n @Override\n public double divide(double input1, double input2) {\n throw new UnsupportedOperationException(\"Method not implemented yet!\");\n }\n }\n}"
},
{
"code": null,
"e": 5400,
"s": 5371,
"text": "Step 4 β Execute test cases "
},
{
"code": null,
"e": 5493,
"s": 5400,
"text": "Create a java class file named TestRunner in C:\\> Mockito_WORKSPACE to execute Test case(s)."
},
{
"code": null,
"e": 5515,
"s": 5493,
"text": "File: TestRunner.java"
},
{
"code": null,
"e": 5956,
"s": 5515,
"text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(MathApplicationTester.class);\n \n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n \n System.out.println(result.wasSuccessful());\n }\n} \t"
},
{
"code": null,
"e": 5983,
"s": 5956,
"text": "Step 5 β Verify the Result"
},
{
"code": null,
"e": 6037,
"s": 5983,
"text": "Compile the classes using javac compiler as follows β"
},
{
"code": null,
"e": 6156,
"s": 6037,
"text": "C:\\Mockito_WORKSPACE>javac CalculatorService.java MathApplication.\n java MathApplicationTester.java TestRunner.java\n"
},
{
"code": null,
"e": 6200,
"s": 6156,
"text": "Now run the Test Runner to see the result β"
},
{
"code": null,
"e": 6238,
"s": 6200,
"text": "C:\\Mockito_WORKSPACE>java TestRunner\n"
},
{
"code": null,
"e": 6257,
"s": 6238,
"text": "Verify the output."
},
{
"code": null,
"e": 6263,
"s": 6257,
"text": "true\n"
},
{
"code": null,
"e": 6295,
"s": 6263,
"text": "\n 31 Lectures \n 43 mins\n"
},
{
"code": null,
"e": 6314,
"s": 6295,
"text": " Abhinav Manchanda"
},
{
"code": null,
"e": 6321,
"s": 6314,
"text": " Print"
},
{
"code": null,
"e": 6332,
"s": 6321,
"text": " Add Notes"
}
] |
Dungeon Game in C++
|
Suppose there is a story like the demons had captured the princess whose name is P and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M row, N column grid-like rooms. Our valiant knight named K was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess.
Now the knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies at that moment.
Some of the rooms have demons to guard that room, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty or contain magic orbs that increase the knight's health (positive integers).
So if he wants to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step. We have to find the minimal initial health that will be sufficient to reach P. So if the input is like, then the answer will be 6, as K can reach to P, using the path Right -> Right -> Down -> Down
To solve this, we will follow these steps β
r := row of dp, c := col of dp
r := row of dp, c := col of dp
for initializing j := r - 2, when j >= 0, decrease j by 1 do βdp[j, c - 1] := minimum of dp[j, c - 1] and dp[j, c - 1] + dp[j + 1, c - 1]
for initializing j := r - 2, when j >= 0, decrease j by 1 do β
dp[j, c - 1] := minimum of dp[j, c - 1] and dp[j, c - 1] + dp[j + 1, c - 1]
dp[j, c - 1] := minimum of dp[j, c - 1] and dp[j, c - 1] + dp[j + 1, c - 1]
for initializing j := c - 2, when j >= 0, decrease j by 1 do βdp[r - 1, j] := minimum of dp[r - 1, j] and dp[r β 1, j] + dp[r β 1, j + 1]
for initializing j := c - 2, when j >= 0, decrease j by 1 do β
dp[r - 1, j] := minimum of dp[r - 1, j] and dp[r β 1, j] + dp[r β 1, j + 1]
dp[r - 1, j] := minimum of dp[r - 1, j] and dp[r β 1, j] + dp[r β 1, j + 1]
for initializing i := r - 2, when i >= 0, decrease i by 1 do βfor initializing j := c - 2, when j >= 0, decrease j by 1 do βdp[i, j] := minimum of dp[i, j] and maximum of dp[i, j] + dp[i + 1, j] and dp[i, j] + dp[i, j + 1]
for initializing i := r - 2, when i >= 0, decrease i by 1 do β
for initializing j := c - 2, when j >= 0, decrease j by 1 do βdp[i, j] := minimum of dp[i, j] and maximum of dp[i, j] + dp[i + 1, j] and dp[i, j] + dp[i, j + 1]
for initializing j := c - 2, when j >= 0, decrease j by 1 do β
dp[i, j] := minimum of dp[i, j] and maximum of dp[i, j] + dp[i + 1, j] and dp[i, j] + dp[i, j + 1]
dp[i, j] := minimum of dp[i, j] and maximum of dp[i, j] + dp[i + 1, j] and dp[i, j] + dp[i, j + 1]
if dp[0, 0] <= 0, then,return |dp[0, 0]| + 1
if dp[0, 0] <= 0, then,
return |dp[0, 0]| + 1
return |dp[0, 0]| + 1
return 1
return 1
Let us see the following implementation to get better understanding β
Live Demo
#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
lli min(lli a, lli b){
return a <= b ? a : b;
}
lli max(lli a, lli b){
return a <= b ? b : a;
}
class Solution {
public:
int calculateMinimumHP(vector<vector<int>>& dp) {
int r = dp.size();
int c = dp[0].size();
for(lli j=r-2;j>=0;j--){
dp[j][c-1] = min(dp[j][c-1], dp[j][c-1]+dp[j+1][c-1]);
}
for(lli j = c-2;j>=0;j--){
dp[r-1][j] =min(dp[r-1][j], dp[r-1][j]+dp[r-1][j+1]);
}
for(lli i = r-2;i>=0;i--){
for(lli j = c-2;j>=0;j--){
dp[i][j] = min(dp[i][j],max(dp[i][j]+dp[i+1][j],dp[i][j]+dp[i][j+1]));
}
}
if(dp[0][0] <= 0 )return abs(dp[0][0])+1;
return 1;
}
};
main(){
Solution ob;
vector<vector<int>> v = {{-2,-2,3},{-5,-10,1},{10,30,-5}};
cout << (ob.calculateMinimumHP(v));
}
{{-2,-2,3},{-5,-10,1},{10,30,-5}}
6
|
[
{
"code": null,
"e": 1402,
"s": 1062,
"text": "Suppose there is a story like the demons had captured the princess whose name is P and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M row, N column grid-like rooms. Our valiant knight named K was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess."
},
{
"code": null,
"e": 1558,
"s": 1402,
"text": "Now the knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies at that moment."
},
{
"code": null,
"e": 1788,
"s": 1558,
"text": "Some of the rooms have demons to guard that room, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty or contain magic orbs that increase the knight's health (positive integers)."
},
{
"code": null,
"e": 2115,
"s": 1788,
"text": "So if he wants to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step. We have to find the minimal initial health that will be sufficient to reach P. So if the input is like, then the answer will be 6, as K can reach to P, using the path Right -> Right -> Down -> Down"
},
{
"code": null,
"e": 2159,
"s": 2115,
"text": "To solve this, we will follow these steps β"
},
{
"code": null,
"e": 2190,
"s": 2159,
"text": "r := row of dp, c := col of dp"
},
{
"code": null,
"e": 2221,
"s": 2190,
"text": "r := row of dp, c := col of dp"
},
{
"code": null,
"e": 2359,
"s": 2221,
"text": "for initializing j := r - 2, when j >= 0, decrease j by 1 do βdp[j, c - 1] := minimum of dp[j, c - 1] and dp[j, c - 1] + dp[j + 1, c - 1]"
},
{
"code": null,
"e": 2422,
"s": 2359,
"text": "for initializing j := r - 2, when j >= 0, decrease j by 1 do β"
},
{
"code": null,
"e": 2498,
"s": 2422,
"text": "dp[j, c - 1] := minimum of dp[j, c - 1] and dp[j, c - 1] + dp[j + 1, c - 1]"
},
{
"code": null,
"e": 2574,
"s": 2498,
"text": "dp[j, c - 1] := minimum of dp[j, c - 1] and dp[j, c - 1] + dp[j + 1, c - 1]"
},
{
"code": null,
"e": 2712,
"s": 2574,
"text": "for initializing j := c - 2, when j >= 0, decrease j by 1 do βdp[r - 1, j] := minimum of dp[r - 1, j] and dp[r β 1, j] + dp[r β 1, j + 1]"
},
{
"code": null,
"e": 2775,
"s": 2712,
"text": "for initializing j := c - 2, when j >= 0, decrease j by 1 do β"
},
{
"code": null,
"e": 2851,
"s": 2775,
"text": "dp[r - 1, j] := minimum of dp[r - 1, j] and dp[r β 1, j] + dp[r β 1, j + 1]"
},
{
"code": null,
"e": 2927,
"s": 2851,
"text": "dp[r - 1, j] := minimum of dp[r - 1, j] and dp[r β 1, j] + dp[r β 1, j + 1]"
},
{
"code": null,
"e": 3150,
"s": 2927,
"text": "for initializing i := r - 2, when i >= 0, decrease i by 1 do βfor initializing j := c - 2, when j >= 0, decrease j by 1 do βdp[i, j] := minimum of dp[i, j] and maximum of dp[i, j] + dp[i + 1, j] and dp[i, j] + dp[i, j + 1]"
},
{
"code": null,
"e": 3213,
"s": 3150,
"text": "for initializing i := r - 2, when i >= 0, decrease i by 1 do β"
},
{
"code": null,
"e": 3374,
"s": 3213,
"text": "for initializing j := c - 2, when j >= 0, decrease j by 1 do βdp[i, j] := minimum of dp[i, j] and maximum of dp[i, j] + dp[i + 1, j] and dp[i, j] + dp[i, j + 1]"
},
{
"code": null,
"e": 3437,
"s": 3374,
"text": "for initializing j := c - 2, when j >= 0, decrease j by 1 do β"
},
{
"code": null,
"e": 3536,
"s": 3437,
"text": "dp[i, j] := minimum of dp[i, j] and maximum of dp[i, j] + dp[i + 1, j] and dp[i, j] + dp[i, j + 1]"
},
{
"code": null,
"e": 3635,
"s": 3536,
"text": "dp[i, j] := minimum of dp[i, j] and maximum of dp[i, j] + dp[i + 1, j] and dp[i, j] + dp[i, j + 1]"
},
{
"code": null,
"e": 3680,
"s": 3635,
"text": "if dp[0, 0] <= 0, then,return |dp[0, 0]| + 1"
},
{
"code": null,
"e": 3704,
"s": 3680,
"text": "if dp[0, 0] <= 0, then,"
},
{
"code": null,
"e": 3726,
"s": 3704,
"text": "return |dp[0, 0]| + 1"
},
{
"code": null,
"e": 3748,
"s": 3726,
"text": "return |dp[0, 0]| + 1"
},
{
"code": null,
"e": 3757,
"s": 3748,
"text": "return 1"
},
{
"code": null,
"e": 3766,
"s": 3757,
"text": "return 1"
},
{
"code": null,
"e": 3836,
"s": 3766,
"text": "Let us see the following implementation to get better understanding β"
},
{
"code": null,
"e": 3847,
"s": 3836,
"text": " Live Demo"
},
{
"code": null,
"e": 4730,
"s": 3847,
"text": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long int lli;\nlli min(lli a, lli b){\n return a <= b ? a : b;\n}\nlli max(lli a, lli b){\n return a <= b ? b : a;\n}\nclass Solution {\npublic:\n int calculateMinimumHP(vector<vector<int>>& dp) {\n int r = dp.size();\n int c = dp[0].size();\n for(lli j=r-2;j>=0;j--){\n dp[j][c-1] = min(dp[j][c-1], dp[j][c-1]+dp[j+1][c-1]);\n }\n for(lli j = c-2;j>=0;j--){\n dp[r-1][j] =min(dp[r-1][j], dp[r-1][j]+dp[r-1][j+1]);\n }\n for(lli i = r-2;i>=0;i--){\n for(lli j = c-2;j>=0;j--){\n dp[i][j] = min(dp[i][j],max(dp[i][j]+dp[i+1][j],dp[i][j]+dp[i][j+1]));\n }\n }\n if(dp[0][0] <= 0 )return abs(dp[0][0])+1;\n return 1;\n }\n};\nmain(){\n Solution ob;\n vector<vector<int>> v = {{-2,-2,3},{-5,-10,1},{10,30,-5}};\n cout << (ob.calculateMinimumHP(v));\n}"
},
{
"code": null,
"e": 4764,
"s": 4730,
"text": "{{-2,-2,3},{-5,-10,1},{10,30,-5}}"
},
{
"code": null,
"e": 4766,
"s": 4764,
"text": "6"
}
] |
Data Analysis in MySQL β Operators, Joins and More in Relational Databases | by Craig Dickson | Towards Data Science
|
This is part 3 of a 3-part series taking you through the process of designing, coding, implementing and querying a relational database using MySQL, starting from zero. See part 1 (Designing a Relational Database and Creating an Entity Relationship Diagram) here, and part 2 (Coding and Implementing a Relational Database using MySQL) here.
All the code and information for this tutorial can be found on the associated GitHub repository. I used Lucidchart to make the diagrams shown in the article.
In parts 1 and 2 of this series, we have gone through the steps of designing our database, implementing it in MySQL and populating it with our data. Itβs a good idea to read those before going into this article, but the SQL code to get you caught up is all contained in the associated GitHub repository if you feel like skipping ahead to this analysis section.
We have designed and implemented a fully functioning relational database from scratch. Great stuff! But what now?
If weβre working in a Data Analyst-type role, weβre going to want to start analysing that data. But first, we need to know how to get to it. This article will describe how to write queries in SQL (specifically MySQL) that will allow us to access the data and relationships that are locked away within our RDBMS.
We covered installing MySQL Community Server in part 2 of this series, so we should have a working instance of that running on our system. We will also once again be using PopSQLβs free plan to run our queries.
The primary form of a SQL query statement is something like:
SELECT columns FROM table WHERE condition;
For example, to select all of the columns from our Teacher table, we used the statement:
SELECT *FROM teacher;
In this case the asterisk character (*) means βall columnsβ. Weβre selecting the teacher table, and there is no condition attached, which means we will be selecting all columns and all records (i.e. all the data) from that table.
If we just want specific attributes from the table, we can name those instead of using the asterisk.
SELECT last_name, dobFROM teacher;
In most cases, we wonβt want to select all of the records in a table, but will be looking for particular records that meet some condition. In these cases, we will need to use a WHERE clause.
Note that we will be using our WHERE clauses with SELECT statements in this article, but that the exact same syntax and operators will work with UPDATE, INSERT or DELETE statements as well. The WHERE clause is an essential aspect of all flavours of SQL to master.
The WHERE clause allows us to set a condition, such as:
SELECT *FROM courseWHERE language = 'ENG';
This will select all details from the course table for courses where the language in English.
Perhaps we want to order the results differently, then we can use ORDER BY to do that.
SELECT *FROM courseWHERE language = 'ENG'ORDER BY start_date;
By default, MySQL orders in ascending order. If we want the results in descending order, we can add DESC like so:
SELECT *FROM courseWHERE language = 'ENG'ORDER BY start_date DESC;
We can also use ORDER BY in series, so we could do:
SELECT *FROM courseWHERE language = 'ENG'ORDER BY start_date DESC, client, teacher;
This would give us our results sorted by that hierarchy of attributes, in the order they were specified.
We can use AND and OR operators within WHERE clauses as well. If youβre familiar with any other programming languages youβll have most likely come across these logical operators before. In SQL they work exactly as you would expect them to.
SELECT *FROM courseWHERE language = 'ENG' AND level = 'C1';
Using the AND operator excludes all results which donβt fit both conditions, so only courses in English at C1 level are shown β in the International Language School database, that gives us just one result. If we use OR in the same statement, we get some different results.
SELECT *FROM courseWHERE language = 'ENG' OR level = 'C1';
Using the OR operator includes all records which satisfy either condition, so now we have all courses which are in English (as these satisfy the language = βEngβ condition) plus the one other course which is at C1 level, Advanced Russian.
We can also use the NOT operator before a condition, to exclude every record which meets that condition and include all other records.
SELECT *FROM courseWHERE NOT language = 'ENG' OR level = 'C1';
This is very useful when we want to exclude certain records.
It is also possible to use other comparison operators in our WHERE clauses. This is the full list of comparison operators we can use in MySQL:
Equal to: =
Not equal to: <> or !=
Less than: <
Less than or equal to: <=
Greater than: >
Greater than or equal to: >=
This opens many possibilities to us. One very simple example would be to identify the names and contact info of all teachers born before 1990:
SELECT first_name, last_name, phone_noFROM teacherWHERE dob < '1990-01-01';
The BETWEEN operator allows us to select the records with a value that falls within a range. We can identify all courses which began in January 2020 by using the following code:
SELECT *FROM courseWHERE start_date BETWEEN '2020-01-01' AND '2020-01-31';
In our example, we are comparing dates, but BETWEEN can also be used to find any value (sales, order quantity, etc) that falls in a particular range. Very useful!
The LIKE operator allows us to search for values which match a specified pattern. We can use two wildcards to build our patterns:
%this wildcard stands for zero, one or multiple characters
_this wildcard stands for exactly one character
If youβre familiar with regular expressions then this will seem familiar to you, as SQL is basically implementing a simplified version of those. This allows us to build patterns and get our RDBMS to find the records which meet those patterns.
Letβs look at an example:
SELECT course_nameFROM courseWHERE course_name LIKE '%interm%';
By using the % wildcard at the beginning and end of our pattern we instructed MySQL to identify the character sequence βintermβ anywhere it occurred in the course_name attribute. This is a very useful feature.
Our next operator is IN β this is effectively shorthand for many OR conditions, allowing us to give MySQL a list of values we would like to use.
SELECT first_name, last_nameFROM participantWHERE last_name IN ('Garcia', 'Nowak', 'Mustermann');
The output here is identical to the output we would receive from the query:
SELECT first_name, last_nameFROM participantWHERE last_name = 'Garcia' OR last_name = 'Nowak' OR last_name = 'Mustermann';
The benefit is that we donβt have to write out the column name repeatedly. This is extremely beneficial when we have a lot of values to include in our query.
The final operator we will discuss in this section is IS NULL, along with its negative cousin IS NOT NULL. This allows us to identify records where a particular attribute (or set of attributes) is NULL. This could be useful to update them with some other value, to exclude them from a data set, or for a wide variety of other reasons.
In our database, we can use this to identify teachers who βonlyβ teach in one language:
SELECT * FROM teacherWHERE language_2 IS NULL;
Alternatively, we can use IS NOT NULL to find the teachers who teach in two languages:
SELECT * FROM teacherWHERE language_2 IS NOT NULL;
Sometimes the data in our database is stored with attribute names which may be confusing for the audience of our reports, or is just formatted in an unattractive way. We can fix this at the query stage by using aliasing.
Here we use the AS keyword to instruct MySQL to display a particular column with a temporary name. For example:
SELECT course_name AS 'Course Name', course_length_weeks AS 'Length of Course (Weeks)'FROM courseWHERE language = 'DEU';
This can be useful when we are preparing reports for other stakeholders and want to make things prettier, or when a column has a name which may be confusing in the context of our particular query, among other situations.
When performing data analysis, itβs also important to be able to aggregate our data. MySQL provides many ways of doing this, and we will not cover them all here. There is a comprehensive list here, for those who would like to dig deeper.
One of the most common aggregations we will want to perform is finding an average. In MySQL we do this with the AVG() aggregator. If we want to know the average length of a course, we can use the following query:
SELECT AVG(course_length_weeks)FROM course;
When using aggregators, it is very common to use these in combination with the GROUP BY statement. This can help us to move beyond the basics and find really useful information in our database.
SELECT client, AVG(course_length_weeks)FROM courseGROUP BY client;
You can see how we can use GROUP BY alongside some of the aggregators to find real insights in our database. Here we may want to look into why client 101 books much longer courses on average than the other clients, and see if we can learn something there to get the other clients to follow suit.
Another essential aggregator to know is COUNT. This lets us count the instances of a particular value in a table.
SELECT COUNT(*)FROM course;
Letβs make that more specific.
SELECT COUNT(*)FROM courseWHERE language = 'Eng';
But we can make this even more useful using GROUP BY.
SELECT language, COUNT(language)FROM courseGROUP BY language;
There is a lot more we can do with aggregating data in MySQL, but this is enough to get us started.
Things can get even more exciting when we start nesting queries within other queries. This is where SQL really shows its power. We will just go through a simple example here to demonstrate the principles, but with nesting queries within queries the possibilities for writing really complex and powerful queries are almost limitless.
Letβs take a look at our Teacher table.
If we want to identify the teachers who are younger than the average of our teachers (exactly what the average of a series of dates is a complicated question, but we will gloss over that for now). We can answer this with a nested query like so:
SELECT *FROM teacherWHERE dob > (SELECT AVG(dob) FROM teacher);
Whatβs happening here is that within our WHERE clause, we have placed another complete SQL query (in parentheses). This is what a nested query is, one complete query being used within another query.
This is a basic example, but hopefully the power and potential of this kind of query is apparent. This wonβt be our last nested query, so we will have more chances to see how this works later.
The whole benefit of a relational database is the way that the entities / tables are related to one another, allowing us to explore and analyse relationships between the various entities. Until this point, all of our queries have been on single tables. Thatβs all well and good, but weβre missing out on some of the main advantages of relational databases. Letβs remedy that by looking at the wonderful world of JOINs.
If you are familiar with other popular data analysis tools like pandas for Python or dplyr for R, then you are probably familiar with joins already. The concepts are exactly the same in MySQL, but the syntax is of course a little different (more capitalisation, for one thing).
To join any table to another, we need to have a column in both tables which contains the same data. In a relational database, this is the function of foreign keys (or for N-to-M relationships, the table which stores those relations), and these connections are what make relational databases such a powerful and efficient way of storing large amounts of data.
There are three types of JOINs in SQL β an INNER JOIN (in MySQL this is the default when only JOIN is used) and the two types of outer joins β LEFT JOIN and RIGHT JOIN. Weβll start with perhaps the most common, and the easiest to understand, the INNER JOIN, also known in SQL as just plain JOIN.
An INNER JOIN takes two tables and joins them based on a column they have in common. This allows us to exploit the relationships which exist between tables. Letβs look at an example to begin:
SELECT course.course_id, course.course_name, course.language, client.client_name, client.addressFROM courseJOIN clientON course.client = client.client_idWHERE course.in_school = FALSE;
Here we have selected columns from two different tables. In MySQL when we are dealing with multiple tables, it is necessary to identify the columns and the tables together. It is also good practice to do this in general, as it makes it clear to anyone reading your code exactly which columns are being referred to.
This is done using the table.column syntax seen above. In our query, we are selecting the course_id, course_name and language columns from the Course table, and the client_name and address columns from the Client table.
Then, as usual, we use the FROM statement to identify our first table (in this case, Course). So far, so good.
Things get interesting on the next couple of lines. First, we let MySQL know that we want to do a JOIN by using the JOIN keyword, followed by the second table (Client). We have to instruct MySQL about which table contains the data that is held in common β it is not possible to join two tables together where no data is shared.
To do this we use the ON keyword, followed by table1.column = table2.column where the columns identified are the columns which contain the data in common (typically the primary key of one table and the foreign key of another).
In our example, we also used the WHERE keyword to add a condition. We are just looking for the details of the courses and the addresses of the companies for courses which do not take place on the premises of the International Language School. This is useful information for our teachers to have so they know where they need to travel!
Perhaps we want to provide one of our teachers β for our example letβs choose Stefanie Martin β with the addresses for the classes she has to teach outside of the school. Using a join, this is simple:
SELECT course.course_id, course.course_name, course.language, client.client_name, client.addressFROM courseJOIN clientON course.client = client.client_idWHERE course.in_school = FALSE AND course.teacher = 2;
We can up the intensity even more by combining JOINs with nested queries to get even more specific insights from our database. What if we wanted to get the names of all the participants in classes taught by Niamh Murphy?
Using two joins and one nested query lets us get this information from our database in no time:
SELECT participant.first_name, participant.last_nameFROM participantJOIN takes_course ON takes_course.participant_id = participant.participant_id JOIN course ON takes_course.course_id = course.course_idWHERE takes_course.course_id = (SELECT takes_course.course_id WHERE course.teacher = 6);
Now things are getting serious! To deconstruct this and see whatβs happening in more complex SQL queries in general, it can be very helpful to work backwards (this can also be a helpful trick when constructing your own more complex queries). If we do that here we can see that we have a sub-query identifying the course_id where the teacher_id = 6 β Niamhβs ID number.
(SELECT takes_course.course_idWHERE course.teacher = 6)
The result of this, which will be the course_id values for all courses taught by Niamh, is used in the WHERE condition of our query. So the condition could be expressed in plain English as βwhere the course is taught by Niamh Murphyβ.
Because the output that we are looking for is the names of the participants, our end goal is to join the course table to the participants table. However, as the relationship between these tables is an N-to-M relation (a participant can take multiple courses, a course can be taken by multiple participants), we canβt simply use the foreign key relation which is typical of a 1-to-N relationship.
Instead, we need to join through the extra Takes_Course table we created to store the N-to-M relationship between the Course and Participant tables. Phew!
SELECT participant.first_name, participant.last_nameFROM participantJOIN takes_course ON takes_course.participant_id = participant.participant_idJOIN course ON takes_course.course_id = course.course_id
We join the Participant table to the Takes_Course table using the key participant_id, then immediately join that to the Course table using course_id. This is how we can extract information from these more complex relationships stored in our database.
This may seem complex and a little daunting at first, but if we spend some time thinking about it and take another look at our ERD, it makes sense that this is how we can unlock the data stored in this structure. The whole process is entirely logical, and driven purely by the code we put into our query.
A great way to understand this is to try and write our own queries. Look at the data and think βhow could we get that connection to come out of the databaseβ and try different combinations. This is always the best way to get used to a new technology, playing with it and seeing what happens. Plus itβs a fun time!
Now we have mastered the INNER JOIN, letβs take a look at the different kinds of OUTER JOINs available in MySQL. The differences between join types become clearer when we have some information that is not included in all tables. The ILS database is beautifully put together, but mostly contains complete data. Sadly that will not be the case in real life, and we need to know how to deal with that.
That means itβs time to add a new table to our database! Exciting times!
The management of the International Language School are carrying out some market research. They want to know which industries to target for new courses, and have consulted the business press and put together this summary table showing the projected outlook for some different industries.
Letβs compare this to our Client table.
When we compare the industry column in each table, we notice that there are some industries which appear in both tables (Retail, Logistics) and other entries which do not.
Before we go further, letβs add the Industry Prospects table to our database.
CREATE TABLE industry_prospects ( industry VARCHAR(20) PRIMARY KEY, outlook VARCHAR(20));INSERT INTO industry_prospects VALUES('Retail', 'Good'),('Hospitality', 'Poor'),('Logistics', 'Terrible'),('Tourism', 'Great'),('Events', 'Good');
To this point, we have been dealing with INNER JOINs. This type of join follows the Venn diagram below.
An INNER JOIN will return only values where there is a match in both tables, and will not return any records which only have a value in the column which the join is being performed ON in one table.
So performing an INNER JOIN on our Client and Industry Prospects tables using the below code will give us the entries where both tables have a matching entry.
SELECT client.client_name, client.industry, industry_prospects.outlookFROM clientJOIN industry_prospectsON client.industry = industry_prospects.industry;
As Retail and Logistics are included in both tables, we get only the entries which match, with no NULL values.
A LEFT JOIN will give us all of the values in the left table, and the matching values from the right table. Where there is no matching value on the right table, we will get NULL values in our output.
The code for a LEFT JOIN is identical to our INNER JOIN code, except that we replace JOIN with LEFT JOIN, like so:
SELECT client.client_name, client.industry, industry_prospects.outlookFROM clientLEFT JOIN industry_prospectsON client.industry = industry_prospects.industry;
Our output now includes every entry from the Client table (it comes first in our code, so it is the βleftβ table, but this is purely because of the way that we have chosen to order the tables). Where there is no corresponding entry in the Industry Prospects table, NULL values are returned.
The LEFT JOIN is good when we want to bring in data from another table, but donβt want to lose any of the data from our primary table. This can happen in a large number of real-life scenarios, and the LEFT JOIN is a staple of our data analysis toolbox.
The RIGHT JOIN is the mirror image of the LEFT JOIN, and is used much less frequently. Because the decision of which table is the left table and which is the right is entirely up to the person writing the query, data analysts and query writers tend to put the table that we want to keep all the data from on the left. There are still some situations where we need the RIGHT JOIN however, particularly in more complex queries where we are joining multiple tables.
For the sake of completeness letβs perform a RIGHT JOIN on our tables.
SELECT client.client_name, client.industry, industry_prospects.outlookFROM clientRIGHT JOIN industry_prospectsON client.industry = industry_prospects.industry;
Our output now includes all the entries from the Industry Prospects table, and the NULL values are now in the data from the Client table, as expected.
This is just the mirror image of the LEFT JOIN, and we could have retrieved the same output simply by swapping the order of clientand industry_prospectsin our code.
There is another type of join which is supported in some other flavours of SQL, the FULL OUTER JOIN. This combines the LEFT JOIN and the RIGHT JOIN and returns all entries from both tables, with NULL values where there is no match.
This is not supported in MySQL, so we wonβt look at it here. It can be simulated in MySQL relatively easily, which is (one presumes) why the developers have not chosen to include it. Itβs good for us to know about it in the event that we end up using another flavour of SQL. So now we know!
Wow! Weβve covered a lot of ground in this article, from learning the very basics of a SQL query to constructing gnarly nested queries featuring multiple joins. Hopefully the power of SQL for creating, reviewing, updating and deleting data in a database is clearer now than it was at the beginning.
Relational databases and SQL are some of the most widely used technologies for handling large data sets, and although they may not be as fashionable as the latest libraries in R or Python, for working Data Analysts they are an essential component, and extremely useful to understand.
The queries we have looked at here have gone from fairly basic to still-pretty-basic, but hopefully we can see how combining the different conditions and operators can let us produce truly awesome results. Go forth and use this new power responsibly!
This is the final article in my three part series on learning to create, update and interrogate your own fully-functional relational database using SQL with free open source software. We covered a lot of ground together, and I hope it has been useful for you.
Iβd love to hear your feedback, if you have any comments or questions then please contact me via my website craigdoesdata.de. If youβd like to keep up with my projects you can follow me here on Medium, keep up with me on GitHub or just visit my website.
Thanks for taking the time to join me, until next time!
|
[
{
"code": null,
"e": 512,
"s": 172,
"text": "This is part 3 of a 3-part series taking you through the process of designing, coding, implementing and querying a relational database using MySQL, starting from zero. See part 1 (Designing a Relational Database and Creating an Entity Relationship Diagram) here, and part 2 (Coding and Implementing a Relational Database using MySQL) here."
},
{
"code": null,
"e": 670,
"s": 512,
"text": "All the code and information for this tutorial can be found on the associated GitHub repository. I used Lucidchart to make the diagrams shown in the article."
},
{
"code": null,
"e": 1031,
"s": 670,
"text": "In parts 1 and 2 of this series, we have gone through the steps of designing our database, implementing it in MySQL and populating it with our data. Itβs a good idea to read those before going into this article, but the SQL code to get you caught up is all contained in the associated GitHub repository if you feel like skipping ahead to this analysis section."
},
{
"code": null,
"e": 1145,
"s": 1031,
"text": "We have designed and implemented a fully functioning relational database from scratch. Great stuff! But what now?"
},
{
"code": null,
"e": 1457,
"s": 1145,
"text": "If weβre working in a Data Analyst-type role, weβre going to want to start analysing that data. But first, we need to know how to get to it. This article will describe how to write queries in SQL (specifically MySQL) that will allow us to access the data and relationships that are locked away within our RDBMS."
},
{
"code": null,
"e": 1668,
"s": 1457,
"text": "We covered installing MySQL Community Server in part 2 of this series, so we should have a working instance of that running on our system. We will also once again be using PopSQLβs free plan to run our queries."
},
{
"code": null,
"e": 1729,
"s": 1668,
"text": "The primary form of a SQL query statement is something like:"
},
{
"code": null,
"e": 1772,
"s": 1729,
"text": "SELECT columns FROM table WHERE condition;"
},
{
"code": null,
"e": 1861,
"s": 1772,
"text": "For example, to select all of the columns from our Teacher table, we used the statement:"
},
{
"code": null,
"e": 1883,
"s": 1861,
"text": "SELECT *FROM teacher;"
},
{
"code": null,
"e": 2113,
"s": 1883,
"text": "In this case the asterisk character (*) means βall columnsβ. Weβre selecting the teacher table, and there is no condition attached, which means we will be selecting all columns and all records (i.e. all the data) from that table."
},
{
"code": null,
"e": 2214,
"s": 2113,
"text": "If we just want specific attributes from the table, we can name those instead of using the asterisk."
},
{
"code": null,
"e": 2249,
"s": 2214,
"text": "SELECT last_name, dobFROM teacher;"
},
{
"code": null,
"e": 2440,
"s": 2249,
"text": "In most cases, we wonβt want to select all of the records in a table, but will be looking for particular records that meet some condition. In these cases, we will need to use a WHERE clause."
},
{
"code": null,
"e": 2704,
"s": 2440,
"text": "Note that we will be using our WHERE clauses with SELECT statements in this article, but that the exact same syntax and operators will work with UPDATE, INSERT or DELETE statements as well. The WHERE clause is an essential aspect of all flavours of SQL to master."
},
{
"code": null,
"e": 2760,
"s": 2704,
"text": "The WHERE clause allows us to set a condition, such as:"
},
{
"code": null,
"e": 2803,
"s": 2760,
"text": "SELECT *FROM courseWHERE language = 'ENG';"
},
{
"code": null,
"e": 2897,
"s": 2803,
"text": "This will select all details from the course table for courses where the language in English."
},
{
"code": null,
"e": 2984,
"s": 2897,
"text": "Perhaps we want to order the results differently, then we can use ORDER BY to do that."
},
{
"code": null,
"e": 3046,
"s": 2984,
"text": "SELECT *FROM courseWHERE language = 'ENG'ORDER BY start_date;"
},
{
"code": null,
"e": 3160,
"s": 3046,
"text": "By default, MySQL orders in ascending order. If we want the results in descending order, we can add DESC like so:"
},
{
"code": null,
"e": 3227,
"s": 3160,
"text": "SELECT *FROM courseWHERE language = 'ENG'ORDER BY start_date DESC;"
},
{
"code": null,
"e": 3279,
"s": 3227,
"text": "We can also use ORDER BY in series, so we could do:"
},
{
"code": null,
"e": 3363,
"s": 3279,
"text": "SELECT *FROM courseWHERE language = 'ENG'ORDER BY start_date DESC, client, teacher;"
},
{
"code": null,
"e": 3468,
"s": 3363,
"text": "This would give us our results sorted by that hierarchy of attributes, in the order they were specified."
},
{
"code": null,
"e": 3708,
"s": 3468,
"text": "We can use AND and OR operators within WHERE clauses as well. If youβre familiar with any other programming languages youβll have most likely come across these logical operators before. In SQL they work exactly as you would expect them to."
},
{
"code": null,
"e": 3768,
"s": 3708,
"text": "SELECT *FROM courseWHERE language = 'ENG' AND level = 'C1';"
},
{
"code": null,
"e": 4041,
"s": 3768,
"text": "Using the AND operator excludes all results which donβt fit both conditions, so only courses in English at C1 level are shown β in the International Language School database, that gives us just one result. If we use OR in the same statement, we get some different results."
},
{
"code": null,
"e": 4100,
"s": 4041,
"text": "SELECT *FROM courseWHERE language = 'ENG' OR level = 'C1';"
},
{
"code": null,
"e": 4339,
"s": 4100,
"text": "Using the OR operator includes all records which satisfy either condition, so now we have all courses which are in English (as these satisfy the language = βEngβ condition) plus the one other course which is at C1 level, Advanced Russian."
},
{
"code": null,
"e": 4474,
"s": 4339,
"text": "We can also use the NOT operator before a condition, to exclude every record which meets that condition and include all other records."
},
{
"code": null,
"e": 4537,
"s": 4474,
"text": "SELECT *FROM courseWHERE NOT language = 'ENG' OR level = 'C1';"
},
{
"code": null,
"e": 4598,
"s": 4537,
"text": "This is very useful when we want to exclude certain records."
},
{
"code": null,
"e": 4741,
"s": 4598,
"text": "It is also possible to use other comparison operators in our WHERE clauses. This is the full list of comparison operators we can use in MySQL:"
},
{
"code": null,
"e": 4753,
"s": 4741,
"text": "Equal to: ="
},
{
"code": null,
"e": 4776,
"s": 4753,
"text": "Not equal to: <> or !="
},
{
"code": null,
"e": 4789,
"s": 4776,
"text": "Less than: <"
},
{
"code": null,
"e": 4815,
"s": 4789,
"text": "Less than or equal to: <="
},
{
"code": null,
"e": 4831,
"s": 4815,
"text": "Greater than: >"
},
{
"code": null,
"e": 4860,
"s": 4831,
"text": "Greater than or equal to: >="
},
{
"code": null,
"e": 5003,
"s": 4860,
"text": "This opens many possibilities to us. One very simple example would be to identify the names and contact info of all teachers born before 1990:"
},
{
"code": null,
"e": 5079,
"s": 5003,
"text": "SELECT first_name, last_name, phone_noFROM teacherWHERE dob < '1990-01-01';"
},
{
"code": null,
"e": 5257,
"s": 5079,
"text": "The BETWEEN operator allows us to select the records with a value that falls within a range. We can identify all courses which began in January 2020 by using the following code:"
},
{
"code": null,
"e": 5332,
"s": 5257,
"text": "SELECT *FROM courseWHERE start_date BETWEEN '2020-01-01' AND '2020-01-31';"
},
{
"code": null,
"e": 5495,
"s": 5332,
"text": "In our example, we are comparing dates, but BETWEEN can also be used to find any value (sales, order quantity, etc) that falls in a particular range. Very useful!"
},
{
"code": null,
"e": 5625,
"s": 5495,
"text": "The LIKE operator allows us to search for values which match a specified pattern. We can use two wildcards to build our patterns:"
},
{
"code": null,
"e": 5684,
"s": 5625,
"text": "%this wildcard stands for zero, one or multiple characters"
},
{
"code": null,
"e": 5732,
"s": 5684,
"text": "_this wildcard stands for exactly one character"
},
{
"code": null,
"e": 5975,
"s": 5732,
"text": "If youβre familiar with regular expressions then this will seem familiar to you, as SQL is basically implementing a simplified version of those. This allows us to build patterns and get our RDBMS to find the records which meet those patterns."
},
{
"code": null,
"e": 6001,
"s": 5975,
"text": "Letβs look at an example:"
},
{
"code": null,
"e": 6065,
"s": 6001,
"text": "SELECT course_nameFROM courseWHERE course_name LIKE '%interm%';"
},
{
"code": null,
"e": 6275,
"s": 6065,
"text": "By using the % wildcard at the beginning and end of our pattern we instructed MySQL to identify the character sequence βintermβ anywhere it occurred in the course_name attribute. This is a very useful feature."
},
{
"code": null,
"e": 6420,
"s": 6275,
"text": "Our next operator is IN β this is effectively shorthand for many OR conditions, allowing us to give MySQL a list of values we would like to use."
},
{
"code": null,
"e": 6518,
"s": 6420,
"text": "SELECT first_name, last_nameFROM participantWHERE last_name IN ('Garcia', 'Nowak', 'Mustermann');"
},
{
"code": null,
"e": 6594,
"s": 6518,
"text": "The output here is identical to the output we would receive from the query:"
},
{
"code": null,
"e": 6717,
"s": 6594,
"text": "SELECT first_name, last_nameFROM participantWHERE last_name = 'Garcia' OR last_name = 'Nowak' OR last_name = 'Mustermann';"
},
{
"code": null,
"e": 6875,
"s": 6717,
"text": "The benefit is that we donβt have to write out the column name repeatedly. This is extremely beneficial when we have a lot of values to include in our query."
},
{
"code": null,
"e": 7210,
"s": 6875,
"text": "The final operator we will discuss in this section is IS NULL, along with its negative cousin IS NOT NULL. This allows us to identify records where a particular attribute (or set of attributes) is NULL. This could be useful to update them with some other value, to exclude them from a data set, or for a wide variety of other reasons."
},
{
"code": null,
"e": 7298,
"s": 7210,
"text": "In our database, we can use this to identify teachers who βonlyβ teach in one language:"
},
{
"code": null,
"e": 7345,
"s": 7298,
"text": "SELECT * FROM teacherWHERE language_2 IS NULL;"
},
{
"code": null,
"e": 7432,
"s": 7345,
"text": "Alternatively, we can use IS NOT NULL to find the teachers who teach in two languages:"
},
{
"code": null,
"e": 7483,
"s": 7432,
"text": "SELECT * FROM teacherWHERE language_2 IS NOT NULL;"
},
{
"code": null,
"e": 7704,
"s": 7483,
"text": "Sometimes the data in our database is stored with attribute names which may be confusing for the audience of our reports, or is just formatted in an unattractive way. We can fix this at the query stage by using aliasing."
},
{
"code": null,
"e": 7816,
"s": 7704,
"text": "Here we use the AS keyword to instruct MySQL to display a particular column with a temporary name. For example:"
},
{
"code": null,
"e": 7937,
"s": 7816,
"text": "SELECT course_name AS 'Course Name', course_length_weeks AS 'Length of Course (Weeks)'FROM courseWHERE language = 'DEU';"
},
{
"code": null,
"e": 8158,
"s": 7937,
"text": "This can be useful when we are preparing reports for other stakeholders and want to make things prettier, or when a column has a name which may be confusing in the context of our particular query, among other situations."
},
{
"code": null,
"e": 8396,
"s": 8158,
"text": "When performing data analysis, itβs also important to be able to aggregate our data. MySQL provides many ways of doing this, and we will not cover them all here. There is a comprehensive list here, for those who would like to dig deeper."
},
{
"code": null,
"e": 8609,
"s": 8396,
"text": "One of the most common aggregations we will want to perform is finding an average. In MySQL we do this with the AVG() aggregator. If we want to know the average length of a course, we can use the following query:"
},
{
"code": null,
"e": 8653,
"s": 8609,
"text": "SELECT AVG(course_length_weeks)FROM course;"
},
{
"code": null,
"e": 8847,
"s": 8653,
"text": "When using aggregators, it is very common to use these in combination with the GROUP BY statement. This can help us to move beyond the basics and find really useful information in our database."
},
{
"code": null,
"e": 8914,
"s": 8847,
"text": "SELECT client, AVG(course_length_weeks)FROM courseGROUP BY client;"
},
{
"code": null,
"e": 9210,
"s": 8914,
"text": "You can see how we can use GROUP BY alongside some of the aggregators to find real insights in our database. Here we may want to look into why client 101 books much longer courses on average than the other clients, and see if we can learn something there to get the other clients to follow suit."
},
{
"code": null,
"e": 9324,
"s": 9210,
"text": "Another essential aggregator to know is COUNT. This lets us count the instances of a particular value in a table."
},
{
"code": null,
"e": 9352,
"s": 9324,
"text": "SELECT COUNT(*)FROM course;"
},
{
"code": null,
"e": 9383,
"s": 9352,
"text": "Letβs make that more specific."
},
{
"code": null,
"e": 9433,
"s": 9383,
"text": "SELECT COUNT(*)FROM courseWHERE language = 'Eng';"
},
{
"code": null,
"e": 9487,
"s": 9433,
"text": "But we can make this even more useful using GROUP BY."
},
{
"code": null,
"e": 9549,
"s": 9487,
"text": "SELECT language, COUNT(language)FROM courseGROUP BY language;"
},
{
"code": null,
"e": 9649,
"s": 9549,
"text": "There is a lot more we can do with aggregating data in MySQL, but this is enough to get us started."
},
{
"code": null,
"e": 9982,
"s": 9649,
"text": "Things can get even more exciting when we start nesting queries within other queries. This is where SQL really shows its power. We will just go through a simple example here to demonstrate the principles, but with nesting queries within queries the possibilities for writing really complex and powerful queries are almost limitless."
},
{
"code": null,
"e": 10022,
"s": 9982,
"text": "Letβs take a look at our Teacher table."
},
{
"code": null,
"e": 10267,
"s": 10022,
"text": "If we want to identify the teachers who are younger than the average of our teachers (exactly what the average of a series of dates is a complicated question, but we will gloss over that for now). We can answer this with a nested query like so:"
},
{
"code": null,
"e": 10338,
"s": 10267,
"text": "SELECT *FROM teacherWHERE dob > (SELECT AVG(dob) FROM teacher);"
},
{
"code": null,
"e": 10537,
"s": 10338,
"text": "Whatβs happening here is that within our WHERE clause, we have placed another complete SQL query (in parentheses). This is what a nested query is, one complete query being used within another query."
},
{
"code": null,
"e": 10730,
"s": 10537,
"text": "This is a basic example, but hopefully the power and potential of this kind of query is apparent. This wonβt be our last nested query, so we will have more chances to see how this works later."
},
{
"code": null,
"e": 11149,
"s": 10730,
"text": "The whole benefit of a relational database is the way that the entities / tables are related to one another, allowing us to explore and analyse relationships between the various entities. Until this point, all of our queries have been on single tables. Thatβs all well and good, but weβre missing out on some of the main advantages of relational databases. Letβs remedy that by looking at the wonderful world of JOINs."
},
{
"code": null,
"e": 11427,
"s": 11149,
"text": "If you are familiar with other popular data analysis tools like pandas for Python or dplyr for R, then you are probably familiar with joins already. The concepts are exactly the same in MySQL, but the syntax is of course a little different (more capitalisation, for one thing)."
},
{
"code": null,
"e": 11786,
"s": 11427,
"text": "To join any table to another, we need to have a column in both tables which contains the same data. In a relational database, this is the function of foreign keys (or for N-to-M relationships, the table which stores those relations), and these connections are what make relational databases such a powerful and efficient way of storing large amounts of data."
},
{
"code": null,
"e": 12082,
"s": 11786,
"text": "There are three types of JOINs in SQL β an INNER JOIN (in MySQL this is the default when only JOIN is used) and the two types of outer joins β LEFT JOIN and RIGHT JOIN. Weβll start with perhaps the most common, and the easiest to understand, the INNER JOIN, also known in SQL as just plain JOIN."
},
{
"code": null,
"e": 12274,
"s": 12082,
"text": "An INNER JOIN takes two tables and joins them based on a column they have in common. This allows us to exploit the relationships which exist between tables. Letβs look at an example to begin:"
},
{
"code": null,
"e": 12459,
"s": 12274,
"text": "SELECT course.course_id, course.course_name, course.language, client.client_name, client.addressFROM courseJOIN clientON course.client = client.client_idWHERE course.in_school = FALSE;"
},
{
"code": null,
"e": 12774,
"s": 12459,
"text": "Here we have selected columns from two different tables. In MySQL when we are dealing with multiple tables, it is necessary to identify the columns and the tables together. It is also good practice to do this in general, as it makes it clear to anyone reading your code exactly which columns are being referred to."
},
{
"code": null,
"e": 12994,
"s": 12774,
"text": "This is done using the table.column syntax seen above. In our query, we are selecting the course_id, course_name and language columns from the Course table, and the client_name and address columns from the Client table."
},
{
"code": null,
"e": 13105,
"s": 12994,
"text": "Then, as usual, we use the FROM statement to identify our first table (in this case, Course). So far, so good."
},
{
"code": null,
"e": 13433,
"s": 13105,
"text": "Things get interesting on the next couple of lines. First, we let MySQL know that we want to do a JOIN by using the JOIN keyword, followed by the second table (Client). We have to instruct MySQL about which table contains the data that is held in common β it is not possible to join two tables together where no data is shared."
},
{
"code": null,
"e": 13660,
"s": 13433,
"text": "To do this we use the ON keyword, followed by table1.column = table2.column where the columns identified are the columns which contain the data in common (typically the primary key of one table and the foreign key of another)."
},
{
"code": null,
"e": 13995,
"s": 13660,
"text": "In our example, we also used the WHERE keyword to add a condition. We are just looking for the details of the courses and the addresses of the companies for courses which do not take place on the premises of the International Language School. This is useful information for our teachers to have so they know where they need to travel!"
},
{
"code": null,
"e": 14196,
"s": 13995,
"text": "Perhaps we want to provide one of our teachers β for our example letβs choose Stefanie Martin β with the addresses for the classes she has to teach outside of the school. Using a join, this is simple:"
},
{
"code": null,
"e": 14404,
"s": 14196,
"text": "SELECT course.course_id, course.course_name, course.language, client.client_name, client.addressFROM courseJOIN clientON course.client = client.client_idWHERE course.in_school = FALSE AND course.teacher = 2;"
},
{
"code": null,
"e": 14625,
"s": 14404,
"text": "We can up the intensity even more by combining JOINs with nested queries to get even more specific insights from our database. What if we wanted to get the names of all the participants in classes taught by Niamh Murphy?"
},
{
"code": null,
"e": 14721,
"s": 14625,
"text": "Using two joins and one nested query lets us get this information from our database in no time:"
},
{
"code": null,
"e": 15020,
"s": 14721,
"text": "SELECT participant.first_name, participant.last_nameFROM participantJOIN takes_course ON takes_course.participant_id = participant.participant_id JOIN course ON takes_course.course_id = course.course_idWHERE takes_course.course_id = (SELECT takes_course.course_id WHERE course.teacher = 6);"
},
{
"code": null,
"e": 15389,
"s": 15020,
"text": "Now things are getting serious! To deconstruct this and see whatβs happening in more complex SQL queries in general, it can be very helpful to work backwards (this can also be a helpful trick when constructing your own more complex queries). If we do that here we can see that we have a sub-query identifying the course_id where the teacher_id = 6 β Niamhβs ID number."
},
{
"code": null,
"e": 15445,
"s": 15389,
"text": "(SELECT takes_course.course_idWHERE course.teacher = 6)"
},
{
"code": null,
"e": 15680,
"s": 15445,
"text": "The result of this, which will be the course_id values for all courses taught by Niamh, is used in the WHERE condition of our query. So the condition could be expressed in plain English as βwhere the course is taught by Niamh Murphyβ."
},
{
"code": null,
"e": 16076,
"s": 15680,
"text": "Because the output that we are looking for is the names of the participants, our end goal is to join the course table to the participants table. However, as the relationship between these tables is an N-to-M relation (a participant can take multiple courses, a course can be taken by multiple participants), we canβt simply use the foreign key relation which is typical of a 1-to-N relationship."
},
{
"code": null,
"e": 16231,
"s": 16076,
"text": "Instead, we need to join through the extra Takes_Course table we created to store the N-to-M relationship between the Course and Participant tables. Phew!"
},
{
"code": null,
"e": 16433,
"s": 16231,
"text": "SELECT participant.first_name, participant.last_nameFROM participantJOIN takes_course ON takes_course.participant_id = participant.participant_idJOIN course ON takes_course.course_id = course.course_id"
},
{
"code": null,
"e": 16684,
"s": 16433,
"text": "We join the Participant table to the Takes_Course table using the key participant_id, then immediately join that to the Course table using course_id. This is how we can extract information from these more complex relationships stored in our database."
},
{
"code": null,
"e": 16989,
"s": 16684,
"text": "This may seem complex and a little daunting at first, but if we spend some time thinking about it and take another look at our ERD, it makes sense that this is how we can unlock the data stored in this structure. The whole process is entirely logical, and driven purely by the code we put into our query."
},
{
"code": null,
"e": 17303,
"s": 16989,
"text": "A great way to understand this is to try and write our own queries. Look at the data and think βhow could we get that connection to come out of the databaseβ and try different combinations. This is always the best way to get used to a new technology, playing with it and seeing what happens. Plus itβs a fun time!"
},
{
"code": null,
"e": 17702,
"s": 17303,
"text": "Now we have mastered the INNER JOIN, letβs take a look at the different kinds of OUTER JOINs available in MySQL. The differences between join types become clearer when we have some information that is not included in all tables. The ILS database is beautifully put together, but mostly contains complete data. Sadly that will not be the case in real life, and we need to know how to deal with that."
},
{
"code": null,
"e": 17775,
"s": 17702,
"text": "That means itβs time to add a new table to our database! Exciting times!"
},
{
"code": null,
"e": 18063,
"s": 17775,
"text": "The management of the International Language School are carrying out some market research. They want to know which industries to target for new courses, and have consulted the business press and put together this summary table showing the projected outlook for some different industries."
},
{
"code": null,
"e": 18103,
"s": 18063,
"text": "Letβs compare this to our Client table."
},
{
"code": null,
"e": 18275,
"s": 18103,
"text": "When we compare the industry column in each table, we notice that there are some industries which appear in both tables (Retail, Logistics) and other entries which do not."
},
{
"code": null,
"e": 18353,
"s": 18275,
"text": "Before we go further, letβs add the Industry Prospects table to our database."
},
{
"code": null,
"e": 18591,
"s": 18353,
"text": "CREATE TABLE industry_prospects ( industry VARCHAR(20) PRIMARY KEY, outlook VARCHAR(20));INSERT INTO industry_prospects VALUES('Retail', 'Good'),('Hospitality', 'Poor'),('Logistics', 'Terrible'),('Tourism', 'Great'),('Events', 'Good');"
},
{
"code": null,
"e": 18695,
"s": 18591,
"text": "To this point, we have been dealing with INNER JOINs. This type of join follows the Venn diagram below."
},
{
"code": null,
"e": 18893,
"s": 18695,
"text": "An INNER JOIN will return only values where there is a match in both tables, and will not return any records which only have a value in the column which the join is being performed ON in one table."
},
{
"code": null,
"e": 19052,
"s": 18893,
"text": "So performing an INNER JOIN on our Client and Industry Prospects tables using the below code will give us the entries where both tables have a matching entry."
},
{
"code": null,
"e": 19206,
"s": 19052,
"text": "SELECT client.client_name, client.industry, industry_prospects.outlookFROM clientJOIN industry_prospectsON client.industry = industry_prospects.industry;"
},
{
"code": null,
"e": 19317,
"s": 19206,
"text": "As Retail and Logistics are included in both tables, we get only the entries which match, with no NULL values."
},
{
"code": null,
"e": 19517,
"s": 19317,
"text": "A LEFT JOIN will give us all of the values in the left table, and the matching values from the right table. Where there is no matching value on the right table, we will get NULL values in our output."
},
{
"code": null,
"e": 19632,
"s": 19517,
"text": "The code for a LEFT JOIN is identical to our INNER JOIN code, except that we replace JOIN with LEFT JOIN, like so:"
},
{
"code": null,
"e": 19791,
"s": 19632,
"text": "SELECT client.client_name, client.industry, industry_prospects.outlookFROM clientLEFT JOIN industry_prospectsON client.industry = industry_prospects.industry;"
},
{
"code": null,
"e": 20082,
"s": 19791,
"text": "Our output now includes every entry from the Client table (it comes first in our code, so it is the βleftβ table, but this is purely because of the way that we have chosen to order the tables). Where there is no corresponding entry in the Industry Prospects table, NULL values are returned."
},
{
"code": null,
"e": 20335,
"s": 20082,
"text": "The LEFT JOIN is good when we want to bring in data from another table, but donβt want to lose any of the data from our primary table. This can happen in a large number of real-life scenarios, and the LEFT JOIN is a staple of our data analysis toolbox."
},
{
"code": null,
"e": 20798,
"s": 20335,
"text": "The RIGHT JOIN is the mirror image of the LEFT JOIN, and is used much less frequently. Because the decision of which table is the left table and which is the right is entirely up to the person writing the query, data analysts and query writers tend to put the table that we want to keep all the data from on the left. There are still some situations where we need the RIGHT JOIN however, particularly in more complex queries where we are joining multiple tables."
},
{
"code": null,
"e": 20869,
"s": 20798,
"text": "For the sake of completeness letβs perform a RIGHT JOIN on our tables."
},
{
"code": null,
"e": 21029,
"s": 20869,
"text": "SELECT client.client_name, client.industry, industry_prospects.outlookFROM clientRIGHT JOIN industry_prospectsON client.industry = industry_prospects.industry;"
},
{
"code": null,
"e": 21180,
"s": 21029,
"text": "Our output now includes all the entries from the Industry Prospects table, and the NULL values are now in the data from the Client table, as expected."
},
{
"code": null,
"e": 21345,
"s": 21180,
"text": "This is just the mirror image of the LEFT JOIN, and we could have retrieved the same output simply by swapping the order of clientand industry_prospectsin our code."
},
{
"code": null,
"e": 21577,
"s": 21345,
"text": "There is another type of join which is supported in some other flavours of SQL, the FULL OUTER JOIN. This combines the LEFT JOIN and the RIGHT JOIN and returns all entries from both tables, with NULL values where there is no match."
},
{
"code": null,
"e": 21868,
"s": 21577,
"text": "This is not supported in MySQL, so we wonβt look at it here. It can be simulated in MySQL relatively easily, which is (one presumes) why the developers have not chosen to include it. Itβs good for us to know about it in the event that we end up using another flavour of SQL. So now we know!"
},
{
"code": null,
"e": 22167,
"s": 21868,
"text": "Wow! Weβve covered a lot of ground in this article, from learning the very basics of a SQL query to constructing gnarly nested queries featuring multiple joins. Hopefully the power of SQL for creating, reviewing, updating and deleting data in a database is clearer now than it was at the beginning."
},
{
"code": null,
"e": 22451,
"s": 22167,
"text": "Relational databases and SQL are some of the most widely used technologies for handling large data sets, and although they may not be as fashionable as the latest libraries in R or Python, for working Data Analysts they are an essential component, and extremely useful to understand."
},
{
"code": null,
"e": 22702,
"s": 22451,
"text": "The queries we have looked at here have gone from fairly basic to still-pretty-basic, but hopefully we can see how combining the different conditions and operators can let us produce truly awesome results. Go forth and use this new power responsibly!"
},
{
"code": null,
"e": 22962,
"s": 22702,
"text": "This is the final article in my three part series on learning to create, update and interrogate your own fully-functional relational database using SQL with free open source software. We covered a lot of ground together, and I hope it has been useful for you."
},
{
"code": null,
"e": 23216,
"s": 22962,
"text": "Iβd love to hear your feedback, if you have any comments or questions then please contact me via my website craigdoesdata.de. If youβd like to keep up with my projects you can follow me here on Medium, keep up with me on GitHub or just visit my website."
}
] |
Git - Quick Guide
|
Version Control System (VCS) is a software that helps software developers to work together and maintain a complete history of their work.
Listed below are the functions of a VCS β
Allows developers to work simultaneously.
Does not allow overwriting each otherβs changes.
Maintains a history of every version.
Following are the types of VCS β
Centralized version control system (CVCS).
Distributed/Decentralized version control system (DVCS).
In this chapter, we will concentrate only on distributed version control system and especially on Git. Git falls under distributed version control system.
Centralized version control system (CVCS) uses a central server to store all files and enables team collaboration. But the major drawback of CVCS is its single point of failure, i.e., failure of the central server. Unfortunately, if the central server goes down for an hour, then during that hour, no one can collaborate at all. And even in a worst case, if the disk of the central server gets corrupted and proper backup has not been taken, then you will lose the entire history of the project. Here, distributed version control system (DVCS) comes into picture.
DVCS clients not only check out the latest snapshot of the directory but they also fully mirror the repository. If the server goes down, then the repository from any client can be copied back to the server to restore it. Every checkout is a full backup of the repository. Git does not rely on the central server and that is why you can perform many operations when you are offline. You can commit changes, create branches, view logs, and perform other operations when you are offline. You require network connection only to publish your changes and take the latest changes.
Git is released under GPLβs open source license. It is available freely over the internet. You can use Git to manage property projects without paying a single penny. As it is an open source, you can download its source code and also perform changes according to your requirements.
As most of the operations are performed locally, it gives a huge benefit in terms of speed. Git does not rely on the central server; that is why, there is no need to interact with the remote server for every operation. The core part of Git is written in C, which avoids runtime overheads associated with other high-level languages. Though Git mirrors entire repository, the size of the data on the client side is small. This illustrates the efficiency of Git at compressing and storing data on the client side.
The chances of losing data are very rare when there are multiple copies of it. Data present on any client side mirrors the repository, hence it can be used in the event of a crash or disk corruption.
Git uses a common cryptographic hash function called secure hash function (SHA1), to name and identify objects within its database. Every file and commit is check-summed and retrieved by its checksum at the time of checkout. It implies that, it is impossible to change file, date, and commit message and any other data from the Git database without knowing Git.
In case of CVCS, the central server needs to be powerful enough to serve requests of the entire team. For smaller teams, it is not an issue, but as the team size grows, the hardware limitations of the server can be a performance bottleneck. In case of DVCS, developers donβt interact with the server unless they need to push or pull changes. All the heavy lifting happens on the client side, so the server hardware can be very simple indeed.
CVCS uses cheap copy mechanism, If we create a new branch, it will copy all the codes to the new branch, so it is time-consuming and not efficient. Also, deletion and merging of branches in CVCS is complicated and time-consuming. But branch management with Git is very simple. It takes only a few seconds to create, delete, and merge branches.
Every VCS tool provides a private workplace as a working copy. Developers make changes in their private workplace and after commit, these changes become a part of the repository. Git takes it one step further by providing them a private copy of the whole repository. Users can perform many operations with this repository such as add file, remove file, rename file, move file, commit changes, and many more.
The working directory is the place where files are checked out. In other CVCS, developers generally make modifications and commit their changes directly to the repository. But Git uses a different strategy. Git doesnβt track each and every modified file. Whenever you do commit an operation, Git looks for the files present in the staging area. Only those files present in the staging area are considered for commit and not all the modified files.
Let us see the basic workflow of Git.
Step 1 β You modify a file from the working directory.
Step 2 β You add these files to the staging area.
Step 3 β You perform commit operation that moves the files from the staging area. After push operation, it stores the changes permanently to the Git repository.
Suppose you modified two files, namely βsort.cβ and βsearch.cβ and you want two different commits for each operation. You can add one file in the staging area and do commit. After the first commit, repeat the same procedure for another file.
# First commit
[bash]$ git add sort.c
# adds file to the staging area
[bash]$ git commit βm βAdded sort operationβ
# Second commit
[bash]$ git add search.c
# adds file to the staging area
[bash]$ git commit βm βAdded search operationβ
Blob stands for Binary Large Object. Each version of a file is represented by blob. A blob holds the file data but doesnβt contain any metadata about the file. It is a binary file, and in Git database, it is named as SHA1 hash of that file. In Git, files are not addressed by names. Everything is content-addressed.
Tree is an object, which represents a directory. It holds blobs as well as other sub-directories. A tree is a binary file that stores references to blobs and trees which are also named as SHA1 hash of the tree object.
Commit holds the current state of the repository. A commit is also named by SHA1 hash. You can consider a commit object as a node of the linked list. Every commit object has a pointer to the parent commit object. From a given commit, you can traverse back by looking at the parent pointer to view the history of the commit. If a commit has multiple parent commits, then that particular commit has been created by merging two branches.
Branches are used to create another line of development. By default, Git has a master branch, which is same as trunk in Subversion. Usually, a branch is created to work on a new feature. Once the feature is completed, it is merged back with the master branch and we delete the branch. Every branch is referenced by HEAD, which points to the latest commit in the branch. Whenever you make a commit, HEAD is updated with the latest commit.
Tag assigns a meaningful name with a specific version in the repository. Tags are very similar to branches, but the difference is that tags are immutable. It means, tag is a branch, which nobody intends to modify. Once a tag is created for a particular commit, even if you create a new commit, it will not be updated. Usually, developers create tags for product releases.
Clone operation creates the instance of the repository. Clone operation not only checks out the working copy, but it also mirrors the complete repository. Users can perform many operations with this local repository. The only time networking gets involved is when the repository instances are being synchronized.
Pull operation copies the changes from a remote repository instance to a local one. The pull operation is used for synchronization between two repository instances. This is same as the update operation in Subversion.
Push operation copies changes from a local repository instance to a remote one. This is used to store the changes permanently into the Git repository. This is same as the commit operation in Subversion.
HEAD is a pointer, which always points to the latest commit in the branch. Whenever you make a commit, HEAD is updated with the latest commit. The heads of the branches are stored in .git/refs/heads/ directory.
[CentOS]$ ls -1 .git/refs/heads/
master
[CentOS]$ cat .git/refs/heads/master
570837e7d58fa4bccd86cb575d884502188b0c49
Revision represents the version of the source code. Revisions in Git are represented by commits. These commits are identified by SHA1 secure hashes.
URL represents the location of the Git repository. Git URL is stored in config file.
[tom@CentOS tom_repo]$ pwd
/home/tom/tom_repo
[tom@CentOS tom_repo]$ cat .git/config
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
[remote "origin"]
url = gituser@git.server.com:project.git
fetch = +refs/heads/*:refs/remotes/origin/*
Before you can use Git, you have to install and do some basic configuration changes. Below are the steps to install Git client on Ubuntu and Centos Linux.
If you are using Debian base GNU/Linux distribution, then apt-get command will do the needful.
[ubuntu ~]$ sudo apt-get install git-core
[sudo] password for ubuntu:
[ubuntu ~]$ git --version
git version 1.8.1.2
And if you are using RPM based GNU/Linux distribution, then use yum command as given.
[CentOS ~]$
su -
Password:
[CentOS ~]# yum -y install git-core
[CentOS ~]# git --version
git version 1.7.1
Git provides the git config tool, which allows you to set configuration variables. Git stores all global configurations in .gitconfig file, which is located in your home directory. To set these configuration values as global, add the --global option, and if you omit --global option, then your configurations are specific for the current Git repository.
You can also set up system wide configuration. Git stores these values in the /etc/gitconfig file, which contains the configuration for every user and repository on the system. To set these values, you must have the root rights and use the --system option.
When the above code is compiled and executed, it produces the following result β
This information is used by Git for each commit.
[jerry@CentOS project]$ git config --global user.name "Jerry Mouse"
This information is used by Git for each commit.
[jerry@CentOS project]$ git config --global user.email "jerry@tutorialspoint.com"
You pull the latest changes from a remote repository, and if these changes are divergent, then by default Git creates merge commits. We can avoid this via following settings.
jerry@CentOS project]$ git config --global branch.autosetuprebase always
The following commands enable color highlighting for Git in the console.
[jerry@CentOS project]$ git config --global color.ui true
[jerry@CentOS project]$ git config --global color.status auto
[jerry@CentOS project]$ git config --global color.branch auto
By default, Git uses the system default editor, which is taken from the VISUAL or EDITOR environment variable. We can configure a different one by using git config.
[jerry@CentOS project]$ git config --global core.editor vim
Git does not provide a default merge tool for integrating conflicting changes into your working tree. We can set default merge tool by enabling following settings.
[jerry@CentOS project]$ git config --global merge.tool vimdiff
To verify your Git settings of the local repository, use git config βlist command as given below.
[jerry@CentOS ~]$ git config --list
The above command will produce the following result.
user.name=Jerry Mouse
user.email=jerry@tutorialspoint.com
push.default=nothing
branch.autosetuprebase=always
color.ui=true
color.status=auto
color.branch=auto
core.editor=vim
merge.tool=vimdiff
In this chapter, we will discuss the life cycle of Git. In later chapters, we will cover the Git commands for each operation.
General workflow is as follows β
You clone the Git repository as a working copy.
You clone the Git repository as a working copy.
You modify the working copy by adding/editing files.
You modify the working copy by adding/editing files.
If necessary, you also update the working copy by taking other developer's changes.
If necessary, you also update the working copy by taking other developer's changes.
You review the changes before commit.
You review the changes before commit.
You commit changes. If everything is fine, then you push the changes to the repository.
You commit changes. If everything is fine, then you push the changes to the repository.
After committing, if you realize something is wrong, then you correct the last commit and push the changes to the repository.
After committing, if you realize something is wrong, then you correct the last commit and push the changes to the repository.
Shown below is the pictorial representation of the work-flow.
In this chapter, we will see how to create a remote Git repository; from now on, we will refer to it as Git Server. We need a Git server to allow team collaboration.
# add new group
[root@CentOS ~]# groupadd dev
# add new user
[root@CentOS ~]# useradd -G devs -d /home/gituser -m -s /bin/bash gituser
# change password
[root@CentOS ~]# passwd gituser
The above command will produce the following result.
Changing password for user gituser.
New password:
Retype new password:
passwd: all authentication token updated successfully.
Let us initialize a new repository by using init command followed by --bare option. It initializes the repository without a working directory. By convention, the bare repository must be named as .git.
[gituser@CentOS ~]$ pwd
/home/gituser
[gituser@CentOS ~]$ mkdir project.git
[gituser@CentOS ~]$ cd project.git/
[gituser@CentOS project.git]$ ls
[gituser@CentOS project.git]$ git --bare init
Initialized empty Git repository in /home/gituser-m/project.git/
[gituser@CentOS project.git]$ ls
branches config description HEAD hooks info objects refs
Let us walk through the process of configuring a Git server, ssh-keygen utility generates public/private RSA key pair, that we will use for user authentication.
Open a terminal and enter the following command and just press enter for each input. After successful completion, it will create a .ssh directory inside the home directory.
tom@CentOS ~]$ pwd
/home/tom
[tom@CentOS ~]$ ssh-keygen
The above command will produce the following result.
Generating public/private rsa key pair.
Enter file in which to save the key (/home/tom/.ssh/id_rsa): Press Enter Only
Created directory '/home/tom/.ssh'.
Enter passphrase (empty for no passphrase): ---------------> Press Enter Only
Enter same passphrase again: ------------------------------> Press Enter Only
Your identification has been saved in /home/tom/.ssh/id_rsa.
Your public key has been saved in /home/tom/.ssh/id_rsa.pub.
The key fingerprint is:
df:93:8c:a1:b8:b7:67:69:3a:1f:65:e8:0e:e9:25:a1 tom@CentOS
The key's randomart image is:
+--[ RSA 2048]----+
| |
| |
| |
|
.
|
| Soo |
| o*B. |
| E = *.= |
| oo==. . |
| ..+Oo
|
+-----------------+
ssh-keygen has generated two keys, first one is private (i.e., id_rsa) and the second one is public (i.e., id_rsa.pub).
Note: Never share your PRIVATE KEY with others.
Suppose there are two developers working on a project, namely Tom and Jerry. Both users have generated public keys. Let us see how to use these keys for authentication.
Tom added his public key to the server by using ssh-copy-id command as given below β
[tom@CentOS ~]$ pwd
/home/tom
[tom@CentOS ~]$ ssh-copy-id -i ~/.ssh/id_rsa.pub gituser@git.server.com
The above command will produce the following result.
gituser@git.server.com's password:
Now try logging into the machine, with "ssh 'gituser@git.server.com'", and check in:
.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.
Similarly, Jerry added his public key to the server by using ssh-copy-id command.
[jerry@CentOS ~]$ pwd
/home/jerry
[jerry@CentOS ~]$ ssh-copy-id -i ~/.ssh/id_rsa gituser@git.server.com
The above command will produce the following result.
gituser@git.server.com's password:
Now try logging into the machine, with "ssh 'gituser@git.server.com'", and check in:
.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.
We have created a bare repository on the server and allowed access for two users. From now on, Tom and Jerry can push their changes to the repository by adding it as a remote.
Git init command creates .git directory to store metadata about the repository every time it reads the configuration from the .git/config file.
Tom creates a new directory, adds README file, and commits his change as initial commit. After commit, he verifies the commit message by running the git log command.
[tom@CentOS ~]$ pwd
/home/tom
[tom@CentOS ~]$ mkdir tom_repo
[tom@CentOS ~]$ cd tom_repo/
[tom@CentOS tom_repo]$ git init
Initialized empty Git repository in /home/tom/tom_repo/.git/
[tom@CentOS tom_repo]$ echo 'TODO: Add contents for README' > README
[tom@CentOS tom_repo]$ git status -s
?? README
[tom@CentOS tom_repo]$ git add .
[tom@CentOS tom_repo]$ git status -s
A README
[tom@CentOS tom_repo]$ git commit -m 'Initial commit'
The above command will produce the following result.
[master (root-commit) 19ae206] Initial commit
1 files changed, 1 insertions(+), 0 deletions(-)
create mode 100644 README
Tom checks the log message by executing the git log command.
[tom@CentOS tom_repo]$ git log
The above command will produce the following result.
commit 19ae20683fc460db7d127cf201a1429523b0e319
Author: Tom Cat <tom@tutorialspoint.com>
Date: Wed Sep 11 07:32:56 2013 +0530
Initial commit
Tom committed his changes to the local repository. Now, itβs time to push the changes to the remote repository. But before that, we have to add the repository as a remote, this is a one-time operation. After this, he can safely push the changes to the remote repository.
Note β By default, Git pushes only to matching branches: For every branch that exists on the local side, the remote side is updated if a branch with the same name already exists there. In our tutorials, every time we push changes to the origin master branch, use appropriate branch name according to your requirement.
[tom@CentOS tom_repo]$ git remote add origin gituser@git.server.com:project.git
[tom@CentOS tom_repo]$ git push origin master
The above command will produce the following result.
Counting objects: 3, done.
Writing objects: 100% (3/3), 242 bytes, done.
Total 3 (delta 0), reused 0 (delta 0)
To gituser@git.server.com:project.git
* [new branch]
master β> master
Now, the changes are successfully committed to the remote repository.
We have a bare repository on the Git server and Tom also pushed his first version. Now, Jerry can view his changes. The Clone operation creates an instance of the remote repository.
Jerry creates a new directory in his home directory and performs the clone operation.
[jerry@CentOS ~]$ mkdir jerry_repo
[jerry@CentOS ~]$ cd jerry_repo/
[jerry@CentOS jerry_repo]$ git clone gituser@git.server.com:project.git
The above command will produce the following result.
Initialized empty Git repository in /home/jerry/jerry_repo/project/.git/
remote: Counting objects: 3, done.
Receiving objects: 100% (3/3), 241 bytes, done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Jerry changes the directory to new local repository and lists its directory contents.
[jerry@CentOS jerry_repo]$ cd project/
[jerry@CentOS jerry_repo]$ ls
README
Jerry clones the repository and decides to implement basic string operations. So he creates string.c file. After adding the contents, string.c will look like as follows β
#include <stdio.h>
int my_strlen(char *s)
{
char *p = s;
while (*p)
++p;
return (p - s);
}
int main(void)
{
int i;
char *s[] =
{
"Git tutorials",
"Tutorials Point"
};
for (i = 0; i < 2; ++i)
printf("string lenght of %s = %d\n", s[i], my_strlen(s[i]));
return 0;
}
He compiled and tested his code and everything is working fine. Now, he can safely add these changes to the repository.
Git add operation adds file to the staging area.
[jerry@CentOS project]$ git status -s
?? string
?? string.c
[jerry@CentOS project]$ git add string.c
Git is showing a question mark before file names. Obviously, these files are not a part of Git, and that is why Git does not know what to do with these files. That is why, Git is showing a question mark before file names.
Jerry has added the file to the stash area, git status command will show files present in the staging area.
[jerry@CentOS project]$ git status -s
A string.c
?? string
To commit the changes, he used the git commit command followed by βm option. If we omit βm option. Git will open a text editor where we can write multiline commit message.
[jerry@CentOS project]$ git commit -m 'Implemented my_strlen function'
The above command will produce the following result β
[master cbe1249] Implemented my_strlen function
1 files changed, 24 insertions(+), 0 deletions(-)
create mode 100644 string.c
After commit to view log details, he runs the git log command. It will display the information of all the commits with their commit ID, commit author, commit date and SHA-1 hash of commit.
[jerry@CentOS project]$ git log
The above command will produce the following result β
commit cbe1249b140dad24b2c35b15cc7e26a6f02d2277
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 08:05:26 2013 +0530
Implemented my_strlen function
commit 19ae20683fc460db7d127cf201a1429523b0e319
Author: Tom Cat <tom@tutorialspoint.com>
Date: Wed Sep 11 07:32:56 2013 +0530
Initial commit
After viewing the commit details, Jerry realizes that the string length cannot be negative, thatβs why he decides to change the return type of my_strlen function.
Jerry uses the git log command to view log details.
[jerry@CentOS project]$ git log
The above command will produce the following result.
commit cbe1249b140dad24b2c35b15cc7e26a6f02d2277
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 08:05:26 2013 +0530
Implemented my_strlen function
Jerry uses the git show command to view the commit details. The git show command takes SHA-1 commit ID as a parameter.
[jerry@CentOS project]$ git show cbe1249b140dad24b2c35b15cc7e26a6f02d2277
The above command will produce the following result β
commit cbe1249b140dad24b2c35b15cc7e26a6f02d2277
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 08:05:26 2013 +0530
Implemented my_strlen function
diff --git a/string.c b/string.c
new file mode 100644
index 0000000..187afb9
--- /dev/null
+++ b/string.c
@@ -0,0 +1,24 @@
+#include <stdio.h>
+
+int my_strlen(char *s)
+{
+
char *p = s;
+
+
while (*p)
+ ++p;
+ return (p -s );
+
}
+
He changes the return type of the function from int to size_t. After testing the code, he reviews his changes by running the git diff command.
[jerry@CentOS project]$ git diff
The above command will produce the following result β
diff --git a/string.c b/string.c
index 187afb9..7da2992 100644
--- a/string.c
+++ b/string.c
@@ -1,6 +1,6 @@
#include <stdio.h>
-int my_strlen(char *s)
+size_t my_strlen(char *s)
{
char *p = s;
@@ -18,7 +18,7 @@ int main(void)
};
for (i = 0; i < 2; ++i)
{
- printf("string lenght of %s = %d\n", s[i], my_strlen(s[i]));
+ printf("string lenght of %s = %lu\n", s[i], my_strlen(s[i]));
return 0;
}
Git diff shows '+' sign before lines, which are newly added and 'β' for deleted lines.
Jerry has already committed the changes and he wants to correct his last commit. In this case, git amend operation will help. The amend operation changes the last commit including your commit message; it creates a new commit ID.
Before amend operation, he checks the commit log.
[jerry@CentOS project]$ git log
The above command will produce the following result.
commit cbe1249b140dad24b2c35b15cc7e26a6f02d2277
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 08:05:26 2013 +0530
Implemented my_strlen function
commit 19ae20683fc460db7d127cf201a1429523b0e319
Author: Tom Cat <tom@tutorialspoint.com>
Date: Wed Sep 11 07:32:56 2013 +0530
Initial commit
Jerry commits the new changes with -- amend operation and views the commit log.
[jerry@CentOS project]$ git status -s
M string.c
?? string
[jerry@CentOS project]$ git add string.c
[jerry@CentOS project]$ git status -s
M string.c
?? string
[jerry@CentOS project]$ git commit --amend -m 'Changed return type of my_strlen to size_t'
[master d1e19d3] Changed return type of my_strlen to size_t
1 files changed, 24 insertions(+), 0 deletions(-)
create mode 100644 string.c
Now, git log will show new commit message with new commit ID β
[jerry@CentOS project]$ git log
The above command will produce the following result.
commit d1e19d316224cddc437e3ed34ec3c931ad803958
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 08:05:26 2013 +0530
Changed return type of my_strlen to size_t
commit 19ae20683fc460db7d127cf201a1429523b0e319
Author: Tom Cat <tom@tutorialspoint.com>
Date: Wed Sep 11 07:32:56 2013 +0530
Initial commit
Jerry modified his last commit by using the amend operation and he is ready to push the changes. The Push operation stores data permanently to the Git repository. After a successful push operation, other developers can see Jerryβs changes.
He executes the git log command to view the commit details.
[jerry@CentOS project]$ git log
The above command will produce the following result:
commit d1e19d316224cddc437e3ed34ec3c931ad803958
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 08:05:26 2013 +0530
Changed return type of my_strlen to size_t
Before push operation, he wants to review his changes, so he uses the git show command to review his changes.
[jerry@CentOS project]$ git show d1e19d316224cddc437e3ed34ec3c931ad803958
The above command will produce the following result:
commit d1e19d316224cddc437e3ed34ec3c931ad803958
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 08:05:26 2013 +0530
Changed return type of my_strlen to size_t
diff --git a/string.c b/string.c
new file mode 100644
index 0000000..7da2992
--- /dev/null
+++ b/string.c
@@ -0,0 +1,24 @@
+#include <stdio.h>
+
+size_t my_strlen(char *s)
+
{
+
char *p = s;
+
+
while (*p)
+ ++p;
+ return (p -s );
+
}
+
+int main(void)
+
{
+ int i;
+ char *s[] =
{
+ "Git tutorials",
+ "Tutorials Point"
+
};
+
+
+
for (i = 0; i < 2; ++i)
printf("string lenght of %s = %lu\n", s[i], my_strlen(s[i]));
+
+
return 0;
+
}
Jerry is happy with his changes and he is ready to push his changes.
[jerry@CentOS project]$ git push origin master
The above command will produce the following result:
Counting objects: 4, done.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 517 bytes, done.
Total 3 (delta 0), reused 0 (delta 0)
To gituser@git.server.com:project.git
19ae206..d1e19d3 master β> master
Jerryβs changes have been successfully pushed to the repository; now other developers can view his changes by performing clone or update operation.
Tom performs the clone operation and finds a new file string.c. He wants to know who added this file to the repository and for what purpose, so, he executes the git log command.
[tom@CentOS ~]$ git clone gituser@git.server.com:project.git
The above command will produce the following result β
Initialized empty Git repository in /home/tom/project/.git/
remote: Counting objects: 6, done.
remote: Compressing objects: 100% (4/4), done.
Receiving objects: 100% (6/6), 726 bytes, done.
remote: Total 6 (delta 0), reused 0 (delta 0)
The Clone operation will create a new directory inside the current working directory. He changes the directory to newly created directory and executes the git log command.
[tom@CentOS ~]$ cd project/
[tom@CentOS project]$ git log
The above command will produce the following result β
commit d1e19d316224cddc437e3ed34ec3c931ad803958
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 08:05:26 2013 +0530
Changed return type of my_strlen to size_t
commit 19ae20683fc460db7d127cf201a1429523b0e319
Author: Tom Cat <tom@tutorialspoint.com>
Date: Wed Sep 11 07:32:56 2013 +0530
Initial commit
After observing the log, he realizes that the file string.c was added by Jerry to implement basic string operations. He is curious about Jerryβs code. So he opens string.c in text editor and immediately finds a bug. In my_strlen function, Jerry is not using a constant pointer. So, he decides to modify Jerryβs code. After modification, the code looks as follows β
[tom@CentOS project]$ git diff
The above command will produce the following result β
diff --git a/string.c b/string.c
index 7da2992..32489eb 100644
--- a/string.c
+++ b/string.c
@@ -1,8 +1,8 @@
#include <stdio.h>
-size_t my_strlen(char *s)
+size_t my_strlen(const char *s)
{
- char *p = s;
+ const char *p = s;
while (*p)
++p;
}
After testing, he commits his change.
[tom@CentOS project]$ git status -s
M string.c
?? string
[tom@CentOS project]$ git add string.c
[tom@CentOS project]$ git commit -m 'Changed char pointer to const char pointer'
[master cea2c00] Changed char pointer to const char pointer
1 files changed, 2 insertions(+), 2 deletions(-)
[tom@CentOS project]$ git log
The above command will produce the following result β
commit cea2c000f53ba99508c5959e3e12fff493b
Author: Tom Cat <tom@tutorialspoint.com>
Date: Wed Sep 11 08:32:07 2013 +0530
Changed char pointer to const char pointer
commit d1e19d316224cddc437e3ed34ec3c931ad803958
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 08:05:26 2013 +0530
Changed return type of my_strlen to size_t
commit 19ae20683fc460db7d127cf201a1429523b0e319
Author: Tom Cat <tom@tutorialspoint.com>
Date: Wed Sep 11 07:32:56 2013 +0530
Initial commit
Tom uses git push command to push his changes.
[tom@CentOS project]$ git push origin master
The above command will produce the following result β
Counting objects: 5, done.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 336 bytes, done.
Total 3 (delta 1), reused 0 (delta 0)
To gituser@git.server.com:project.git
d1e19d3..cea2c00 master β> master
Meanwhile, Jerry decides to implement string compare functionality. So he modifies string.c. After modification, the file looks as follows β
[jerry@CentOS project]$ git diff
The above command will produce the following result β
index 7da2992..bc864ed 100644
--- a/string.c
+++ b/string.c
30Git Tutorials
@@ -9,9 +9,20 @@ size_t my_strlen(char *s)
return (p -s );
}
+char *my_strcpy(char *t, char *s)
+
{
+
char *p = t;
+
+ while (*t++ = *s++)
+ ;
+
+
return p;
+
}
+
int main(void)
{
int i;
+
char p1[32];
char *s[] =
{
"Git tutorials",
"Tutorials Point"
@@ -20,5 +31,7 @@ int main(void)
for (i = 0; i < 2; ++i)
printf("string lenght of %s = %lu\n", s[i], my_strlen(s[i]));
+
printf("%s\n", my_strcpy(p1, "Hello, World !!!"));
+
return 0;
}
}
After testing, he is ready to push his change.
[jerry@CentOS project]$ git status -s
M string.c
?? string
[jerry@CentOS project]$ git add string.c
[jerry@CentOS project]$ git commit -m "Added my_strcpy function"
[master e944e5a] Added my_strcpy function
1 files changed, 13 insertions(+), 0 deletions(-)
Before push operation, he verifies commit by viewing log messages.
[jerry@CentOS project]$ git log
The above command will produce the following result β
commit e944e5aab74b26e7447d3281b225309e4e59efcd
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 08:41:42 2013 +0530
Added my_strcpy function
commit d1e19d316224cddc437e3ed34ec3c931ad803958
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 08:05:26 2013 +0530
Changed return type of my_strlen to size_t
commit 19ae20683fc460db7d127cf201a1429523b0e319
Author: Tom Cat <tom@tutorialspoint.com>
Date: Wed Sep 11 07:32:56 2013 +0530
Initial commit
Jerry is happy with the changes and he wants to push his changes.
[jerry@CentOS project]$ git push origin master
The above command will produce the following result β
To gituser@git.server.com:project.git
! [rejected]
master β> master (non-fast-forward)
error: failed to push some refs to 'gituser@git.server.com:project.git'
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes before pushing again. See the 'Note about
fast-forwards' section of 'git push --help' for details.
But Git is not allowing Jerry to push his changes. Because Git identified that remote repository and Jerryβs local repository are not in sync. Because of this, he can lose the history of the project. To avoid this mess, Git failed this operation. Now, Jerry has to first update the local repository and only thereafter, he can push his own changes.
Jerry executes the git pull command to synchronize his local repository with the remote one.
[jerry@CentOS project]$ git pull
The above command will produce the following result β
remote: Counting objects: 5, done.
remote: Compressing objects: 100% (3/3), done.
remote: Total 3 (delta 1), reused 0 (delta 0)
Unpacking objects: 100% (3/3), done.
From git.server.com:project
d1e19d3..cea2c00 master β> origin/master
First, rewinding head to replay your work on top of it...
Applying: Added my_strcpy function
After pull operation, Jerry checks the log messages and finds the details of Tomβs commit with commit ID cea2c000f53ba99508c5959e3e12fff493ba6f69
[jerry@CentOS project]$ git log
The above command will produce the following result β
commit e86f0621c2a3f68190bba633a9fe6c57c94f8e4f
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 08:41:42 2013 +0530
Added my_strcpy function
commit cea2c000f53ba99508c5959e3e12fff493ba6f69
Author: Tom Cat <tom@tutorialspoint.com>
Date: Wed Sep 11 08:32:07 2013 +0530
Changed char pointer to const char pointer
commit d1e19d316224cddc437e3ed34ec3c931ad803958
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 08:05:26 2013 +0530
Changed return type of my_strlen to size_t
commit 19ae20683fc460db7d127cf201a1429523b0e319
Author: Tom Cat <tom@tutorialspoint.com>
Date: Wed Sep 11 07:32:56 2013 +0530
Initial commit
Now, Jerryβs local repository is fully synchronized with the remote repository. So he can safely push his changes.
[jerry@CentOS project]$ git push origin master
The above command will produce the following result β
Counting objects: 5, done.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 455 bytes, done.
Total 3 (delta 1), reused 0 (delta 0)
To gituser@git.server.com:project.git
cea2c00..e86f062 master β> master
Suppose you are implementing a new feature for your product. Your code is in progress and suddenly a customer escalation comes. Because of this, you have to keep aside your new feature work for a few hours. You cannot commit your partial code and also cannot throw away your changes. So you need some temporary space, where you can store your partial changes and later on commit it.
In Git, the stash operation takes your modified tracked files, stages changes, and saves them on a stack of unfinished changes that you can reapply at any time.
[jerry@CentOS project]$ git status -s
M string.c
?? string
Now, you want to switch branches for customer escalation, but you donβt want to commit what youβve been working on yet; so youβll stash the changes. To push a new stash onto your stack, run the git stash command.
[jerry@CentOS project]$ git stash
Saved working directory and index state WIP on master: e86f062 Added my_strcpy function
HEAD is now at e86f062 Added my_strcpy function
Now, your working directory is clean and all the changes are saved on a stack. Let us verify it with the git status command.
[jerry@CentOS project]$ git status -s
?? string
Now you can safely switch the branch and work elsewhere. We can view a list of stashed changes by using the git stash list command.
[jerry@CentOS project]$ git stash list
stash@{0}: WIP on master: e86f062 Added my_strcpy function
Suppose you have resolved the customer escalation and you are back on your new feature looking for your half-done code, just execute the git stash pop command, to remove the changes from the stack and place them in the current working directory.
[jerry@CentOS project]$ git status -s
?? string
[jerry@CentOS project]$ git stash pop
The above command will produce the following result:
# On branch master
# Changed but not updated:
# (use "git add ..." to update what will be committed)
# (use "git checkout -- ..." to discard changes in working directory)
#
#
modified: string.c
#
# Untracked files:
# (use "git add ..." to include in what will be committed)
#
#
string
no changes added to commit (use "git add" and/or "git commit -a")
Dropped refs/stash@{0} (36f79dfedae4ac20e2e8558830154bd6315e72d4)
[jerry@CentOS project]$ git status -s
M string.c
?? string
As the name suggests, the move operation moves a directory or a file from one location to another. Tom decides to move the source code into src directory. The modified directory structure will appear as follows β
[tom@CentOS project]$ pwd
/home/tom/project
[tom@CentOS project]$ ls
README string string.c
[tom@CentOS project]$ mkdir src
[tom@CentOS project]$ git mv string.c src/
[tom@CentOS project]$ git status -s
R string.c β> src/string.c
?? string
To make these changes permanent, we have to push the modified directory structure to the remote repository so that other developers can see this.
[tom@CentOS project]$ git commit -m "Modified directory structure"
[master 7d9ea97] Modified directory structure
1 files changed, 0 insertions(+), 0 deletions(-)
rename string.c => src/string.c (100%)
[tom@CentOS project]$ git push origin master
Counting objects: 4, done.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 320 bytes, done.
Total 3 (delta 0), reused 0 (delta 0)
To gituser@git.server.com:project.git
e86f062..7d9ea97 master β> master
In Jerryβs local repository, before the pull operation, it will show the old directory structure.
[jerry@CentOS project]$ pwd
/home/jerry/jerry_repo/project
[jerry@CentOS project]$ ls
README string string.c
But after the pull operation, the directory structure will get updated. Now, Jerry can see the src directory and the file present inside that directory.
[jerry@CentOS project]$ git pull
remote: Counting objects: 4, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (3/3), done.
From git.server.com:project
e86f062..7d9ea97 master β> origin/master
First, rewinding head to replay your work on top of it...
Fast-forwarded master to 7d9ea97683da90bcdb87c28ec9b4f64160673c8a.
[jerry@CentOS project]$ ls
README src string
[jerry@CentOS project]$ ls src/
string.c
Till now, both Tom and Jerry were using manual commands to compile their project. Now, Jerry decides to create Makefile for their project and also give a proper name to the file βstring.cβ.
[jerry@CentOS project]$ pwd
/home/jerry/jerry_repo/project
[jerry@CentOS project]$ ls
README src
[jerry@CentOS project]$ cd src/
[jerry@CentOS src]$ git add Makefile
[jerry@CentOS src]$ git mv string.c string_operations.c
[jerry@CentOS src]$ git status -s
A Makefile
R string.c β> string_operations.c
Git is showing R before file name to indicate that the file has been renamed.
For commit operation, Jerry used -a flag, that makes git commit automatically detect the modified files.
[jerry@CentOS src]$ git commit -a -m 'Added Makefile and renamed strings.c to
string_operations.c '
[master 94f7b26] Added Makefile and renamed strings.c to string_operations.c
1 files changed, 0 insertions(+), 0 deletions(-)
create mode 100644 src/Makefile
rename src/{string.c => string_operations.c} (100%)
After commit, he pushes his changes to the repository.
[jerry@CentOS src]$ git push origin master
The above command will produce the following result β
Counting objects: 6, done.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (4/4), 396 bytes, done.
Total 4 (delta 0), reused 0 (delta 0)
To gituser@git.server.com:project.git
7d9ea97..94f7b26 master β> master
Now, other developers can view these modifications by updating their local repository.
Tom updates his local repository and finds the compiled binary in the src directory. After viewing the commit message, he realizes that the compiled binary was added by Jerry.
[tom@CentOS src]$ pwd
/home/tom/project/src
[tom@CentOS src]$ ls
Makefile string_operations string_operations.c
[tom@CentOS src]$ file string_operations
string_operations: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses
shared libs), for GNU/Linux 2.6.18, not stripped
[tom@CentOS src]$ git log
commit 29af9d45947dc044e33d69b9141d8d2dad37cc62
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 10:16:25 2013 +0530
Added compiled binary
VCS is used to store the source code only and not executable binaries. So, Tom decides to remove this file from the repository. For further operation, he uses the git rm command.
[tom@CentOS src]$ ls
Makefile string_operations string_operations.c
[tom@CentOS src]$ git rm string_operations
rm 'src/string_operations'
[tom@CentOS src]$ git commit -a -m "Removed executable binary"
[master 5776472] Removed executable binary
1 files changed, 0 insertions(+), 0 deletions(-)
delete mode 100755 src/string_operations
After commit, he pushes his changes to the repository.
[tom@CentOS src]$ git push origin master
The above command will produce the following result.
Counting objects: 5, done.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 310 bytes, done.
Total 3 (delta 1), reused 0 (delta 0)
To gituser@git.server.com:project.git
29af9d4..5776472 master β> master
To err is human. So every VCS provides a feature to fix mistakes until a certain point. Git provides a feature that we can use to undo the modifications that have been made to the local repository.
Suppose the user accidentally does some changes to his local repository and then wants to undo these changes. In such cases, the revert operation plays an important role.
Let us suppose Jerry accidentally modifies a file from his local repository. But he wants to undo his modification. To handle this situation, we can use the git checkout command. We can use this command to revert the contents of a file.
[jerry@CentOS src]$ pwd
/home/jerry/jerry_repo/project/src
[jerry@CentOS src]$ git status -s
M string_operations.c
[jerry@CentOS src]$ git checkout string_operations.c
[jerry@CentOS src]$ git status βs
Further, we can use the git checkout command to obtain a deleted file from the local repository. Let us suppose Tom deletes a file from the local repository and we want this file back. We can achieve this by using the same command.
[tom@CentOS src]$ pwd
/home/tom/top_repo/project/src
[tom@CentOS src]$ ls -1
Makefile
string_operations.c
[tom@CentOS src]$ rm string_operations.c
[tom@CentOS src]$ ls -1
Makefile
[tom@CentOS src]$ git status -s
D string_operations.c
Git is showing the letter D before the filename. This indicates that the file has been deleted from the local repository.
[tom@CentOS src]$ git checkout string_operations.c
[tom@CentOS src]$ ls -1
Makefile
string_operations.c
[tom@CentOS src]$ git status -s
Note β We can perform all these operations before commit.
We have seen that when we perform an add operation, the files move from the local repository to the stating area. If a user accidently modifies a file and adds it into the staging area, he can revert his changes, by using the git checkout command.
In Git, there is one HEAD pointer that always points to the latest commit. If you want to undo a change from the staged area, then you can use the git checkout command, but with the checkout command, you have to provide an additional parameter, i.e., the HEAD pointer. The additional commit pointer parameter instructs the git checkout command to reset the working tree and also to remove the staged changes.
Let us suppose Tom modifies a file from his local repository. If we view the status of this file, it will show that the file was modified but not added into the staging area.
tom@CentOS src]$ pwd
/home/tom/top_repo/project/src
# Unmodified file
[tom@CentOS src]$ git status -s
# Modify file and view itβs status.
[tom@CentOS src]$ git status -s
M string_operations.c
[tom@CentOS src]$ git add string_operations.c
Git status shows that the file is present in the staging area, now revert it by using the git checkout command and view the status of the reverted file.
[tom@CentOS src]$ git checkout HEAD -- string_operations.c
[tom@CentOS src]$ git status -s
After doing few changes, you may decide to remove these changes. The Git reset command is used to reset or revert changes. We can perform three different types of reset operations.
Below diagram shows the pictorial representation of Git reset command.
Each branch has a HEAD pointer, which points to the latest commit. If we use Git reset command with --soft option followed by commit ID, then it will reset the HEAD pointer only without destroying anything.
.git/refs/heads/master file stores the commit ID of the HEAD pointer. We can verify it by using the git log -1 command.
[jerry@CentOS project]$ cat .git/refs/heads/master
577647211ed44fe2ae479427a0668a4f12ed71a1
Now, view the latest commit ID, which will match with the above commit ID.
[jerry@CentOS project]$ git log -2
The above command will produce the following result.
commit 577647211ed44fe2ae479427a0668a4f12ed71a1
Author: Tom Cat <tom@tutorialspoint.com>
Date: Wed Sep 11 10:21:20 2013 +0530
Removed executable binary
commit 29af9d45947dc044e33d69b9141d8d2dad37cc62
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 10:16:25 2013 +0530
Added compiled binary
Let us reset the HEAD pointer.
[jerry@CentOS project]$ git reset --soft HEAD~
Now, we just reset the HEAD pointer back by one position. Let us check the contents of .git/refs/heads/master file.
[jerry@CentOS project]$ cat .git/refs/heads/master
29af9d45947dc044e33d69b9141d8d2dad37cc62
Commit ID from file is changed, now verify it by viewing commit messages.
jerry@CentOS project]$ git log -2
The above command will produce the following result.
commit 29af9d45947dc044e33d69b9141d8d2dad37cc62
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 10:16:25 2013 +0530
Added compiled binary
commit 94f7b26005f856f1a1b733ad438e97a0cd509c1a
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 10:08:01 2013 +0530
Added Makefile and renamed strings.c to string_operations.c
Git reset with --mixed option reverts those changes from the staging area that have not been committed yet. It reverts the changes from the staging area only. The actual changes made to the working copy of the file are unaffected. The default Git reset is equivalent to the git reset -- mixed.
If you use --hard option with the Git reset command, it will clear the staging area; it will reset the HEAD pointer to the latest commit of the specific commit ID and delete the local file changes too.
Let us check the commit ID.
[jerry@CentOS src]$ pwd
/home/jerry/jerry_repo/project/src
[jerry@CentOS src]$ git log -1
The above command will produce the following result.
commit 577647211ed44fe2ae479427a0668a4f12ed71a1
Author: Tom Cat <tom@tutorialspoint.com>
Date: Wed Sep 11 10:21:20 2013 +0530
Removed executable binary
Jerry modified a file by adding single-line comment at the start of file.
[jerry@CentOS src]$ head -2 string_operations.c
/* This line be removed by git reset operation */
#include <stdio.h>
He verified it by using the git status command.
[jerry@CentOS src]$ git status -s
M string_operations.c
Jerry adds the modified file to the staging area and verifies it with the git status command.
[jerry@CentOS src]$ git add string_operations.c
[jerry@CentOS src]$ git status
The above command will produce the following result.
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
#
modified: string_operations.c
#
Git status is showing that the file is present in the staging area. Now, reset HEAD with -- hard option.
[jerry@CentOS src]$ git reset --hard 577647211ed44fe2ae479427a0668a4f12ed71a1
HEAD is now at 5776472 Removed executable binary
Git reset command succeeded, which will revert the file from the staging area as well as remove any local changes made to the file.
[jerry@CentOS src]$ git status -s
Git status is showing that the file has been reverted from the staging area.
[jerry@CentOS src]$ head -2 string_operations.c
#include <stdio.h>
The head command also shows that the reset operation removed the local changes too.
Tag operation allows giving meaningful names to a specific version in the repository. Suppose Tom and Jerry decide to tag their project code so that they can later access it easily.
Let us tag the current HEAD by using the git tag command. Tom provides a tag name with -a option and provides a tag message with βm option.
tom@CentOS project]$ pwd
/home/tom/top_repo/project
[tom@CentOS project]$ git tag -a 'Release_1_0' -m 'Tagged basic string operation code' HEAD
If you want to tag a particular commit, then use the appropriate COMMIT ID instead of the HEAD pointer. Tom uses the following command to push the tag into the remote repository.
[tom@CentOS project]$ git push origin tag Release_1_0
The above command will produce the following result β
Counting objects: 1, done.
Writing objects: 100% (1/1), 183 bytes, done.
Total 1 (delta 0), reused 0 (delta 0)
To gituser@git.server.com:project.git
* [new tag]
Release_1_0 β> Release_1_0
Tom created tags. Now, Jerry can view all the available tags by using the Git tag command with βl option.
[jerry@CentOS src]$ pwd
/home/jerry/jerry_repo/project/src
[jerry@CentOS src]$ git pull
remote: Counting objects: 1, done.
remote: Total 1 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (1/1), done.
From git.server.com:project
* [new tag]
Release_1_0 β> Release_1_0
Current branch master is up to date.
[jerry@CentOS src]$ git tag -l
Release_1_0
Jerry uses the Git show command followed by its tag name to view more details about tag.
[jerry@CentOS src]$ git show Release_1_0
The above command will produce the following result β
tag Release_1_0
Tagger: Tom Cat <tom@tutorialspoint.com>
Date: Wed Sep 11 13:45:54 2013 +0530
Tagged basic string operation code
commit 577647211ed44fe2ae479427a0668a4f12ed71a1
Author: Tom Cat <tom@tutorialspoint.com>
Date: Wed Sep 11 10:21:20 2013 +0530
Removed executable binary
diff --git a/src/string_operations b/src/string_operations
deleted file mode 100755
index 654004b..0000000
Binary files a/src/string_operations and /dev/null differ
Tom uses the following command to delete tags from the local as well as the remote repository.
[tom@CentOS project]$ git tag
Release_1_0
[tom@CentOS project]$ git tag -d Release_1_0
Deleted tag 'Release_1_0' (was 0f81ff4)
# Remove tag from remote repository.
[tom@CentOS project]$ git push origin :Release_1_0
To gituser@git.server.com:project.git
- [deleted]
Release_1_0
Patch is a text file, whose contents are similar to Git diff, but along with code, it also has metadata about commits; e.g., commit ID, date, commit message, etc. We can create a patch from commits and other people can apply them to their repository.
Jerry implements the strcat function for his project. Jerry can create a path of his code and send it to Tom. Then, he can apply the received patch to his code.
Jerry uses the Git format-patch command to create a patch for the latest commit. If you want to create a patch for a specific commit, then use COMMIT_ID with the format-patch command.
[jerry@CentOS project]$ pwd
/home/jerry/jerry_repo/project/src
[jerry@CentOS src]$ git status -s
M string_operations.c
?? string_operations
[jerry@CentOS src]$ git add string_operations.c
[jerry@CentOS src]$ git commit -m "Added my_strcat function"
[master b4c7f09] Added my_strcat function
1 files changed, 13 insertions(+), 0 deletions(-)
[jerry@CentOS src]$ git format-patch -1
0001-Added-my_strcat-function.patch
The above command creates .patch files inside the current working directory. Tom can use this patch to modify his files. Git provides two commands to apply patches git amand git apply, respectively. Git apply modifies the local files without creating commit, while git am modifies the file and creates commit as well.
To apply patch and create commit, use the following command β
[tom@CentOS src]$ pwd
/home/tom/top_repo/project/src
[tom@CentOS src]$ git diff
[tom@CentOS src]$ git status βs
[tom@CentOS src]$ git apply 0001-Added-my_strcat-function.patch
[tom@CentOS src]$ git status -s
M string_operations.c
?? 0001-Added-my_strcat-function.patch
The patch gets applied successfully, now we can view the modifications by using the git diff command.
[tom@CentOS src]$ git diff
The above command will produce the following result β
diff --git a/src/string_operations.c b/src/string_operations.c
index 8ab7f42..f282fcf 100644
--- a/src/string_operations.c
+++ b/src/string_operations.c
@@ -1,5 +1,16 @@
#include <stdio.h>
+char *my_strcat(char *t, char *s)
diff --git a/src/string_operations.c b/src/string_operations.c
index 8ab7f42..f282fcf 100644
--- a/src/string_operations.c
+++ b/src/string_operations.c
@@ -1,5 +1,16 @@
#include <stdio.h>
+char *my_strcat(char *t, char *s)
+
{
+
char *p = t;
+
+
+
while (*p)
++p;
+
while (*p++ = *s++)
+ ;
+ return t;
+
}
+
size_t my_strlen(const char *s)
{
const char *p = s;
@@ -23,6 +34,7 @@ int main(void)
{
Branch operation allows creating another line of development. We can use this operation to fork off the development process into two different directions. For example, we released a product for 6.0 version and we might want to create a branch so that the development of 7.0 features can be kept separate from 6.0 bug fixes.
Tom creates a new branch using the git branch <branch name> command. We can create a new branch from an existing one. We can use a specific commit or tag as the starting point. If any specific commit ID is not provided, then the branch will be created with HEAD as its starting point.
[jerry@CentOS src]$ git branch new_branch
[jerry@CentOS src]$ git branch
* master
new_branch
A new branch is created; Tom used the git branch command to list the available branches. Git shows an asterisk mark before currently checked out branch.
The pictorial representation of create branch operation is shown below β
Jerry uses the git checkout command to switch between branches.
[jerry@CentOS src]$ git checkout new_branch
Switched to branch 'new_branch'
[jerry@CentOS src]$ git branch
master
* new_branch
In the above example, we have used two commands to create and switch branches, respectively. Git provides βb option with the checkout command; this operation creates a new branch and immediately switches to the new branch.
[jerry@CentOS src]$ git checkout -b test_branch
Switched to a new branch 'test_branch'
[jerry@CentOS src]$ git branch
master
new_branch
* test_branch
A branch can be deleted by providing βD option with git branch command. But before deleting the existing branch, switch to the other branch.
Jerry is currently on test_branch and he wants to remove that branch. So he switches branch and deletes branch as shown below.
[jerry@CentOS src]$ git branch
master
new_branch
* test_branch
[jerry@CentOS src]$ git checkout master
Switched to branch 'master'
[jerry@CentOS src]$ git branch -D test_branch
Deleted branch test_branch (was 5776472).
Now, Git will show only two branches.
[jerry@CentOS src]$ git branch
* master
new_branch
Jerry decides to add support for wide characters in his string operations project. He has already created a new branch, but the branch name is not appropriate. So he changes the branch name by using βm option followed by the old branch name and the new branch name.
[jerry@CentOS src]$ git branch
* master
new_branch
[jerry@CentOS src]$ git branch -m new_branch wchar_support
Now, the git branch command will show the new branch name.
[jerry@CentOS src]$ git branch
* master
wchar_support
Jerry implements a function to return the string length of wide character string. New the code will appear as follows β
[jerry@CentOS src]$ git branch
master
* wchar_support
[jerry@CentOS src]$ pwd
/home/jerry/jerry_repo/project/src
[jerry@CentOS src]$ git diff
The above command produces the following result β
t a/src/string_operations.c b/src/string_operations.c
index 8ab7f42..8fb4b00 100644
--- a/src/string_operations.c
+++ b/src/string_operations.c
@@ -1,4 +1,14 @@
#include <stdio.h>
+#include <wchar.h>
+
+size_t w_strlen(const wchar_t *s)
+
{
+
const wchar_t *p = s;
+
+
while (*p)
+ ++p;
+ return (p - s);
+
}
After testing, he commits and pushes his changes to the new branch.
[jerry@CentOS src]$ git status -s
M string_operations.c
?? string_operations
[jerry@CentOS src]$ git add string_operations.c
[jerry@CentOS src]$ git commit -m 'Added w_strlen function to return string lenght of wchar_t
string'
[wchar_support 64192f9] Added w_strlen function to return string lenght of wchar_t string
1 files changed, 10 insertions(+), 0 deletions(-)
Note that Jerry is pushing these changes to the new branch, which is why he used the branch name wchar_support instead of master branch.
[jerry@CentOS src]$ git push origin wchar_support <βββ Observer branch_name
The above command will produce the following result.
Counting objects: 7, done.
Compressing objects: 100% (4/4), done.
Writing objects: 100% (4/4), 507 bytes, done.
Total 4 (delta 1), reused 0 (delta 0)
To gituser@git.server.com:project.git
* [new branch]
wchar_support -> wchar_support
After committing the changes, the new branch will appear as follows β
Tom is curious about what Jerry is doing in his private branch and he checks the log from the wchar_support branch.
[tom@CentOS src]$ pwd
/home/tom/top_repo/project/src
[tom@CentOS src]$ git log origin/wchar_support -2
The above command will produce the following result.
commit 64192f91d7cc2bcdf3bf946dd33ece63b74184a3
Author: Jerry Mouse <jerry@tutorialspoint.com>
Date: Wed Sep 11 16:10:06 2013 +0530
Added w_strlen function to return string lenght of wchar_t string
commit 577647211ed44fe2ae479427a0668a4f12ed71a1
Author: Tom Cat <tom@tutorialspoint.com>
Date: Wed Sep 11 10:21:20 2013 +0530
Removed executable binary
By viewing commit messages, Tom realizes that Jerry implemented the strlen function for wide character and he wants the same functionality in the master branch. Instead of re-implementing, he decides to take Jerryβs code by merging his branch with the master branch.
[tom@CentOS project]$ git branch
* master
[tom@CentOS project]$ pwd
/home/tom/top_repo/project
[tom@CentOS project]$ git merge origin/wchar_support
Updating 5776472..64192f9
Fast-forward
src/string_operations.c | 10 ++++++++++
1 files changed, 10 insertions(+), 0 deletions(-)
After the merge operation, the master branch will appear as follows β
Now, the branch wchar_support has been merged with the master branch. We can verify it by viewing the commit message or by viewing the modifications done into the string_operation.c file.
[tom@CentOS project]$ cd src/
[tom@CentOS src]$ git log -1
commit 64192f91d7cc2bcdf3bf946dd33ece63b74184a3
Author: Jerry Mouse
Date: Wed Sep 11 16:10:06 2013 +0530
Added w_strlen function to return string lenght of wchar_t string
[tom@CentOS src]$ head -12 string_operations.c
The above command will produce the following result.
#include <stdio.h>
#include <wchar.h>
size_t w_strlen(const wchar_t *s)
{
const wchar_t *p = s;
while (*p)
++p;
return (p - s);
}
After testing, he pushes his code changes to the master branch.
[tom@CentOS src]$ git push origin master
Total 0 (delta 0), reused 0 (delta 0)
To gituser@git.server.com:project.git
5776472..64192f9 master β> master
The Git rebase command is a branch merge command, but the difference is that it modifies the order of commits.
The Git merge command tries to put the commits from other branches on top of the HEAD of the current local branch. For example, your local branch has commits Aβ>Bβ>Cβ>D and the merge branch has commits Aβ>Bβ>Xβ>Y, then git merge will convert the current local branch to something like Aβ>Bβ>Cβ>Dβ>Xβ>Y
The Git rebase command tries to find out the common ancestor between the current local branch and the merge branch. It then pushes the commits to the local branch by modifying the order of commits in the current local branch. For example, if your local branch has commits Aβ>Bβ>Cβ>D and the merge branch has commits Aβ>Bβ>Xβ>Y, then Git rebase will convert the current local branch to something like Aβ>Bβ>Xβ>Yβ>Cβ>D.
When multiple developers work on a single remote repository, you cannot modify the order of the commits in the remote repository. In this situation, you can use rebase operation to put your local commits on top of the remote repository commits and you can push these changes.
Jerry is working on the wchar_support branch. He changes the name of the functions and after testing, he commits his changes.
[jerry@CentOS src]$ git branch
master
* wchar_support
[jerry@CentOS src]$ git diff
The above command produces the following result β
diff --git a/src/string_operations.c b/src/string_operations.c
index 8fb4b00..01ff4e0 100644
--- a/src/string_operations.c
+++ b/src/string_operations.c
@@ -1,7 +1,7 @@
#include <stdio.h>
#include <wchar.h>
-size_t w_strlen(const wchar_t *s)
+size_t my_wstrlen(const wchar_t *s)
{
const wchar_t *p = s;
After verifying the code he commits his changes.
[jerry@CentOS src]$ git status -s
M string_operations.c
[jerry@CentOS src]$ git add string_operations.c
[jerry@CentOS src]$ git commit -m 'Changed function name'
[wchar_support 3789fe8] Changed function name
1 files changed, 1 insertions(+), 1 deletions(-)
[jerry@CentOS src]$ git push origin wchar_support
The above command will produce the following result β
Counting objects: 7, done.
Compressing objects: 100% (4/4), done.
Writing objects: 100% (4/4), 409 bytes, done.
Total 4 (delta 1), reused 0 (delta 0)
To gituser@git.server.com:project.git
64192f9..3789fe8 wchar_support -> wchar_support
Meanwhile in the master branch, Tom also changes the name of the same function and pushes his changes to the master branch.
[tom@CentOS src]$ git branch
* master
[tom@CentOS src]$ git diff
The above command produces the following result β
diff --git a/src/string_operations.c b/src/string_operations.c
index 8fb4b00..52bec84 100644
--- a/src/string_operations.c
+++ b/src/string_operations.c
@@ -1,7 +1,8 @@
#include <stdio.h>
#include <wchar.h>
-size_t w_strlen(const wchar_t *s)
+/* wide character strlen fucntion */
+size_t my_wc_strlen(const wchar_t *s)
{
const wchar_t *p = s;
After verifying diff, he commits his changes.
[tom@CentOS src]$ git status -s
M string_operations.c
[tom@CentOS src]$ git add string_operations.c
[tom@CentOS src]$ git commit -m 'Changed function name from w_strlen to my_wc_strlen'
[master ad4b530] Changed function name from w_strlen to my_wc_strlen
1 files changed, 2 insertions(+), 1 deletions(-)
[tom@CentOS src]$ git push origin master
The above command will produce the following result β
Counting objects: 7, done.
Compressing objects: 100% (4/4), done.
Writing objects: 100% (4/4), 470 bytes, done.
Total 4 (delta 1), reused 0 (delta 0)
To gituser@git.server.com:project.git
64192f9..ad4b530 master -> master
On the wchar_support branch, Jerry implements strchr function for wide character string. After testing, he commits and pushes his changes to the wchar_support branch.
[jerry@CentOS src]$ git branch
master
* wchar_support
[jerry@CentOS src]$ git diff
The above command produces the following result β
diff --git a/src/string_operations.c b/src/string_operations.c
index 01ff4e0..163a779 100644
--- a/src/string_operations.c
+++ b/src/string_operations.c
@@ -1,6 +1,16 @@
#include <stdio.h>
#include <wchar.h>
+wchar_t *my_wstrchr(wchar_t *ws, wchar_t wc)
+
{
+
while (*ws)
{
+
if (*ws == wc)
+
return ws;
+
++ws;
+
}
+ return NULL;
+
}
+
size_t my_wstrlen(const wchar_t *s)
{
const wchar_t *p = s;
After verifying, he commits his changes.
[jerry@CentOS src]$ git status -s
M string_operations.c
[jerry@CentOS src]$ git add string_operations.c
[jerry@CentOS src]$ git commit -m 'Addded strchr function for wide character string'
[wchar_support 9d201a9] Addded strchr function for wide character string
1 files changed, 10 insertions(+), 0 deletions(-)
[jerry@CentOS src]$ git push origin wchar_support
The above command will produce the following result β
Counting objects: 7, done.
Compressing objects: 100% (4/4), done.
Writing objects: 100% (4/4), 516 bytes, done.
Total 4 (delta 1), reused 0 (delta 0)
To gituser@git.server.com:project.git
3789fe8..9d201a9 wchar_support -> wchar_support
Tom wants to see what Jerry is doing on his private branch so, he tries to pull the latest changes from the wchar_support branch, but Git aborts the operation with the following error message.
[tom@CentOS src]$ git pull origin wchar_support
The above command produces the following result β
remote: Counting objects: 11, done.
63Git Tutorials
remote: Compressing objects: 100% (8/8), done.
remote: Total 8 (delta 2), reused 0 (delta 0)
Unpacking objects: 100% (8/8), done.
From git.server.com:project
* branch
wchar_support -> FETCH_HEAD
Auto-merging src/string_operations.c
CONFLICT (content): Merge conflict in src/string_operations.c
Automatic merge failed; fix conflicts and then commit the result.
From the error message, it is clear that there is a conflict in src/string_operations.c . He runs the git diff command to view further details.
[tom@CentOS src]$ git diff
The above command produces the following result β
diff --cc src/string_operations.c
index 52bec84,163a779..0000000
--- a/src/string_operations.c
+++ b/src/string_operations.c
@@@ -1,8 -1,17 +1,22 @@@
#include <stdio.h>
#include <wchar.h>
++<<<<<<< HEAD
+/* wide character strlen fucntion */
+size_t my_wc_strlen(const wchar_t *s)
++=======
+ wchar_t *my_wstrchr(wchar_t *ws, wchar_t wc)
+
{
+
+
while (*ws)
{
if (*ws == wc)
+
return ws;
+
++ws;
+
}
+ return NULL;
+
}
+
+ size_t my_wstrlen(const wchar_t *s)
++>>>>>>>9d201a9c61bc4713f4095175f8954b642dae8f86
{
const wchar_t *p = s;
As both Tom and Jerry changed the name of the same function, Git is in a state of confusion and it asks the user to resolve the conflict manually.
Tom decides to keep the function name suggested by Jerry, but he keeps the comment added by him, as it is. After removing the conflict markers, git diff will look like this.
[tom@CentOS src]$ git diff
The above command produces the following result.
diff --cc src/string_operations.c
diff --cc src/string_operations.c
index 52bec84,163a779..0000000
--- a/src/string_operations.c
+++ b/src/string_operations.c
@@@ -1,8 -1,17 +1,18 @@@
#include <stdio.h>
#include <wchar.h>
+ wchar_t *my_wstrchr(wchar_t *ws, wchar_t wc)
+
{
+
while (*ws)
{
+
if (*ws == wc)
+
return ws;
+
++ws;
+
}
+ return NULL;
+
}
+
+/* wide character strlen fucntion */
- size_t my_wc_strlen(const wchar_t *s)
+ size_t my_wstrlen(const wchar_t *s)
{
const wchar_t *p = s;
As Tom has modified the files, he has to commit these changes first and thereafter, he can pull the changes.
[tom@CentOS src]$ git commit -a -m 'Resolved conflict'
[master 6b1ac36] Resolved conflict
[tom@CentOS src]$ git pull origin wchar_support.
Tom has resolved the conflict, now the pull operation will succeed.
GNU/Linux and Mac OS uses line-feed (LF), or new line as line ending character, while Windows uses line-feed and carriage-return (LFCR) combination to represent the line-ending character.
To avoid unnecessary commits because of these line-ending differences, we have to configure the Git client to write the same line ending to the Git repository.
For Windows system, we can configure the Git client to convert line endings to CRLF format while checking out, and convert them back to LF format during the commit operation. The following settings will do the needful.
[tom@CentOS project]$ git config --global core.autocrlf true
For GNU/Linux or Mac OS, we can configure the Git client to convert line endings from CRLF to LF while performing the checkout operation.
[tom@CentOS project]$ git config --global core.autocrlf input
GitHub is a web-based hosting service for software development projects that uses the Git revision control system. It also has their standard GUI application available for download (Windows, Mac, GNU/ Linux) directly from the service's website. But in this session, we will see only CLI part.
Go to github.com. If you already have the GitHub account, then login using that account or create a new one. Follow the steps from github.com website to create a new repository.
Tom decides to use the GitHub server. To start a new project, he creates a new directory and one file inside that.
[tom@CentOS]$ mkdir github_repo
[tom@CentOS]$ cd github_repo/
[tom@CentOS]$ vi hello.c
[tom@CentOS]$ make hello
cc hello.c -o hello
[tom@CentOS]$ ./hello
The above command will produce the following result:
Hello, World !!!
After verifying his code, he initializes the directory with the git init command and commits his changes locally.
[tom@CentOS]$ git init
Initialized empty Git repository in /home/tom/github_repo/.git/
[tom@CentOS]$ git status -s
?? hello
?? hello.c
[tom@CentOS]$ git add hello.c
[tom@CentOS]$ git status -s
A hello.c
?? hello
[tom@CentOS]$ git commit -m 'Initial commit'
After that, he adds the GitHub repository URL as a remote origin and pushes his changes to the remote repository.
[tom@CentOS]$ git remote add origin https://github.com/kangralkar/testing_repo.git
[tom@CentOS]$ git push -u origin master
Push operation will ask for GitHub user name and password. After successful authentication, the operation will succeed.
The above command will produce the following result:
Username for 'https://github.com': kangralkar
Password for 'https://kangralkar@github.com':
Counting objects: 3, done.
Writing objects: 100% (3/3), 214 bytes, done.
Total 3 (delta 0), reused 0 (delta 0)
To https://github.com/kangralkar/test_repo.git
* [new branch] master β> master
Branch master set up to track remote branch master from origin.
From now, Tom can push any changes to the GitHub repository. He can use all the commands discussed in this chapter with the GitHub repository.
Tom successfully pushed all his changes to the GitHub repository. Now, other developers can view these changes by performing clone operation or updating their local repository.
Jerry creates a new directory in his home directory and clones the GitHub repository by using the git clone command.
[jerry@CentOS]$ pwd
/home/jerry
[jerry@CentOS]$ mkdir jerry_repo
[jerry@CentOS]$ git clone https://github.com/kangralkar/test_repo.git
The above command produces the following result:
Cloning into 'test_repo'...
remote: Counting objects: 3, done.
remote: Total 3 (delta 0), reused 3 (delta 0)
Unpacking objects: 100% (3/3), done.
He verifies the directory contents by executing the ls command.
[jerry@CentOS]$ ls
test_repo
[jerry@CentOS]$ ls test_repo/
hello.c
251 Lectures
35.5 hours
Gowthami Swarna
23 Lectures
2 hours
Asif Hussain
15 Lectures
1.5 hours
Abhilash Nelson
125 Lectures
9 hours
John Shea
13 Lectures
2.5 hours
Raghu Pandey
13 Lectures
3 hours
Sebastian Sulinski
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2183,
"s": 2045,
"text": "Version Control System (VCS) is a software that helps software developers to work together and maintain a complete history of their work."
},
{
"code": null,
"e": 2225,
"s": 2183,
"text": "Listed below are the functions of a VCS β"
},
{
"code": null,
"e": 2267,
"s": 2225,
"text": "Allows developers to work simultaneously."
},
{
"code": null,
"e": 2316,
"s": 2267,
"text": "Does not allow overwriting each otherβs changes."
},
{
"code": null,
"e": 2354,
"s": 2316,
"text": "Maintains a history of every version."
},
{
"code": null,
"e": 2387,
"s": 2354,
"text": "Following are the types of VCS β"
},
{
"code": null,
"e": 2430,
"s": 2387,
"text": "Centralized version control system (CVCS)."
},
{
"code": null,
"e": 2487,
"s": 2430,
"text": "Distributed/Decentralized version control system (DVCS)."
},
{
"code": null,
"e": 2642,
"s": 2487,
"text": "In this chapter, we will concentrate only on distributed version control system and especially on Git. Git falls under distributed version control system."
},
{
"code": null,
"e": 3206,
"s": 2642,
"text": "Centralized version control system (CVCS) uses a central server to store all files and enables team collaboration. But the major drawback of CVCS is its single point of failure, i.e., failure of the central server. Unfortunately, if the central server goes down for an hour, then during that hour, no one can collaborate at all. And even in a worst case, if the disk of the central server gets corrupted and proper backup has not been taken, then you will lose the entire history of the project. Here, distributed version control system (DVCS) comes into picture."
},
{
"code": null,
"e": 3780,
"s": 3206,
"text": "DVCS clients not only check out the latest snapshot of the directory but they also fully mirror the repository. If the server goes down, then the repository from any client can be copied back to the server to restore it. Every checkout is a full backup of the repository. Git does not rely on the central server and that is why you can perform many operations when you are offline. You can commit changes, create branches, view logs, and perform other operations when you are offline. You require network connection only to publish your changes and take the latest changes."
},
{
"code": null,
"e": 4061,
"s": 3780,
"text": "Git is released under GPLβs open source license. It is available freely over the internet. You can use Git to manage property projects without paying a single penny. As it is an open source, you can download its source code and also perform changes according to your requirements."
},
{
"code": null,
"e": 4572,
"s": 4061,
"text": "As most of the operations are performed locally, it gives a huge benefit in terms of speed. Git does not rely on the central server; that is why, there is no need to interact with the remote server for every operation. The core part of Git is written in C, which avoids runtime overheads associated with other high-level languages. Though Git mirrors entire repository, the size of the data on the client side is small. This illustrates the efficiency of Git at compressing and storing data on the client side."
},
{
"code": null,
"e": 4772,
"s": 4572,
"text": "The chances of losing data are very rare when there are multiple copies of it. Data present on any client side mirrors the repository, hence it can be used in the event of a crash or disk corruption."
},
{
"code": null,
"e": 5134,
"s": 4772,
"text": "Git uses a common cryptographic hash function called secure hash function (SHA1), to name and identify objects within its database. Every file and commit is check-summed and retrieved by its checksum at the time of checkout. It implies that, it is impossible to change file, date, and commit message and any other data from the Git database without knowing Git."
},
{
"code": null,
"e": 5576,
"s": 5134,
"text": "In case of CVCS, the central server needs to be powerful enough to serve requests of the entire team. For smaller teams, it is not an issue, but as the team size grows, the hardware limitations of the server can be a performance bottleneck. In case of DVCS, developers donβt interact with the server unless they need to push or pull changes. All the heavy lifting happens on the client side, so the server hardware can be very simple indeed."
},
{
"code": null,
"e": 5920,
"s": 5576,
"text": "CVCS uses cheap copy mechanism, If we create a new branch, it will copy all the codes to the new branch, so it is time-consuming and not efficient. Also, deletion and merging of branches in CVCS is complicated and time-consuming. But branch management with Git is very simple. It takes only a few seconds to create, delete, and merge branches."
},
{
"code": null,
"e": 6328,
"s": 5920,
"text": "Every VCS tool provides a private workplace as a working copy. Developers make changes in their private workplace and after commit, these changes become a part of the repository. Git takes it one step further by providing them a private copy of the whole repository. Users can perform many operations with this repository such as add file, remove file, rename file, move file, commit changes, and many more."
},
{
"code": null,
"e": 6776,
"s": 6328,
"text": "The working directory is the place where files are checked out. In other CVCS, developers generally make modifications and commit their changes directly to the repository. But Git uses a different strategy. Git doesnβt track each and every modified file. Whenever you do commit an operation, Git looks for the files present in the staging area. Only those files present in the staging area are considered for commit and not all the modified files."
},
{
"code": null,
"e": 6814,
"s": 6776,
"text": "Let us see the basic workflow of Git."
},
{
"code": null,
"e": 6869,
"s": 6814,
"text": "Step 1 β You modify a file from the working directory."
},
{
"code": null,
"e": 6919,
"s": 6869,
"text": "Step 2 β You add these files to the staging area."
},
{
"code": null,
"e": 7080,
"s": 6919,
"text": "Step 3 β You perform commit operation that moves the files from the staging area. After push operation, it stores the changes permanently to the Git repository."
},
{
"code": null,
"e": 7322,
"s": 7080,
"text": "Suppose you modified two files, namely βsort.cβ and βsearch.cβ and you want two different commits for each operation. You can add one file in the staging area and do commit. After the first commit, repeat the same procedure for another file."
},
{
"code": null,
"e": 7561,
"s": 7322,
"text": "# First commit\n[bash]$ git add sort.c\n\n# adds file to the staging area\n[bash]$ git commit βm βAdded sort operationβ\n\n# Second commit\n[bash]$ git add search.c\n\n# adds file to the staging area\n[bash]$ git commit βm βAdded search operationβ\n"
},
{
"code": null,
"e": 7877,
"s": 7561,
"text": "Blob stands for Binary Large Object. Each version of a file is represented by blob. A blob holds the file data but doesnβt contain any metadata about the file. It is a binary file, and in Git database, it is named as SHA1 hash of that file. In Git, files are not addressed by names. Everything is content-addressed."
},
{
"code": null,
"e": 8095,
"s": 7877,
"text": "Tree is an object, which represents a directory. It holds blobs as well as other sub-directories. A tree is a binary file that stores references to blobs and trees which are also named as SHA1 hash of the tree object."
},
{
"code": null,
"e": 8530,
"s": 8095,
"text": "Commit holds the current state of the repository. A commit is also named by SHA1 hash. You can consider a commit object as a node of the linked list. Every commit object has a pointer to the parent commit object. From a given commit, you can traverse back by looking at the parent pointer to view the history of the commit. If a commit has multiple parent commits, then that particular commit has been created by merging two branches."
},
{
"code": null,
"e": 8969,
"s": 8530,
"text": "Branches are used to create another line of development. By default, Git has a master branch, which is same as trunk in Subversion. Usually, a branch is created to work on a new feature. Once the feature is completed, it is merged back with the master branch and we delete the branch. Every branch is referenced by HEAD, which points to the latest commit in the branch. Whenever you make a commit, HEAD is updated with the latest commit."
},
{
"code": null,
"e": 9341,
"s": 8969,
"text": "Tag assigns a meaningful name with a specific version in the repository. Tags are very similar to branches, but the difference is that tags are immutable. It means, tag is a branch, which nobody intends to modify. Once a tag is created for a particular commit, even if you create a new commit, it will not be updated. Usually, developers create tags for product releases."
},
{
"code": null,
"e": 9654,
"s": 9341,
"text": "Clone operation creates the instance of the repository. Clone operation not only checks out the working copy, but it also mirrors the complete repository. Users can perform many operations with this local repository. The only time networking gets involved is when the repository instances are being synchronized."
},
{
"code": null,
"e": 9871,
"s": 9654,
"text": "Pull operation copies the changes from a remote repository instance to a local one. The pull operation is used for synchronization between two repository instances. This is same as the update operation in Subversion."
},
{
"code": null,
"e": 10074,
"s": 9871,
"text": "Push operation copies changes from a local repository instance to a remote one. This is used to store the changes permanently into the Git repository. This is same as the commit operation in Subversion."
},
{
"code": null,
"e": 10285,
"s": 10074,
"text": "HEAD is a pointer, which always points to the latest commit in the branch. Whenever you make a commit, HEAD is updated with the latest commit. The heads of the branches are stored in .git/refs/heads/ directory."
},
{
"code": null,
"e": 10405,
"s": 10285,
"text": "[CentOS]$ ls -1 .git/refs/heads/\nmaster\n\n[CentOS]$ cat .git/refs/heads/master\n570837e7d58fa4bccd86cb575d884502188b0c49\n"
},
{
"code": null,
"e": 10554,
"s": 10405,
"text": "Revision represents the version of the source code. Revisions in Git are represented by commits. These commits are identified by SHA1 secure hashes."
},
{
"code": null,
"e": 10639,
"s": 10554,
"text": "URL represents the location of the Git repository. Git URL is stored in config file."
},
{
"code": null,
"e": 10917,
"s": 10639,
"text": "[tom@CentOS tom_repo]$ pwd\n/home/tom/tom_repo\n\n[tom@CentOS tom_repo]$ cat .git/config\n[core]\nrepositoryformatversion = 0\nfilemode = true\nbare = false\nlogallrefupdates = true\n[remote \"origin\"]\nurl = gituser@git.server.com:project.git\nfetch = +refs/heads/*:refs/remotes/origin/*\n"
},
{
"code": null,
"e": 11072,
"s": 10917,
"text": "Before you can use Git, you have to install and do some basic configuration changes. Below are the steps to install Git client on Ubuntu and Centos Linux."
},
{
"code": null,
"e": 11167,
"s": 11072,
"text": "If you are using Debian base GNU/Linux distribution, then apt-get command will do the needful."
},
{
"code": null,
"e": 11285,
"s": 11167,
"text": "[ubuntu ~]$ sudo apt-get install git-core\n[sudo] password for ubuntu:\n\n[ubuntu ~]$ git --version\ngit version 1.8.1.2\n"
},
{
"code": null,
"e": 11371,
"s": 11285,
"text": "And if you are using RPM based GNU/Linux distribution, then use yum command as given."
},
{
"code": null,
"e": 11481,
"s": 11371,
"text": "[CentOS ~]$\nsu -\nPassword:\n\n[CentOS ~]# yum -y install git-core\n\n[CentOS ~]# git --version\ngit version 1.7.1\n"
},
{
"code": null,
"e": 11835,
"s": 11481,
"text": "Git provides the git config tool, which allows you to set configuration variables. Git stores all global configurations in .gitconfig file, which is located in your home directory. To set these configuration values as global, add the --global option, and if you omit --global option, then your configurations are specific for the current Git repository."
},
{
"code": null,
"e": 12092,
"s": 11835,
"text": "You can also set up system wide configuration. Git stores these values in the /etc/gitconfig file, which contains the configuration for every user and repository on the system. To set these values, you must have the root rights and use the --system option."
},
{
"code": null,
"e": 12173,
"s": 12092,
"text": "When the above code is compiled and executed, it produces the following result β"
},
{
"code": null,
"e": 12222,
"s": 12173,
"text": "This information is used by Git for each commit."
},
{
"code": null,
"e": 12291,
"s": 12222,
"text": "[jerry@CentOS project]$ git config --global user.name \"Jerry Mouse\"\n"
},
{
"code": null,
"e": 12340,
"s": 12291,
"text": "This information is used by Git for each commit."
},
{
"code": null,
"e": 12423,
"s": 12340,
"text": "[jerry@CentOS project]$ git config --global user.email \"jerry@tutorialspoint.com\"\n"
},
{
"code": null,
"e": 12598,
"s": 12423,
"text": "You pull the latest changes from a remote repository, and if these changes are divergent, then by default Git creates merge commits. We can avoid this via following settings."
},
{
"code": null,
"e": 12672,
"s": 12598,
"text": "jerry@CentOS project]$ git config --global branch.autosetuprebase always\n"
},
{
"code": null,
"e": 12745,
"s": 12672,
"text": "The following commands enable color highlighting for Git in the console."
},
{
"code": null,
"e": 12930,
"s": 12745,
"text": "[jerry@CentOS project]$ git config --global color.ui true\n\n[jerry@CentOS project]$ git config --global color.status auto\n\n[jerry@CentOS project]$ git config --global color.branch auto\n"
},
{
"code": null,
"e": 13095,
"s": 12930,
"text": "By default, Git uses the system default editor, which is taken from the VISUAL or EDITOR environment variable. We can configure a different one by using git config."
},
{
"code": null,
"e": 13156,
"s": 13095,
"text": "[jerry@CentOS project]$ git config --global core.editor vim\n"
},
{
"code": null,
"e": 13320,
"s": 13156,
"text": "Git does not provide a default merge tool for integrating conflicting changes into your working tree. We can set default merge tool by enabling following settings."
},
{
"code": null,
"e": 13384,
"s": 13320,
"text": "[jerry@CentOS project]$ git config --global merge.tool vimdiff\n"
},
{
"code": null,
"e": 13482,
"s": 13384,
"text": "To verify your Git settings of the local repository, use git config βlist command as given below."
},
{
"code": null,
"e": 13519,
"s": 13482,
"text": "[jerry@CentOS ~]$ git config --list\n"
},
{
"code": null,
"e": 13572,
"s": 13519,
"text": "The above command will produce the following result."
},
{
"code": null,
"e": 13767,
"s": 13572,
"text": "user.name=Jerry Mouse\nuser.email=jerry@tutorialspoint.com\npush.default=nothing\nbranch.autosetuprebase=always\ncolor.ui=true\ncolor.status=auto\ncolor.branch=auto\ncore.editor=vim\nmerge.tool=vimdiff\n"
},
{
"code": null,
"e": 13893,
"s": 13767,
"text": "In this chapter, we will discuss the life cycle of Git. In later chapters, we will cover the Git commands for each operation."
},
{
"code": null,
"e": 13926,
"s": 13893,
"text": "General workflow is as follows β"
},
{
"code": null,
"e": 13974,
"s": 13926,
"text": "You clone the Git repository as a working copy."
},
{
"code": null,
"e": 14022,
"s": 13974,
"text": "You clone the Git repository as a working copy."
},
{
"code": null,
"e": 14075,
"s": 14022,
"text": "You modify the working copy by adding/editing files."
},
{
"code": null,
"e": 14128,
"s": 14075,
"text": "You modify the working copy by adding/editing files."
},
{
"code": null,
"e": 14212,
"s": 14128,
"text": "If necessary, you also update the working copy by taking other developer's changes."
},
{
"code": null,
"e": 14296,
"s": 14212,
"text": "If necessary, you also update the working copy by taking other developer's changes."
},
{
"code": null,
"e": 14334,
"s": 14296,
"text": "You review the changes before commit."
},
{
"code": null,
"e": 14372,
"s": 14334,
"text": "You review the changes before commit."
},
{
"code": null,
"e": 14460,
"s": 14372,
"text": "You commit changes. If everything is fine, then you push the changes to the repository."
},
{
"code": null,
"e": 14548,
"s": 14460,
"text": "You commit changes. If everything is fine, then you push the changes to the repository."
},
{
"code": null,
"e": 14674,
"s": 14548,
"text": "After committing, if you realize something is wrong, then you correct the last commit\tand push the changes to the repository."
},
{
"code": null,
"e": 14800,
"s": 14674,
"text": "After committing, if you realize something is wrong, then you correct the last commit\tand push the changes to the repository."
},
{
"code": null,
"e": 14862,
"s": 14800,
"text": "Shown below is the pictorial representation of the work-flow."
},
{
"code": null,
"e": 15028,
"s": 14862,
"text": "In this chapter, we will see how to create a remote Git repository; from now on, we will refer to it as Git Server. We need a Git server to allow team collaboration."
},
{
"code": null,
"e": 15216,
"s": 15028,
"text": "# add new group\n[root@CentOS ~]# groupadd dev\n\n# add new user\n[root@CentOS ~]# useradd -G devs -d /home/gituser -m -s /bin/bash gituser\n\n# change password\n[root@CentOS ~]# passwd gituser\n"
},
{
"code": null,
"e": 15269,
"s": 15216,
"text": "The above command will produce the following result."
},
{
"code": null,
"e": 15396,
"s": 15269,
"text": "Changing password for user gituser.\nNew password:\nRetype new password:\npasswd: all authentication token updated successfully.\n"
},
{
"code": null,
"e": 15597,
"s": 15396,
"text": "Let us initialize a new repository by using init command followed by --bare option. It initializes the repository without a working directory. By convention, the bare repository must be named as .git."
},
{
"code": null,
"e": 15949,
"s": 15597,
"text": "[gituser@CentOS ~]$ pwd\n/home/gituser\n\n[gituser@CentOS ~]$ mkdir project.git\n\n[gituser@CentOS ~]$ cd project.git/\n\n[gituser@CentOS project.git]$ ls\n\n[gituser@CentOS project.git]$ git --bare init\nInitialized empty Git repository in /home/gituser-m/project.git/\n\n[gituser@CentOS project.git]$ ls\nbranches config description HEAD hooks info objects refs\n"
},
{
"code": null,
"e": 16110,
"s": 15949,
"text": "Let us walk through the process of configuring a Git server, ssh-keygen utility generates public/private RSA key pair, that we will use for user authentication."
},
{
"code": null,
"e": 16283,
"s": 16110,
"text": "Open a terminal and enter the following command and just press enter for each input. After successful completion, it will create a .ssh directory inside the home directory."
},
{
"code": null,
"e": 16341,
"s": 16283,
"text": "tom@CentOS ~]$ pwd\n/home/tom\n\n[tom@CentOS ~]$ ssh-keygen\n"
},
{
"code": null,
"e": 16394,
"s": 16341,
"text": "The above command will produce the following result."
},
{
"code": null,
"e": 17049,
"s": 16394,
"text": "Generating public/private rsa key pair.\nEnter file in which to save the key (/home/tom/.ssh/id_rsa): Press Enter Only\nCreated directory '/home/tom/.ssh'.\nEnter passphrase (empty for no passphrase): ---------------> Press Enter Only\nEnter same passphrase again: ------------------------------> Press Enter Only\nYour identification has been saved in /home/tom/.ssh/id_rsa.\nYour public key has been saved in /home/tom/.ssh/id_rsa.pub.\nThe key fingerprint is:\ndf:93:8c:a1:b8:b7:67:69:3a:1f:65:e8:0e:e9:25:a1 tom@CentOS\nThe key's randomart image is:\n+--[ RSA 2048]----+\n| |\n| |\n| |\n|\n.\n|\n| Soo |\n| o*B. |\n| E = *.= |\n| oo==. . |\n| ..+Oo\n|\n+-----------------+\n"
},
{
"code": null,
"e": 17169,
"s": 17049,
"text": "ssh-keygen has generated two keys, first one is private (i.e., id_rsa) and the second one is public (i.e., id_rsa.pub)."
},
{
"code": null,
"e": 17217,
"s": 17169,
"text": "Note: Never share your PRIVATE KEY with others."
},
{
"code": null,
"e": 17386,
"s": 17217,
"text": "Suppose there are two developers working on a project, namely Tom and Jerry. Both users have generated public keys. Let us see how to use these keys for authentication."
},
{
"code": null,
"e": 17471,
"s": 17386,
"text": "Tom added his public key to the server by using ssh-copy-id command as given below β"
},
{
"code": null,
"e": 17575,
"s": 17471,
"text": "[tom@CentOS ~]$ pwd\n/home/tom\n\n[tom@CentOS ~]$ ssh-copy-id -i ~/.ssh/id_rsa.pub gituser@git.server.com\n"
},
{
"code": null,
"e": 17628,
"s": 17575,
"text": "The above command will produce the following result."
},
{
"code": null,
"e": 17839,
"s": 17628,
"text": "gituser@git.server.com's password:\nNow try logging into the machine, with \"ssh 'gituser@git.server.com'\", and check in:\n.ssh/authorized_keys\nto make sure we haven't added extra keys that you weren't expecting.\n"
},
{
"code": null,
"e": 17921,
"s": 17839,
"text": "Similarly, Jerry added his public key to the server by using ssh-copy-id command."
},
{
"code": null,
"e": 18027,
"s": 17921,
"text": "[jerry@CentOS ~]$ pwd\n/home/jerry\n\n[jerry@CentOS ~]$ ssh-copy-id -i ~/.ssh/id_rsa gituser@git.server.com\n"
},
{
"code": null,
"e": 18080,
"s": 18027,
"text": "The above command will produce the following result."
},
{
"code": null,
"e": 18291,
"s": 18080,
"text": "gituser@git.server.com's password:\nNow try logging into the machine, with \"ssh 'gituser@git.server.com'\", and check in:\n.ssh/authorized_keys\nto make sure we haven't added extra keys that you weren't expecting.\n"
},
{
"code": null,
"e": 18467,
"s": 18291,
"text": "We have created a bare repository on the server and allowed access for two users. From now on, Tom and Jerry can push their changes to the repository by adding it as a remote."
},
{
"code": null,
"e": 18611,
"s": 18467,
"text": "Git init command creates .git directory to store metadata about the repository every time it reads the configuration from the .git/config file."
},
{
"code": null,
"e": 18777,
"s": 18611,
"text": "Tom creates a new directory, adds README file, and commits his change as initial commit. After commit, he verifies the commit message by running the git log command."
},
{
"code": null,
"e": 19218,
"s": 18777,
"text": "[tom@CentOS ~]$ pwd\n/home/tom\n\n[tom@CentOS ~]$ mkdir tom_repo\n\n[tom@CentOS ~]$ cd tom_repo/\n\n[tom@CentOS tom_repo]$ git init\nInitialized empty Git repository in /home/tom/tom_repo/.git/\n\n[tom@CentOS tom_repo]$ echo 'TODO: Add contents for README' > README\n\n[tom@CentOS tom_repo]$ git status -s\n?? README\n\n[tom@CentOS tom_repo]$ git add .\n\n[tom@CentOS tom_repo]$ git status -s\nA README\n\n[tom@CentOS tom_repo]$ git commit -m 'Initial commit'\n"
},
{
"code": null,
"e": 19271,
"s": 19218,
"text": "The above command will produce the following result."
},
{
"code": null,
"e": 19393,
"s": 19271,
"text": "[master (root-commit) 19ae206] Initial commit\n1 files changed, 1 insertions(+), 0 deletions(-)\ncreate mode 100644 README\n"
},
{
"code": null,
"e": 19454,
"s": 19393,
"text": "Tom checks the log message by executing the git log command."
},
{
"code": null,
"e": 19486,
"s": 19454,
"text": "[tom@CentOS tom_repo]$ git log\n"
},
{
"code": null,
"e": 19539,
"s": 19486,
"text": "The above command will produce the following result."
},
{
"code": null,
"e": 19682,
"s": 19539,
"text": "commit 19ae20683fc460db7d127cf201a1429523b0e319\nAuthor: Tom Cat <tom@tutorialspoint.com>\nDate: Wed Sep 11 07:32:56 2013 +0530\n\nInitial commit\n"
},
{
"code": null,
"e": 19953,
"s": 19682,
"text": "Tom committed his changes to the local repository. Now, itβs time to push the changes to the remote repository. But before that, we have to add the repository as a remote, this is a one-time operation. After this, he can safely push the changes to the remote repository."
},
{
"code": null,
"e": 20271,
"s": 19953,
"text": "Note β By default, Git pushes only to matching branches: For every branch that exists on the local side, the remote side is updated if a branch with the same name already exists there. In our tutorials, every time we push changes to the origin master branch, use appropriate branch name according to your requirement."
},
{
"code": null,
"e": 20399,
"s": 20271,
"text": "[tom@CentOS tom_repo]$ git remote add origin gituser@git.server.com:project.git\n\n[tom@CentOS tom_repo]$ git push origin master\n"
},
{
"code": null,
"e": 20452,
"s": 20399,
"text": "The above command will produce the following result."
},
{
"code": null,
"e": 20634,
"s": 20452,
"text": "Counting objects: 3, done.\nWriting objects: 100% (3/3), 242 bytes, done.\nTotal 3 (delta 0), reused 0 (delta 0)\nTo gituser@git.server.com:project.git\n* [new branch]\nmaster β> master\n"
},
{
"code": null,
"e": 20704,
"s": 20634,
"text": "Now, the changes are successfully committed to the remote repository."
},
{
"code": null,
"e": 20886,
"s": 20704,
"text": "We have a bare repository on the Git server and Tom also pushed his first version. Now, Jerry can view his changes. The Clone operation creates an instance of the remote repository."
},
{
"code": null,
"e": 20972,
"s": 20886,
"text": "Jerry creates a new directory in his home directory and performs the clone operation."
},
{
"code": null,
"e": 21115,
"s": 20972,
"text": "[jerry@CentOS ~]$ mkdir jerry_repo\n\n[jerry@CentOS ~]$ cd jerry_repo/\n\n[jerry@CentOS jerry_repo]$ git clone gituser@git.server.com:project.git\n"
},
{
"code": null,
"e": 21168,
"s": 21115,
"text": "The above command will produce the following result."
},
{
"code": null,
"e": 21371,
"s": 21168,
"text": "Initialized empty Git repository in /home/jerry/jerry_repo/project/.git/\nremote: Counting objects: 3, done.\nReceiving objects: 100% (3/3), 241 bytes, done.\nremote: Total 3 (delta 0), reused 0 (delta 0)\n"
},
{
"code": null,
"e": 21457,
"s": 21371,
"text": "Jerry changes the directory to new local repository and lists its directory contents."
},
{
"code": null,
"e": 21535,
"s": 21457,
"text": "[jerry@CentOS jerry_repo]$ cd project/\n\n[jerry@CentOS jerry_repo]$ ls\nREADME\n"
},
{
"code": null,
"e": 21706,
"s": 21535,
"text": "Jerry clones the repository and decides to implement basic string operations. So he creates string.c file. After adding the contents, string.c will look like as follows β"
},
{
"code": null,
"e": 22032,
"s": 21706,
"text": "#include <stdio.h>\n\nint my_strlen(char *s)\n{\n char *p = s;\n\n while (*p)\n ++p;\n\n return (p - s);\n}\n\nint main(void)\n{\n int i;\n char *s[] = \n {\n \"Git tutorials\",\n \"Tutorials Point\"\n };\n\n for (i = 0; i < 2; ++i)\n \n printf(\"string lenght of %s = %d\\n\", s[i], my_strlen(s[i]));\n\n return 0;\n}"
},
{
"code": null,
"e": 22152,
"s": 22032,
"text": "He compiled and tested his code and everything is working fine. Now, he can safely add these changes to the repository."
},
{
"code": null,
"e": 22201,
"s": 22152,
"text": "Git add operation adds file to the staging area."
},
{
"code": null,
"e": 22304,
"s": 22201,
"text": "[jerry@CentOS project]$ git status -s\n?? string\n?? string.c\n\n[jerry@CentOS project]$ git add string.c\n"
},
{
"code": null,
"e": 22526,
"s": 22304,
"text": "Git is showing a question mark before file names. Obviously, these files are not a part of Git, and that is why Git does not know what to do with these files. That is why, Git is showing a question mark before file names."
},
{
"code": null,
"e": 22634,
"s": 22526,
"text": "Jerry has added the file to the stash area, git status command will show files present in the staging area."
},
{
"code": null,
"e": 22694,
"s": 22634,
"text": "[jerry@CentOS project]$ git status -s\nA string.c\n?? string\n"
},
{
"code": null,
"e": 22866,
"s": 22694,
"text": "To commit the changes, he used the git commit command followed by βm option. If we omit βm option. Git will open a text editor where we can write multiline commit message."
},
{
"code": null,
"e": 22938,
"s": 22866,
"text": "[jerry@CentOS project]$ git commit -m 'Implemented my_strlen function'\n"
},
{
"code": null,
"e": 22992,
"s": 22938,
"text": "The above command will produce the following result β"
},
{
"code": null,
"e": 23119,
"s": 22992,
"text": "[master cbe1249] Implemented my_strlen function\n1 files changed, 24 insertions(+), 0 deletions(-)\ncreate mode 100644 string.c\n"
},
{
"code": null,
"e": 23308,
"s": 23119,
"text": "After commit to view log details, he runs the git log command. It will display the information of all the commits with their commit ID, commit author, commit date and SHA-1 hash of commit."
},
{
"code": null,
"e": 23341,
"s": 23308,
"text": "[jerry@CentOS project]$ git log\n"
},
{
"code": null,
"e": 23395,
"s": 23341,
"text": "The above command will produce the following result β"
},
{
"code": null,
"e": 23704,
"s": 23395,
"text": "commit cbe1249b140dad24b2c35b15cc7e26a6f02d2277\nAuthor: Jerry Mouse <jerry@tutorialspoint.com>\nDate: Wed Sep 11 08:05:26 2013 +0530\n\nImplemented my_strlen function\n\n\ncommit 19ae20683fc460db7d127cf201a1429523b0e319\nAuthor: Tom Cat <tom@tutorialspoint.com>\nDate: Wed Sep 11 07:32:56 2013 +0530\n\nInitial commit\n"
},
{
"code": null,
"e": 23867,
"s": 23704,
"text": "After viewing the commit details, Jerry realizes that the string length cannot be negative, thatβs why he decides to change the return type of my_strlen function."
},
{
"code": null,
"e": 23919,
"s": 23867,
"text": "Jerry uses the git log command to view log details."
},
{
"code": null,
"e": 23952,
"s": 23919,
"text": "[jerry@CentOS project]$ git log\n"
},
{
"code": null,
"e": 24005,
"s": 23952,
"text": "The above command will produce the following result."
},
{
"code": null,
"e": 24170,
"s": 24005,
"text": "commit cbe1249b140dad24b2c35b15cc7e26a6f02d2277\nAuthor: Jerry Mouse <jerry@tutorialspoint.com>\nDate: Wed Sep 11 08:05:26 2013 +0530\n\nImplemented my_strlen function\n"
},
{
"code": null,
"e": 24289,
"s": 24170,
"text": "Jerry uses the git show command to view the commit details. The git show command takes SHA-1 commit ID as a parameter."
},
{
"code": null,
"e": 24364,
"s": 24289,
"text": "[jerry@CentOS project]$ git show cbe1249b140dad24b2c35b15cc7e26a6f02d2277\n"
},
{
"code": null,
"e": 24418,
"s": 24364,
"text": "The above command will produce the following result β"
},
{
"code": null,
"e": 24842,
"s": 24418,
"text": "commit cbe1249b140dad24b2c35b15cc7e26a6f02d2277\nAuthor: Jerry Mouse <jerry@tutorialspoint.com>\nDate: Wed Sep 11 08:05:26 2013 +0530\n\nImplemented my_strlen function\n\n\ndiff --git a/string.c b/string.c\nnew file mode 100644\nindex 0000000..187afb9\n--- /dev/null\n+++ b/string.c\n@@ -0,0 +1,24 @@\n+#include <stdio.h>\n+\n+int my_strlen(char *s)\n+{\n +\n char *p = s;\n +\n +\n while (*p)\n + ++p;\n + return (p -s );\n +\n}\n+\n"
},
{
"code": null,
"e": 24985,
"s": 24842,
"text": "He changes the return type of the function from int to size_t. After testing the code, he reviews his changes by running the git diff command."
},
{
"code": null,
"e": 25019,
"s": 24985,
"text": "[jerry@CentOS project]$ git diff\n"
},
{
"code": null,
"e": 25073,
"s": 25019,
"text": "The above command will produce the following result β"
},
{
"code": null,
"e": 25485,
"s": 25073,
"text": "diff --git a/string.c b/string.c\nindex 187afb9..7da2992 100644\n--- a/string.c\n+++ b/string.c\n@@ -1,6 +1,6 @@\n#include <stdio.h>\n\n-int my_strlen(char *s)\n+size_t my_strlen(char *s)\n{\n char *p = s;\n @@ -18,7 +18,7 @@ int main(void)\n};\nfor (i = 0; i < 2; ++i)\n{\n - printf(\"string lenght of %s = %d\\n\", s[i], my_strlen(s[i]));\n + printf(\"string lenght of %s = %lu\\n\", s[i], my_strlen(s[i]));\n return 0;\n}\n"
},
{
"code": null,
"e": 25572,
"s": 25485,
"text": "Git diff shows '+' sign before lines, which are newly added and 'β' for deleted lines."
},
{
"code": null,
"e": 25801,
"s": 25572,
"text": "Jerry has already committed the changes and he wants to correct his last commit. In this case, git amend operation will help. The amend operation changes the last commit including your commit message; it creates a new commit ID."
},
{
"code": null,
"e": 25851,
"s": 25801,
"text": "Before amend operation, he checks the commit log."
},
{
"code": null,
"e": 25884,
"s": 25851,
"text": "[jerry@CentOS project]$ git log\n"
},
{
"code": null,
"e": 25937,
"s": 25884,
"text": "The above command will produce the following result."
},
{
"code": null,
"e": 26246,
"s": 25937,
"text": "commit cbe1249b140dad24b2c35b15cc7e26a6f02d2277\nAuthor: Jerry Mouse <jerry@tutorialspoint.com>\nDate: Wed Sep 11 08:05:26 2013 +0530\n\nImplemented my_strlen function\n\n\ncommit 19ae20683fc460db7d127cf201a1429523b0e319\nAuthor: Tom Cat <tom@tutorialspoint.com>\nDate: Wed Sep 11 07:32:56 2013 +0530\n\nInitial commit\n"
},
{
"code": null,
"e": 26326,
"s": 26246,
"text": "Jerry commits the new changes with -- amend operation and views the commit log."
},
{
"code": null,
"e": 26718,
"s": 26326,
"text": "[jerry@CentOS project]$ git status -s\nM string.c\n?? string\n\n[jerry@CentOS project]$ git add string.c\n\n[jerry@CentOS project]$ git status -s\nM string.c\n?? string\n\n[jerry@CentOS project]$ git commit --amend -m 'Changed return type of my_strlen to size_t'\n[master d1e19d3] Changed return type of my_strlen to size_t\n1 files changed, 24 insertions(+), 0 deletions(-)\ncreate mode 100644 string.c\n"
},
{
"code": null,
"e": 26781,
"s": 26718,
"text": "Now, git log will show new commit message with new commit ID β"
},
{
"code": null,
"e": 26814,
"s": 26781,
"text": "[jerry@CentOS project]$ git log\n"
},
{
"code": null,
"e": 26867,
"s": 26814,
"text": "The above command will produce the following result."
},
{
"code": null,
"e": 27188,
"s": 26867,
"text": "commit d1e19d316224cddc437e3ed34ec3c931ad803958\nAuthor: Jerry Mouse <jerry@tutorialspoint.com>\nDate: Wed Sep 11 08:05:26 2013 +0530\n\nChanged return type of my_strlen to size_t\n\n\ncommit 19ae20683fc460db7d127cf201a1429523b0e319\nAuthor: Tom Cat <tom@tutorialspoint.com>\nDate: Wed Sep 11 07:32:56 2013 +0530\n\nInitial commit\n"
},
{
"code": null,
"e": 27428,
"s": 27188,
"text": "Jerry modified his last commit by using the amend operation and he is ready to push the changes. The Push operation stores data permanently to the Git repository. After a successful push operation, other developers can see Jerryβs changes."
},
{
"code": null,
"e": 27488,
"s": 27428,
"text": "He executes the git log command to view the commit details."
},
{
"code": null,
"e": 27521,
"s": 27488,
"text": "[jerry@CentOS project]$ git log\n"
},
{
"code": null,
"e": 27574,
"s": 27521,
"text": "The above command will produce the following result:"
},
{
"code": null,
"e": 27751,
"s": 27574,
"text": "commit d1e19d316224cddc437e3ed34ec3c931ad803958\nAuthor: Jerry Mouse <jerry@tutorialspoint.com>\nDate: Wed Sep 11 08:05:26 2013 +0530\n\nChanged return type of my_strlen to size_t\n"
},
{
"code": null,
"e": 27861,
"s": 27751,
"text": "Before push operation, he wants to review his changes, so he uses the git show command to review his changes."
},
{
"code": null,
"e": 27936,
"s": 27861,
"text": "[jerry@CentOS project]$ git show d1e19d316224cddc437e3ed34ec3c931ad803958\n"
},
{
"code": null,
"e": 27989,
"s": 27936,
"text": "The above command will produce the following result:"
},
{
"code": null,
"e": 28685,
"s": 27989,
"text": "commit d1e19d316224cddc437e3ed34ec3c931ad803958\nAuthor: Jerry Mouse <jerry@tutorialspoint.com>\nDate: Wed Sep 11 08:05:26 2013 +0530\n\nChanged return type of my_strlen to size_t\n\ndiff --git a/string.c b/string.c\nnew file mode 100644\nindex 0000000..7da2992\n--- /dev/null\n+++ b/string.c\n@@ -0,0 +1,24 @@\n+#include <stdio.h>\n+\n+size_t my_strlen(char *s)\n+\n{\n +\n char *p = s;\n +\n +\n while (*p)\n + ++p;\n + return (p -s );\n +\n}\n+\n+int main(void)\n+\n{\n + int i;\n + char *s[] = \n {\n + \"Git tutorials\",\n + \"Tutorials Point\"\n +\n };\n +\n +\n +\n for (i = 0; i < 2; ++i)\n printf(\"string lenght of %s = %lu\\n\", s[i], my_strlen(s[i]));\n +\n +\n return 0;\n +\n}\n"
},
{
"code": null,
"e": 28754,
"s": 28685,
"text": "Jerry is happy with his changes and he is ready to push his changes."
},
{
"code": null,
"e": 28802,
"s": 28754,
"text": "[jerry@CentOS project]$ git push origin master\n"
},
{
"code": null,
"e": 28855,
"s": 28802,
"text": "The above command will produce the following result:"
},
{
"code": null,
"e": 29078,
"s": 28855,
"text": "Counting objects: 4, done.\nCompressing objects: 100% (3/3), done.\nWriting objects: 100% (3/3), 517 bytes, done.\nTotal 3 (delta 0), reused 0 (delta 0)\nTo gituser@git.server.com:project.git\n19ae206..d1e19d3 master β> master\n"
},
{
"code": null,
"e": 29226,
"s": 29078,
"text": "Jerryβs changes have been successfully pushed to the repository; now other developers can view his changes by performing clone or update operation."
},
{
"code": null,
"e": 29404,
"s": 29226,
"text": "Tom performs the clone operation and finds a new file string.c. He wants to know who added this file to the repository and for what purpose, so, he executes the git log command."
},
{
"code": null,
"e": 29466,
"s": 29404,
"text": "[tom@CentOS ~]$ git clone gituser@git.server.com:project.git\n"
},
{
"code": null,
"e": 29520,
"s": 29466,
"text": "The above command will produce the following result β"
},
{
"code": null,
"e": 29757,
"s": 29520,
"text": "Initialized empty Git repository in /home/tom/project/.git/\nremote: Counting objects: 6, done.\nremote: Compressing objects: 100% (4/4), done.\nReceiving objects: 100% (6/6), 726 bytes, done.\nremote: Total 6 (delta 0), reused 0 (delta 0)\n"
},
{
"code": null,
"e": 29929,
"s": 29757,
"text": "The Clone operation will create a new directory inside the current working directory. He changes the directory to newly created directory and executes the git log command."
},
{
"code": null,
"e": 29989,
"s": 29929,
"text": "[tom@CentOS ~]$ cd project/\n\n[tom@CentOS project]$ git log\n"
},
{
"code": null,
"e": 30043,
"s": 29989,
"text": "The above command will produce the following result β"
},
{
"code": null,
"e": 30364,
"s": 30043,
"text": "commit d1e19d316224cddc437e3ed34ec3c931ad803958\nAuthor: Jerry Mouse <jerry@tutorialspoint.com>\nDate: Wed Sep 11 08:05:26 2013 +0530\n\nChanged return type of my_strlen to size_t\n\n\ncommit 19ae20683fc460db7d127cf201a1429523b0e319\nAuthor: Tom Cat <tom@tutorialspoint.com>\nDate: Wed Sep 11 07:32:56 2013 +0530\n\nInitial commit\n"
},
{
"code": null,
"e": 30729,
"s": 30364,
"text": "After observing the log, he realizes that the file string.c was added by Jerry to implement basic string operations. He is curious about Jerryβs code. So he opens string.c in text editor and immediately finds a bug. In my_strlen function, Jerry is not using a constant pointer. So, he decides to modify Jerryβs code. After modification, the code looks as follows β"
},
{
"code": null,
"e": 30761,
"s": 30729,
"text": "[tom@CentOS project]$ git diff\n"
},
{
"code": null,
"e": 30815,
"s": 30761,
"text": "The above command will produce the following result β"
},
{
"code": null,
"e": 31072,
"s": 30815,
"text": "diff --git a/string.c b/string.c\nindex 7da2992..32489eb 100644\n--- a/string.c\n+++ b/string.c\n@@ -1,8 +1,8 @@\n#include <stdio.h>\n-size_t my_strlen(char *s)\n+size_t my_strlen(const char *s)\n{\n - char *p = s;\n + const char *p = s;\n while (*p)\n ++p;\n}\n"
},
{
"code": null,
"e": 31110,
"s": 31072,
"text": "After testing, he commits his change."
},
{
"code": null,
"e": 31430,
"s": 31110,
"text": "[tom@CentOS project]$ git status -s\nM string.c\n?? string\n\n[tom@CentOS project]$ git add string.c\n\n[tom@CentOS project]$ git commit -m 'Changed char pointer to const char pointer'\n[master cea2c00] Changed char pointer to const char pointer\n1 files changed, 2 insertions(+), 2 deletions(-)\n\n[tom@CentOS project]$ git log\n"
},
{
"code": null,
"e": 31484,
"s": 31430,
"text": "The above command will produce the following result β"
},
{
"code": null,
"e": 31971,
"s": 31484,
"text": "commit cea2c000f53ba99508c5959e3e12fff493b\nAuthor: Tom Cat <tom@tutorialspoint.com>\nDate: Wed Sep 11 08:32:07 2013 +0530\n\nChanged char pointer to const char pointer\n\n\ncommit d1e19d316224cddc437e3ed34ec3c931ad803958\nAuthor: Jerry Mouse <jerry@tutorialspoint.com>\nDate: Wed Sep 11 08:05:26 2013 +0530\n\nChanged return type of my_strlen to size_t\n\n\ncommit 19ae20683fc460db7d127cf201a1429523b0e319\nAuthor: Tom Cat <tom@tutorialspoint.com>\nDate: Wed Sep 11 07:32:56 2013 +0530\nInitial commit\n"
},
{
"code": null,
"e": 32018,
"s": 31971,
"text": "Tom uses git push command to push his changes."
},
{
"code": null,
"e": 32064,
"s": 32018,
"text": "[tom@CentOS project]$ git push origin master\n"
},
{
"code": null,
"e": 32118,
"s": 32064,
"text": "The above command will produce the following result β"
},
{
"code": null,
"e": 32341,
"s": 32118,
"text": "Counting objects: 5, done.\nCompressing objects: 100% (3/3), done.\nWriting objects: 100% (3/3), 336 bytes, done.\nTotal 3 (delta 1), reused 0 (delta 0)\nTo gituser@git.server.com:project.git\nd1e19d3..cea2c00 master β> master\n"
},
{
"code": null,
"e": 32482,
"s": 32341,
"text": "Meanwhile, Jerry decides to implement string compare functionality. So he modifies string.c. After modification, the file looks as follows β"
},
{
"code": null,
"e": 32516,
"s": 32482,
"text": "[jerry@CentOS project]$ git diff\n"
},
{
"code": null,
"e": 32570,
"s": 32516,
"text": "The above command will produce the following result β"
},
{
"code": null,
"e": 33187,
"s": 32570,
"text": "index 7da2992..bc864ed 100644\n--- a/string.c\n+++ b/string.c\n30Git Tutorials\n@@ -9,9 +9,20 @@ size_t my_strlen(char *s)\nreturn (p -s );\n}\n+char *my_strcpy(char *t, char *s)\n+\n{\n +\n char *p = t;\n +\n + while (*t++ = *s++)\n + ;\n +\n +\n return p;\n +\n}\n+\nint main(void)\n{\n int i; \n +\n char p1[32];\n char *s[] = \n {\n \"Git tutorials\",\n \"Tutorials Point\"\n @@ -20,5 +31,7 @@ int main(void)\n for (i = 0; i < 2; ++i)\n printf(\"string lenght of %s = %lu\\n\", s[i], my_strlen(s[i]));\n +\n printf(\"%s\\n\", my_strcpy(p1, \"Hello, World !!!\"));\n +\n return 0;\n }\n}\n"
},
{
"code": null,
"e": 33234,
"s": 33187,
"text": "After testing, he is ready to push his change."
},
{
"code": null,
"e": 33494,
"s": 33234,
"text": "[jerry@CentOS project]$ git status -s\nM string.c\n?? string\n\n[jerry@CentOS project]$ git add string.c\n\n[jerry@CentOS project]$ git commit -m \"Added my_strcpy function\"\n[master e944e5a] Added my_strcpy function\n1 files changed, 13 insertions(+), 0 deletions(-)\n"
},
{
"code": null,
"e": 33561,
"s": 33494,
"text": "Before push operation, he verifies commit by viewing log messages."
},
{
"code": null,
"e": 33594,
"s": 33561,
"text": "[jerry@CentOS project]$ git log\n"
},
{
"code": null,
"e": 33648,
"s": 33594,
"text": "The above command will produce the following result β"
},
{
"code": null,
"e": 34129,
"s": 33648,
"text": "commit e944e5aab74b26e7447d3281b225309e4e59efcd\nAuthor: Jerry Mouse <jerry@tutorialspoint.com>\nDate: Wed Sep 11 08:41:42 2013 +0530\n\nAdded my_strcpy function\n\n\ncommit d1e19d316224cddc437e3ed34ec3c931ad803958\nAuthor: Jerry Mouse <jerry@tutorialspoint.com>\nDate: Wed Sep 11 08:05:26 2013 +0530\n\nChanged return type of my_strlen to size_t\n\n\ncommit 19ae20683fc460db7d127cf201a1429523b0e319\nAuthor: Tom Cat <tom@tutorialspoint.com>\nDate: Wed Sep 11 07:32:56 2013 +0530\n\nInitial commit\n"
},
{
"code": null,
"e": 34195,
"s": 34129,
"text": "Jerry is happy with the changes and he wants to push his changes."
},
{
"code": null,
"e": 34243,
"s": 34195,
"text": "[jerry@CentOS project]$ git push origin master\n"
},
{
"code": null,
"e": 34297,
"s": 34243,
"text": "The above command will produce the following result β"
},
{
"code": null,
"e": 34656,
"s": 34297,
"text": "To gituser@git.server.com:project.git\n! [rejected]\nmaster β> master (non-fast-forward)\nerror: failed to push some refs to 'gituser@git.server.com:project.git'\nTo prevent you from losing history, non-fast-forward updates were rejected\nMerge the remote changes before pushing again. See the 'Note about\nfast-forwards' section of 'git push --help' for details.\n"
},
{
"code": null,
"e": 35005,
"s": 34656,
"text": "But Git is not allowing Jerry to push his changes. Because Git identified that remote repository and Jerryβs local repository are not in sync. Because of this, he can lose the history of the project. To avoid this mess, Git failed this operation. Now, Jerry has to first update the local repository and only thereafter, he can push his own changes."
},
{
"code": null,
"e": 35099,
"s": 35005,
"text": "Jerry executes the git pull command to synchronize his local repository with the remote one."
},
{
"code": null,
"e": 35133,
"s": 35099,
"text": "[jerry@CentOS project]$ git pull\n"
},
{
"code": null,
"e": 35187,
"s": 35133,
"text": "The above command will produce the following result β"
},
{
"code": null,
"e": 35515,
"s": 35187,
"text": "remote: Counting objects: 5, done.\nremote: Compressing objects: 100% (3/3), done.\nremote: Total 3 (delta 1), reused 0 (delta 0)\nUnpacking objects: 100% (3/3), done.\nFrom git.server.com:project\nd1e19d3..cea2c00 master β> origin/master\nFirst, rewinding head to replay your work on top of it...\nApplying: Added my_strcpy function\n"
},
{
"code": null,
"e": 35661,
"s": 35515,
"text": "After pull operation, Jerry checks the log messages and finds the details of Tomβs commit with commit ID cea2c000f53ba99508c5959e3e12fff493ba6f69"
},
{
"code": null,
"e": 35694,
"s": 35661,
"text": "[jerry@CentOS project]$ git log\n"
},
{
"code": null,
"e": 35748,
"s": 35694,
"text": "The above command will produce the following result β"
},
{
"code": null,
"e": 36400,
"s": 35748,
"text": "commit e86f0621c2a3f68190bba633a9fe6c57c94f8e4f\nAuthor: Jerry Mouse <jerry@tutorialspoint.com>\nDate: Wed Sep 11 08:41:42 2013 +0530\n\nAdded my_strcpy function\n\n\ncommit cea2c000f53ba99508c5959e3e12fff493ba6f69\nAuthor: Tom Cat <tom@tutorialspoint.com>\nDate: Wed Sep 11 08:32:07 2013 +0530\n\nChanged char pointer to const char pointer\n\n\ncommit d1e19d316224cddc437e3ed34ec3c931ad803958\nAuthor: Jerry Mouse <jerry@tutorialspoint.com>\nDate: Wed Sep 11 08:05:26 2013 +0530\n\nChanged return type of my_strlen to size_t\n\n\ncommit 19ae20683fc460db7d127cf201a1429523b0e319\nAuthor: Tom Cat <tom@tutorialspoint.com>\nDate: Wed Sep 11 07:32:56 2013 +0530\nInitial commit\n"
},
{
"code": null,
"e": 36515,
"s": 36400,
"text": "Now, Jerryβs local repository is fully synchronized with the remote repository. So he can safely push his changes."
},
{
"code": null,
"e": 36563,
"s": 36515,
"text": "[jerry@CentOS project]$ git push origin master\n"
},
{
"code": null,
"e": 36617,
"s": 36563,
"text": "The above command will produce the following result β"
},
{
"code": null,
"e": 36840,
"s": 36617,
"text": "Counting objects: 5, done.\nCompressing objects: 100% (3/3), done.\nWriting objects: 100% (3/3), 455 bytes, done.\nTotal 3 (delta 1), reused 0 (delta 0)\nTo gituser@git.server.com:project.git\ncea2c00..e86f062 master β> master\n"
},
{
"code": null,
"e": 37223,
"s": 36840,
"text": "Suppose you are implementing a new feature for your product. Your code is in progress and suddenly a customer escalation comes. Because of this, you have to keep aside your new feature work for a few hours. You cannot commit your partial code and also cannot throw away your changes. So you need some temporary space, where you can store your partial changes and later on commit it."
},
{
"code": null,
"e": 37384,
"s": 37223,
"text": "In Git, the stash operation takes your modified tracked files, stages changes, and saves them on a stack of unfinished changes that you can reapply at any time."
},
{
"code": null,
"e": 37444,
"s": 37384,
"text": "[jerry@CentOS project]$ git status -s\nM string.c\n?? string\n"
},
{
"code": null,
"e": 37657,
"s": 37444,
"text": "Now, you want to switch branches for customer escalation, but you donβt want to commit what youβve been working on yet; so youβll stash the changes. To push a new stash onto your stack, run the git stash command."
},
{
"code": null,
"e": 37828,
"s": 37657,
"text": "[jerry@CentOS project]$ git stash\nSaved working directory and index state WIP on master: e86f062 Added my_strcpy function\nHEAD is now at e86f062 Added my_strcpy function\n"
},
{
"code": null,
"e": 37953,
"s": 37828,
"text": "Now, your working directory is clean and all the changes are saved on a stack. Let us verify it with the git status command."
},
{
"code": null,
"e": 38002,
"s": 37953,
"text": "[jerry@CentOS project]$ git status -s\n?? string\n"
},
{
"code": null,
"e": 38134,
"s": 38002,
"text": "Now you can safely switch the branch and work elsewhere. We can view a list of stashed changes by using the git stash list command."
},
{
"code": null,
"e": 38233,
"s": 38134,
"text": "[jerry@CentOS project]$ git stash list\nstash@{0}: WIP on master: e86f062 Added my_strcpy function\n"
},
{
"code": null,
"e": 38479,
"s": 38233,
"text": "Suppose you have resolved the customer escalation and you are back on your new feature looking for your half-done code, just execute the git stash pop command, to remove the changes from the stack and place them in the current working directory."
},
{
"code": null,
"e": 38567,
"s": 38479,
"text": "[jerry@CentOS project]$ git status -s\n?? string\n\n[jerry@CentOS project]$ git stash pop\n"
},
{
"code": null,
"e": 38620,
"s": 38567,
"text": "The above command will produce the following result:"
},
{
"code": null,
"e": 39098,
"s": 38620,
"text": "# On branch master\n# Changed but not updated:\n# (use \"git add ...\" to update what will be committed)\n# (use \"git checkout -- ...\" to discard changes in working directory)\n#\n#\nmodified: string.c\n#\n# Untracked files:\n# (use \"git add ...\" to include in what will be committed)\n#\n#\nstring\nno changes added to commit (use \"git add\" and/or \"git commit -a\")\nDropped refs/stash@{0} (36f79dfedae4ac20e2e8558830154bd6315e72d4)\n\n[jerry@CentOS project]$ git status -s\nM string.c\n?? string\n"
},
{
"code": null,
"e": 39311,
"s": 39098,
"text": "As the name suggests, the move operation moves a directory or a file from one location to another. Tom decides to move the source code into src directory. The modified directory structure will appear as follows β"
},
{
"code": null,
"e": 39556,
"s": 39311,
"text": "[tom@CentOS project]$ pwd\n/home/tom/project\n\n[tom@CentOS project]$ ls\nREADME string string.c\n\n[tom@CentOS project]$ mkdir src\n\n[tom@CentOS project]$ git mv string.c src/\n\n[tom@CentOS project]$ git status -s\nR string.c β> src/string.c\n?? string\n"
},
{
"code": null,
"e": 39702,
"s": 39556,
"text": "To make these changes permanent, we have to push the modified directory structure to the remote repository so that other developers can see this."
},
{
"code": null,
"e": 40173,
"s": 39702,
"text": "[tom@CentOS project]$ git commit -m \"Modified directory structure\"\n\n[master 7d9ea97] Modified directory structure\n1 files changed, 0 insertions(+), 0 deletions(-)\nrename string.c => src/string.c (100%)\n\n[tom@CentOS project]$ git push origin master\nCounting objects: 4, done.\nCompressing objects: 100% (2/2), done.\nWriting objects: 100% (3/3), 320 bytes, done.\nTotal 3 (delta 0), reused 0 (delta 0)\nTo gituser@git.server.com:project.git\ne86f062..7d9ea97 master β> master\n"
},
{
"code": null,
"e": 40271,
"s": 40173,
"text": "In Jerryβs local repository, before the pull operation, it will show the old directory structure."
},
{
"code": null,
"e": 40382,
"s": 40271,
"text": "[jerry@CentOS project]$ pwd\n/home/jerry/jerry_repo/project\n\n[jerry@CentOS project]$ ls\nREADME string string.c\n"
},
{
"code": null,
"e": 40535,
"s": 40382,
"text": "But after the pull operation, the directory structure will get updated. Now, Jerry can see the src directory and the file present inside that directory."
},
{
"code": null,
"e": 41016,
"s": 40535,
"text": "[jerry@CentOS project]$ git pull\nremote: Counting objects: 4, done.\nremote: Compressing objects: 100% (2/2), done.\nremote: Total 3 (delta 0), reused 0 (delta 0)\nUnpacking objects: 100% (3/3), done.\nFrom git.server.com:project\ne86f062..7d9ea97 master β> origin/master\nFirst, rewinding head to replay your work on top of it...\nFast-forwarded master to 7d9ea97683da90bcdb87c28ec9b4f64160673c8a.\n\n[jerry@CentOS project]$ ls\nREADME src string\n\n[jerry@CentOS project]$ ls src/\nstring.c\n"
},
{
"code": null,
"e": 41206,
"s": 41016,
"text": "Till now, both Tom and Jerry were using manual commands to compile their project. Now, Jerry decides to create Makefile for their project and also give a proper name to the file βstring.cβ."
},
{
"code": null,
"e": 41513,
"s": 41206,
"text": "[jerry@CentOS project]$ pwd\n/home/jerry/jerry_repo/project\n\n[jerry@CentOS project]$ ls\nREADME src\n\n[jerry@CentOS project]$ cd src/\n\n[jerry@CentOS src]$ git add Makefile\n\n[jerry@CentOS src]$ git mv string.c string_operations.c\n\n[jerry@CentOS src]$ git status -s\nA Makefile\nR string.c β> string_operations.c\n"
},
{
"code": null,
"e": 41591,
"s": 41513,
"text": "Git is showing R before file name to indicate that the file has been renamed."
},
{
"code": null,
"e": 41696,
"s": 41591,
"text": "For commit operation, Jerry used -a flag, that makes git commit automatically detect the modified files."
},
{
"code": null,
"e": 42008,
"s": 41696,
"text": "[jerry@CentOS src]$ git commit -a -m 'Added Makefile and renamed strings.c to\nstring_operations.c '\n\n[master 94f7b26] Added Makefile and renamed strings.c to string_operations.c\n1 files changed, 0 insertions(+), 0 deletions(-)\ncreate mode 100644 src/Makefile\nrename src/{string.c => string_operations.c} (100%)\n"
},
{
"code": null,
"e": 42063,
"s": 42008,
"text": "After commit, he pushes his changes to the repository."
},
{
"code": null,
"e": 42107,
"s": 42063,
"text": "[jerry@CentOS src]$ git push origin master\n"
},
{
"code": null,
"e": 42161,
"s": 42107,
"text": "The above command will produce the following result β"
},
{
"code": null,
"e": 42384,
"s": 42161,
"text": "Counting objects: 6, done.\nCompressing objects: 100% (3/3), done.\nWriting objects: 100% (4/4), 396 bytes, done.\nTotal 4 (delta 0), reused 0 (delta 0)\nTo gituser@git.server.com:project.git\n7d9ea97..94f7b26 master β> master\n"
},
{
"code": null,
"e": 42471,
"s": 42384,
"text": "Now, other developers can view these modifications by updating their local repository."
},
{
"code": null,
"e": 42647,
"s": 42471,
"text": "Tom updates his local repository and finds the compiled binary in the src directory. After viewing the commit message, he realizes that the compiled binary was added by Jerry."
},
{
"code": null,
"e": 43131,
"s": 42647,
"text": "[tom@CentOS src]$ pwd\n/home/tom/project/src\n\n[tom@CentOS src]$ ls\nMakefile string_operations string_operations.c\n\n[tom@CentOS src]$ file string_operations\nstring_operations: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses\nshared libs), for GNU/Linux 2.6.18, not stripped\n\n[tom@CentOS src]$ git log\ncommit 29af9d45947dc044e33d69b9141d8d2dad37cc62\nAuthor: Jerry Mouse <jerry@tutorialspoint.com>\nDate: Wed Sep 11 10:16:25 2013 +0530\n\nAdded compiled binary\n"
},
{
"code": null,
"e": 43310,
"s": 43131,
"text": "VCS is used to store the source code only and not executable binaries. So, Tom decides to remove this file from the repository. For further operation, he uses the git rm command."
},
{
"code": null,
"e": 43648,
"s": 43310,
"text": "[tom@CentOS src]$ ls\nMakefile string_operations string_operations.c\n\n[tom@CentOS src]$ git rm string_operations\nrm 'src/string_operations'\n\n[tom@CentOS src]$ git commit -a -m \"Removed executable binary\"\n\n[master 5776472] Removed executable binary\n1 files changed, 0 insertions(+), 0 deletions(-)\ndelete mode 100755 src/string_operations\n"
},
{
"code": null,
"e": 43703,
"s": 43648,
"text": "After commit, he pushes his changes to the repository."
},
{
"code": null,
"e": 43745,
"s": 43703,
"text": "[tom@CentOS src]$ git push origin master\n"
},
{
"code": null,
"e": 43798,
"s": 43745,
"text": "The above command will produce the following result."
},
{
"code": null,
"e": 44021,
"s": 43798,
"text": "Counting objects: 5, done.\nCompressing objects: 100% (3/3), done.\nWriting objects: 100% (3/3), 310 bytes, done.\nTotal 3 (delta 1), reused 0 (delta 0)\nTo gituser@git.server.com:project.git\n29af9d4..5776472 master β> master\n"
},
{
"code": null,
"e": 44219,
"s": 44021,
"text": "To err is human. So every VCS provides a feature to fix mistakes until a certain point. Git provides a feature that we can use to undo the modifications that have been made to the local repository."
},
{
"code": null,
"e": 44390,
"s": 44219,
"text": "Suppose the user accidentally does some changes to his local repository and then wants to undo these changes. In such cases, the revert operation plays an important role."
},
{
"code": null,
"e": 44627,
"s": 44390,
"text": "Let us suppose Jerry accidentally modifies a file from his local repository. But he wants to undo his modification. To handle this situation, we can use the git checkout command. We can use this command to revert the contents of a file."
},
{
"code": null,
"e": 44833,
"s": 44627,
"text": "[jerry@CentOS src]$ pwd\n/home/jerry/jerry_repo/project/src\n\n[jerry@CentOS src]$ git status -s\nM string_operations.c\n\n[jerry@CentOS src]$ git checkout string_operations.c\n\n[jerry@CentOS src]$ git status βs\n"
},
{
"code": null,
"e": 45065,
"s": 44833,
"text": "Further, we can use the git checkout command to obtain a deleted file from the local repository. Let us suppose Tom deletes a file from the local repository and we want this file back. We can achieve this by using the same command."
},
{
"code": null,
"e": 45304,
"s": 45065,
"text": "[tom@CentOS src]$ pwd\n/home/tom/top_repo/project/src\n\n[tom@CentOS src]$ ls -1\nMakefile\nstring_operations.c\n\n[tom@CentOS src]$ rm string_operations.c\n\n[tom@CentOS src]$ ls -1\nMakefile\n\n[tom@CentOS src]$ git status -s\nD string_operations.c\n"
},
{
"code": null,
"e": 45426,
"s": 45304,
"text": "Git is showing the letter D before the filename. This indicates that the file has been deleted from the local repository."
},
{
"code": null,
"e": 45565,
"s": 45426,
"text": "[tom@CentOS src]$ git checkout string_operations.c\n\n[tom@CentOS src]$ ls -1\nMakefile\nstring_operations.c\n\n[tom@CentOS src]$ git status -s\n"
},
{
"code": null,
"e": 45623,
"s": 45565,
"text": "Note β We can perform all these operations before commit."
},
{
"code": null,
"e": 45872,
"s": 45623,
"text": "We have seen that when we perform an add operation, the files move from the local repository to the stating area. If a user accidently modifies a file and adds it into the staging area, he can revert his changes, by using the git checkout command."
},
{
"code": null,
"e": 46281,
"s": 45872,
"text": "In Git, there is one HEAD pointer that always points to the latest commit. If you want to undo a change from the staged area, then you can use the git checkout command, but with the checkout command, you have to provide an additional parameter, i.e., the HEAD pointer. The additional commit pointer parameter instructs the git checkout command to reset the working tree and also to remove the staged changes."
},
{
"code": null,
"e": 46456,
"s": 46281,
"text": "Let us suppose Tom modifies a file from his local repository. If we view the status of this file, it will show that the file was modified but not added into the staging area."
},
{
"code": null,
"e": 46698,
"s": 46456,
"text": "tom@CentOS src]$ pwd\n/home/tom/top_repo/project/src\n# Unmodified file\n\n[tom@CentOS src]$ git status -s\n\n# Modify file and view itβs status.\n[tom@CentOS src]$ git status -s\nM string_operations.c\n\n[tom@CentOS src]$ git add string_operations.c\n"
},
{
"code": null,
"e": 46851,
"s": 46698,
"text": "Git status shows that the file is present in the staging area, now revert it by using the git checkout command and view the status of the reverted file."
},
{
"code": null,
"e": 46944,
"s": 46851,
"text": "[tom@CentOS src]$ git checkout HEAD -- string_operations.c\n\n[tom@CentOS src]$ git status -s\n"
},
{
"code": null,
"e": 47125,
"s": 46944,
"text": "After doing few changes, you may decide to remove these changes. The Git reset command is used to reset or revert changes. We can perform three different types of reset operations."
},
{
"code": null,
"e": 47196,
"s": 47125,
"text": "Below diagram shows the pictorial representation of Git reset command."
},
{
"code": null,
"e": 47403,
"s": 47196,
"text": "Each branch has a HEAD pointer, which points to the latest commit. If we use Git reset command with --soft option followed by commit ID, then it will reset the HEAD pointer only without destroying anything."
},
{
"code": null,
"e": 47523,
"s": 47403,
"text": ".git/refs/heads/master file stores the commit ID of the HEAD pointer. We can verify it by using the git log -1 command."
},
{
"code": null,
"e": 47616,
"s": 47523,
"text": "[jerry@CentOS project]$ cat .git/refs/heads/master\n577647211ed44fe2ae479427a0668a4f12ed71a1\n"
},
{
"code": null,
"e": 47691,
"s": 47616,
"text": "Now, view the latest commit ID, which will match with the above commit ID."
},
{
"code": null,
"e": 47727,
"s": 47691,
"text": "[jerry@CentOS project]$ git log -2\n"
},
{
"code": null,
"e": 47780,
"s": 47727,
"text": "The above command will produce the following result."
},
{
"code": null,
"e": 48091,
"s": 47780,
"text": "commit 577647211ed44fe2ae479427a0668a4f12ed71a1\nAuthor: Tom Cat <tom@tutorialspoint.com>\nDate: Wed Sep 11 10:21:20 2013 +0530\n\nRemoved executable binary\n\n\ncommit 29af9d45947dc044e33d69b9141d8d2dad37cc62\nAuthor: Jerry Mouse <jerry@tutorialspoint.com>\nDate: Wed Sep 11 10:16:25 2013 +0530\n\nAdded compiled binary\n"
},
{
"code": null,
"e": 48122,
"s": 48091,
"text": "Let us reset the HEAD pointer."
},
{
"code": null,
"e": 48170,
"s": 48122,
"text": "[jerry@CentOS project]$ git reset --soft HEAD~\n"
},
{
"code": null,
"e": 48286,
"s": 48170,
"text": "Now, we just reset the HEAD pointer back by one position. Let us check the contents of .git/refs/heads/master file."
},
{
"code": null,
"e": 48379,
"s": 48286,
"text": "[jerry@CentOS project]$ cat .git/refs/heads/master\n29af9d45947dc044e33d69b9141d8d2dad37cc62\n"
},
{
"code": null,
"e": 48453,
"s": 48379,
"text": "Commit ID from file is changed, now verify it by viewing commit messages."
},
{
"code": null,
"e": 48488,
"s": 48453,
"text": "jerry@CentOS project]$ git log -2\n"
},
{
"code": null,
"e": 48541,
"s": 48488,
"text": "The above command will produce the following result."
},
{
"code": null,
"e": 48892,
"s": 48541,
"text": "commit 29af9d45947dc044e33d69b9141d8d2dad37cc62\nAuthor: Jerry Mouse <jerry@tutorialspoint.com>\nDate: Wed Sep 11 10:16:25 2013 +0530\n\nAdded compiled binary\n\n\ncommit 94f7b26005f856f1a1b733ad438e97a0cd509c1a\nAuthor: Jerry Mouse <jerry@tutorialspoint.com>\nDate: Wed Sep 11 10:08:01 2013 +0530\n\nAdded Makefile and renamed strings.c to string_operations.c\n"
},
{
"code": null,
"e": 49186,
"s": 48892,
"text": "Git reset with --mixed option reverts those changes from the staging area that have not been committed yet. It reverts the changes from the staging area only. The actual changes made to the working copy of the file are unaffected. The default Git reset is equivalent to the git reset -- mixed."
},
{
"code": null,
"e": 49388,
"s": 49186,
"text": "If you use --hard option with the Git reset command, it will clear the staging area; it will reset the HEAD pointer to the latest commit of the specific commit ID and delete the local file changes too."
},
{
"code": null,
"e": 49416,
"s": 49388,
"text": "Let us check the commit ID."
},
{
"code": null,
"e": 49508,
"s": 49416,
"text": "[jerry@CentOS src]$ pwd\n/home/jerry/jerry_repo/project/src\n\n[jerry@CentOS src]$ git log -1\n"
},
{
"code": null,
"e": 49561,
"s": 49508,
"text": "The above command will produce the following result."
},
{
"code": null,
"e": 49715,
"s": 49561,
"text": "commit 577647211ed44fe2ae479427a0668a4f12ed71a1\nAuthor: Tom Cat <tom@tutorialspoint.com>\nDate: Wed Sep 11 10:21:20 2013 +0530\n\nRemoved executable binary\n"
},
{
"code": null,
"e": 49789,
"s": 49715,
"text": "Jerry modified a file by adding single-line comment at the start of file."
},
{
"code": null,
"e": 49907,
"s": 49789,
"text": "[jerry@CentOS src]$ head -2 string_operations.c\n/* This line be removed by git reset operation */\n#include <stdio.h>\n"
},
{
"code": null,
"e": 49955,
"s": 49907,
"text": "He verified it by using the git status command."
},
{
"code": null,
"e": 50012,
"s": 49955,
"text": "[jerry@CentOS src]$ git status -s\nM string_operations.c\n"
},
{
"code": null,
"e": 50106,
"s": 50012,
"text": "Jerry adds the modified file to the staging area and verifies it with the git status command."
},
{
"code": null,
"e": 50186,
"s": 50106,
"text": "[jerry@CentOS src]$ git add string_operations.c\n[jerry@CentOS src]$ git status\n"
},
{
"code": null,
"e": 50239,
"s": 50186,
"text": "The above command will produce the following result."
},
{
"code": null,
"e": 50368,
"s": 50239,
"text": "# On branch master\n# Changes to be committed:\n# (use \"git reset HEAD <file>...\" to unstage)\n#\n#\nmodified: string_operations.c\n#\n"
},
{
"code": null,
"e": 50473,
"s": 50368,
"text": "Git status is showing that the file is present in the staging area. Now, reset HEAD with -- hard option."
},
{
"code": null,
"e": 50602,
"s": 50473,
"text": "[jerry@CentOS src]$ git reset --hard 577647211ed44fe2ae479427a0668a4f12ed71a1\n\nHEAD is now at 5776472 Removed executable binary\n"
},
{
"code": null,
"e": 50734,
"s": 50602,
"text": "Git reset command succeeded, which will revert the file from the staging area as well as remove any local changes made to the file."
},
{
"code": null,
"e": 50769,
"s": 50734,
"text": "[jerry@CentOS src]$ git status -s\n"
},
{
"code": null,
"e": 50846,
"s": 50769,
"text": "Git status is showing that the file has been reverted from the staging area."
},
{
"code": null,
"e": 50914,
"s": 50846,
"text": "[jerry@CentOS src]$ head -2 string_operations.c\n#include <stdio.h>\n"
},
{
"code": null,
"e": 50998,
"s": 50914,
"text": "The head command also shows that the reset operation removed the local changes too."
},
{
"code": null,
"e": 51180,
"s": 50998,
"text": "Tag operation allows giving meaningful names to a specific version in the repository. Suppose Tom and Jerry decide to tag their project code so that they can later access it easily."
},
{
"code": null,
"e": 51320,
"s": 51180,
"text": "Let us tag the current HEAD by using the git tag command. Tom provides a tag name with -a option and provides a tag message with βm option."
},
{
"code": null,
"e": 51466,
"s": 51320,
"text": "tom@CentOS project]$ pwd\n/home/tom/top_repo/project\n\n[tom@CentOS project]$ git tag -a 'Release_1_0' -m 'Tagged basic string operation code' HEAD\n"
},
{
"code": null,
"e": 51645,
"s": 51466,
"text": "If you want to tag a particular commit, then use the appropriate COMMIT ID instead of the HEAD pointer. Tom uses the following command to push the tag into the remote repository."
},
{
"code": null,
"e": 51700,
"s": 51645,
"text": "[tom@CentOS project]$ git push origin tag Release_1_0\n"
},
{
"code": null,
"e": 51754,
"s": 51700,
"text": "The above command will produce the following result β"
},
{
"code": null,
"e": 51943,
"s": 51754,
"text": "Counting objects: 1, done.\nWriting objects: 100% (1/1), 183 bytes, done.\nTotal 1 (delta 0), reused 0 (delta 0)\nTo gituser@git.server.com:project.git\n* [new tag]\nRelease_1_0 β> Release_1_0\n"
},
{
"code": null,
"e": 52049,
"s": 51943,
"text": "Tom created tags. Now, Jerry can view all the available tags by using the Git tag command with βl option."
},
{
"code": null,
"e": 52405,
"s": 52049,
"text": "[jerry@CentOS src]$ pwd\n/home/jerry/jerry_repo/project/src\n\n[jerry@CentOS src]$ git pull\nremote: Counting objects: 1, done.\nremote: Total 1 (delta 0), reused 0 (delta 0)\nUnpacking objects: 100% (1/1), done.\nFrom git.server.com:project\n* [new tag]\nRelease_1_0 β> Release_1_0\nCurrent branch master is up to date.\n\n[jerry@CentOS src]$ git tag -l\nRelease_1_0\n"
},
{
"code": null,
"e": 52494,
"s": 52405,
"text": "Jerry uses the Git show command followed by its tag name to view more details about tag."
},
{
"code": null,
"e": 52536,
"s": 52494,
"text": "[jerry@CentOS src]$ git show Release_1_0\n"
},
{
"code": null,
"e": 52590,
"s": 52536,
"text": "The above command will produce the following result β"
},
{
"code": null,
"e": 53042,
"s": 52590,
"text": "tag Release_1_0\nTagger: Tom Cat <tom@tutorialspoint.com>\nDate: Wed Sep 11 13:45:54 2013 +0530\n\nTagged basic string operation code\n\n\ncommit 577647211ed44fe2ae479427a0668a4f12ed71a1\nAuthor: Tom Cat <tom@tutorialspoint.com>\nDate: Wed Sep 11 10:21:20 2013 +0530\n\nRemoved executable binary\n\ndiff --git a/src/string_operations b/src/string_operations\ndeleted file mode 100755\nindex 654004b..0000000\nBinary files a/src/string_operations and /dev/null differ\n"
},
{
"code": null,
"e": 53137,
"s": 53042,
"text": "Tom uses the following command to delete tags from the local as well as the remote repository."
},
{
"code": null,
"e": 53417,
"s": 53137,
"text": "[tom@CentOS project]$ git tag\nRelease_1_0\n\n[tom@CentOS project]$ git tag -d Release_1_0\nDeleted tag 'Release_1_0' (was 0f81ff4)\n# Remove tag from remote repository.\n\n[tom@CentOS project]$ git push origin :Release_1_0\nTo gituser@git.server.com:project.git\n- [deleted]\nRelease_1_0\n"
},
{
"code": null,
"e": 53668,
"s": 53417,
"text": "Patch is a text file, whose contents are similar to Git diff, but along with code, it also has metadata about commits; e.g., commit ID, date, commit message, etc. We can create a patch from commits and other people can apply them to their repository."
},
{
"code": null,
"e": 53829,
"s": 53668,
"text": "Jerry implements the strcat function for his project. Jerry can create a path of his code and send it to Tom. Then, he can apply the received patch to his code."
},
{
"code": null,
"e": 54013,
"s": 53829,
"text": "Jerry uses the Git format-patch command to create a patch for the latest commit. If you want to create a patch for a specific commit, then use COMMIT_ID with the format-patch command."
},
{
"code": null,
"e": 54436,
"s": 54013,
"text": "[jerry@CentOS project]$ pwd\n/home/jerry/jerry_repo/project/src\n\n[jerry@CentOS src]$ git status -s\nM string_operations.c\n?? string_operations\n\n[jerry@CentOS src]$ git add string_operations.c\n\n[jerry@CentOS src]$ git commit -m \"Added my_strcat function\"\n\n[master b4c7f09] Added my_strcat function\n1 files changed, 13 insertions(+), 0 deletions(-)\n\n[jerry@CentOS src]$ git format-patch -1\n0001-Added-my_strcat-function.patch\n"
},
{
"code": null,
"e": 54754,
"s": 54436,
"text": "The above command creates .patch files inside the current working directory. Tom can use this patch to modify his files. Git provides two commands to apply patches git amand git apply, respectively. Git apply modifies the local files without creating commit, while git am modifies the file and creates commit as well."
},
{
"code": null,
"e": 54816,
"s": 54754,
"text": "To apply patch and create commit, use the following command β"
},
{
"code": null,
"e": 55090,
"s": 54816,
"text": "[tom@CentOS src]$ pwd\n/home/tom/top_repo/project/src\n\n[tom@CentOS src]$ git diff\n\n[tom@CentOS src]$ git status βs\n\n[tom@CentOS src]$ git apply 0001-Added-my_strcat-function.patch\n\n[tom@CentOS src]$ git status -s\nM string_operations.c\n?? 0001-Added-my_strcat-function.patch\n"
},
{
"code": null,
"e": 55192,
"s": 55090,
"text": "The patch gets applied successfully, now we can view the modifications by using the git diff command."
},
{
"code": null,
"e": 55220,
"s": 55192,
"text": "[tom@CentOS src]$ git diff\n"
},
{
"code": null,
"e": 55274,
"s": 55220,
"text": "The above command will produce the following result β"
},
{
"code": null,
"e": 55941,
"s": 55274,
"text": "diff --git a/src/string_operations.c b/src/string_operations.c\nindex 8ab7f42..f282fcf 100644\n--- a/src/string_operations.c\n+++ b/src/string_operations.c\n@@ -1,5 +1,16 @@\n#include <stdio.h>\n+char *my_strcat(char *t, char *s)\ndiff --git a/src/string_operations.c b/src/string_operations.c\nindex 8ab7f42..f282fcf 100644\n--- a/src/string_operations.c\n+++ b/src/string_operations.c\n@@ -1,5 +1,16 @@\n#include <stdio.h>\n+char *my_strcat(char *t, char *s)\n+\n{\n +\n char *p = t;\n +\n +\n +\n while (*p)\n ++p;\n +\n while (*p++ = *s++)\n + ;\n + return t;\n +\n}\n+\nsize_t my_strlen(const char *s)\n{\n const char *p = s;\n @@ -23,6 +34,7 @@ int main(void)\n {\n"
},
{
"code": null,
"e": 56265,
"s": 55941,
"text": "Branch operation allows creating another line of development. We can use this operation to fork off the development process into two different directions. For example, we released a product for 6.0 version and we might want to create a branch so that the development of 7.0 features can be kept separate from 6.0 bug fixes."
},
{
"code": null,
"e": 56550,
"s": 56265,
"text": "Tom creates a new branch using the git branch <branch name> command. We can create a new branch from an existing one. We can use a specific commit or tag as the starting point. If any specific commit ID is not provided, then the branch will be created with HEAD as its starting point."
},
{
"code": null,
"e": 56645,
"s": 56550,
"text": "[jerry@CentOS src]$ git branch new_branch\n\n[jerry@CentOS src]$ git branch\n* master\nnew_branch\n"
},
{
"code": null,
"e": 56798,
"s": 56645,
"text": "A new branch is created; Tom used the git branch command to list the available branches. Git shows an asterisk mark before currently checked out branch."
},
{
"code": null,
"e": 56871,
"s": 56798,
"text": "The pictorial representation of create branch operation is shown below β"
},
{
"code": null,
"e": 56935,
"s": 56871,
"text": "Jerry uses the git checkout command to switch between branches."
},
{
"code": null,
"e": 57063,
"s": 56935,
"text": "[jerry@CentOS src]$ git checkout new_branch\nSwitched to branch 'new_branch'\n[jerry@CentOS src]$ git branch\nmaster\n* new_branch\n"
},
{
"code": null,
"e": 57286,
"s": 57063,
"text": "In the above example, we have used two commands to create and switch branches, respectively. Git provides βb option with the checkout command; this operation creates a new branch and immediately switches to the new branch."
},
{
"code": null,
"e": 57438,
"s": 57286,
"text": "[jerry@CentOS src]$ git checkout -b test_branch\nSwitched to a new branch 'test_branch'\n\n[jerry@CentOS src]$ git branch\nmaster\nnew_branch\n* test_branch\n"
},
{
"code": null,
"e": 57579,
"s": 57438,
"text": "A branch can be deleted by providing βD option with git branch command. But before deleting the existing branch, switch to the other branch."
},
{
"code": null,
"e": 57706,
"s": 57579,
"text": "Jerry is currently on test_branch and he wants to remove that branch. So he switches branch and deletes branch as shown below."
},
{
"code": null,
"e": 57928,
"s": 57706,
"text": "[jerry@CentOS src]$ git branch\nmaster\nnew_branch\n* test_branch\n\n[jerry@CentOS src]$ git checkout master\nSwitched to branch 'master'\n\n[jerry@CentOS src]$ git branch -D test_branch\nDeleted branch test_branch (was 5776472).\n"
},
{
"code": null,
"e": 57966,
"s": 57928,
"text": "Now, Git will show only two branches."
},
{
"code": null,
"e": 58018,
"s": 57966,
"text": "[jerry@CentOS src]$ git branch\n* master\nnew_branch\n"
},
{
"code": null,
"e": 58284,
"s": 58018,
"text": "Jerry decides to add support for wide characters in his string operations project. He has already created a new branch, but the branch name is not appropriate. So he changes the branch name by using βm option followed by the old branch name and the new branch name."
},
{
"code": null,
"e": 58396,
"s": 58284,
"text": "[jerry@CentOS src]$ git branch\n* master\nnew_branch\n\n[jerry@CentOS src]$ git branch -m new_branch wchar_support\n"
},
{
"code": null,
"e": 58455,
"s": 58396,
"text": "Now, the git branch command will show the new branch name."
},
{
"code": null,
"e": 58510,
"s": 58455,
"text": "[jerry@CentOS src]$ git branch\n* master\nwchar_support\n"
},
{
"code": null,
"e": 58630,
"s": 58510,
"text": "Jerry implements a function to return the string length of wide character string. New the code will appear as follows β"
},
{
"code": null,
"e": 58775,
"s": 58630,
"text": "[jerry@CentOS src]$ git branch\nmaster\n* wchar_support\n\n[jerry@CentOS src]$ pwd\n/home/jerry/jerry_repo/project/src\n\n[jerry@CentOS src]$ git diff\n"
},
{
"code": null,
"e": 58825,
"s": 58775,
"text": "The above command produces the following result β"
},
{
"code": null,
"e": 59159,
"s": 58825,
"text": "t a/src/string_operations.c b/src/string_operations.c\nindex 8ab7f42..8fb4b00 100644\n--- a/src/string_operations.c\n+++ b/src/string_operations.c\n@@ -1,4 +1,14 @@\n#include <stdio.h>\n+#include <wchar.h>\n+\n+size_t w_strlen(const wchar_t *s)\n+\n{\n +\n const wchar_t *p = s;\n +\n +\n while (*p)\n + ++p;\n + return (p - s);\n +\n}\n"
},
{
"code": null,
"e": 59227,
"s": 59159,
"text": "After testing, he commits and pushes his changes to the new branch."
},
{
"code": null,
"e": 59598,
"s": 59227,
"text": "[jerry@CentOS src]$ git status -s\nM string_operations.c\n?? string_operations\n\n[jerry@CentOS src]$ git add string_operations.c\n\n[jerry@CentOS src]$ git commit -m 'Added w_strlen function to return string lenght of wchar_t\nstring'\n\n[wchar_support 64192f9] Added w_strlen function to return string lenght of wchar_t string\n1 files changed, 10 insertions(+), 0 deletions(-)\n"
},
{
"code": null,
"e": 59735,
"s": 59598,
"text": "Note that Jerry is pushing these changes to the new branch, which is why he used the branch name wchar_support instead of master branch."
},
{
"code": null,
"e": 59814,
"s": 59735,
"text": "[jerry@CentOS src]$ git push origin wchar_support <βββ Observer branch_name\n"
},
{
"code": null,
"e": 59867,
"s": 59814,
"text": "The above command will produce the following result."
},
{
"code": null,
"e": 60102,
"s": 59867,
"text": "Counting objects: 7, done.\nCompressing objects: 100% (4/4), done.\nWriting objects: 100% (4/4), 507 bytes, done.\nTotal 4 (delta 1), reused 0 (delta 0)\nTo gituser@git.server.com:project.git\n* [new branch]\nwchar_support -> wchar_support\n"
},
{
"code": null,
"e": 60172,
"s": 60102,
"text": "After committing the changes, the new branch will appear as follows β"
},
{
"code": null,
"e": 60288,
"s": 60172,
"text": "Tom is curious about what Jerry is doing in his private branch and he checks the log from the wchar_support branch."
},
{
"code": null,
"e": 60392,
"s": 60288,
"text": "[tom@CentOS src]$ pwd\n/home/tom/top_repo/project/src\n\n[tom@CentOS src]$ git log origin/wchar_support -2"
},
{
"code": null,
"e": 60445,
"s": 60392,
"text": "The above command will produce the following result."
},
{
"code": null,
"e": 60800,
"s": 60445,
"text": "commit 64192f91d7cc2bcdf3bf946dd33ece63b74184a3\nAuthor: Jerry Mouse <jerry@tutorialspoint.com>\nDate: Wed Sep 11 16:10:06 2013 +0530\n\nAdded w_strlen function to return string lenght of wchar_t string\n\n\ncommit 577647211ed44fe2ae479427a0668a4f12ed71a1\nAuthor: Tom Cat <tom@tutorialspoint.com>\nDate: Wed Sep 11 10:21:20 2013 +0530\n\nRemoved executable binary\n"
},
{
"code": null,
"e": 61067,
"s": 60800,
"text": "By viewing commit messages, Tom realizes that Jerry implemented the strlen function for wide character and he wants the same functionality in the master branch. Instead of re-implementing, he decides to take Jerryβs code by merging his branch with the master branch."
},
{
"code": null,
"e": 61347,
"s": 61067,
"text": "[tom@CentOS project]$ git branch\n* master\n\n[tom@CentOS project]$ pwd\n/home/tom/top_repo/project\n\n[tom@CentOS project]$ git merge origin/wchar_support\nUpdating 5776472..64192f9\nFast-forward\nsrc/string_operations.c | 10 ++++++++++\n1 files changed, 10 insertions(+), 0 deletions(-)\n"
},
{
"code": null,
"e": 61417,
"s": 61347,
"text": "After the merge operation, the master branch will appear as follows β"
},
{
"code": null,
"e": 61605,
"s": 61417,
"text": "Now, the branch wchar_support has been merged with the master branch. We can verify it by viewing the commit message or by viewing the modifications done into the string_operation.c file."
},
{
"code": null,
"e": 61887,
"s": 61605,
"text": "[tom@CentOS project]$ cd src/\n\n[tom@CentOS src]$ git log -1\n\ncommit 64192f91d7cc2bcdf3bf946dd33ece63b74184a3\nAuthor: Jerry Mouse \nDate: Wed Sep 11 16:10:06 2013 +0530\n\nAdded w_strlen function to return string lenght of wchar_t string\n\n[tom@CentOS src]$ head -12 string_operations.c"
},
{
"code": null,
"e": 61940,
"s": 61887,
"text": "The above command will produce the following result."
},
{
"code": null,
"e": 62088,
"s": 61940,
"text": "#include <stdio.h>\n#include <wchar.h>\nsize_t w_strlen(const wchar_t *s)\n{\n const wchar_t *p = s;\n\n while (*p)\n ++p;\n\n return (p - s);\n}\n"
},
{
"code": null,
"e": 62152,
"s": 62088,
"text": "After testing, he pushes his code changes to the master branch."
},
{
"code": null,
"e": 62303,
"s": 62152,
"text": "[tom@CentOS src]$ git push origin master\nTotal 0 (delta 0), reused 0 (delta 0)\nTo gituser@git.server.com:project.git\n5776472..64192f9 master β> master"
},
{
"code": null,
"e": 62414,
"s": 62303,
"text": "The Git rebase command is a branch merge command, but the difference is that it modifies the order of commits."
},
{
"code": null,
"e": 62716,
"s": 62414,
"text": "The Git merge command tries to put the commits from other branches on top of the HEAD of the current local branch. For example, your local branch has commits Aβ>Bβ>Cβ>D and the merge branch has commits Aβ>Bβ>Xβ>Y, then git merge will convert the current local branch to something like Aβ>Bβ>Cβ>Dβ>Xβ>Y"
},
{
"code": null,
"e": 63134,
"s": 62716,
"text": "The Git rebase command tries to find out the common ancestor between the current local branch and the merge branch. It then pushes the commits to the local branch by modifying the order of commits in the current local branch. For example, if your local branch has commits Aβ>Bβ>Cβ>D and the merge branch has commits Aβ>Bβ>Xβ>Y, then Git rebase will convert the current local branch to something like Aβ>Bβ>Xβ>Yβ>Cβ>D."
},
{
"code": null,
"e": 63410,
"s": 63134,
"text": "When multiple developers work on a single remote repository, you cannot modify the order of the commits in the remote repository. In this situation, you can use rebase operation to put your local commits on top of the remote repository commits and you can push these changes."
},
{
"code": null,
"e": 63536,
"s": 63410,
"text": "Jerry is working on the wchar_support branch. He changes the name of the functions and after testing, he commits his changes."
},
{
"code": null,
"e": 63621,
"s": 63536,
"text": "[jerry@CentOS src]$ git branch\n master\n* wchar_support\n[jerry@CentOS src]$ git diff\n"
},
{
"code": null,
"e": 63671,
"s": 63621,
"text": "The above command produces the following result β"
},
{
"code": null,
"e": 63978,
"s": 63671,
"text": "diff --git a/src/string_operations.c b/src/string_operations.c\nindex 8fb4b00..01ff4e0 100644\n--- a/src/string_operations.c\n+++ b/src/string_operations.c\n@@ -1,7 +1,7 @@\n#include <stdio.h>\n#include <wchar.h>\n-size_t w_strlen(const wchar_t *s)\n+size_t my_wstrlen(const wchar_t *s)\n{\n const wchar_t *p = s;\n"
},
{
"code": null,
"e": 64027,
"s": 63978,
"text": "After verifying the code he commits his changes."
},
{
"code": null,
"e": 64338,
"s": 64027,
"text": "[jerry@CentOS src]$ git status -s\nM string_operations.c\n\n[jerry@CentOS src]$ git add string_operations.c\n\n[jerry@CentOS src]$ git commit -m 'Changed function name'\n[wchar_support 3789fe8] Changed function name\n1 files changed, 1 insertions(+), 1 deletions(-)\n\n[jerry@CentOS src]$ git push origin wchar_support\n"
},
{
"code": null,
"e": 64392,
"s": 64338,
"text": "The above command will produce the following result β"
},
{
"code": null,
"e": 64629,
"s": 64392,
"text": "Counting objects: 7, done.\nCompressing objects: 100% (4/4), done.\nWriting objects: 100% (4/4), 409 bytes, done.\nTotal 4 (delta 1), reused 0 (delta 0)\nTo gituser@git.server.com:project.git\n64192f9..3789fe8 wchar_support -> wchar_support\n"
},
{
"code": null,
"e": 64753,
"s": 64629,
"text": "Meanwhile in the master branch, Tom also changes the name of the same function and pushes his changes to the master branch."
},
{
"code": null,
"e": 64819,
"s": 64753,
"text": "[tom@CentOS src]$ git branch\n* master\n[tom@CentOS src]$ git diff\n"
},
{
"code": null,
"e": 64869,
"s": 64819,
"text": "The above command produces the following result β"
},
{
"code": null,
"e": 65216,
"s": 64869,
"text": "diff --git a/src/string_operations.c b/src/string_operations.c\nindex 8fb4b00..52bec84 100644\n--- a/src/string_operations.c\n+++ b/src/string_operations.c\n@@ -1,7 +1,8 @@\n#include <stdio.h>\n#include <wchar.h>\n-size_t w_strlen(const wchar_t *s)\n+/* wide character strlen fucntion */\n+size_t my_wc_strlen(const wchar_t *s)\n{\n const wchar_t *p = s;\n"
},
{
"code": null,
"e": 65262,
"s": 65216,
"text": "After verifying diff, he commits his changes."
},
{
"code": null,
"e": 65611,
"s": 65262,
"text": "[tom@CentOS src]$ git status -s\nM string_operations.c\n\n[tom@CentOS src]$ git add string_operations.c\n\n[tom@CentOS src]$ git commit -m 'Changed function name from w_strlen to my_wc_strlen'\n[master ad4b530] Changed function name from w_strlen to my_wc_strlen\n1 files changed, 2 insertions(+), 1 deletions(-)\n\n[tom@CentOS src]$ git push origin master\n"
},
{
"code": null,
"e": 65665,
"s": 65611,
"text": "The above command will produce the following result β"
},
{
"code": null,
"e": 65888,
"s": 65665,
"text": "Counting objects: 7, done.\nCompressing objects: 100% (4/4), done.\nWriting objects: 100% (4/4), 470 bytes, done.\nTotal 4 (delta 1), reused 0 (delta 0)\nTo gituser@git.server.com:project.git\n64192f9..ad4b530 master -> master\n"
},
{
"code": null,
"e": 66055,
"s": 65888,
"text": "On the wchar_support branch, Jerry implements strchr function for wide character string. After testing, he commits and pushes his changes to the wchar_support branch."
},
{
"code": null,
"e": 66139,
"s": 66055,
"text": "[jerry@CentOS src]$ git branch\nmaster\n* wchar_support\n[jerry@CentOS src]$ git diff\n"
},
{
"code": null,
"e": 66189,
"s": 66139,
"text": "The above command produces the following result β"
},
{
"code": null,
"e": 66652,
"s": 66189,
"text": "diff --git a/src/string_operations.c b/src/string_operations.c\nindex 01ff4e0..163a779 100644\n--- a/src/string_operations.c\n+++ b/src/string_operations.c\n@@ -1,6 +1,16 @@\n#include <stdio.h>\n#include <wchar.h>\n+wchar_t *my_wstrchr(wchar_t *ws, wchar_t wc)\n+\n{\n +\n while (*ws) \n {\n +\n if (*ws == wc)\n +\n return ws;\n +\n ++ws;\n + \n }\n + return NULL;\n +\n}\n+\nsize_t my_wstrlen(const wchar_t *s)\n{\n const wchar_t *p = s;\n"
},
{
"code": null,
"e": 66693,
"s": 66652,
"text": "After verifying, he commits his changes."
},
{
"code": null,
"e": 67059,
"s": 66693,
"text": "[jerry@CentOS src]$ git status -s\nM string_operations.c\n\n[jerry@CentOS src]$ git add string_operations.c\n\n[jerry@CentOS src]$ git commit -m 'Addded strchr function for wide character string'\n[wchar_support 9d201a9] Addded strchr function for wide character string\n1 files changed, 10 insertions(+), 0 deletions(-)\n\n[jerry@CentOS src]$ git push origin wchar_support\n"
},
{
"code": null,
"e": 67113,
"s": 67059,
"text": "The above command will produce the following result β"
},
{
"code": null,
"e": 67350,
"s": 67113,
"text": "Counting objects: 7, done.\nCompressing objects: 100% (4/4), done.\nWriting objects: 100% (4/4), 516 bytes, done.\nTotal 4 (delta 1), reused 0 (delta 0)\nTo gituser@git.server.com:project.git\n3789fe8..9d201a9 wchar_support -> wchar_support\n"
},
{
"code": null,
"e": 67543,
"s": 67350,
"text": "Tom wants to see what Jerry is doing on his private branch so, he tries to pull the latest changes from the wchar_support branch, but Git aborts the operation with the following error message."
},
{
"code": null,
"e": 67592,
"s": 67543,
"text": "[tom@CentOS src]$ git pull origin wchar_support\n"
},
{
"code": null,
"e": 67642,
"s": 67592,
"text": "The above command produces the following result β"
},
{
"code": null,
"e": 68055,
"s": 67642,
"text": "remote: Counting objects: 11, done.\n63Git Tutorials\nremote: Compressing objects: 100% (8/8), done.\nremote: Total 8 (delta 2), reused 0 (delta 0)\nUnpacking objects: 100% (8/8), done.\nFrom git.server.com:project\n* branch\nwchar_support -> FETCH_HEAD\nAuto-merging src/string_operations.c\nCONFLICT (content): Merge conflict in src/string_operations.c\nAutomatic merge failed; fix conflicts and then commit the result.\n"
},
{
"code": null,
"e": 68199,
"s": 68055,
"text": "From the error message, it is clear that there is a conflict in src/string_operations.c . He runs the git diff command to view further details."
},
{
"code": null,
"e": 68227,
"s": 68199,
"text": "[tom@CentOS src]$ git diff\n"
},
{
"code": null,
"e": 68277,
"s": 68227,
"text": "The above command produces the following result β"
},
{
"code": null,
"e": 68872,
"s": 68277,
"text": "diff --cc src/string_operations.c\nindex 52bec84,163a779..0000000\n--- a/src/string_operations.c\n+++ b/src/string_operations.c\n@@@ -1,8 -1,17 +1,22 @@@\n#include <stdio.h>\n#include <wchar.h>\n++<<<<<<< HEAD\n+/* wide character strlen fucntion */\n+size_t my_wc_strlen(const wchar_t *s)\n++=======\n+ wchar_t *my_wstrchr(wchar_t *ws, wchar_t wc)\n+\n{\n +\n +\n while (*ws) \n {\n if (*ws == wc)\n +\n return ws;\n +\n ++ws;\n + \n }\n + return NULL;\n +\n}\n+\n+ size_t my_wstrlen(const wchar_t *s)\n++>>>>>>>9d201a9c61bc4713f4095175f8954b642dae8f86\n{\n const wchar_t *p = s;\n"
},
{
"code": null,
"e": 69019,
"s": 68872,
"text": "As both Tom and Jerry changed the name of the same function, Git is in a state of confusion and it asks the user to resolve the conflict manually."
},
{
"code": null,
"e": 69193,
"s": 69019,
"text": "Tom decides to keep the function name suggested by Jerry, but he keeps the comment added by him, as it is. After removing the conflict markers, git diff will look like this."
},
{
"code": null,
"e": 69221,
"s": 69193,
"text": "[tom@CentOS src]$ git diff\n"
},
{
"code": null,
"e": 69270,
"s": 69221,
"text": "The above command produces the following result."
},
{
"code": null,
"e": 69828,
"s": 69270,
"text": "diff --cc src/string_operations.c\ndiff --cc src/string_operations.c\nindex 52bec84,163a779..0000000\n--- a/src/string_operations.c\n+++ b/src/string_operations.c\n@@@ -1,8 -1,17 +1,18 @@@\n#include <stdio.h>\n#include <wchar.h>\n+ wchar_t *my_wstrchr(wchar_t *ws, wchar_t wc)\n+\n{\n +\n while (*ws) \n {\n +\n if (*ws == wc)\n +\n return ws;\n +\n ++ws;\n + \n }\n + return NULL;\n +\n}\n+\n+/* wide character strlen fucntion */\n- size_t my_wc_strlen(const wchar_t *s)\n+ size_t my_wstrlen(const wchar_t *s)\n{\n const wchar_t *p = s;\n"
},
{
"code": null,
"e": 69937,
"s": 69828,
"text": "As Tom has modified the files, he has to commit these changes first and thereafter, he can pull the changes."
},
{
"code": null,
"e": 70078,
"s": 69937,
"text": "[tom@CentOS src]$ git commit -a -m 'Resolved conflict'\n[master 6b1ac36] Resolved conflict\n\n[tom@CentOS src]$ git pull origin wchar_support.\n"
},
{
"code": null,
"e": 70146,
"s": 70078,
"text": "Tom has resolved the conflict, now the pull operation will succeed."
},
{
"code": null,
"e": 70334,
"s": 70146,
"text": "GNU/Linux and Mac OS uses line-feed (LF), or new line as line ending character, while Windows uses line-feed and carriage-return (LFCR) combination to represent the line-ending character."
},
{
"code": null,
"e": 70494,
"s": 70334,
"text": "To avoid unnecessary commits because of these line-ending differences, we have to configure the Git client to write the same line ending to the Git repository."
},
{
"code": null,
"e": 70713,
"s": 70494,
"text": "For Windows system, we can configure the Git client to convert line endings to CRLF format while checking out, and convert them back to LF format during the commit operation. The following settings will do the needful."
},
{
"code": null,
"e": 70775,
"s": 70713,
"text": "[tom@CentOS project]$ git config --global core.autocrlf true\n"
},
{
"code": null,
"e": 70913,
"s": 70775,
"text": "For GNU/Linux or Mac OS, we can configure the Git client to convert line endings from CRLF to LF while performing the checkout operation."
},
{
"code": null,
"e": 70976,
"s": 70913,
"text": "[tom@CentOS project]$ git config --global core.autocrlf input\n"
},
{
"code": null,
"e": 71269,
"s": 70976,
"text": "GitHub is a web-based hosting service for software development projects that uses the Git revision control system. It also has their standard GUI application available for download (Windows, Mac, GNU/ Linux) directly from the service's website. But in this session, we will see only CLI part."
},
{
"code": null,
"e": 71447,
"s": 71269,
"text": "Go to github.com. If you already have the GitHub account, then login using that account or create a new one. Follow the steps from github.com website to create a new repository."
},
{
"code": null,
"e": 71562,
"s": 71447,
"text": "Tom decides to use the GitHub server. To start a new project, he creates a new directory and one file inside that."
},
{
"code": null,
"e": 71721,
"s": 71562,
"text": "[tom@CentOS]$ mkdir github_repo\n\n[tom@CentOS]$ cd github_repo/\n\n[tom@CentOS]$ vi hello.c\n\n[tom@CentOS]$ make hello\ncc hello.c -o hello\n\n[tom@CentOS]$ ./hello\n"
},
{
"code": null,
"e": 71774,
"s": 71721,
"text": "The above command will produce the following result:"
},
{
"code": null,
"e": 71792,
"s": 71774,
"text": "Hello, World !!!\n"
},
{
"code": null,
"e": 71906,
"s": 71792,
"text": "After verifying his code, he initializes the directory with the git init command and commits his changes locally."
},
{
"code": null,
"e": 72168,
"s": 71906,
"text": "[tom@CentOS]$ git init\nInitialized empty Git repository in /home/tom/github_repo/.git/\n\n[tom@CentOS]$ git status -s\n?? hello\n?? hello.c\n\n[tom@CentOS]$ git add hello.c\n\n[tom@CentOS]$ git status -s\nA hello.c\n?? hello\n\n[tom@CentOS]$ git commit -m 'Initial commit'\n"
},
{
"code": null,
"e": 72282,
"s": 72168,
"text": "After that, he adds the GitHub repository URL as a remote origin and pushes his changes to the remote repository."
},
{
"code": null,
"e": 72407,
"s": 72282,
"text": "[tom@CentOS]$ git remote add origin https://github.com/kangralkar/testing_repo.git\n\n[tom@CentOS]$ git push -u origin master\n"
},
{
"code": null,
"e": 72527,
"s": 72407,
"text": "Push operation will ask for GitHub user name and password. After successful authentication, the operation will succeed."
},
{
"code": null,
"e": 72580,
"s": 72527,
"text": "The above command will produce the following result:"
},
{
"code": null,
"e": 72935,
"s": 72580,
"text": "Username for 'https://github.com': kangralkar\nPassword for 'https://kangralkar@github.com': \nCounting objects: 3, done.\nWriting objects: 100% (3/3), 214 bytes, done.\nTotal 3 (delta 0), reused 0 (delta 0)\nTo https://github.com/kangralkar/test_repo.git\n * [new branch] master β> master\n Branch master set up to track remote branch master from origin.\n"
},
{
"code": null,
"e": 73078,
"s": 72935,
"text": "From now, Tom can push any changes to the GitHub repository. He can use all the commands discussed in this chapter with the GitHub repository."
},
{
"code": null,
"e": 73255,
"s": 73078,
"text": "Tom successfully pushed all his changes to the GitHub repository. Now, other developers can view these changes by performing clone operation or updating their local repository."
},
{
"code": null,
"e": 73372,
"s": 73255,
"text": "Jerry creates a new directory in his home directory and clones the GitHub repository by using the git clone command."
},
{
"code": null,
"e": 73510,
"s": 73372,
"text": "[jerry@CentOS]$ pwd\n/home/jerry\n\n[jerry@CentOS]$ mkdir jerry_repo\n\n[jerry@CentOS]$ git clone https://github.com/kangralkar/test_repo.git\n"
},
{
"code": null,
"e": 73559,
"s": 73510,
"text": "The above command produces the following result:"
},
{
"code": null,
"e": 73706,
"s": 73559,
"text": "Cloning into 'test_repo'...\nremote: Counting objects: 3, done.\nremote: Total 3 (delta 0), reused 3 (delta 0)\nUnpacking objects: 100% (3/3), done.\n"
},
{
"code": null,
"e": 73770,
"s": 73706,
"text": "He verifies the directory contents by executing the ls command."
},
{
"code": null,
"e": 73839,
"s": 73770,
"text": "[jerry@CentOS]$ ls\ntest_repo\n\n[jerry@CentOS]$ ls test_repo/\nhello.c\n"
},
{
"code": null,
"e": 73876,
"s": 73839,
"text": "\n 251 Lectures \n 35.5 hours \n"
},
{
"code": null,
"e": 73893,
"s": 73876,
"text": " Gowthami Swarna"
},
{
"code": null,
"e": 73926,
"s": 73893,
"text": "\n 23 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 73940,
"s": 73926,
"text": " Asif Hussain"
},
{
"code": null,
"e": 73975,
"s": 73940,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 73992,
"s": 73975,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 74026,
"s": 73992,
"text": "\n 125 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 74037,
"s": 74026,
"text": " John Shea"
},
{
"code": null,
"e": 74072,
"s": 74037,
"text": "\n 13 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 74086,
"s": 74072,
"text": " Raghu Pandey"
},
{
"code": null,
"e": 74119,
"s": 74086,
"text": "\n 13 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 74139,
"s": 74119,
"text": " Sebastian Sulinski"
},
{
"code": null,
"e": 74146,
"s": 74139,
"text": " Print"
},
{
"code": null,
"e": 74157,
"s": 74146,
"text": " Add Notes"
}
] |
How to resolve a NullPointerException in Java?
|
A NullPointerException is a runtime exception thrown by the JVM when our application code, other referenced API or the middleware encounters the following conditions
Attempting to invoke an instance method of a null object.
Attempting to access or modify a particular field of a null object.
Attempting to obtain the length of a null object as an array.
Review the java.lang.NullPointerException stack trace and determine where the Exception is triggered (Application code, third-party API, middleware software and extract the line).
If the problem is at the application code then a code walk-through will be required. If the problem is found from third-party API or middleware, need to first review the referenced code and determine if it could indirectly be the source of the problem, for instance, passing a null value to a third party API method, etc.
If problem found within the application code, then attempt to determine which Object instance is null and causing the problem. We need to modify the code in order to add proper null check validations and proper logging so we can understand the source of the null value as well.
public class NPEDemo {
private String field1 = null;
private String field2 = null;
public String getField1() {
return field1;
}
private void setField1(String field1) {
this.field1 = field1;
}
public String getField2() {
return field2;
}
private void setField2(String field2) {
this.field2 = field2;
}
public static void main(String[] args) {
try {
NPEDemo npe = new NPEDemo();
npe.setField1("field1 value");
npe = null;
npe.setField2("field2 Value");
} catch (Throwable e) {
System.out.println("Java Error is: "+e );
e.printStackTrace();
}
}
}
Java Error is: java.lang.NullPointerException
java.lang.NullPointerException
at NPEDemo.main(NPEDemo.java:24)
|
[
{
"code": null,
"e": 1228,
"s": 1062,
"text": "A NullPointerException is a runtime exception thrown by the JVM when our application code, other referenced API or the middleware encounters the following conditions"
},
{
"code": null,
"e": 1286,
"s": 1228,
"text": "Attempting to invoke an instance method of a null object."
},
{
"code": null,
"e": 1354,
"s": 1286,
"text": "Attempting to access or modify a particular field of a null object."
},
{
"code": null,
"e": 1416,
"s": 1354,
"text": "Attempting to obtain the length of a null object as an array."
},
{
"code": null,
"e": 1596,
"s": 1416,
"text": "Review the java.lang.NullPointerException stack trace and determine where the Exception is triggered (Application code, third-party API, middleware software and extract the line)."
},
{
"code": null,
"e": 1918,
"s": 1596,
"text": "If the problem is at the application code then a code walk-through will be required. If the problem is found from third-party API or middleware, need to first review the referenced code and determine if it could indirectly be the source of the problem, for instance, passing a null value to a third party API method, etc."
},
{
"code": null,
"e": 2196,
"s": 1918,
"text": "If problem found within the application code, then attempt to determine which Object instance is null and causing the problem. We need to modify the code in order to add proper null check validations and proper logging so we can understand the source of the null value as well."
},
{
"code": null,
"e": 2872,
"s": 2196,
"text": "public class NPEDemo {\n private String field1 = null;\n private String field2 = null;\n public String getField1() {\n return field1;\n }\n private void setField1(String field1) {\n this.field1 = field1;\n }\n public String getField2() {\n return field2;\n }\n private void setField2(String field2) {\n this.field2 = field2;\n }\n public static void main(String[] args) {\n try {\n NPEDemo npe = new NPEDemo();\n npe.setField1(\"field1 value\");\n npe = null;\n npe.setField2(\"field2 Value\");\n } catch (Throwable e) {\n System.out.println(\"Java Error is: \"+e );\n e.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 2982,
"s": 2872,
"text": "Java Error is: java.lang.NullPointerException\njava.lang.NullPointerException\nat NPEDemo.main(NPEDemo.java:24)"
}
] |
Encode an ASCII string into Base-64 Format - GeeksforGeeks
|
24 Sep, 2021
Base 64 is an encoding scheme that converts binary data into text format so that encoded textual data can be easily transported over network un-corrupted and without any data loss. Base64 is used commonly in a number of applications including email via MIME, and storing complex data in XML. Problem with sending normal binary data to a network is that bits can be misinterpreted by underlying protocols, produce incorrect data at receiving node and that is why we use this code.
Why base 64 ?
Resultant text after encoding our data has those characters which are widely present in many character sets so there is very less chance of data being corrupted or modified.
How to convert into base 64 format ?
The character set in base64 is
char_set = "ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz0123456789+/"
// 64 characters
Basic idea
Lets take an example. We have to encode string βMENONβ into base64 format. Lets call βMENONβ as input_str, above base64 character set (βABC..+/β) as char_set and resultant encoded string as res_str.
Take 3 characters from input_str i.e βMENβ since each character size is 8 bits we will have(8 * 3) 24 bits with us.Group them in a block of 6 bits each (24 / 6 = 4 blocks). (why 6?) because 2^6 = 64 characters, with 6 bits we can represent each character in char_set.Convert each block of 6 bits to its corresponding decimal value. Decimal value obtained is the index of resultant encoded character in char_set.So for each 3 characters from input_str we will receive 4 characters in res_str.What if we have less than 3 characters in input_str left i.e βONβ. We have 16 bits and blocks will be 16 / 6 = 2 blocks. Rightmost 4 bits will not make a proper block (1 block = 6 bits) so we append zeros to right side of block to make it a proper block i.e 2 zeros will be appended to right. Now we have 3 proper blocks, find corresponding decimal value of each block to get index.Since There were less than 3 characters (βONβ) in input_str we will append β=β in res_str. e.g βONβ here 3 β 2 = 1 padding of β=β in res_str.
Take 3 characters from input_str i.e βMENβ since each character size is 8 bits we will have(8 * 3) 24 bits with us.
Group them in a block of 6 bits each (24 / 6 = 4 blocks). (why 6?) because 2^6 = 64 characters, with 6 bits we can represent each character in char_set.
Convert each block of 6 bits to its corresponding decimal value. Decimal value obtained is the index of resultant encoded character in char_set.
So for each 3 characters from input_str we will receive 4 characters in res_str.
What if we have less than 3 characters in input_str left i.e βONβ. We have 16 bits and blocks will be 16 / 6 = 2 blocks. Rightmost 4 bits will not make a proper block (1 block = 6 bits) so we append zeros to right side of block to make it a proper block i.e 2 zeros will be appended to right. Now we have 3 proper blocks, find corresponding decimal value of each block to get index.
Since There were less than 3 characters (βONβ) in input_str we will append β=β in res_str. e.g βONβ here 3 β 2 = 1 padding of β=β in res_str.
Example
1. Convert βMENONβ into its (8 bit) binary state format. Take each characters of the string and write its 8 β bit binary representation. ASCII values of characters in string to be encoded
M : 77 (01001101), E : 69 (01000101),
N : 78 (01001110), O : 79 (01001111), N : 78 (01001110)
resultant binary data of above string is :
01001101 01000101 01001110 01001111 01001110
2. Starting from left make blocks of 6 bits until all bits are covered BIT-STREAM :
(010011) (010100) (010101) (001110) (010011) (110100) (1110)
3. If the rightmost block is less than 6 bits just append zeros to the right of that block to make it 6 bits. Here in above example we have to appended 2 zeros to make it 6. BIT-STREAM :
(010011) (010100) (010101) (001110) (010011) (110100) (111000)
Notice the bold zeros.4. Take 3 characters from input_str (βMENβ) i.e 24 bits and find corresponding decimal value (index to char_set). BLOCKS :
INDEX --> (010011) : 19, (010100) : 20, (010101) : 21, (001110) : 14
char_set[19] = T, char_set[20] = U, char_set[21] = V, char_set[14] = O
So our input_str = βMENβ will be converted to encoded string βTUVOβ.5. Take remaining characters (βONβ). We have to pad resultant encoded string with 1 β=β as number of characters is less than 3 in input_str. (3 β 2 = 1 padding) BLOCKS :
INDEX --> (010011) : 19 (110100) : 52 (111000) : 56
char_set[19] = T char_set[52] = 0 char_set[56] = 4
So our input_str = "ON" will be converted to encoded string "T04=".
Examples:
Input : MENON // string in ASCII
Output :TUVOT04= // encoded string in Base 64.
Input : geeksforgeeks
Output : Z2Vla3Nmb3JnZWVrcw==
We can use bitwise operators to encode our string. We can take an integer βvalβ (usually 4 bytes on most compilers) and store all characters of input_str (3 at a time) in val. The characters from input_str will be stored in val in form of bits. We will use (OR operator) to store the characters and (LEFT β SHIFT) by 8 so to make room for another 8 bits. In similar fashion we will use (RIGHT β SHIFT) to retrieve bits from val 6 at a time and find value of bits by doing & with 63 (111111) which will give us index. Then we can get our resultant character by just going to that index of char_set.
C++
C
// C++ program to encode an ASCII// string in Base64 format#include <iostream>using namespace std;#define SIZE 1000 // Takes string to be encoded as input// and its length and returns encoded stringchar* base64Encoder(char input_str[], int len_str){ // Character set of base64 encoding scheme char char_set[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; // Resultant string char *res_str = (char *) malloc(SIZE * sizeof(char)); int index, no_of_bits = 0, padding = 0, val = 0, count = 0, temp; int i, j, k = 0; // Loop takes 3 characters at a time from // input_str and stores it in val for (i = 0; i < len_str; i += 3) { val = 0, count = 0, no_of_bits = 0; for (j = i; j < len_str && j <= i + 2; j++) { // binary data of input_str is stored in val val = val << 8; // (A + 0 = A) stores character in val val = val | input_str[j]; // calculates how many time loop // ran if "MEN" -> 3 otherwise "ON" -> 2 count++; } no_of_bits = count * 8; // calculates how many "=" to append after res_str. padding = no_of_bits % 3; // extracts all bits from val (6 at a time) // and find the value of each block while (no_of_bits != 0) { // retrieve the value of each block if (no_of_bits >= 6) { temp = no_of_bits - 6; // binary of 63 is (111111) f index = (val >> temp) & 63; no_of_bits -= 6; } else { temp = 6 - no_of_bits; // append zeros to right if bits are less than 6 index = (val << temp) & 63; no_of_bits = 0; } res_str[k++] = char_set[index]; } } // padding is done here for (i = 1; i <= padding; i++) { res_str[k++] = '='; } res_str[k] = '\0'; return res_str; } // Driver codeint main(){ char input_str[] = "MENON"; int len_str; // calculates length of string len_str = sizeof(input_str) / sizeof(input_str[0]); // to exclude '\0' character len_str -= 1; cout <<"Input string is : "<< input_str << endl; cout <<"Encoded string is : "<< base64Encoder(input_str, len_str)<< endl; return 0;} // This code is contributed by shivanisinghss2110
// C program to encode an ASCII// string in Base64 format#include <stdio.h>#include <stdlib.h>#define SIZE 1000 // Takes string to be encoded as input// and its length and returns encoded stringchar* base64Encoder(char input_str[], int len_str){ // Character set of base64 encoding scheme char char_set[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; // Resultant string char *res_str = (char *) malloc(SIZE * sizeof(char)); int index, no_of_bits = 0, padding = 0, val = 0, count = 0, temp; int i, j, k = 0; // Loop takes 3 characters at a time from // input_str and stores it in val for (i = 0; i < len_str; i += 3) { val = 0, count = 0, no_of_bits = 0; for (j = i; j < len_str && j <= i + 2; j++) { // binary data of input_str is stored in val val = val << 8; // (A + 0 = A) stores character in val val = val | input_str[j]; // calculates how many time loop // ran if "MEN" -> 3 otherwise "ON" -> 2 count++; } no_of_bits = count * 8; // calculates how many "=" to append after res_str. padding = no_of_bits % 3; // extracts all bits from val (6 at a time) // and find the value of each block while (no_of_bits != 0) { // retrieve the value of each block if (no_of_bits >= 6) { temp = no_of_bits - 6; // binary of 63 is (111111) f index = (val >> temp) & 63; no_of_bits -= 6; } else { temp = 6 - no_of_bits; // append zeros to right if bits are less than 6 index = (val << temp) & 63; no_of_bits = 0; } res_str[k++] = char_set[index]; } } // padding is done here for (i = 1; i <= padding; i++) { res_str[k++] = '='; } res_str[k] = '\0;'; return res_str; } // Driver codeint main(){ char input_str[] = "MENON"; int len_str; // calculates length of string len_str = sizeof(input_str) / sizeof(input_str[0]); // to exclude '\0' character len_str -= 1; printf("Input string is : %s\n", input_str); printf("Encoded string is : %s\n", base64Encoder(input_str, len_str)); return 0;}
Input string is : MENON
Encoded string is : TUVOT04=
Time Complexity: O(2 * N) inserting bits into val + retrieving bits form valExercise : Implement a base 64 decoderThis article is contributed by Arshpreet Soodan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ashug716716716
shivanisinghss2110
prajalpatidar01
C-String
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
'this' pointer in C++
Multithreading in C
Arrow operator -> in C/C++ with Examples
Smart Pointers in C++ and How to Use Them
Multiple Inheritance in C++
Understanding "extern" keyword in C
Ways to copy a vector in C++
UDP Server-Client implementation in C
|
[
{
"code": null,
"e": 25477,
"s": 25449,
"text": "\n24 Sep, 2021"
},
{
"code": null,
"e": 25959,
"s": 25477,
"text": "Base 64 is an encoding scheme that converts binary data into text format so that encoded textual data can be easily transported over network un-corrupted and without any data loss. Base64 is used commonly in a number of applications including email via MIME, and storing complex data in XML. Problem with sending normal binary data to a network is that bits can be misinterpreted by underlying protocols, produce incorrect data at receiving node and that is why we use this code. "
},
{
"code": null,
"e": 25973,
"s": 25959,
"text": "Why base 64 ?"
},
{
"code": null,
"e": 26149,
"s": 25973,
"text": "Resultant text after encoding our data has those characters which are widely present in many character sets so there is very less chance of data being corrupted or modified. "
},
{
"code": null,
"e": 26186,
"s": 26149,
"text": "How to convert into base 64 format ?"
},
{
"code": null,
"e": 26219,
"s": 26186,
"text": "The character set in base64 is "
},
{
"code": null,
"e": 26316,
"s": 26219,
"text": "char_set = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\nabcdefghijklmnopqrstuvwxyz0123456789+/\" \n// 64 characters"
},
{
"code": null,
"e": 26329,
"s": 26318,
"text": "Basic idea"
},
{
"code": null,
"e": 26530,
"s": 26329,
"text": "Lets take an example. We have to encode string βMENONβ into base64 format. Lets call βMENONβ as input_str, above base64 character set (βABC..+/β) as char_set and resultant encoded string as res_str. "
},
{
"code": null,
"e": 27545,
"s": 26530,
"text": "Take 3 characters from input_str i.e βMENβ since each character size is 8 bits we will have(8 * 3) 24 bits with us.Group them in a block of 6 bits each (24 / 6 = 4 blocks). (why 6?) because 2^6 = 64 characters, with 6 bits we can represent each character in char_set.Convert each block of 6 bits to its corresponding decimal value. Decimal value obtained is the index of resultant encoded character in char_set.So for each 3 characters from input_str we will receive 4 characters in res_str.What if we have less than 3 characters in input_str left i.e βONβ. We have 16 bits and blocks will be 16 / 6 = 2 blocks. Rightmost 4 bits will not make a proper block (1 block = 6 bits) so we append zeros to right side of block to make it a proper block i.e 2 zeros will be appended to right. Now we have 3 proper blocks, find corresponding decimal value of each block to get index.Since There were less than 3 characters (βONβ) in input_str we will append β=β in res_str. e.g βONβ here 3 β 2 = 1 padding of β=β in res_str."
},
{
"code": null,
"e": 27661,
"s": 27545,
"text": "Take 3 characters from input_str i.e βMENβ since each character size is 8 bits we will have(8 * 3) 24 bits with us."
},
{
"code": null,
"e": 27814,
"s": 27661,
"text": "Group them in a block of 6 bits each (24 / 6 = 4 blocks). (why 6?) because 2^6 = 64 characters, with 6 bits we can represent each character in char_set."
},
{
"code": null,
"e": 27959,
"s": 27814,
"text": "Convert each block of 6 bits to its corresponding decimal value. Decimal value obtained is the index of resultant encoded character in char_set."
},
{
"code": null,
"e": 28040,
"s": 27959,
"text": "So for each 3 characters from input_str we will receive 4 characters in res_str."
},
{
"code": null,
"e": 28423,
"s": 28040,
"text": "What if we have less than 3 characters in input_str left i.e βONβ. We have 16 bits and blocks will be 16 / 6 = 2 blocks. Rightmost 4 bits will not make a proper block (1 block = 6 bits) so we append zeros to right side of block to make it a proper block i.e 2 zeros will be appended to right. Now we have 3 proper blocks, find corresponding decimal value of each block to get index."
},
{
"code": null,
"e": 28565,
"s": 28423,
"text": "Since There were less than 3 characters (βONβ) in input_str we will append β=β in res_str. e.g βONβ here 3 β 2 = 1 padding of β=β in res_str."
},
{
"code": null,
"e": 28575,
"s": 28567,
"text": "Example"
},
{
"code": null,
"e": 28765,
"s": 28575,
"text": "1. Convert βMENONβ into its (8 bit) binary state format. Take each characters of the string and write its 8 β bit binary representation. ASCII values of characters in string to be encoded "
},
{
"code": null,
"e": 28860,
"s": 28765,
"text": "M : 77 (01001101), E : 69 (01000101), \nN : 78 (01001110), O : 79 (01001111), N : 78 (01001110)"
},
{
"code": null,
"e": 28905,
"s": 28860,
"text": "resultant binary data of above string is : "
},
{
"code": null,
"e": 28950,
"s": 28905,
"text": "01001101 01000101 01001110 01001111 01001110"
},
{
"code": null,
"e": 29036,
"s": 28950,
"text": "2. Starting from left make blocks of 6 bits until all bits are covered BIT-STREAM : "
},
{
"code": null,
"e": 29097,
"s": 29036,
"text": "(010011) (010100) (010101) (001110) (010011) (110100) (1110)"
},
{
"code": null,
"e": 29286,
"s": 29097,
"text": "3. If the rightmost block is less than 6 bits just append zeros to the right of that block to make it 6 bits. Here in above example we have to appended 2 zeros to make it 6. BIT-STREAM : "
},
{
"code": null,
"e": 29349,
"s": 29286,
"text": "(010011) (010100) (010101) (001110) (010011) (110100) (111000)"
},
{
"code": null,
"e": 29496,
"s": 29349,
"text": "Notice the bold zeros.4. Take 3 characters from input_str (βMENβ) i.e 24 bits and find corresponding decimal value (index to char_set). BLOCKS : "
},
{
"code": null,
"e": 29636,
"s": 29496,
"text": "INDEX --> (010011) : 19, (010100) : 20, (010101) : 21, (001110) : 14\nchar_set[19] = T, char_set[20] = U, char_set[21] = V, char_set[14] = O"
},
{
"code": null,
"e": 29876,
"s": 29636,
"text": "So our input_str = βMENβ will be converted to encoded string βTUVOβ.5. Take remaining characters (βONβ). We have to pad resultant encoded string with 1 β=β as number of characters is less than 3 in input_str. (3 β 2 = 1 padding) BLOCKS : "
},
{
"code": null,
"e": 30047,
"s": 29876,
"text": "INDEX --> (010011) : 19 (110100) : 52 (111000) : 56\nchar_set[19] = T char_set[52] = 0 char_set[56] = 4\nSo our input_str = \"ON\" will be converted to encoded string \"T04=\"."
},
{
"code": null,
"e": 30059,
"s": 30047,
"text": "Examples: "
},
{
"code": null,
"e": 30192,
"s": 30059,
"text": "Input : MENON // string in ASCII\nOutput :TUVOT04= // encoded string in Base 64.\n\nInput : geeksforgeeks\nOutput : Z2Vla3Nmb3JnZWVrcw=="
},
{
"code": null,
"e": 30793,
"s": 30194,
"text": "We can use bitwise operators to encode our string. We can take an integer βvalβ (usually 4 bytes on most compilers) and store all characters of input_str (3 at a time) in val. The characters from input_str will be stored in val in form of bits. We will use (OR operator) to store the characters and (LEFT β SHIFT) by 8 so to make room for another 8 bits. In similar fashion we will use (RIGHT β SHIFT) to retrieve bits from val 6 at a time and find value of bits by doing & with 63 (111111) which will give us index. Then we can get our resultant character by just going to that index of char_set. "
},
{
"code": null,
"e": 30797,
"s": 30793,
"text": "C++"
},
{
"code": null,
"e": 30799,
"s": 30797,
"text": "C"
},
{
"code": "// C++ program to encode an ASCII// string in Base64 format#include <iostream>using namespace std;#define SIZE 1000 // Takes string to be encoded as input// and its length and returns encoded stringchar* base64Encoder(char input_str[], int len_str){ // Character set of base64 encoding scheme char char_set[] = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"; // Resultant string char *res_str = (char *) malloc(SIZE * sizeof(char)); int index, no_of_bits = 0, padding = 0, val = 0, count = 0, temp; int i, j, k = 0; // Loop takes 3 characters at a time from // input_str and stores it in val for (i = 0; i < len_str; i += 3) { val = 0, count = 0, no_of_bits = 0; for (j = i; j < len_str && j <= i + 2; j++) { // binary data of input_str is stored in val val = val << 8; // (A + 0 = A) stores character in val val = val | input_str[j]; // calculates how many time loop // ran if \"MEN\" -> 3 otherwise \"ON\" -> 2 count++; } no_of_bits = count * 8; // calculates how many \"=\" to append after res_str. padding = no_of_bits % 3; // extracts all bits from val (6 at a time) // and find the value of each block while (no_of_bits != 0) { // retrieve the value of each block if (no_of_bits >= 6) { temp = no_of_bits - 6; // binary of 63 is (111111) f index = (val >> temp) & 63; no_of_bits -= 6; } else { temp = 6 - no_of_bits; // append zeros to right if bits are less than 6 index = (val << temp) & 63; no_of_bits = 0; } res_str[k++] = char_set[index]; } } // padding is done here for (i = 1; i <= padding; i++) { res_str[k++] = '='; } res_str[k] = '\\0'; return res_str; } // Driver codeint main(){ char input_str[] = \"MENON\"; int len_str; // calculates length of string len_str = sizeof(input_str) / sizeof(input_str[0]); // to exclude '\\0' character len_str -= 1; cout <<\"Input string is : \"<< input_str << endl; cout <<\"Encoded string is : \"<< base64Encoder(input_str, len_str)<< endl; return 0;} // This code is contributed by shivanisinghss2110",
"e": 33510,
"s": 30799,
"text": null
},
{
"code": "// C program to encode an ASCII// string in Base64 format#include <stdio.h>#include <stdlib.h>#define SIZE 1000 // Takes string to be encoded as input// and its length and returns encoded stringchar* base64Encoder(char input_str[], int len_str){ // Character set of base64 encoding scheme char char_set[] = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"; // Resultant string char *res_str = (char *) malloc(SIZE * sizeof(char)); int index, no_of_bits = 0, padding = 0, val = 0, count = 0, temp; int i, j, k = 0; // Loop takes 3 characters at a time from // input_str and stores it in val for (i = 0; i < len_str; i += 3) { val = 0, count = 0, no_of_bits = 0; for (j = i; j < len_str && j <= i + 2; j++) { // binary data of input_str is stored in val val = val << 8; // (A + 0 = A) stores character in val val = val | input_str[j]; // calculates how many time loop // ran if \"MEN\" -> 3 otherwise \"ON\" -> 2 count++; } no_of_bits = count * 8; // calculates how many \"=\" to append after res_str. padding = no_of_bits % 3; // extracts all bits from val (6 at a time) // and find the value of each block while (no_of_bits != 0) { // retrieve the value of each block if (no_of_bits >= 6) { temp = no_of_bits - 6; // binary of 63 is (111111) f index = (val >> temp) & 63; no_of_bits -= 6; } else { temp = 6 - no_of_bits; // append zeros to right if bits are less than 6 index = (val << temp) & 63; no_of_bits = 0; } res_str[k++] = char_set[index]; } } // padding is done here for (i = 1; i <= padding; i++) { res_str[k++] = '='; } res_str[k] = '\\0;'; return res_str; } // Driver codeint main(){ char input_str[] = \"MENON\"; int len_str; // calculates length of string len_str = sizeof(input_str) / sizeof(input_str[0]); // to exclude '\\0' character len_str -= 1; printf(\"Input string is : %s\\n\", input_str); printf(\"Encoded string is : %s\\n\", base64Encoder(input_str, len_str)); return 0;}",
"e": 36136,
"s": 33510,
"text": null
},
{
"code": null,
"e": 36190,
"s": 36136,
"text": "Input string is : MENON\nEncoded string is : TUVOT04=\n"
},
{
"code": null,
"e": 36729,
"s": 36190,
"text": "Time Complexity: O(2 * N) inserting bits into val + retrieving bits form valExercise : Implement a base 64 decoderThis article is contributed by Arshpreet Soodan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 36744,
"s": 36729,
"text": "ashug716716716"
},
{
"code": null,
"e": 36763,
"s": 36744,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 36779,
"s": 36763,
"text": "prajalpatidar01"
},
{
"code": null,
"e": 36788,
"s": 36779,
"text": "C-String"
},
{
"code": null,
"e": 36799,
"s": 36788,
"text": "C Language"
},
{
"code": null,
"e": 36897,
"s": 36799,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36935,
"s": 36897,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 36961,
"s": 36935,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 36983,
"s": 36961,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 37003,
"s": 36983,
"text": "Multithreading in C"
},
{
"code": null,
"e": 37044,
"s": 37003,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 37086,
"s": 37044,
"text": "Smart Pointers in C++ and How to Use Them"
},
{
"code": null,
"e": 37114,
"s": 37086,
"text": "Multiple Inheritance in C++"
},
{
"code": null,
"e": 37150,
"s": 37114,
"text": "Understanding \"extern\" keyword in C"
},
{
"code": null,
"e": 37179,
"s": 37150,
"text": "Ways to copy a vector in C++"
}
] |
C Program for sum of cos(x) series
|
We are given with the value of x and n where, x is the angle for cos and n is the number of terms in the cos(x) series.
Cos(x) is a trigonometric function which is used to calculate the value of x angle.
cosβ‘(x)=βk=0β(β1)k(2k!)x2k
Cos(x) = 1 β (x*2 / 2!) + (x*4 / 4!) β (x*6 / 6!) + (x*8 / 8!)......
Input-: x = 10, n = 3
Output-: 0.984804
Input-: x = 8, n = 2
Output-: 0.990266
Approach used in the below program is as follows β
Input the value of x and n
Apply the formula for calculating cos(x) series
Print the result as the sum of all the series
Start
Step 1 Declare and initialize const double PI = 3.142
Step 2 In function double series_sum(double x, int n)
Set x = x * (PI / 180.0)
Set result = 1
Set s = 1, fact = 1, pow = 1
Loop For i = 1 and i < 5 and i++
Set s = s * -1
Set fact = fact * (2 * i - 1) * (2 * i)
Set pow = pow * x * x
Set result = result + s * pow / fact
End Loop
Return result
Step 3 In function int main() s
Declare and set x = 10
Declare and set n = 3
Print series_sum(x, n)
Stop
#include <stdio.h>
const double PI = 3.142;
//will return the sum of cos(x)
double series_sum(double x, int n) {
x = x * (PI / 180.0);
double result = 1;
double s = 1, fact = 1, pow = 1;
for (int i = 1; i < 5; i++) {
s = s * -1;
fact = fact * (2 * i - 1) * (2 * i);
pow = pow * x * x;
result = result + s * pow / fact;
}
return result;
}
//main function
int main() {
float x = 10;
int n = 3;
printf("%lf\n", series_sum(x, n));
return 0;
}
X=10; n=30.984804
X=13; n=80.974363
X=8; n=2 0.990266
|
[
{
"code": null,
"e": 1182,
"s": 1062,
"text": "We are given with the value of x and n where, x is the angle for cos and n is the number of terms in the cos(x) series."
},
{
"code": null,
"e": 1266,
"s": 1182,
"text": "Cos(x) is a trigonometric function which is used to calculate the value of x angle."
},
{
"code": null,
"e": 1293,
"s": 1266,
"text": "cosβ‘(x)=βk=0β(β1)k(2k!)x2k"
},
{
"code": null,
"e": 1362,
"s": 1293,
"text": "Cos(x) = 1 β (x*2 / 2!) + (x*4 / 4!) β (x*6 / 6!) + (x*8 / 8!)......"
},
{
"code": null,
"e": 1441,
"s": 1362,
"text": "Input-: x = 10, n = 3\nOutput-: 0.984804\nInput-: x = 8, n = 2\nOutput-: 0.990266"
},
{
"code": null,
"e": 1492,
"s": 1441,
"text": "Approach used in the below program is as follows β"
},
{
"code": null,
"e": 1519,
"s": 1492,
"text": "Input the value of x and n"
},
{
"code": null,
"e": 1567,
"s": 1519,
"text": "Apply the formula for calculating cos(x) series"
},
{
"code": null,
"e": 1613,
"s": 1567,
"text": "Print the result as the sum of all the series"
},
{
"code": null,
"e": 2129,
"s": 1613,
"text": "Start\nStep 1 Declare and initialize const double PI = 3.142\nStep 2 In function double series_sum(double x, int n)\n Set x = x * (PI / 180.0)\nSet result = 1\nSet s = 1, fact = 1, pow = 1\n Loop For i = 1 and i < 5 and i++\n Set s = s * -1\n Set fact = fact * (2 * i - 1) * (2 * i)\n Set pow = pow * x * x\n Set result = result + s * pow / fact\n End Loop\n Return result\nStep 3 In function int main() s\n Declare and set x = 10\nDeclare and set n = 3\n Print series_sum(x, n) \nStop"
},
{
"code": null,
"e": 2642,
"s": 2129,
"text": "#include <stdio.h>\nconst double PI = 3.142;\n//will return the sum of cos(x)\ndouble series_sum(double x, int n) {\n x = x * (PI / 180.0);\n double result = 1;\n double s = 1, fact = 1, pow = 1;\n for (int i = 1; i < 5; i++) {\n s = s * -1;\n fact = fact * (2 * i - 1) * (2 * i);\n pow = pow * x * x;\n result = result + s * pow / fact;\n }\n return result;\n}\n//main function\nint main() {\n float x = 10;\n int n = 3;\n printf(\"%lf\\n\", series_sum(x, n)); \n return 0;\n}"
},
{
"code": null,
"e": 2696,
"s": 2642,
"text": "X=10; n=30.984804\nX=13; n=80.974363\nX=8; n=2 0.990266"
}
] |
C++ Program to Find Fibonacci Numbers using Matrix Exponentiation
|
The Fibonacci numbers, commonly denoted Fn form a sequence, called the Fibonacci sequence, i.e; each number is the sum of the two preceding ones, starting from 0 and 1. That is β
F0 = 0 and F1 = 1
And
Fn = Fn-1 + Fn-2
for n > 1.
Begin
Take two 2 dimensional array
Create a function and Perform matrix multiplication
Create another function to find out power of matrix
Create a function then to find out the Fibonacci number
Multiply(arr1[2][2], arr2[2][2])
Take 4 variables a, b, c, d
a = arr1[0][0] * arr2[0][0] + arr1[0][1] * arr2[1][0]
b= arr1[0][0] * arr2[0][1] + arr1[0][1] * arr2[1][1]
c = arr1[1][0] * arr2[0][0] + arr1[1][1] * arr2[1][0]
d = arr1[1][0] * arr2[0][1] + arr1[1][1] * arr2[1][1]
arr1[0][0] = a
arr1[0][1] = b
arr1[1][0] = c
arr1[1][1] = d
Power(arr1[2][2], take integer n as input)
if (n == 0 or n == 1)
return;
arr1 [2][2] = {{1,1}, {1,0}}
power(arr1, n / 2)
multiply(arr1, arr1)
if (n mod 2 not equal to 0)
multiply(arr1, arr2)
fibonacci_matrix(n)
arr1[2][2] = {{1,1}, {1,0}}
if n ==0
return 0
power(arr1 n - 1)
return arr1[0][0]
End
#include <iostream>
using namespace std;
void multiply(int F[2][2], int M[2][2]) {
int a = F[0][0] * M[0][0] + F[0][1] * M[1][0];
int b= F[0][0] * M[0][1] + F[0][1] * M[1][1];
int c = F[1][0] * M[0][0] + F[1][1] * M[1][0];
int d = F[1][0] * M[0][1] + F[1][1] * M[1][1];
F[0][0] = a;
F[0][1] = b;
F[1][0] = c;
F[1][1] = d;
}
void power(int F[2][2], int n) {
if (n == 0 || n == 1)
return;
int M[2][2] = {{1,1},{1,0}};
power(F, n / 2);
multiply(F, F);
if (n % 2 != 0)
multiply(F, M);
}
int fibonacci_matrix(int n) {
int F[2][2] = {{1,1},{1,0}};
if (n == 0)
return 0;
power(F, n - 1);
return F[0][0];
}
int main() {
int n;
while (1) {
cout<<"Enter the integer n to find nth fibonacci no. (enter 0 to exit):";
cin>>n;
if (n == 0)
break;
cout<<fibonacci_matrix(n)<<endl;
}
return 0;
}
Enter the integer n to find nth fibonacci no. (enter 0 to exit): 2
1
Enter the integer n to find nth fibonacci no. (enter 0 to exit): 6
8
Enter the integer n to find nth fibonacci no. (enter 0 to exit): 7
13
Enter the integer n to find nth fibonacci no. (enter 0 to exit): 0
|
[
{
"code": null,
"e": 1241,
"s": 1062,
"text": "The Fibonacci numbers, commonly denoted Fn form a sequence, called the Fibonacci sequence, i.e; each number is the sum of the two preceding ones, starting from 0 and 1. That is β"
},
{
"code": null,
"e": 1291,
"s": 1241,
"text": "F0 = 0 and F1 = 1\nAnd\nFn = Fn-1 + Fn-2\nfor n > 1."
},
{
"code": null,
"e": 2215,
"s": 1291,
"text": "Begin\n Take two 2 dimensional array\n Create a function and Perform matrix multiplication\n Create another function to find out power of matrix\n Create a function then to find out the Fibonacci number\n Multiply(arr1[2][2], arr2[2][2])\n Take 4 variables a, b, c, d\n a = arr1[0][0] * arr2[0][0] + arr1[0][1] * arr2[1][0]\n b= arr1[0][0] * arr2[0][1] + arr1[0][1] * arr2[1][1]\n c = arr1[1][0] * arr2[0][0] + arr1[1][1] * arr2[1][0]\n d = arr1[1][0] * arr2[0][1] + arr1[1][1] * arr2[1][1]\n arr1[0][0] = a\n arr1[0][1] = b\n arr1[1][0] = c\n arr1[1][1] = d\n Power(arr1[2][2], take integer n as input)\n if (n == 0 or n == 1)\n return;\n arr1 [2][2] = {{1,1}, {1,0}}\n power(arr1, n / 2)\n multiply(arr1, arr1)\n if (n mod 2 not equal to 0)\n multiply(arr1, arr2)\n fibonacci_matrix(n)\n arr1[2][2] = {{1,1}, {1,0}}\n if n ==0\n return 0\n power(arr1 n - 1)\n return arr1[0][0]\nEnd"
},
{
"code": null,
"e": 3108,
"s": 2215,
"text": "#include <iostream>\nusing namespace std;\nvoid multiply(int F[2][2], int M[2][2]) {\n int a = F[0][0] * M[0][0] + F[0][1] * M[1][0];\n int b= F[0][0] * M[0][1] + F[0][1] * M[1][1];\n int c = F[1][0] * M[0][0] + F[1][1] * M[1][0];\n int d = F[1][0] * M[0][1] + F[1][1] * M[1][1];\n F[0][0] = a;\n F[0][1] = b;\n F[1][0] = c;\n F[1][1] = d;\n}\nvoid power(int F[2][2], int n) {\n if (n == 0 || n == 1)\n return;\n int M[2][2] = {{1,1},{1,0}};\n power(F, n / 2);\n multiply(F, F);\n if (n % 2 != 0)\n multiply(F, M);\n}\nint fibonacci_matrix(int n) {\n int F[2][2] = {{1,1},{1,0}};\n if (n == 0)\n return 0;\n power(F, n - 1);\n return F[0][0];\n}\nint main() {\n int n;\n while (1) {\n cout<<\"Enter the integer n to find nth fibonacci no. (enter 0 to exit):\";\n cin>>n;\n if (n == 0)\n break;\n cout<<fibonacci_matrix(n)<<endl;\n }\n return 0;\n}"
},
{
"code": null,
"e": 3383,
"s": 3108,
"text": "Enter the integer n to find nth fibonacci no. (enter 0 to exit): 2\n1\nEnter the integer n to find nth fibonacci no. (enter 0 to exit): 6\n8\nEnter the integer n to find nth fibonacci no. (enter 0 to exit): 7\n13\nEnter the integer n to find nth fibonacci no. (enter 0 to exit): 0"
}
] |
Binary Representations in Digital Logic - GeeksforGeeks
|
07 Jul, 2021
Binary is a base-2 number system that uses two states 0 and 1 to represent a number. We can also call it to be a true state and a false state. A binary number is built the same way as we build the normal decimal number.
For example, a decimal number 45 can be represented as 4*10^1+5*10^0 = 40+5
Now in binary 45 is represented as 101101. As we have powers of 10 in decimal number similarly there are powers of 2 in binary numbers. Hence 45 which is 101101 in binary can be represented as:
2^0*1+2^1*0+2^2*1+2^3*1+2^4*0+2^5*1 = 45
The binary number is traversed from left to right.
Sign and Magnitude representation β There are many ways for representing negative integers. One of the way is sign-magnitude. This system uses one bit to indicate the sign. Mathematical numbers are generally made up of a sign and a value. The sign indicates whether the number is positive, (+) or negative, (β) while the value indicates the size of the number.
For example 13, +256 or -574. Presenting numbers is this way is called sign-magnitude representation since the left most digit can be used to indicate the sign and the remaining digits the magnitude or value of the number.
Sign-magnitude notation is the simplest and one of the most common methods of representing positive and negative numbers. Thus negative numbers are obtained simply by changing the sign of the corresponding positive number, for example, +2 and -2, +10 and -10, etc. Similarly adding a 1 to the front of a binary number is negative and a 0 makes it positive.
For example 0101101 represents +45 and 1101101 represents -45 if 6 digits of a binary number are considered and the leftmost digit represents the sign.
But a problem with the sign-magnitude method is that it can result in the possibility of two different bit patterns having the same binary value. For example, +0 and -0 would be 0000 and 1000 respectively as a signed 4-bit binary number. So using this method there can be two representations for zero, a positive zero 0000 and also a negative zero 1000 which can cause big complications for computers and digital systems.
The 2 complement notations used to represent signed magnitude numbers are:
1. Oneβs complement β Oneβs Complement is a method which can be used to represent negative binary numbers in a signed binary number system. In oneβs complement, positive numbers remain unchanged as before.
Negative numbers however, are represented by taking the oneβs complement of the unsigned positive number. Since positive numbers always start with a 0, the complement will always start with a 1 to indicate a negative number.
The oneβs complement of a negative binary number is the complement of its positive, so to take the oneβs complement of a binary number, all we need to do is subtract 1βs equal to the number of digits present in the number from that number. This can also be achieved by just interchanging the digits of the number. Thus the oneβs complement of 1 is 0 and vice versa.
For example Oneβs Complement of 1010100:
1111111
-1010100
0101011
The oneβs complement of number can also be obtained by just interchanging the digits of the binary number.
2. Twoβs complement β Twoβs Complement is another method like oneβs complement form, which we can use to represent negative binary numbers in a signed binary number system. In twoβs complement, the positive numbers are exactly the same as before for unsigned binary numbers. A negative number, however, is represented by a binary number, which when added to its corresponding positive equivalent results in zero.
In twoβs complement representation, a negative number is the 2βs complement of its positive number. If the subtraction of two numbers is X β Y then it can be represented as X + (2βs complement of Y).
The twoβs complement is oneβs complement + 1 of a number in binary.
The main advantage of twoβs complement over the previous oneβs complement is that there is no double-zero problem and it is a lot easier to generate the twoβs complement of a signed binary number. In twoβs complement arithmetic operations are relatively easier to perform when the numbers are represented in the twoβs complement format.
For example to represent -27 27 in binary is: 00011011
11111111
-00011011
11100100 <-- 1's Complement
+1
11100101 <-- The 2's Complement
The above 2 are the formats that can be too long practically. So real number representations are used.
Real number representations β The goal is to represent a number with a decimal point in binary using the form. IEEE 754 standard defines how to encode a real number. This standard offers a way to code a number using 32 bits (as well as 64 bits), and defines three components:
The plus/minus sign is represented by one bit, the highest-weighted bit (furthest to the left). The exponent is encoded using 8 bits (11 bits in 64 bit representation) immediately after the sign. The mantissa (the bits after the decimal point) with the remaining 23 bits(52 bits in 64 bit representation).
The plus/minus sign is represented by one bit, the highest-weighted bit (furthest to the left).
The exponent is encoded using 8 bits (11 bits in 64 bit representation) immediately after the sign.
The mantissa (the bits after the decimal point) with the remaining 23 bits(52 bits in 64 bit representation).
sooda367
binary-representation
Picked
Digital Electronics & Logic Design
GATE CS
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to memory and memory units
Analog to Digital Conversion
Introduction of Sequential Circuits
Restoring Division Algorithm For Unsigned Integer
Latches in Digital Logic
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
|
[
{
"code": null,
"e": 25815,
"s": 25787,
"text": "\n07 Jul, 2021"
},
{
"code": null,
"e": 26036,
"s": 25815,
"text": "Binary is a base-2 number system that uses two states 0 and 1 to represent a number. We can also call it to be a true state and a false state. A binary number is built the same way as we build the normal decimal number. "
},
{
"code": null,
"e": 26113,
"s": 26036,
"text": "For example, a decimal number 45 can be represented as 4*10^1+5*10^0 = 40+5 "
},
{
"code": null,
"e": 26309,
"s": 26113,
"text": "Now in binary 45 is represented as 101101. As we have powers of 10 in decimal number similarly there are powers of 2 in binary numbers. Hence 45 which is 101101 in binary can be represented as: "
},
{
"code": null,
"e": 26351,
"s": 26309,
"text": "2^0*1+2^1*0+2^2*1+2^3*1+2^4*0+2^5*1 = 45 "
},
{
"code": null,
"e": 26403,
"s": 26351,
"text": "The binary number is traversed from left to right. "
},
{
"code": null,
"e": 26765,
"s": 26403,
"text": "Sign and Magnitude representation β There are many ways for representing negative integers. One of the way is sign-magnitude. This system uses one bit to indicate the sign. Mathematical numbers are generally made up of a sign and a value. The sign indicates whether the number is positive, (+) or negative, (β) while the value indicates the size of the number. "
},
{
"code": null,
"e": 26989,
"s": 26765,
"text": "For example 13, +256 or -574. Presenting numbers is this way is called sign-magnitude representation since the left most digit can be used to indicate the sign and the remaining digits the magnitude or value of the number. "
},
{
"code": null,
"e": 27347,
"s": 26989,
"text": "Sign-magnitude notation is the simplest and one of the most common methods of representing positive and negative numbers. Thus negative numbers are obtained simply by changing the sign of the corresponding positive number, for example, +2 and -2, +10 and -10, etc. Similarly adding a 1 to the front of a binary number is negative and a 0 makes it positive. "
},
{
"code": null,
"e": 27500,
"s": 27347,
"text": "For example 0101101 represents +45 and 1101101 represents -45 if 6 digits of a binary number are considered and the leftmost digit represents the sign. "
},
{
"code": null,
"e": 27923,
"s": 27500,
"text": "But a problem with the sign-magnitude method is that it can result in the possibility of two different bit patterns having the same binary value. For example, +0 and -0 would be 0000 and 1000 respectively as a signed 4-bit binary number. So using this method there can be two representations for zero, a positive zero 0000 and also a negative zero 1000 which can cause big complications for computers and digital systems. "
},
{
"code": null,
"e": 28000,
"s": 27923,
"text": "The 2 complement notations used to represent signed magnitude numbers are: "
},
{
"code": null,
"e": 28207,
"s": 28000,
"text": "1. Oneβs complement β Oneβs Complement is a method which can be used to represent negative binary numbers in a signed binary number system. In oneβs complement, positive numbers remain unchanged as before. "
},
{
"code": null,
"e": 28433,
"s": 28207,
"text": "Negative numbers however, are represented by taking the oneβs complement of the unsigned positive number. Since positive numbers always start with a 0, the complement will always start with a 1 to indicate a negative number. "
},
{
"code": null,
"e": 28800,
"s": 28433,
"text": "The oneβs complement of a negative binary number is the complement of its positive, so to take the oneβs complement of a binary number, all we need to do is subtract 1βs equal to the number of digits present in the number from that number. This can also be achieved by just interchanging the digits of the number. Thus the oneβs complement of 1 is 0 and vice versa. "
},
{
"code": null,
"e": 28843,
"s": 28800,
"text": "For example Oneβs Complement of 1010100: "
},
{
"code": null,
"e": 28869,
"s": 28843,
"text": "1111111\n-1010100\n0101011 "
},
{
"code": null,
"e": 28978,
"s": 28869,
"text": "The oneβs complement of number can also be obtained by just interchanging the digits of the binary number. "
},
{
"code": null,
"e": 29392,
"s": 28978,
"text": "2. Twoβs complement β Twoβs Complement is another method like oneβs complement form, which we can use to represent negative binary numbers in a signed binary number system. In twoβs complement, the positive numbers are exactly the same as before for unsigned binary numbers. A negative number, however, is represented by a binary number, which when added to its corresponding positive equivalent results in zero. "
},
{
"code": null,
"e": 29593,
"s": 29392,
"text": "In twoβs complement representation, a negative number is the 2βs complement of its positive number. If the subtraction of two numbers is X β Y then it can be represented as X + (2βs complement of Y). "
},
{
"code": null,
"e": 29662,
"s": 29593,
"text": "The twoβs complement is oneβs complement + 1 of a number in binary. "
},
{
"code": null,
"e": 30000,
"s": 29662,
"text": "The main advantage of twoβs complement over the previous oneβs complement is that there is no double-zero problem and it is a lot easier to generate the twoβs complement of a signed binary number. In twoβs complement arithmetic operations are relatively easier to perform when the numbers are represented in the twoβs complement format. "
},
{
"code": null,
"e": 30057,
"s": 30000,
"text": "For example to represent -27 27 in binary is: 00011011 "
},
{
"code": null,
"e": 30146,
"s": 30057,
"text": "11111111\n-00011011\n11100100 <-- 1's Complement\n +1\n11100101 <-- The 2's Complement "
},
{
"code": null,
"e": 30250,
"s": 30146,
"text": "The above 2 are the formats that can be too long practically. So real number representations are used. "
},
{
"code": null,
"e": 30527,
"s": 30250,
"text": "Real number representations β The goal is to represent a number with a decimal point in binary using the form. IEEE 754 standard defines how to encode a real number. This standard offers a way to code a number using 32 bits (as well as 64 bits), and defines three components: "
},
{
"code": null,
"e": 30834,
"s": 30527,
"text": "The plus/minus sign is represented by one bit, the highest-weighted bit (furthest to the left). The exponent is encoded using 8 bits (11 bits in 64 bit representation) immediately after the sign. The mantissa (the bits after the decimal point) with the remaining 23 bits(52 bits in 64 bit representation). "
},
{
"code": null,
"e": 30931,
"s": 30834,
"text": "The plus/minus sign is represented by one bit, the highest-weighted bit (furthest to the left). "
},
{
"code": null,
"e": 31032,
"s": 30931,
"text": "The exponent is encoded using 8 bits (11 bits in 64 bit representation) immediately after the sign. "
},
{
"code": null,
"e": 31143,
"s": 31032,
"text": "The mantissa (the bits after the decimal point) with the remaining 23 bits(52 bits in 64 bit representation). "
},
{
"code": null,
"e": 31152,
"s": 31143,
"text": "sooda367"
},
{
"code": null,
"e": 31174,
"s": 31152,
"text": "binary-representation"
},
{
"code": null,
"e": 31181,
"s": 31174,
"text": "Picked"
},
{
"code": null,
"e": 31216,
"s": 31181,
"text": "Digital Electronics & Logic Design"
},
{
"code": null,
"e": 31224,
"s": 31216,
"text": "GATE CS"
},
{
"code": null,
"e": 31243,
"s": 31224,
"text": "School Programming"
},
{
"code": null,
"e": 31341,
"s": 31243,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31381,
"s": 31341,
"text": "Introduction to memory and memory units"
},
{
"code": null,
"e": 31410,
"s": 31381,
"text": "Analog to Digital Conversion"
},
{
"code": null,
"e": 31446,
"s": 31410,
"text": "Introduction of Sequential Circuits"
},
{
"code": null,
"e": 31496,
"s": 31446,
"text": "Restoring Division Algorithm For Unsigned Integer"
},
{
"code": null,
"e": 31521,
"s": 31496,
"text": "Latches in Digital Logic"
},
{
"code": null,
"e": 31541,
"s": 31521,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 31565,
"s": 31541,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 31578,
"s": 31565,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 31605,
"s": 31578,
"text": "Types of Operating Systems"
}
] |
Why do we Need Immutables in Python ?
|
10 Jul, 2020
When a Novice steps into the Programming world and kicks off to learn about different concepts of it and yet eventually reaching to the Data Structures and Algorithms, learning and implementing them, but one or the other way he/she tends to read once and forget about the Immutable object.
Mutable and Immutables exists in every programming language, yet one only tends to care about the mutable, like lists, queues, etc and take no or little notice of the immutables because at first impression it seems to be just an add-on and doesnβt seem to have any real-life problem-solving applications, and to debunk this idea, let us discuss the concept, need of it and Limitations.
Mutability is a differentiating property of a data types in Python that makes a big contrast from the other data types, It tends to be an ability of data types to allow being modified after it is created, to which a value can be added as well as can be popped out of it. On the other hand, looking on the other side there are objects too that donβt follow this principle and are unalterable and donβt allow any modification to it after itβs defined. Its State cannot be changed whatsoever, It tends to represent a constant value once initialized. Examples β integer, complex, string, float, Tuple, Complex, Frozen set.
Therefore if any variable has initialized a value corresponding to any of these immutable data types, one cannot change it ever. To ever change it, one has to initialize the same variable to the modification one wants. When a variable is reassigned to some other string it tends to allot a different memory location for both the objects.
Example:
Python3
# string initializedvar = 'Geeks'print(id(var))print(var) # Reassigned to another valuevar = 'For Geeks' # New Memory Location assignedprint(id(var))print(var)
Output:
139758810541392
Geeks
139758782345520
For Geeks
Note: In Python there tends to be an exception in case of tupleβs immutability as the tuples themselves is an immutable yet cannot be modified after itβs initialized and the values it is given at the time of initialization be the final values it holds, nothing can add or delete value to/from it, However, a mutable field like a List embedded in a tuple can be modified without any error, and yet it proves that objects referenced by the tuple can be modified, this phenomenon is occasionally called βnon-transitive immutabilityβ.
In Python, coders have more advantage of optimization around the property of immutability, mainly for the string objects.
Example:
Python3
var1 = 'GFG' var2 = 'GFG'var3 = 'GFG'var4 = 'GFG'var5 = 'GFG' # All the variables points to a# single Stringprint(id(var1), id(var2), id(var3), id(var4), id(var5))
Output:
140080377558384 140080377558384 140080377558384 140080377558384 140080377558384
If one tends to create 20 string objects one after the other, holding up same values, Then Python wonβt be allocating different memory locations for each value, yet itβll make every identifier to refer to the same string as it will not ever be modified further, Thus Saving lots of memory. The exception being that the same scenario wonβt be applicable for every immutable object other than a string, yet this optimization trick proves to be Implementation Dependent.
Improves the Exactness and simplicity of the whole code, as it provides an ease to the coder to pass around the object in the program without any fear as it never seems to be ever modified. whereas the mutable is much harder to reason about. In mutable, the aliasing leads to many irregularities and eventually intimidating fidelity of the code, At the end resulting in variability.Thread Safe β As an object after the assignment cannot be modified, this deduces that a read-only data is being shared among the threads, which certainly provides thread-safety. In simpler words, In immutables, since there is no scope of change for an object, there is no need to be scared of accessing it from many threads. Mutation in any sense in immutable objects can be achieved in such a way that one creates a new object instead of trying to modify existing ones.
Improves the Exactness and simplicity of the whole code, as it provides an ease to the coder to pass around the object in the program without any fear as it never seems to be ever modified. whereas the mutable is much harder to reason about. In mutable, the aliasing leads to many irregularities and eventually intimidating fidelity of the code, At the end resulting in variability.
Thread Safe β As an object after the assignment cannot be modified, this deduces that a read-only data is being shared among the threads, which certainly provides thread-safety. In simpler words, In immutables, since there is no scope of change for an object, there is no need to be scared of accessing it from many threads. Mutation in any sense in immutable objects can be achieved in such a way that one creates a new object instead of trying to modify existing ones.
Over time, different conclusions get introduced with it, as we read that Immutables is Thread safe, and no matter which thread reads their values, They get the right values, but The immutables are found to be immune to βMemory Consistency Errorsβ, that can be furthermore explained as; Immutable objects by themselves are not thread-safe. It is the code that uses them that must be written to be thread-safe. Simply using immutable objects is not enough to achieve this. One has to also guard against deadlock, livelock, and starvation.
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
How to iterate through Excel rows in Python?
Enumerate() in Python
Rotate axis tick labels in Seaborn and Matplotlib
Python Dictionary
Deque in Python
Stack in Python
Queue in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 342,
"s": 52,
"text": "When a Novice steps into the Programming world and kicks off to learn about different concepts of it and yet eventually reaching to the Data Structures and Algorithms, learning and implementing them, but one or the other way he/she tends to read once and forget about the Immutable object."
},
{
"code": null,
"e": 728,
"s": 342,
"text": "Mutable and Immutables exists in every programming language, yet one only tends to care about the mutable, like lists, queues, etc and take no or little notice of the immutables because at first impression it seems to be just an add-on and doesnβt seem to have any real-life problem-solving applications, and to debunk this idea, let us discuss the concept, need of it and Limitations."
},
{
"code": null,
"e": 1347,
"s": 728,
"text": "Mutability is a differentiating property of a data types in Python that makes a big contrast from the other data types, It tends to be an ability of data types to allow being modified after it is created, to which a value can be added as well as can be popped out of it. On the other hand, looking on the other side there are objects too that donβt follow this principle and are unalterable and donβt allow any modification to it after itβs defined. Its State cannot be changed whatsoever, It tends to represent a constant value once initialized. Examples β integer, complex, string, float, Tuple, Complex, Frozen set."
},
{
"code": null,
"e": 1685,
"s": 1347,
"text": "Therefore if any variable has initialized a value corresponding to any of these immutable data types, one cannot change it ever. To ever change it, one has to initialize the same variable to the modification one wants. When a variable is reassigned to some other string it tends to allot a different memory location for both the objects."
},
{
"code": null,
"e": 1694,
"s": 1685,
"text": "Example:"
},
{
"code": null,
"e": 1702,
"s": 1694,
"text": "Python3"
},
{
"code": "# string initializedvar = 'Geeks'print(id(var))print(var) # Reassigned to another valuevar = 'For Geeks' # New Memory Location assignedprint(id(var))print(var)",
"e": 1864,
"s": 1702,
"text": null
},
{
"code": null,
"e": 1872,
"s": 1864,
"text": "Output:"
},
{
"code": null,
"e": 1920,
"s": 1872,
"text": "139758810541392\nGeeks\n139758782345520\nFor Geeks"
},
{
"code": null,
"e": 2451,
"s": 1920,
"text": "Note: In Python there tends to be an exception in case of tupleβs immutability as the tuples themselves is an immutable yet cannot be modified after itβs initialized and the values it is given at the time of initialization be the final values it holds, nothing can add or delete value to/from it, However, a mutable field like a List embedded in a tuple can be modified without any error, and yet it proves that objects referenced by the tuple can be modified, this phenomenon is occasionally called βnon-transitive immutabilityβ."
},
{
"code": null,
"e": 2573,
"s": 2451,
"text": "In Python, coders have more advantage of optimization around the property of immutability, mainly for the string objects."
},
{
"code": null,
"e": 2582,
"s": 2573,
"text": "Example:"
},
{
"code": null,
"e": 2590,
"s": 2582,
"text": "Python3"
},
{
"code": "var1 = 'GFG' var2 = 'GFG'var3 = 'GFG'var4 = 'GFG'var5 = 'GFG' # All the variables points to a# single Stringprint(id(var1), id(var2), id(var3), id(var4), id(var5))",
"e": 2760,
"s": 2590,
"text": null
},
{
"code": null,
"e": 2768,
"s": 2760,
"text": "Output:"
},
{
"code": null,
"e": 2848,
"s": 2768,
"text": "140080377558384 140080377558384 140080377558384 140080377558384 140080377558384"
},
{
"code": null,
"e": 3316,
"s": 2848,
"text": "If one tends to create 20 string objects one after the other, holding up same values, Then Python wonβt be allocating different memory locations for each value, yet itβll make every identifier to refer to the same string as it will not ever be modified further, Thus Saving lots of memory. The exception being that the same scenario wonβt be applicable for every immutable object other than a string, yet this optimization trick proves to be Implementation Dependent."
},
{
"code": null,
"e": 4169,
"s": 3316,
"text": "Improves the Exactness and simplicity of the whole code, as it provides an ease to the coder to pass around the object in the program without any fear as it never seems to be ever modified. whereas the mutable is much harder to reason about. In mutable, the aliasing leads to many irregularities and eventually intimidating fidelity of the code, At the end resulting in variability.Thread Safe β As an object after the assignment cannot be modified, this deduces that a read-only data is being shared among the threads, which certainly provides thread-safety. In simpler words, In immutables, since there is no scope of change for an object, there is no need to be scared of accessing it from many threads. Mutation in any sense in immutable objects can be achieved in such a way that one creates a new object instead of trying to modify existing ones."
},
{
"code": null,
"e": 4552,
"s": 4169,
"text": "Improves the Exactness and simplicity of the whole code, as it provides an ease to the coder to pass around the object in the program without any fear as it never seems to be ever modified. whereas the mutable is much harder to reason about. In mutable, the aliasing leads to many irregularities and eventually intimidating fidelity of the code, At the end resulting in variability."
},
{
"code": null,
"e": 5023,
"s": 4552,
"text": "Thread Safe β As an object after the assignment cannot be modified, this deduces that a read-only data is being shared among the threads, which certainly provides thread-safety. In simpler words, In immutables, since there is no scope of change for an object, there is no need to be scared of accessing it from many threads. Mutation in any sense in immutable objects can be achieved in such a way that one creates a new object instead of trying to modify existing ones."
},
{
"code": null,
"e": 5560,
"s": 5023,
"text": "Over time, different conclusions get introduced with it, as we read that Immutables is Thread safe, and no matter which thread reads their values, They get the right values, but The immutables are found to be immune to βMemory Consistency Errorsβ, that can be furthermore explained as; Immutable objects by themselves are not thread-safe. It is the code that uses them that must be written to be thread-safe. Simply using immutable objects is not enough to achieve this. One has to also guard against deadlock, livelock, and starvation."
},
{
"code": null,
"e": 5574,
"s": 5560,
"text": "python-basics"
},
{
"code": null,
"e": 5581,
"s": 5574,
"text": "Python"
},
{
"code": null,
"e": 5679,
"s": 5581,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5709,
"s": 5679,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 5754,
"s": 5709,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 5776,
"s": 5754,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 5826,
"s": 5776,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 5844,
"s": 5826,
"text": "Python Dictionary"
},
{
"code": null,
"e": 5860,
"s": 5844,
"text": "Deque in Python"
},
{
"code": null,
"e": 5876,
"s": 5860,
"text": "Stack in Python"
},
{
"code": null,
"e": 5892,
"s": 5876,
"text": "Queue in Python"
},
{
"code": null,
"e": 5914,
"s": 5892,
"text": "Defaultdict in Python"
}
] |
ReactJS Reactstrap Collapse Component
|
24 Nov, 2021
Reactstrap is a popular front-end library that is easy to use React Bootstrap 4 components. This library contains the stateless React components for Bootstrap 4. The Collapse component is used as a content area that can be collapsed and expanded. We can use the following approach in ReactJS to use the ReactJS Reactstrap Collapse Component.
Collapse Props:
inOpen: It is used to show the component.
children: It is used to pass the children element to this component.
tag: It is used to denote the tag for our collapse component.
className: It is used to denote the class name for styling.
navbar: It is used to indicate whether it is associate with the navbar component or not.
cssModule: It is used to denote the CSS module for styling.
innerRef: It is used to denote the inner reference element.
mountOnEnter: It is used to mount the component as it waits until the first enter transition is triggered.
unmountOnExit: It is used to unmount the component.
appear: When the component mounts, it is used to run the collapse-in animation.
enter: It is used to enable or disable enter transitions
exit: It is used to enable or disable exit transitions
timeout: It is used to denote the duration of collapse animation in milliseconds.
addEndListener: It is used to denote a function that listens to an end event.
onEnter: It is a callback function that is triggered before the component collapse in.
onEntered: It is a callback function that is triggered after the has component collapsed in.
onEntering: It is a callback function that is triggered after the component starts to collapse in.
onExit: It is a callback function that is triggered before the component collapse out.
onExited: It is a callback function that is triggered after the component has collapsed out.
onExiting: It is a callback function that is triggered after the component starts to collapse out.
baseClass: It is used to denote the class that is always applied to the collapse element.
baseClassActive: It is used to denote the class applied to the collapse element when it is in an active state.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install reactstrap bootstrap
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Collapse, Button } from "reactstrap" function App() { // Collapse Open state const [isOpen, setIsOpen] = React.useState(false); return ( <div style={{ display: 'block', width: 900, padding: 30 }}> <h4>ReactJS Reactstrap Collapse Component</h4> <Button color="primary" onClick={() => { setIsOpen(!isOpen) }}>Toggle Me to see Collapse Component!</Button> <Collapse isOpen={isOpen}> <p>I am sample Text to display</p> </Collapse> </div > );} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://reactstrap.github.io/components/collapse/
sumitgumber28
Reactstrap
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
Axios in React: A Guide for Beginners
ReactJS Functional Components
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 370,
"s": 28,
"text": "Reactstrap is a popular front-end library that is easy to use React Bootstrap 4 components. This library contains the stateless React components for Bootstrap 4. The Collapse component is used as a content area that can be collapsed and expanded. We can use the following approach in ReactJS to use the ReactJS Reactstrap Collapse Component."
},
{
"code": null,
"e": 386,
"s": 370,
"text": "Collapse Props:"
},
{
"code": null,
"e": 428,
"s": 386,
"text": "inOpen: It is used to show the component."
},
{
"code": null,
"e": 497,
"s": 428,
"text": "children: It is used to pass the children element to this component."
},
{
"code": null,
"e": 559,
"s": 497,
"text": "tag: It is used to denote the tag for our collapse component."
},
{
"code": null,
"e": 619,
"s": 559,
"text": "className: It is used to denote the class name for styling."
},
{
"code": null,
"e": 708,
"s": 619,
"text": "navbar: It is used to indicate whether it is associate with the navbar component or not."
},
{
"code": null,
"e": 768,
"s": 708,
"text": "cssModule: It is used to denote the CSS module for styling."
},
{
"code": null,
"e": 828,
"s": 768,
"text": "innerRef: It is used to denote the inner reference element."
},
{
"code": null,
"e": 935,
"s": 828,
"text": "mountOnEnter: It is used to mount the component as it waits until the first enter transition is triggered."
},
{
"code": null,
"e": 987,
"s": 935,
"text": "unmountOnExit: It is used to unmount the component."
},
{
"code": null,
"e": 1069,
"s": 987,
"text": "appear: When the component mounts, it is used to run the collapse-in animation. "
},
{
"code": null,
"e": 1126,
"s": 1069,
"text": "enter: It is used to enable or disable enter transitions"
},
{
"code": null,
"e": 1181,
"s": 1126,
"text": "exit: It is used to enable or disable exit transitions"
},
{
"code": null,
"e": 1264,
"s": 1181,
"text": "timeout: It is used to denote the duration of collapse animation in milliseconds. "
},
{
"code": null,
"e": 1342,
"s": 1264,
"text": "addEndListener: It is used to denote a function that listens to an end event."
},
{
"code": null,
"e": 1429,
"s": 1342,
"text": "onEnter: It is a callback function that is triggered before the component collapse in."
},
{
"code": null,
"e": 1522,
"s": 1429,
"text": "onEntered: It is a callback function that is triggered after the has component collapsed in."
},
{
"code": null,
"e": 1621,
"s": 1522,
"text": "onEntering: It is a callback function that is triggered after the component starts to collapse in."
},
{
"code": null,
"e": 1708,
"s": 1621,
"text": "onExit: It is a callback function that is triggered before the component collapse out."
},
{
"code": null,
"e": 1801,
"s": 1708,
"text": "onExited: It is a callback function that is triggered after the component has collapsed out."
},
{
"code": null,
"e": 1900,
"s": 1801,
"text": "onExiting: It is a callback function that is triggered after the component starts to collapse out."
},
{
"code": null,
"e": 1990,
"s": 1900,
"text": "baseClass: It is used to denote the class that is always applied to the collapse element."
},
{
"code": null,
"e": 2101,
"s": 1990,
"text": "baseClassActive: It is used to denote the class applied to the collapse element when it is in an active state."
},
{
"code": null,
"e": 2151,
"s": 2101,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 2215,
"s": 2151,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 2247,
"s": 2215,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 2349,
"s": 2249,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 2363,
"s": 2349,
"text": "cd foldername"
},
{
"code": null,
"e": 2468,
"s": 2363,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:"
},
{
"code": null,
"e": 2501,
"s": 2468,
"text": "npm install reactstrap bootstrap"
},
{
"code": null,
"e": 2553,
"s": 2501,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 2571,
"s": 2553,
"text": "Project Structure"
},
{
"code": null,
"e": 2701,
"s": 2571,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 2712,
"s": 2701,
"text": "Javascript"
},
{
"code": "import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Collapse, Button } from \"reactstrap\" function App() { // Collapse Open state const [isOpen, setIsOpen] = React.useState(false); return ( <div style={{ display: 'block', width: 900, padding: 30 }}> <h4>ReactJS Reactstrap Collapse Component</h4> <Button color=\"primary\" onClick={() => { setIsOpen(!isOpen) }}>Toggle Me to see Collapse Component!</Button> <Collapse isOpen={isOpen}> <p>I am sample Text to display</p> </Collapse> </div > );} export default App;",
"e": 3386,
"s": 2712,
"text": null
},
{
"code": null,
"e": 3499,
"s": 3386,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 3509,
"s": 3499,
"text": "npm start"
},
{
"code": null,
"e": 3608,
"s": 3509,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 3669,
"s": 3608,
"text": "Reference: https://reactstrap.github.io/components/collapse/"
},
{
"code": null,
"e": 3683,
"s": 3669,
"text": "sumitgumber28"
},
{
"code": null,
"e": 3694,
"s": 3683,
"text": "Reactstrap"
},
{
"code": null,
"e": 3705,
"s": 3694,
"text": "JavaScript"
},
{
"code": null,
"e": 3713,
"s": 3705,
"text": "ReactJS"
},
{
"code": null,
"e": 3730,
"s": 3713,
"text": "Web Technologies"
},
{
"code": null,
"e": 3828,
"s": 3730,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3889,
"s": 3828,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3929,
"s": 3889,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3970,
"s": 3929,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 4012,
"s": 3970,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 4034,
"s": 4012,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 4077,
"s": 4034,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 4122,
"s": 4077,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 4160,
"s": 4122,
"text": "Axios in React: A Guide for Beginners"
}
] |
How to Fix: βnumpy.ndarrayβ object has no attribute βappendβ
|
28 Nov, 2021
NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays. If you are into analytics, you might have come across this library in python. In the beginning, some things might confuse a programmer when switching from python traditional lists to NumPy arrays. One such error that we might come across is βAttributeError: βnumpy.ndarrayβ object has no attribute βappendββ. In this article, let us look at why do we see this error and how to fix it.
When adding an item to a python list, we make use of the listβs append method. The syntax is pretty simple and when we try to replicate the same on a NumPy array we get the above-mentioned error. Let us look through it with an example.
Example: Code that depicts the error
Python
# Append method on python lists import numpyprint("-"*15, "Python List", "-"*15) # Create a python listpylist = [1, 2, 3, 4] # View the data type of the list objectprint("Data type of python list:", type(pylist)) # Add (append) an item to the python listpylist.append(5) # View the items in the listprint("After appending item 5 to the pylist:", pylist) print("-"*15, "Numpy Array", "-"*15) # Append method on numpy arrays # Import the numpy library # Create a numpy arraynplist = numpy.array([1, 2, 3, 4]) # View the data type of the numpy arrayprint("Data type of numpy array:", type(nplist)) # Add (append) an item to the numpy arraynplist.append(5)
Output:
Numpy Append Error
In the above output, we can see that the python list has a data type of list. When we perform the append operation, the item i.e., 5 gets appended to the end of the list `pylist`. While we try the same method for the NumPy array, it fails and throws an error βAttributeError: βnumpy.ndarrayβ object has no attribute βappendββ. The output is pretty explanatory, the NumPy array has a type of numpy.ndarray which does not have any append() method.
Now, we know that the append is not supported by NumPy arrays then how do we use it? It is actually a method of NumPy and not its array, let us understand it through the example given below, where we actually perform the append operation on a numpy list.
Syntax:
numpy.append(arr, values, axis=None)
Parameters:
arr: numpy array: The array to which the values are appended to as a copy of it.
values: numpy array or value: These values are appended to a copy of arr. It must be of the correct shape (the same shape as arr, excluding axis). If axis is not specified, values can be any shape and will be flattened before use.
axis: int, optional: The axis along which values are appended. If axis is not given, both arr and values are flattened before use.
Example: Fixed code
Python
# Append method on numpy arrays # Import the numpy libraryimport numpy # Create a numpy arraynplist = numpy.array([1, 2, 3, 4]) # View the data type of the numpy arrayprint("Data type of numpy array:", type(nplist)) # View the items in the numpy arrayprint("Initial items in nplist:", nplist) # Add (append) an item to the numpy arraynplist = numpy.append(nplist, 5) # View the items in the numpy arrayprint("After appending item 5 to the nplist:", nplist)
Output:
Numpy Append Output
As in the output, we can see that initially, the NumPy array had 4 items (1, 2, 3, 4). After appending 5 to the list, it is reflected in the NumPy array. This is so because here the append function is used on NumPy and not on NumPy array object (numpy.ndarray).
Picked
Python How-to-fix
Python-numpy
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 630,
"s": 28,
"text": "NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays. If you are into analytics, you might have come across this library in python. In the beginning, some things might confuse a programmer when switching from python traditional lists to NumPy arrays. One such error that we might come across is βAttributeError: βnumpy.ndarrayβ object has no attribute βappendββ. In this article, let us look at why do we see this error and how to fix it."
},
{
"code": null,
"e": 866,
"s": 630,
"text": "When adding an item to a python list, we make use of the listβs append method. The syntax is pretty simple and when we try to replicate the same on a NumPy array we get the above-mentioned error. Let us look through it with an example."
},
{
"code": null,
"e": 903,
"s": 866,
"text": "Example: Code that depicts the error"
},
{
"code": null,
"e": 910,
"s": 903,
"text": "Python"
},
{
"code": "# Append method on python lists import numpyprint(\"-\"*15, \"Python List\", \"-\"*15) # Create a python listpylist = [1, 2, 3, 4] # View the data type of the list objectprint(\"Data type of python list:\", type(pylist)) # Add (append) an item to the python listpylist.append(5) # View the items in the listprint(\"After appending item 5 to the pylist:\", pylist) print(\"-\"*15, \"Numpy Array\", \"-\"*15) # Append method on numpy arrays # Import the numpy library # Create a numpy arraynplist = numpy.array([1, 2, 3, 4]) # View the data type of the numpy arrayprint(\"Data type of numpy array:\", type(nplist)) # Add (append) an item to the numpy arraynplist.append(5)",
"e": 1574,
"s": 910,
"text": null
},
{
"code": null,
"e": 1582,
"s": 1574,
"text": "Output:"
},
{
"code": null,
"e": 1601,
"s": 1582,
"text": "Numpy Append Error"
},
{
"code": null,
"e": 2048,
"s": 1601,
"text": "In the above output, we can see that the python list has a data type of list. When we perform the append operation, the item i.e., 5 gets appended to the end of the list `pylist`. While we try the same method for the NumPy array, it fails and throws an error βAttributeError: βnumpy.ndarrayβ object has no attribute βappendββ. The output is pretty explanatory, the NumPy array has a type of numpy.ndarray which does not have any append() method. "
},
{
"code": null,
"e": 2303,
"s": 2048,
"text": "Now, we know that the append is not supported by NumPy arrays then how do we use it? It is actually a method of NumPy and not its array, let us understand it through the example given below, where we actually perform the append operation on a numpy list."
},
{
"code": null,
"e": 2311,
"s": 2303,
"text": "Syntax:"
},
{
"code": null,
"e": 2348,
"s": 2311,
"text": "numpy.append(arr, values, axis=None)"
},
{
"code": null,
"e": 2360,
"s": 2348,
"text": "Parameters:"
},
{
"code": null,
"e": 2441,
"s": 2360,
"text": "arr: numpy array: The array to which the values are appended to as a copy of it."
},
{
"code": null,
"e": 2672,
"s": 2441,
"text": "values: numpy array or value: These values are appended to a copy of arr. It must be of the correct shape (the same shape as arr, excluding axis). If axis is not specified, values can be any shape and will be flattened before use."
},
{
"code": null,
"e": 2803,
"s": 2672,
"text": "axis: int, optional: The axis along which values are appended. If axis is not given, both arr and values are flattened before use."
},
{
"code": null,
"e": 2824,
"s": 2803,
"text": "Example: Fixed code "
},
{
"code": null,
"e": 2831,
"s": 2824,
"text": "Python"
},
{
"code": "# Append method on numpy arrays # Import the numpy libraryimport numpy # Create a numpy arraynplist = numpy.array([1, 2, 3, 4]) # View the data type of the numpy arrayprint(\"Data type of numpy array:\", type(nplist)) # View the items in the numpy arrayprint(\"Initial items in nplist:\", nplist) # Add (append) an item to the numpy arraynplist = numpy.append(nplist, 5) # View the items in the numpy arrayprint(\"After appending item 5 to the nplist:\", nplist)",
"e": 3294,
"s": 2831,
"text": null
},
{
"code": null,
"e": 3302,
"s": 3294,
"text": "Output:"
},
{
"code": null,
"e": 3322,
"s": 3302,
"text": "Numpy Append Output"
},
{
"code": null,
"e": 3585,
"s": 3322,
"text": "As in the output, we can see that initially, the NumPy array had 4 items (1, 2, 3, 4). After appending 5 to the list, it is reflected in the NumPy array. This is so because here the append function is used on NumPy and not on NumPy array object (numpy.ndarray). "
},
{
"code": null,
"e": 3592,
"s": 3585,
"text": "Picked"
},
{
"code": null,
"e": 3610,
"s": 3592,
"text": "Python How-to-fix"
},
{
"code": null,
"e": 3623,
"s": 3610,
"text": "Python-numpy"
},
{
"code": null,
"e": 3630,
"s": 3623,
"text": "Python"
},
{
"code": null,
"e": 3728,
"s": 3630,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3760,
"s": 3728,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3787,
"s": 3760,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3808,
"s": 3787,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3831,
"s": 3808,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3862,
"s": 3831,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3918,
"s": 3862,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3960,
"s": 3918,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 4002,
"s": 3960,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4041,
"s": 4002,
"text": "Python | Get unique values from a list"
}
] |
Information Security | Integrity
|
13 Jun, 2022
Integrity is the protection of system data from intentional or accidental unauthorized changes. The challenges of the security program are to ensure that data is maintained in the state that is expected by the users. Although the security program cannot improve the accuracy of the data that is put into the system by users. It can help ensure that any changes are intended and correctly applied. An additional element of integrity is the need to protect the process or program used to manipulate the data from unauthorized modification. A critical requirement of both commercial and government data processing is to ensure the integrity of data to prevent fraud and errors. It is imperative, therefore, no user be able to modify data in a way that might corrupt or lose assets or financial records or render decision making information unreliable. Examples of government systems in which integrity is crucial include air traffic control system, military fire control systems, social security and welfare systems. Examples of commercial systems that require a high level of integrity include medical prescription system, credit reporting systems, production control systems and payroll systems.
Protecting against Threats to Integrity: Like confidentiality, integrity can also be arbitrated by hackers, masqueraders, unprotected downloaded files, LANs, unauthorized user activities, and unauthorized programs like Trojan Horse and viruses, because each of these threads can lead to unauthorized changes to data or programs. For example, unauthorized user can corrupt or change data and programs intentionally or accidentally if their activities on the system are not properly controlled. Generally, three basic principles are used to establish integrity controls:
Need-to-know access: User should be granted access only on to those files and programs that they need in order to perform their assigned jobs functions.Separation of duties: To ensure that no single employee has control of a transaction from beginning to end, two or more people should be responsible for performing it.Rotation of duties: Job assignment should be changed periodically so that it becomes more difficult for the users to collaborate to exercise complete control of a transaction and subvert it for fraudulent purposes.
Need-to-know access: User should be granted access only on to those files and programs that they need in order to perform their assigned jobs functions.
Separation of duties: To ensure that no single employee has control of a transaction from beginning to end, two or more people should be responsible for performing it.
Rotation of duties: Job assignment should be changed periodically so that it becomes more difficult for the users to collaborate to exercise complete control of a transaction and subvert it for fraudulent purposes.
Integrity Models β Integrity models are used to describe what needs to be done to enforce the information integrity policy. There are three goals of integrity, which the models address in various ways:
Preventing unauthorized users from making modifications to data or programs.Preventing authorized users from making improper or unauthorized modifications.Maintaining internal and external consistency of data and programs.
Preventing unauthorized users from making modifications to data or programs.
Preventing authorized users from making improper or unauthorized modifications.
Maintaining internal and external consistency of data and programs.
Integrity models includes five models that suggests different approaches to achieving integrity, they are β
iamharrypo92lv
Information-Security
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!
Geek Streak - 24 Days POTD Challenge
What is Hashing | A Complete Tutorial
GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?
GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa
Types of Software Testing
Roadmap to Learn JavaScript For Beginners
How to Learn Data Science in 10 weeks?
What is Data Structure: Types, Classifications and Applications
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 1224,
"s": 28,
"text": "Integrity is the protection of system data from intentional or accidental unauthorized changes. The challenges of the security program are to ensure that data is maintained in the state that is expected by the users. Although the security program cannot improve the accuracy of the data that is put into the system by users. It can help ensure that any changes are intended and correctly applied. An additional element of integrity is the need to protect the process or program used to manipulate the data from unauthorized modification. A critical requirement of both commercial and government data processing is to ensure the integrity of data to prevent fraud and errors. It is imperative, therefore, no user be able to modify data in a way that might corrupt or lose assets or financial records or render decision making information unreliable. Examples of government systems in which integrity is crucial include air traffic control system, military fire control systems, social security and welfare systems. Examples of commercial systems that require a high level of integrity include medical prescription system, credit reporting systems, production control systems and payroll systems. "
},
{
"code": null,
"e": 1793,
"s": 1224,
"text": "Protecting against Threats to Integrity: Like confidentiality, integrity can also be arbitrated by hackers, masqueraders, unprotected downloaded files, LANs, unauthorized user activities, and unauthorized programs like Trojan Horse and viruses, because each of these threads can lead to unauthorized changes to data or programs. For example, unauthorized user can corrupt or change data and programs intentionally or accidentally if their activities on the system are not properly controlled. Generally, three basic principles are used to establish integrity controls:"
},
{
"code": null,
"e": 2327,
"s": 1793,
"text": "Need-to-know access: User should be granted access only on to those files and programs that they need in order to perform their assigned jobs functions.Separation of duties: To ensure that no single employee has control of a transaction from beginning to end, two or more people should be responsible for performing it.Rotation of duties: Job assignment should be changed periodically so that it becomes more difficult for the users to collaborate to exercise complete control of a transaction and subvert it for fraudulent purposes."
},
{
"code": null,
"e": 2480,
"s": 2327,
"text": "Need-to-know access: User should be granted access only on to those files and programs that they need in order to perform their assigned jobs functions."
},
{
"code": null,
"e": 2648,
"s": 2480,
"text": "Separation of duties: To ensure that no single employee has control of a transaction from beginning to end, two or more people should be responsible for performing it."
},
{
"code": null,
"e": 2863,
"s": 2648,
"text": "Rotation of duties: Job assignment should be changed periodically so that it becomes more difficult for the users to collaborate to exercise complete control of a transaction and subvert it for fraudulent purposes."
},
{
"code": null,
"e": 3065,
"s": 2863,
"text": "Integrity Models β Integrity models are used to describe what needs to be done to enforce the information integrity policy. There are three goals of integrity, which the models address in various ways:"
},
{
"code": null,
"e": 3288,
"s": 3065,
"text": "Preventing unauthorized users from making modifications to data or programs.Preventing authorized users from making improper or unauthorized modifications.Maintaining internal and external consistency of data and programs."
},
{
"code": null,
"e": 3365,
"s": 3288,
"text": "Preventing unauthorized users from making modifications to data or programs."
},
{
"code": null,
"e": 3445,
"s": 3365,
"text": "Preventing authorized users from making improper or unauthorized modifications."
},
{
"code": null,
"e": 3513,
"s": 3445,
"text": "Maintaining internal and external consistency of data and programs."
},
{
"code": null,
"e": 3621,
"s": 3513,
"text": "Integrity models includes five models that suggests different approaches to achieving integrity, they are β"
},
{
"code": null,
"e": 3636,
"s": 3621,
"text": "iamharrypo92lv"
},
{
"code": null,
"e": 3657,
"s": 3636,
"text": "Information-Security"
},
{
"code": null,
"e": 3663,
"s": 3657,
"text": "GBlog"
},
{
"code": null,
"e": 3761,
"s": 3663,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3786,
"s": 3761,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 3841,
"s": 3786,
"text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!"
},
{
"code": null,
"e": 3878,
"s": 3841,
"text": "Geek Streak - 24 Days POTD Challenge"
},
{
"code": null,
"e": 3916,
"s": 3878,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 3982,
"s": 3916,
"text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?"
},
{
"code": null,
"e": 4053,
"s": 3982,
"text": "GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa"
},
{
"code": null,
"e": 4079,
"s": 4053,
"text": "Types of Software Testing"
},
{
"code": null,
"e": 4121,
"s": 4079,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 4160,
"s": 4121,
"text": "How to Learn Data Science in 10 weeks?"
}
] |
ReactJS | Setting up Development Environment
|
25 Jan, 2021
To run any React application, we must have NodeJS installed on our PC. So, the very first step will be to install NodeJS.
Step 1: Install NodeJS. You may visit the official download link of NodeJS to download and install the latest version of NodeJS. Once we have set up NodeJS on our PC, the next thing we need to do is set up React Boilerplate.
Step 2: Setting up react environment for older and latest versions, follow anyone according to your node version.
For Older Versions which include Node < 8.10 and npm < 5.6: Setting up React Boilerplate. We will install the boilerplate globally. Run the below command in your terminal or command prompt to install the React Boilerplate.
npm install -g create-react-app
After running the above command and successfully installing the boilerplate your terminal will show some output as shown in the below image:
Now after successfully installing the boilerplate the next thing we will do is create our React app. We can use the create-react-app command for creating an app to React.
For the Latest Versions which include Node >=8.10 and npm >=5.6: For using the latest features of JavaScript which provides a good development experience the machine should contain a version of Node >=8.10 and npm >=5.6.
Run the below command to create a new project
npx create-react-app my-app
The above command will create the app name my-app as shown in the image below :
You can run the project by typing the command cd my-app.
cd my-app
npm start
It will give you the output in the terminal as shown in the image below :
Now you can view your app in the browser as shown in the image below :
Step 3: Create a React app. Now to create an app we will use the boilerplate we installed. The below command will create an app named myapp.
create-react-app myapp
The above statement will create a new directory named myapp inside your current directory with a bunch of files needed to successfully run a React app.
Letβs have a look at the directory created by the above command:
In the above directory, you can see a number of files. The main files we will be working on within the basic course are index.html and index.js. The index.html file will have a div element with id = βrootβ, inside which everything will be rendered and all of our React code will be inside the index.js file.
Now, that we have successfully set up the development environment. The last thing left is to start the development server.
Step 4: Start the development server. To start the development server, go inside your current directory βmyappβ and execute the below command:
npm start
On successfully running the above command your compiler will show the below message:
You can go to the URL shown in the above message to see the changes you are making in your App. By default, the above URL will show the below page:
Thatβs all! We have a development environment set up and ready. Now we will move ahead to start learning ReactJS development to make some use of it.
shubhamyadav4
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
Axios in React: A Guide for Beginners
ReactJS setState()
How to pass data from one component to other component in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n25 Jan, 2021"
},
{
"code": null,
"e": 176,
"s": 53,
"text": "To run any React application, we must have NodeJS installed on our PC. So, the very first step will be to install NodeJS. "
},
{
"code": null,
"e": 402,
"s": 176,
"text": "Step 1: Install NodeJS. You may visit the official download link of NodeJS to download and install the latest version of NodeJS. Once we have set up NodeJS on our PC, the next thing we need to do is set up React Boilerplate. "
},
{
"code": null,
"e": 516,
"s": 402,
"text": "Step 2: Setting up react environment for older and latest versions, follow anyone according to your node version."
},
{
"code": null,
"e": 739,
"s": 516,
"text": "For Older Versions which include Node < 8.10 and npm < 5.6: Setting up React Boilerplate. We will install the boilerplate globally. Run the below command in your terminal or command prompt to install the React Boilerplate."
},
{
"code": null,
"e": 771,
"s": 739,
"text": "npm install -g create-react-app"
},
{
"code": null,
"e": 914,
"s": 771,
"text": "After running the above command and successfully installing the boilerplate your terminal will show some output as shown in the below image: "
},
{
"code": null,
"e": 1086,
"s": 914,
"text": "Now after successfully installing the boilerplate the next thing we will do is create our React app. We can use the create-react-app command for creating an app to React. "
},
{
"code": null,
"e": 1307,
"s": 1086,
"text": "For the Latest Versions which include Node >=8.10 and npm >=5.6: For using the latest features of JavaScript which provides a good development experience the machine should contain a version of Node >=8.10 and npm >=5.6."
},
{
"code": null,
"e": 1353,
"s": 1307,
"text": "Run the below command to create a new project"
},
{
"code": null,
"e": 1381,
"s": 1353,
"text": "npx create-react-app my-app"
},
{
"code": null,
"e": 1462,
"s": 1381,
"text": "The above command will create the app name my-app as shown in the image below : "
},
{
"code": null,
"e": 1519,
"s": 1462,
"text": "You can run the project by typing the command cd my-app."
},
{
"code": null,
"e": 1539,
"s": 1519,
"text": "cd my-app\nnpm start"
},
{
"code": null,
"e": 1613,
"s": 1539,
"text": "It will give you the output in the terminal as shown in the image below :"
},
{
"code": null,
"e": 1684,
"s": 1613,
"text": "Now you can view your app in the browser as shown in the image below :"
},
{
"code": null,
"e": 1826,
"s": 1684,
"text": "Step 3: Create a React app. Now to create an app we will use the boilerplate we installed. The below command will create an app named myapp. "
},
{
"code": null,
"e": 1849,
"s": 1826,
"text": "create-react-app myapp"
},
{
"code": null,
"e": 2002,
"s": 1849,
"text": "The above statement will create a new directory named myapp inside your current directory with a bunch of files needed to successfully run a React app. "
},
{
"code": null,
"e": 2069,
"s": 2002,
"text": "Letβs have a look at the directory created by the above command: "
},
{
"code": null,
"e": 2378,
"s": 2069,
"text": "In the above directory, you can see a number of files. The main files we will be working on within the basic course are index.html and index.js. The index.html file will have a div element with id = βrootβ, inside which everything will be rendered and all of our React code will be inside the index.js file. "
},
{
"code": null,
"e": 2502,
"s": 2378,
"text": "Now, that we have successfully set up the development environment. The last thing left is to start the development server. "
},
{
"code": null,
"e": 2647,
"s": 2502,
"text": "Step 4: Start the development server. To start the development server, go inside your current directory βmyappβ and execute the below command: "
},
{
"code": null,
"e": 2657,
"s": 2647,
"text": "npm start"
},
{
"code": null,
"e": 2744,
"s": 2657,
"text": "On successfully running the above command your compiler will show the below message: "
},
{
"code": null,
"e": 2894,
"s": 2744,
"text": "You can go to the URL shown in the above message to see the changes you are making in your App. By default, the above URL will show the below page: "
},
{
"code": null,
"e": 3044,
"s": 2894,
"text": "Thatβs all! We have a development environment set up and ready. Now we will move ahead to start learning ReactJS development to make some use of it. "
},
{
"code": null,
"e": 3058,
"s": 3044,
"text": "shubhamyadav4"
},
{
"code": null,
"e": 3066,
"s": 3058,
"text": "ReactJS"
},
{
"code": null,
"e": 3083,
"s": 3066,
"text": "Web Technologies"
},
{
"code": null,
"e": 3181,
"s": 3083,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3224,
"s": 3181,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 3269,
"s": 3224,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 3307,
"s": 3269,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 3326,
"s": 3307,
"text": "ReactJS setState()"
},
{
"code": null,
"e": 3394,
"s": 3326,
"text": "How to pass data from one component to other component in ReactJS ?"
},
{
"code": null,
"e": 3456,
"s": 3394,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3489,
"s": 3456,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3550,
"s": 3489,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3600,
"s": 3550,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
JavaScript | Object Properties
|
27 Mar, 2019
Object properties are defined as a simple association between name and value. All properties have a name and value is one of the attributes linked with the property, which defines the access granted to the property. Properties refer to the collection of values which are associated with the JavaScript object. This collection may not follow any particular order. JavaScript provides the feature to add, delete and modify the properties. Properties are denoted by name:values pairs.
Syntax:
objectName.property
objectName.property
objectName["property"]
objectName["property"]
objectName[expression]
objectName[expression]
Properties:
addition: It can add new objects by simply giving values to those new objects.
deletion: It uses delete keyword, to delete a property from an object.
Example 1: Shows adding a new property to the existing object.
<!DOCTYPE html><html> <head> <title> JavaScript Object Properties </title></head> <body> <h1>Geeks</h1> <h3>JavaScript Object Properties</h3> <p id="gfg"></p> <!-- Script to add object property --> <script> var employee = { name:"Steve", id:"123" }; employee.age="25"; document.getElementById("gfg").innerHTML = employee.name + " age " + employee.age + " years, and has unique id " + employee.id +"."; </script></body> </html>
Output:
Example 2: Shows deleting a property from the existing object.
<!DOCTYPE html><html> <head> <title> JavaScript Object Properties </title></head> <body> <h1>Geeks</h1> <h3>JavaScript Object Properties</h3> <p id="gfg"></p> <!-- Script to delete object content --> <script> var employee = { name:"Steve", id:"123" }; /* Delete employee id */ delete employee.id; document.getElementById("gfg").innerHTML = employee.name + " has unique id " + employee.id +"." ; </script></body> </html>
Output:
There are different ways to accessing the object properties. Following examples demonstrate the different accessing techniques:
Example: This example uses .property to access object element.<!DOCTYPE html><html> <head> <title> JavaScript Object Properties </title></head> <body> <h1>Geeks</h1> <h3>JavaScript Object Properties</h3> <p>Using .property to access an object</p> <p id="gfg"></p> <script> var employee = { name:"Steve", id:"123" }; document.getElementById("gfg").innerHTML = employee.name + " has unique id " + employee.id ; </script></body> </html> Output:
<!DOCTYPE html><html> <head> <title> JavaScript Object Properties </title></head> <body> <h1>Geeks</h1> <h3>JavaScript Object Properties</h3> <p>Using .property to access an object</p> <p id="gfg"></p> <script> var employee = { name:"Steve", id:"123" }; document.getElementById("gfg").innerHTML = employee.name + " has unique id " + employee.id ; </script></body> </html>
Output:
Example: This example uses [βpropertyβ] to access the object element.<!DOCTYPE html><html> <head> <title> JavaScript Object Properties </title></head> <body> <h1>GeeksforGeeks</h1> <h3>JavaScript Object Properties</h3> <p>Using ["property"] to access an object</p> <p id="gfg"></p> <!-- Script to access an object --> <script> var employee = { name:"Steve", id:"123" }; document.getElementById("gfg").innerHTML = employee["name"] + " has unique id " + employee["id"] ; </script></body> </html> Output:
<!DOCTYPE html><html> <head> <title> JavaScript Object Properties </title></head> <body> <h1>GeeksforGeeks</h1> <h3>JavaScript Object Properties</h3> <p>Using ["property"] to access an object</p> <p id="gfg"></p> <!-- Script to access an object --> <script> var employee = { name:"Steve", id:"123" }; document.getElementById("gfg").innerHTML = employee["name"] + " has unique id " + employee["id"] ; </script></body> </html>
Output:
Example: This example uses for...in loop to access the object element.<!DOCTYPE html><html> <head> <title> JavaScript Object Properties </title></head> <body> <h1>GeeksforGeeks</h1> <h3>JavaScript Object Properties</h3> <p>Using for...in loop</p> <p id="GFG"></p> <!-- Script to use loop to access object content --> <script> var gfg = ""; var employee = { name:"Steve", id:"123" }; var z; for (z in employee) { gfg += employee[z] + " "; } document.getElementById("GFG").innerHTML = gfg; </script></body> </html> Output:
<!DOCTYPE html><html> <head> <title> JavaScript Object Properties </title></head> <body> <h1>GeeksforGeeks</h1> <h3>JavaScript Object Properties</h3> <p>Using for...in loop</p> <p id="GFG"></p> <!-- Script to use loop to access object content --> <script> var gfg = ""; var employee = { name:"Steve", id:"123" }; var z; for (z in employee) { gfg += employee[z] + " "; } document.getElementById("GFG").innerHTML = gfg; </script></body> </html>
Output:
riarawal99
javascript-object
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Mar, 2019"
},
{
"code": null,
"e": 510,
"s": 28,
"text": "Object properties are defined as a simple association between name and value. All properties have a name and value is one of the attributes linked with the property, which defines the access granted to the property. Properties refer to the collection of values which are associated with the JavaScript object. This collection may not follow any particular order. JavaScript provides the feature to add, delete and modify the properties. Properties are denoted by name:values pairs."
},
{
"code": null,
"e": 518,
"s": 510,
"text": "Syntax:"
},
{
"code": null,
"e": 539,
"s": 518,
"text": "objectName.property "
},
{
"code": null,
"e": 560,
"s": 539,
"text": "objectName.property "
},
{
"code": null,
"e": 583,
"s": 560,
"text": "objectName[\"property\"]"
},
{
"code": null,
"e": 606,
"s": 583,
"text": "objectName[\"property\"]"
},
{
"code": null,
"e": 629,
"s": 606,
"text": "objectName[expression]"
},
{
"code": null,
"e": 652,
"s": 629,
"text": "objectName[expression]"
},
{
"code": null,
"e": 664,
"s": 652,
"text": "Properties:"
},
{
"code": null,
"e": 743,
"s": 664,
"text": "addition: It can add new objects by simply giving values to those new objects."
},
{
"code": null,
"e": 814,
"s": 743,
"text": "deletion: It uses delete keyword, to delete a property from an object."
},
{
"code": null,
"e": 877,
"s": 814,
"text": "Example 1: Shows adding a new property to the existing object."
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript Object Properties </title></head> <body> <h1>Geeks</h1> <h3>JavaScript Object Properties</h3> <p id=\"gfg\"></p> <!-- Script to add object property --> <script> var employee = { name:\"Steve\", id:\"123\" }; employee.age=\"25\"; document.getElementById(\"gfg\").innerHTML = employee.name + \" age \" + employee.age + \" years, and has unique id \" + employee.id +\".\"; </script></body> </html> ",
"e": 1476,
"s": 877,
"text": null
},
{
"code": null,
"e": 1484,
"s": 1476,
"text": "Output:"
},
{
"code": null,
"e": 1547,
"s": 1484,
"text": "Example 2: Shows deleting a property from the existing object."
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript Object Properties </title></head> <body> <h1>Geeks</h1> <h3>JavaScript Object Properties</h3> <p id=\"gfg\"></p> <!-- Script to delete object content --> <script> var employee = { name:\"Steve\", id:\"123\" }; /* Delete employee id */ delete employee.id; document.getElementById(\"gfg\").innerHTML = employee.name + \" has unique id \" + employee.id +\".\" ; </script></body> </html> ",
"e": 2117,
"s": 1547,
"text": null
},
{
"code": null,
"e": 2125,
"s": 2117,
"text": "Output:"
},
{
"code": null,
"e": 2253,
"s": 2125,
"text": "There are different ways to accessing the object properties. Following examples demonstrate the different accessing techniques:"
},
{
"code": null,
"e": 2832,
"s": 2253,
"text": "Example: This example uses .property to access object element.<!DOCTYPE html><html> <head> <title> JavaScript Object Properties </title></head> <body> <h1>Geeks</h1> <h3>JavaScript Object Properties</h3> <p>Using .property to access an object</p> <p id=\"gfg\"></p> <script> var employee = { name:\"Steve\", id:\"123\" }; document.getElementById(\"gfg\").innerHTML = employee.name + \" has unique id \" + employee.id ; </script></body> </html> Output:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript Object Properties </title></head> <body> <h1>Geeks</h1> <h3>JavaScript Object Properties</h3> <p>Using .property to access an object</p> <p id=\"gfg\"></p> <script> var employee = { name:\"Steve\", id:\"123\" }; document.getElementById(\"gfg\").innerHTML = employee.name + \" has unique id \" + employee.id ; </script></body> </html> ",
"e": 3342,
"s": 2832,
"text": null
},
{
"code": null,
"e": 3350,
"s": 3342,
"text": "Output:"
},
{
"code": null,
"e": 3996,
"s": 3350,
"text": "Example: This example uses [βpropertyβ] to access the object element.<!DOCTYPE html><html> <head> <title> JavaScript Object Properties </title></head> <body> <h1>GeeksforGeeks</h1> <h3>JavaScript Object Properties</h3> <p>Using [\"property\"] to access an object</p> <p id=\"gfg\"></p> <!-- Script to access an object --> <script> var employee = { name:\"Steve\", id:\"123\" }; document.getElementById(\"gfg\").innerHTML = employee[\"name\"] + \" has unique id \" + employee[\"id\"] ; </script></body> </html> Output:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript Object Properties </title></head> <body> <h1>GeeksforGeeks</h1> <h3>JavaScript Object Properties</h3> <p>Using [\"property\"] to access an object</p> <p id=\"gfg\"></p> <!-- Script to access an object --> <script> var employee = { name:\"Steve\", id:\"123\" }; document.getElementById(\"gfg\").innerHTML = employee[\"name\"] + \" has unique id \" + employee[\"id\"] ; </script></body> </html> ",
"e": 4566,
"s": 3996,
"text": null
},
{
"code": null,
"e": 4574,
"s": 4566,
"text": "Output:"
},
{
"code": null,
"e": 5263,
"s": 4574,
"text": "Example: This example uses for...in loop to access the object element.<!DOCTYPE html><html> <head> <title> JavaScript Object Properties </title></head> <body> <h1>GeeksforGeeks</h1> <h3>JavaScript Object Properties</h3> <p>Using for...in loop</p> <p id=\"GFG\"></p> <!-- Script to use loop to access object content --> <script> var gfg = \"\"; var employee = { name:\"Steve\", id:\"123\" }; var z; for (z in employee) { gfg += employee[z] + \" \"; } document.getElementById(\"GFG\").innerHTML = gfg; </script></body> </html> Output:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript Object Properties </title></head> <body> <h1>GeeksforGeeks</h1> <h3>JavaScript Object Properties</h3> <p>Using for...in loop</p> <p id=\"GFG\"></p> <!-- Script to use loop to access object content --> <script> var gfg = \"\"; var employee = { name:\"Steve\", id:\"123\" }; var z; for (z in employee) { gfg += employee[z] + \" \"; } document.getElementById(\"GFG\").innerHTML = gfg; </script></body> </html> ",
"e": 5875,
"s": 5263,
"text": null
},
{
"code": null,
"e": 5883,
"s": 5875,
"text": "Output:"
},
{
"code": null,
"e": 5894,
"s": 5883,
"text": "riarawal99"
},
{
"code": null,
"e": 5912,
"s": 5894,
"text": "javascript-object"
},
{
"code": null,
"e": 5919,
"s": 5912,
"text": "Picked"
},
{
"code": null,
"e": 5930,
"s": 5919,
"text": "JavaScript"
},
{
"code": null,
"e": 5947,
"s": 5930,
"text": "Web Technologies"
}
] |
Design a Parallax Webpage using HTML & CSS
|
13 Apr, 2021
A parallax website includes fixed images in the background that is kept in place and user can scroll down the page to see different parts of the image. In this article, we are creating a parallax webpage using HTML and CSS. We will use basic tags of HTML like div, paragraph, and heading to write our content and will use CSS to align and beautify our basic HTML design.
Approach:
We have used a container element and add a background image to the container. Then we have used the background-attachment: fixed to create the actual parallax effect.
For each HTML section we have given a class so that it can be target in the CSS.
In the HTML page, we have divisions and in each division, there is a header and a small paragraph. In the CSS file, we have decorated our text and placed the head at a fixed position.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <style> /* Styling the body */ * { margin: 0px; padding: 0px; } /* Styling the first parallax's height, width and background color */ .parallax-1 { width: 100%; height: 600px; background: url('https://media.geeksforgeeks.org/wp-content/uploads/20210402175040/back22.jpg'); background-size: 100% 100%; background-attachment: fixed; } /* Styling the title of first parallax */ .parallax-1 h2 { margin: auto; position: relative; left: 500x; top: 300px; width: 250px; height: 32px; padding: 10px; background-color: black; color: white; text-align: center; } /* Styling the second parallax's height, width and background color */ .parallax-2 { width: 100%; height: 600px; background: url('https://media.geeksforgeeks.org/wp-content/uploads/20210402175040/back22.jpg'); background-size: 100% 100%; background-attachment: fixed; } /* Styling the title of second parallax */ .parallax-2 h2 { margin: auto; position: relative; left: 500x; top: 300px; width: 250px; height: 37px; padding: 10px; background-color: white; color: black; text-align: center; font-size: 30px; font-family: Verdana; } /* Styling the content or paragraph */ .para-1 { padding: 50px; background-color: black; color: white; font-size: 17px; } /* Styling the content or paragraph */ .para-2 { text-align: center; padding: 25px; font-size: 17px; font-family: Verdana; background-color: black; color: white; } </style></head> <body> <!-- Giving title of the first parallax --> <div class="parallax-1"> <h2>SUSHANT GAURAV</h2> </div> <!--Content of first parallax --> <div class="para-1"> <p> Thankyou for showing interest, here is a quick story of me and this website. My programming journey started back in 2019, few months before I started studying CSE in LNCT Bhopal. I am currently in my second year and doing Technical Content Writing Internship at GeeksForGeeks. I like coding all kind of problems from the very basic like adding numbers to the complex ones like competitive programming problems. I love making projects and games. Infact this website is one of my Web Development Projects which is built using HTML and CSS.<br> <br>Languages known : C Language, C++, JAVA, Python, JavaScript, MySQL.<br> IT Constructs : Data Structures and Algorithm, OOP, HTML, CSS, LINUX, and Git & GitHub. </p> </div> <!-- Giving title of the first parallax --> <div class="parallax-2"> <h2>PROJECTS</h2> </div> <!--Content of first parallax --> <div class="para-2"> <p> Calendar Tic-Tac-Toe Quiz Game Survey Form Chat Bot in C Tribute Webpage Portfolio Website Guess the Number Rock Paper Scissor To-Do List using JS Notes Taker using JS BMI Calculator using JS Loan Calculator using JS Travel Management System Random Password Generator Different Management Systems </p> </div> <!--This will be same as first parallax--> <div class="parallax-1"> <h2>ACHIEVEMENTS</h2> </div> <div class="para-2"> <p> Technical Content Writer Intern at GeeksForGeeks Microsoft Learn Student Ambassador - Beta Participant in GirlScript Summer of Code 2021 Mentored HackTX Hackathon </p> </div></body> </html>
Output:
CSS-Properties
CSS-Questions
CSS-Selectors
HTML-Questions
HTML-Tags
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Apr, 2021"
},
{
"code": null,
"e": 425,
"s": 54,
"text": "A parallax website includes fixed images in the background that is kept in place and user can scroll down the page to see different parts of the image. In this article, we are creating a parallax webpage using HTML and CSS. We will use basic tags of HTML like div, paragraph, and heading to write our content and will use CSS to align and beautify our basic HTML design."
},
{
"code": null,
"e": 435,
"s": 425,
"text": "Approach:"
},
{
"code": null,
"e": 602,
"s": 435,
"text": "We have used a container element and add a background image to the container. Then we have used the background-attachment: fixed to create the actual parallax effect."
},
{
"code": null,
"e": 683,
"s": 602,
"text": "For each HTML section we have given a class so that it can be target in the CSS."
},
{
"code": null,
"e": 867,
"s": 683,
"text": "In the HTML page, we have divisions and in each division, there is a header and a small paragraph. In the CSS file, we have decorated our text and placed the head at a fixed position."
},
{
"code": null,
"e": 876,
"s": 867,
"text": "Example:"
},
{
"code": null,
"e": 881,
"s": 876,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> /* Styling the body */ * { margin: 0px; padding: 0px; } /* Styling the first parallax's height, width and background color */ .parallax-1 { width: 100%; height: 600px; background: url('https://media.geeksforgeeks.org/wp-content/uploads/20210402175040/back22.jpg'); background-size: 100% 100%; background-attachment: fixed; } /* Styling the title of first parallax */ .parallax-1 h2 { margin: auto; position: relative; left: 500x; top: 300px; width: 250px; height: 32px; padding: 10px; background-color: black; color: white; text-align: center; } /* Styling the second parallax's height, width and background color */ .parallax-2 { width: 100%; height: 600px; background: url('https://media.geeksforgeeks.org/wp-content/uploads/20210402175040/back22.jpg'); background-size: 100% 100%; background-attachment: fixed; } /* Styling the title of second parallax */ .parallax-2 h2 { margin: auto; position: relative; left: 500x; top: 300px; width: 250px; height: 37px; padding: 10px; background-color: white; color: black; text-align: center; font-size: 30px; font-family: Verdana; } /* Styling the content or paragraph */ .para-1 { padding: 50px; background-color: black; color: white; font-size: 17px; } /* Styling the content or paragraph */ .para-2 { text-align: center; padding: 25px; font-size: 17px; font-family: Verdana; background-color: black; color: white; } </style></head> <body> <!-- Giving title of the first parallax --> <div class=\"parallax-1\"> <h2>SUSHANT GAURAV</h2> </div> <!--Content of first parallax --> <div class=\"para-1\"> <p> Thankyou for showing interest, here is a quick story of me and this website. My programming journey started back in 2019, few months before I started studying CSE in LNCT Bhopal. I am currently in my second year and doing Technical Content Writing Internship at GeeksForGeeks. I like coding all kind of problems from the very basic like adding numbers to the complex ones like competitive programming problems. I love making projects and games. Infact this website is one of my Web Development Projects which is built using HTML and CSS.<br> <br>Languages known : C Language, C++, JAVA, Python, JavaScript, MySQL.<br> IT Constructs : Data Structures and Algorithm, OOP, HTML, CSS, LINUX, and Git & GitHub. </p> </div> <!-- Giving title of the first parallax --> <div class=\"parallax-2\"> <h2>PROJECTS</h2> </div> <!--Content of first parallax --> <div class=\"para-2\"> <p> Calendar Tic-Tac-Toe Quiz Game Survey Form Chat Bot in C Tribute Webpage Portfolio Website Guess the Number Rock Paper Scissor To-Do List using JS Notes Taker using JS BMI Calculator using JS Loan Calculator using JS Travel Management System Random Password Generator Different Management Systems </p> </div> <!--This will be same as first parallax--> <div class=\"parallax-1\"> <h2>ACHIEVEMENTS</h2> </div> <div class=\"para-2\"> <p> Technical Content Writer Intern at GeeksForGeeks Microsoft Learn Student Ambassador - Beta Participant in GirlScript Summer of Code 2021 Mentored HackTX Hackathon </p> </div></body> </html>",
"e": 5342,
"s": 881,
"text": null
},
{
"code": null,
"e": 5350,
"s": 5342,
"text": "Output:"
},
{
"code": null,
"e": 5365,
"s": 5350,
"text": "CSS-Properties"
},
{
"code": null,
"e": 5379,
"s": 5365,
"text": "CSS-Questions"
},
{
"code": null,
"e": 5393,
"s": 5379,
"text": "CSS-Selectors"
},
{
"code": null,
"e": 5408,
"s": 5393,
"text": "HTML-Questions"
},
{
"code": null,
"e": 5418,
"s": 5408,
"text": "HTML-Tags"
},
{
"code": null,
"e": 5422,
"s": 5418,
"text": "CSS"
},
{
"code": null,
"e": 5427,
"s": 5422,
"text": "HTML"
},
{
"code": null,
"e": 5444,
"s": 5427,
"text": "Web Technologies"
},
{
"code": null,
"e": 5449,
"s": 5444,
"text": "HTML"
}
] |
How to create linear gradient text using HTML and CSS ?
|
11 Jun, 2020
The linear-gradient is a kind of text-styling in which the text is filled with linear-gradient color codes. These kinds of effects are generally used in dark-themed websites or apps to make the text look attractive and bold. They are almost suitable for dark themes and do not go well with the lighter themes.
Approach: Please refer linear-gradient() method to sreate a gradient background and then use webkit properties to overlay that background with our text.
HTML Code: In the following section, the text used for demonstration is wrapped inside h1 tag.
<!-- Write HTML code here --><!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <title>Gradient Text</title> </head><body> <h1>GEEKSFORGEEKS</h1> </body></html>
CSS Code: For CSS code, please follow the steps given below.
Step 1: Apply a basic background to the body tag and align the text to center of the page.
Step 2: Do some basic styling like font-size and family etc.
Step 3: Apply the linear gradient property with any colors of your choice.
Step 4: Now apply webkit properties, the first one will make the whole gradient-background transparent and the second property will fill the text with the gradient background.
Note: You can apply some shadow to the text to give it a darker or matte finishing kind of look.
<style> body { background: rgb(39, 39, 39); } h1 { position: absolute; top: 40%; left: 40%; font-size: 40px; font-family: Arial, Helvetica, sans-serif; background: linear-gradient( to right, #f32170, #ff6b08, #cf23cf, #eedd44); -webkit-text-fill-color: transparent; -webkit-background-clip: text; }</style>
Complete Code: It is the combination of the above two sections of code.
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <title>Gradient Text</title> <style> body { background: rgb(39, 39, 39); } h1 { position: absolute; top: 40%; left: 40%; font-size: 40px; font-family: Arial, Helvetica, sans-serif; background: linear-gradient(to right, #f32170, #ff6b08, #cf23cf, #eedd44); -webkit-text-fill-color: transparent; -webkit-background-clip: text; } </style></head> <body> <h1>GEEKSFORGEEKS</h1></body> </html>
Output:
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of CSS (Cascading Style Sheet)
How to set space between the flexbox ?
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
REST API (Introduction)
How to set input type date in dd-mm-yyyy format using HTML ?
How to set the default value for an HTML <select> element ?
Design a Tribute Page using HTML & CSS
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Jun, 2020"
},
{
"code": null,
"e": 338,
"s": 28,
"text": "The linear-gradient is a kind of text-styling in which the text is filled with linear-gradient color codes. These kinds of effects are generally used in dark-themed websites or apps to make the text look attractive and bold. They are almost suitable for dark themes and do not go well with the lighter themes."
},
{
"code": null,
"e": 491,
"s": 338,
"text": "Approach: Please refer linear-gradient() method to sreate a gradient background and then use webkit properties to overlay that background with our text."
},
{
"code": null,
"e": 586,
"s": 491,
"text": "HTML Code: In the following section, the text used for demonstration is wrapped inside h1 tag."
},
{
"code": "<!-- Write HTML code here --><!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <title>Gradient Text</title> </head><body> <h1>GEEKSFORGEEKS</h1> </body></html>",
"e": 864,
"s": 586,
"text": null
},
{
"code": null,
"e": 925,
"s": 864,
"text": "CSS Code: For CSS code, please follow the steps given below."
},
{
"code": null,
"e": 1016,
"s": 925,
"text": "Step 1: Apply a basic background to the body tag and align the text to center of the page."
},
{
"code": null,
"e": 1077,
"s": 1016,
"text": "Step 2: Do some basic styling like font-size and family etc."
},
{
"code": null,
"e": 1152,
"s": 1077,
"text": "Step 3: Apply the linear gradient property with any colors of your choice."
},
{
"code": null,
"e": 1328,
"s": 1152,
"text": "Step 4: Now apply webkit properties, the first one will make the whole gradient-background transparent and the second property will fill the text with the gradient background."
},
{
"code": null,
"e": 1425,
"s": 1328,
"text": "Note: You can apply some shadow to the text to give it a darker or matte finishing kind of look."
},
{
"code": "<style> body { background: rgb(39, 39, 39); } h1 { position: absolute; top: 40%; left: 40%; font-size: 40px; font-family: Arial, Helvetica, sans-serif; background: linear-gradient( to right, #f32170, #ff6b08, #cf23cf, #eedd44); -webkit-text-fill-color: transparent; -webkit-background-clip: text; }</style>",
"e": 1846,
"s": 1425,
"text": null
},
{
"code": null,
"e": 1918,
"s": 1846,
"text": "Complete Code: It is the combination of the above two sections of code."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <title>Gradient Text</title> <style> body { background: rgb(39, 39, 39); } h1 { position: absolute; top: 40%; left: 40%; font-size: 40px; font-family: Arial, Helvetica, sans-serif; background: linear-gradient(to right, #f32170, #ff6b08, #cf23cf, #eedd44); -webkit-text-fill-color: transparent; -webkit-background-clip: text; } </style></head> <body> <h1>GEEKSFORGEEKS</h1></body> </html>",
"e": 2622,
"s": 1918,
"text": null
},
{
"code": null,
"e": 2630,
"s": 2622,
"text": "Output:"
},
{
"code": null,
"e": 2639,
"s": 2630,
"text": "CSS-Misc"
},
{
"code": null,
"e": 2649,
"s": 2639,
"text": "HTML-Misc"
},
{
"code": null,
"e": 2653,
"s": 2649,
"text": "CSS"
},
{
"code": null,
"e": 2658,
"s": 2653,
"text": "HTML"
},
{
"code": null,
"e": 2675,
"s": 2658,
"text": "Web Technologies"
},
{
"code": null,
"e": 2702,
"s": 2675,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2707,
"s": 2702,
"text": "HTML"
},
{
"code": null,
"e": 2805,
"s": 2707,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2842,
"s": 2805,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 2881,
"s": 2842,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 2945,
"s": 2881,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 3006,
"s": 2945,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 3045,
"s": 3006,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 3082,
"s": 3045,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 3106,
"s": 3082,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 3167,
"s": 3106,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 3227,
"s": 3167,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
Python β Extract elements from Ranges in List
|
02 Sep, 2020
Given a list, and a list of tuples with ranges, extract all elements in those ranges from list.
Input : test_list = [4, 5, 4, 6, 7, 5, 4, 5, 6, 10], range_list = [(2, 4), (7, 8)]Output : [4, 6, 7, 5, 6]Explanation : 4, 6, 7 are elements at idx 2, 3, 4 and 5, 6 at idx 7, 8.
Input : test_list = [4, 5, 4, 6, 7, 5, 4, 5, 6, 10], range_list = [(2, 6)]Output : [4, 6, 7, 5, 4]Explanation : Elements from 2-6 index are extracted.
Method #1 : Using loop + list slicing
In this, we extract each range using list slicing and using loop iterate for each range and keep extending the extracting slices to extending list.
Python3
# Python3 code to demonstrate working of # Extract elements from Ranges in List# Using loop + list slicing # initializing listtest_list = [4, 5, 4, 6, 7, 5, 4, 5, 4, 6, 4, 6, 9, 8] # printing original listprint("The original list is : " + str(test_list)) # initializing rangesrange_list = [(2, 4), (7, 8), (10, 12)] res = []for ele in range_list: # extending ranges res.extend(test_list[ele[0] : ele[1] + 1]) # printing result print("Ranges elements : " + str(res))
The original list is : [4, 5, 4, 6, 7, 5, 4, 5, 4, 6, 4, 6, 9, 8]
Ranges elements : [4, 6, 7, 5, 4, 4, 6, 9]
Method #2 : Using list comprehension
In this, we apply similar method as above function, difference being that list comprehension is used to solve this in compact form.
Python3
# Python3 code to demonstrate working of # Extract elements from Ranges in List# Using list comprehensionfrom itertools import chain # initializing listtest_list = [4, 5, 4, 6, 7, 5, 4, 5, 4, 6, 4, 6, 9, 8] # printing original listprint("The original list is : " + str(test_list)) # initializing rangesrange_list = [(2, 4), (7, 8), (10, 12)] # using one-liner to solve this problemres = list(chain.from_iterable([test_list[ele[0] : ele[1] + 1] for ele in range_list])) # printing result print("Ranges elements : " + str(res))
The original list is : [4, 5, 4, 6, 7, 5, 4, 5, 4, 6, 4, 6, 9, 8]
Ranges elements : [4, 6, 7, 5, 4, 4, 6, 9]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Sep, 2020"
},
{
"code": null,
"e": 124,
"s": 28,
"text": "Given a list, and a list of tuples with ranges, extract all elements in those ranges from list."
},
{
"code": null,
"e": 302,
"s": 124,
"text": "Input : test_list = [4, 5, 4, 6, 7, 5, 4, 5, 6, 10], range_list = [(2, 4), (7, 8)]Output : [4, 6, 7, 5, 6]Explanation : 4, 6, 7 are elements at idx 2, 3, 4 and 5, 6 at idx 7, 8."
},
{
"code": null,
"e": 453,
"s": 302,
"text": "Input : test_list = [4, 5, 4, 6, 7, 5, 4, 5, 6, 10], range_list = [(2, 6)]Output : [4, 6, 7, 5, 4]Explanation : Elements from 2-6 index are extracted."
},
{
"code": null,
"e": 492,
"s": 453,
"text": "Method #1 : Using loop + list slicing "
},
{
"code": null,
"e": 640,
"s": 492,
"text": "In this, we extract each range using list slicing and using loop iterate for each range and keep extending the extracting slices to extending list."
},
{
"code": null,
"e": 648,
"s": 640,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Extract elements from Ranges in List# Using loop + list slicing # initializing listtest_list = [4, 5, 4, 6, 7, 5, 4, 5, 4, 6, 4, 6, 9, 8] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing rangesrange_list = [(2, 4), (7, 8), (10, 12)] res = []for ele in range_list: # extending ranges res.extend(test_list[ele[0] : ele[1] + 1]) # printing result print(\"Ranges elements : \" + str(res))",
"e": 1132,
"s": 648,
"text": null
},
{
"code": null,
"e": 1242,
"s": 1132,
"text": "The original list is : [4, 5, 4, 6, 7, 5, 4, 5, 4, 6, 4, 6, 9, 8]\nRanges elements : [4, 6, 7, 5, 4, 4, 6, 9]\n"
},
{
"code": null,
"e": 1280,
"s": 1242,
"text": "Method #2 : Using list comprehension"
},
{
"code": null,
"e": 1412,
"s": 1280,
"text": "In this, we apply similar method as above function, difference being that list comprehension is used to solve this in compact form."
},
{
"code": null,
"e": 1420,
"s": 1412,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Extract elements from Ranges in List# Using list comprehensionfrom itertools import chain # initializing listtest_list = [4, 5, 4, 6, 7, 5, 4, 5, 4, 6, 4, 6, 9, 8] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing rangesrange_list = [(2, 4), (7, 8), (10, 12)] # using one-liner to solve this problemres = list(chain.from_iterable([test_list[ele[0] : ele[1] + 1] for ele in range_list])) # printing result print(\"Ranges elements : \" + str(res))",
"e": 1951,
"s": 1420,
"text": null
},
{
"code": null,
"e": 2061,
"s": 1951,
"text": "The original list is : [4, 5, 4, 6, 7, 5, 4, 5, 4, 6, 4, 6, 9, 8]\nRanges elements : [4, 6, 7, 5, 4, 4, 6, 9]\n"
},
{
"code": null,
"e": 2082,
"s": 2061,
"text": "Python list-programs"
},
{
"code": null,
"e": 2089,
"s": 2082,
"text": "Python"
},
{
"code": null,
"e": 2105,
"s": 2089,
"text": "Python Programs"
},
{
"code": null,
"e": 2203,
"s": 2105,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2221,
"s": 2203,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2263,
"s": 2221,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2285,
"s": 2263,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2320,
"s": 2285,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2352,
"s": 2320,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2395,
"s": 2352,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2417,
"s": 2395,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2456,
"s": 2417,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2494,
"s": 2456,
"text": "Python | Convert a list to dictionary"
}
] |
VB.Net - Operators
|
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. VB.Net is rich in built-in operators and provides following types of commonly used operators β
Arithmetic Operators
Arithmetic Operators
Comparison Operators
Comparison Operators
Logical/Bitwise Operators
Logical/Bitwise Operators
Bit Shift Operators
Bit Shift Operators
Assignment Operators
Assignment Operators
Miscellaneous Operators
Miscellaneous Operators
This tutorial will explain the most commonly used operators.
Following table shows all the arithmetic operators supported by VB.Net. Assume variable A holds 2 and variable B holds 7, then β
Show Examples
Following table shows all the comparison operators supported by VB.Net. Assume variable A holds 10 and variable B holds 20, then β
Show Examples
Apart from the above, VB.Net provides three more comparison operators, which we will be using in forthcoming chapters; however, we give a brief description here.
Is Operator β It compares two object reference variables and determines if two object references refer to the same object without performing value comparisons. If object1 and object2 both refer to the exact same object instance, result is True; otherwise, result is False.
Is Operator β It compares two object reference variables and determines if two object references refer to the same object without performing value comparisons. If object1 and object2 both refer to the exact same object instance, result is True; otherwise, result is False.
IsNot Operator β It also compares two object reference variables and determines if two object references refer to different objects. If object1 and object2 both refer to the exact same object instance, result is False; otherwise, result is True.
IsNot Operator β It also compares two object reference variables and determines if two object references refer to different objects. If object1 and object2 both refer to the exact same object instance, result is False; otherwise, result is True.
Like Operator β It compares a string against a pattern.
Like Operator β It compares a string against a pattern.
Following table shows all the logical operators supported by VB.Net. Assume variable A holds Boolean value True and variable B holds Boolean value False, then β
Show Examples
We have already discussed the bitwise operators. The bit shift operators perform the shift operations on binary values. Before coming into the bit shift operators, let us understand the bit operations.
Bitwise operators work on bits and perform bit-by-bit operations. The truth tables for &, |, and ^ are as follows β
Assume if A = 60; and B = 13; now in binary format they will be as follows β
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
We have seen that the Bitwise operators supported by VB.Net are And, Or, Xor and Not. The Bit shift operators are >> and << for left shift and right shift, respectively.
Assume that the variable A holds 60 and variable B holds 13, then β
Show Examples
There are following assignment operators supported by VB.Net β
Show Examples
Str1 &= Str2 is same as
Str1 = Str1 & Str2
There are few other important operators supported by VB.Net.
Show Examples
AddHandler Button1.Click,
AddressOf Button1_Click
Dim result As res
= Await AsyncMethodThatReturnsResult()
Await AsyncMethod()
MsgBox(GetType(Integer).ToString())
Dim add5 = Function(num As
Integer) num + 5
'prints 10
Console.WriteLine(add5(5))
Dim num = 5
Console.WriteLine(If(num >= 0,
"Positive", "Negative"))
Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator β
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
|
[
{
"code": null,
"e": 2636,
"s": 2434,
"text": "An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. VB.Net is rich in built-in operators and provides following types of commonly used operators β"
},
{
"code": null,
"e": 2657,
"s": 2636,
"text": "Arithmetic Operators"
},
{
"code": null,
"e": 2678,
"s": 2657,
"text": "Arithmetic Operators"
},
{
"code": null,
"e": 2699,
"s": 2678,
"text": "Comparison Operators"
},
{
"code": null,
"e": 2720,
"s": 2699,
"text": "Comparison Operators"
},
{
"code": null,
"e": 2746,
"s": 2720,
"text": "Logical/Bitwise Operators"
},
{
"code": null,
"e": 2772,
"s": 2746,
"text": "Logical/Bitwise Operators"
},
{
"code": null,
"e": 2792,
"s": 2772,
"text": "Bit Shift Operators"
},
{
"code": null,
"e": 2812,
"s": 2792,
"text": "Bit Shift Operators"
},
{
"code": null,
"e": 2833,
"s": 2812,
"text": "Assignment Operators"
},
{
"code": null,
"e": 2854,
"s": 2833,
"text": "Assignment Operators"
},
{
"code": null,
"e": 2878,
"s": 2854,
"text": "Miscellaneous Operators"
},
{
"code": null,
"e": 2902,
"s": 2878,
"text": "Miscellaneous Operators"
},
{
"code": null,
"e": 2963,
"s": 2902,
"text": "This tutorial will explain the most commonly used operators."
},
{
"code": null,
"e": 3092,
"s": 2963,
"text": "Following table shows all the arithmetic operators supported by VB.Net. Assume variable A holds 2 and variable B holds 7, then β"
},
{
"code": null,
"e": 3106,
"s": 3092,
"text": "Show Examples"
},
{
"code": null,
"e": 3237,
"s": 3106,
"text": "Following table shows all the comparison operators supported by VB.Net. Assume variable A holds 10 and variable B holds 20, then β"
},
{
"code": null,
"e": 3251,
"s": 3237,
"text": "Show Examples"
},
{
"code": null,
"e": 3413,
"s": 3251,
"text": "Apart from the above, VB.Net provides three more comparison operators, which we will be using in forthcoming chapters; however, we give a brief description here."
},
{
"code": null,
"e": 3686,
"s": 3413,
"text": "Is Operator β It compares two object reference variables and determines if two object references refer to the same object without performing value comparisons. If object1 and object2 both refer to the exact same object instance, result is True; otherwise, result is False."
},
{
"code": null,
"e": 3959,
"s": 3686,
"text": "Is Operator β It compares two object reference variables and determines if two object references refer to the same object without performing value comparisons. If object1 and object2 both refer to the exact same object instance, result is True; otherwise, result is False."
},
{
"code": null,
"e": 4205,
"s": 3959,
"text": "IsNot Operator β It also compares two object reference variables and determines if two object references refer to different objects. If object1 and object2 both refer to the exact same object instance, result is False; otherwise, result is True."
},
{
"code": null,
"e": 4451,
"s": 4205,
"text": "IsNot Operator β It also compares two object reference variables and determines if two object references refer to different objects. If object1 and object2 both refer to the exact same object instance, result is False; otherwise, result is True."
},
{
"code": null,
"e": 4507,
"s": 4451,
"text": "Like Operator β It compares a string against a pattern."
},
{
"code": null,
"e": 4563,
"s": 4507,
"text": "Like Operator β It compares a string against a pattern."
},
{
"code": null,
"e": 4724,
"s": 4563,
"text": "Following table shows all the logical operators supported by VB.Net. Assume variable A holds Boolean value True and variable B holds Boolean value False, then β"
},
{
"code": null,
"e": 4738,
"s": 4724,
"text": "Show Examples"
},
{
"code": null,
"e": 4940,
"s": 4738,
"text": "We have already discussed the bitwise operators. The bit shift operators perform the shift operations on binary values. Before coming into the bit shift operators, let us understand the bit operations."
},
{
"code": null,
"e": 5056,
"s": 4940,
"text": "Bitwise operators work on bits and perform bit-by-bit operations. The truth tables for &, |, and ^ are as follows β"
},
{
"code": null,
"e": 5133,
"s": 5056,
"text": "Assume if A = 60; and B = 13; now in binary format they will be as follows β"
},
{
"code": null,
"e": 5147,
"s": 5133,
"text": "A = 0011 1100"
},
{
"code": null,
"e": 5161,
"s": 5147,
"text": "B = 0000 1101"
},
{
"code": null,
"e": 5179,
"s": 5161,
"text": "-----------------"
},
{
"code": null,
"e": 5195,
"s": 5179,
"text": "A&B = 0000 1100"
},
{
"code": null,
"e": 5211,
"s": 5195,
"text": "A|B = 0011 1101"
},
{
"code": null,
"e": 5227,
"s": 5211,
"text": "A^B = 0011 0001"
},
{
"code": null,
"e": 5243,
"s": 5227,
"text": "~A = 1100 0011"
},
{
"code": null,
"e": 5413,
"s": 5243,
"text": "We have seen that the Bitwise operators supported by VB.Net are And, Or, Xor and Not. The Bit shift operators are >> and << for left shift and right shift, respectively."
},
{
"code": null,
"e": 5481,
"s": 5413,
"text": "Assume that the variable A holds 60 and variable B holds 13, then β"
},
{
"code": null,
"e": 5495,
"s": 5481,
"text": "Show Examples"
},
{
"code": null,
"e": 5558,
"s": 5495,
"text": "There are following assignment operators supported by VB.Net β"
},
{
"code": null,
"e": 5572,
"s": 5558,
"text": "Show Examples"
},
{
"code": null,
"e": 5596,
"s": 5572,
"text": "Str1 &= Str2 is same as"
},
{
"code": null,
"e": 5615,
"s": 5596,
"text": "Str1 = Str1 & Str2"
},
{
"code": null,
"e": 5676,
"s": 5615,
"text": "There are few other important operators supported by VB.Net."
},
{
"code": null,
"e": 5690,
"s": 5676,
"text": "Show Examples"
},
{
"code": null,
"e": 5740,
"s": 5690,
"text": "AddHandler Button1.Click,\nAddressOf Button1_Click"
},
{
"code": null,
"e": 5819,
"s": 5740,
"text": " \nDim result As res\n= Await AsyncMethodThatReturnsResult()\nAwait AsyncMethod()"
},
{
"code": null,
"e": 5855,
"s": 5819,
"text": "MsgBox(GetType(Integer).ToString())"
},
{
"code": null,
"e": 5940,
"s": 5855,
"text": "Dim add5 = Function(num As\n Integer) num + 5\n'prints 10\nConsole.WriteLine(add5(5))"
},
{
"code": null,
"e": 6008,
"s": 5940,
"text": "Dim num = 5\nConsole.WriteLine(If(num >= 0,\n\"Positive\", \"Negative\"))"
},
{
"code": null,
"e": 6270,
"s": 6008,
"text": "Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator β"
},
{
"code": null,
"e": 6437,
"s": 6270,
"text": "For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7."
}
] |
A Covid Analysis. From a country-wise analysis of... | by Deepika Vijay | Towards Data Science
|
In this article, we are going to walk through
Relationships between variables such as a countryβs poverty rates, life expectancy rates, stringency indices and, covid cases and deathsVaccination rates per country and their predictions up until the end of JuneHow I went about the data and the analyses (only the jupyter notebook part)
Relationships between variables such as a countryβs poverty rates, life expectancy rates, stringency indices and, covid cases and deaths
Vaccination rates per country and their predictions up until the end of June
How I went about the data and the analyses (only the jupyter notebook part)
For the past year, covid-19 has captured the worldβs attention. There are so many questions still unanswered about this virus that has caused havoc in the world. So literally any kind of analysis can bring about a better understanding and useful insights for ourselves and potentially the society. Hence Iβm hoping that the following analyses will give readers a better idea of what factors likely influence the rate of infections and deaths from Covid-19 in a given country. Now, bear in mind that this of course doesnβt give us the full picture. For instance, in my perspective, literacy rates, population density, obesity rates, cultural aspects such as social norms, behaviour etc. all play a huge role in the increase of cases or deaths per country but I donβt have all the data and some of such factors canβt even be measured in usable ways.
Getting right to the analysis. Letβs start with the data. I got this amazing dataset from Our World in Data. The description and the source of each column are available here. I have taken the liberty of computing a few columns myself β namely country-wise vaccination rates, testing rates, infection rates and death rates. The scope of analysis using this dataset is incredible and this article covers only a part of it!
The data comprises of all the above 42 columns where βlocationβ is the country column and each country has data ranging from 1st of Jan 2020 to the 10th of April 2021. While much of the data is available almost from the beginning of this range, we know that testing was only made available much later and vaccinations even more so β late in December for most advanced countries.
Impact of testing rate on the rate of covid infections and deathsImpact of stringency index on the rate of covid infections and deathsImpact of age on covid related deathsImpact of poverty on life expectancy (unrelated to covid)Vaccination rates and predicting future rates by country
Impact of testing rate on the rate of covid infections and deaths
Impact of stringency index on the rate of covid infections and deaths
Impact of age on covid related deaths
Impact of poverty on life expectancy (unrelated to covid)
Vaccination rates and predicting future rates by country
Does aggressive testing have an impact on curbing deaths and infections or does high rates of infections and deaths certainly mean more testing?
Note: Unfortunately, embedding the interactive Tableau dashboard was rather challenging. The vizes can be followed here.
Above is a tableau visualization of rates of infections and deaths by country, tinted by testing rates. I have considered βMaximumβ as the aggregate as it gives us the most recent observation for each of these columns. For instance, the testing rate is measured by:
testing_rate = (total_tests/population)*100
Since each cell of total_tests per country is an aggregated sum of tests per day, max testing_rate would give us the maximum test rate of the country as well as its most recent testing rate. We can see that there is no particularly obvious pattern implying a correlation between testing and either infection or death rates. Letβs take a look at the following viz.
Note that the overshoot of 100% in the testing rate is because each record of testing indicates total tests in a country where 1 person couldβve been tested more than once.
To the left is a scatter plot representing the most recent and the highest rate of infections against the most recent and highest rate of testing by country. Noticeably, although it shows a subtle correlation directing toward a higher rate of infection meaning a higher rate of testing, it doesnβt strongly do so. The same can be said of the scatter plot on the right analyzing the relationship between testing rates and death rates which appears to be even more scattered than the former. Upon hovering on the lower points of the plot, its visibly the rather low-mid-income countries such as Brazil, Peru, Columbia, Indonesia etc. that occupy these points indicating low testing rates in low-mid-income economies. Letβs see the correlations rates:
Whilst it cannot for certain be determined whether high infections or deaths directly imply more testing, it is certain that factors like the countryβs economic standing in addition could play a role. An interesting study conducted by researchers of Scientific Reports determined that there is indeed a very low correlation between mortality and testing rates while the correlation between testing and infection rates, although above average, is boosted up further in higher income countries according to Our World in Data reports as well as Scientific Reports [2]. This correlation gap could potentially be attributed to the lack of testing resources in low-income countries causing a bias in the over-all analysis. Where there is a lack of testing, there is a lack of knowledge of existing cases. This gap/bias was remedied in their study by splitting the data into subgroups of low, middle and high-income countries and then conducting individual regression analyses [3].
Does being a βstricterβ country with regard to the implementation of measures in the covid era make the infections or deaths look any better? Or does having high rates of infections and deaths influence the stringency index?
As defined by Our World in Data, the stringency index is the measure of the strictness of a country with regard to how many covid restrictions are put in place, ranging from 0 to 100, 0 being the lowest. Stringency alone shows a rather low correlation with rates of deaths or infections as the countries indicated by the points is pretty scattered throughout. A very small amount of variance in death and infection rates is explainable by stringency and this can be backed by the following correlation statistics.
Although one would expect that countries get stricter as cases and deaths grow, stringency seems to be rather subjective to a countryβs governing body. The countries lying in the strictest range (close to 100) are from around the globe and not necessarily do all of them share an overwhelmingly high rate of cases/deaths compared to the rest of the world (RoW). There is a lack of literature to back the study of stringency levelβs impact on cases/deaths potentially due to the newness of the measure. It may be possible that countries face stricter measures following a surge of covid cases, however, statistics related to this measure may not be able to represent the reality accurately. As Our World in Data put it, this is because βIt does not measure or imply the appropriateness or effectiveness of a countryβs response. A higher score does not necessarily mean that a countryβs response is βbetterβ than others lower on the index.β [3]
Do countries with a good percentage of population above 65 years of age see greater deaths?
Yes, from the above plot it is reasonable to say that there is a certain persistent pattern here i.e. much of the variance in death rates can be explained by whether or not a good percentage of the population lies in the above 65 age range. The point to the bottom right is an outlier where a big chunk of their population of 27% is 65 years and older and yet, they have seen very low deaths compared to the RoW. This point unsurprisingly is Japan. Could this be attributed to their advancements in technology or simply their famous reputation for immunity and generally great health?
The correlation statistics drawn from python confirm an above-average correlation between deaths and the percentage of population greater than 65 years of age. There have been various studies claiming that age has a vital role to play in covid related mortalities. One such scientific article interestingly claims βseveral researchers have pointed to factors such as different scales and profiles of social interactions within households, endemic infections and median population age as affecting COVID-19 risk and mortalityβ [4]. Needless to explain, older populations face greater risks of infections and deaths from infection as a result of the physiological changes and underlying conditions that are accompanied by ageing, reports WHO [5].
Albeit unrelated to covid, it is interesting to see how well the poverty rate is correlated to low life expectancy as in the figure below.
Visibly from the chart above, countries living in extreme poverty experience low median life expectancy. The darker tint of blue indicating high rates of poverty lies mostly between the life expectancy range of 50 to 70 years while the majority of countries with populations living in low rates of poverty, experience rich, long lives. It is indeed alarming to see that some countries have life expectancies in as low a range as 50 to 60s. The following figure proves that a vast amount of the variance in life expectancy can be explained by poverty rates.
The above chart indicates pretty strongly that lower rates of poverty explain higher life expectancy. The following correlation statistic confirms the significant negative correlation.
A very articulate report by Urban Institute and Center on Society and Health has explored the details of the role that poverty plays in life expectancy and provided gripping statistics to support inferences such as βPeople with Lower Incomes Report Poorer Health and Have a Higher Risk of Disease and Deathβ [6]. A countless number of elements foster this gap between income and life expectancy ranging from hygiene standards to the ability to seek timely medical attention to the availability of resources and so on.
Now, moving on to the well-awaited analysis of vaccination rates by country. Do note that I am considering a fully vaccinated population for this computation i.e. both first and second doses if applicable. After having studied some of the columns as closely as presented in the above sections, we have obtained a good understanding of the data to do some more complex analyses.
Although not very visible on the above map, the country (independent territory rather) boasting its highest vaccination rate of 87.4% is Gibraltar, located to the south of Spain. Runner up is Isreal which is almost 60% vaccinated. Evidently, the RoW still has a lot of catching up to do. We can see that the US, Morroco, Serbia, Chile and a few others are also slightly ahead of the RoW with around 20% of the population having already acquired the vaccinations.
Now that we have an understanding of the current rates, Iβm going to try and predict the rates of vaccinations two months down the road. Are we about to gain freedom yet? To reach a point where the majority of the restrictions can be lifted, scientists have placed a threshold of 65β70% [1] implying that this percentage of the population of each country must be vaccinated or immune in order for the restrictions to be eased. Iβd like to determine which countries are able to get there by vaccinations in the next two months using polynomial regression.
Note that I am simply going by current and historic rates of vaccination. By no means am I suggesting that the predictions are as good as they get, as in reality, adding in variables such as scheduled vaccine deliveries for each country might give us the ideal results but Iβm just going with what I have here. Without further ado, letβs dive in!
Import libraries
import pandas as pdimport numpy as npfrom matplotlib import pyplotimport matplotlib.pyplot as pltfrom matplotlib import rcParamsimport seaborn as snsfrom IPython.display import displayfrom sklearn import linear_modelfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import PolynomialFeaturesfrom sklearn.metrics import r2_scoreimport statsmodels.formula.api as smffrom statsmodels.regression.linear_model import OLSfrom sklearn.linear_model import LinearRegressionimport mathfrom math import sqrtfrom sklearn.metrics import mean_squared_errorfrom random import randomimport datetime as dt
Prepare and Analyse Dataframe
df = pd.read_csv(r'C:\Users\Deepika\OneDrive\Documents\Professional\owid-covid-data.csv') #Keeping only relevant columnsdf = df[['iso_code', 'continent', 'location', 'date', 'total_cases', 'new_cases','total_deaths', 'new_deaths','reproduction_rate', 'icu_patients', 'hosp_patients','new_tests', 'total_tests','positive_rate', 'tests_per_case', 'tests_units', 'total_vaccinations', 'people_vaccinated', 'people_fully_vaccinated', 'new_vaccinations','stringency_index', 'population', 'population_density', 'median_age', 'aged_65_older', 'aged_70_older', 'gdp_per_capita', 'extreme_poverty', 'cardiovasc_death_rate', 'diabetes_prevalence', 'female_smokers', 'male_smokers', 'handwashing_facilities', 'hospital_beds_per_thousand', 'life_expectancy', 'human_development_index']]#A very important stepdf['date'] = pd.to_datetime(df['date'])
Creating a function for additional columns and some analysis
# Creating function for additional columns and some analysesdef analyse_df(df): df['case_rate'] = (df['total_cases']/df['population'])*100 df['death_rate'] = (df['total_deaths']/df['population'])*100 df['test_rate'] = (df['total_tests']/df['population'])*100 df['admissions_rate'] = (df['hosp_patients']/df['population'])*100 df['critical_rate'] = (df['icu_patients']/df['population'])*100 df['vaccination_rate'] = (df['people_fully_vaccinated']/df['population'])*100 print('Columns: ', df.columns) print('Dataframe shape: ', df.shape) print('Date Range', df['date'].min(),df['date'].max()) #get some stats for each country using groupby stats_df = df.groupby('location')[['date','case_rate','death_rate','test_rate','vaccination_rate', 'admissions_rate','critical_rate','stringency_index', 'population']].agg({"date":['max', 'count'], 'case_rate':'max','death_rate':'max','test_rate':'max','vaccination_rate':'max', 'admissions_rate':'mean','critical_rate':'mean','stringency_index':'mean','population':'mean'}) display(stats_df) display(df.corr()) sns.heatmap(df.corr(), vmin=-1, vmax=1, center=0,cmap=sns.diverging_palette(20, 220, n=200),square=True) plt.xticks(rotation=45) rcParams['figure.figsize'] = 12,8 return df, stats_df
Calling the function
df = analyse_df(df)[0]stats_df = analyse_df(df)[1]
The above code snippet returns a bunch of stats about some interesting rates in each country and how well or poorly each variable is correlated with another. We then have to save the data frame (as df here) with the newly created columns for further analyses. The below GIF provides a quick peek into this output.
Build Regression Model
I chose the polynomial model for this particular case as it is the most straightforward way to analyse and predict the upward trending behaviour of the vaccination rates. I did try a more advanced time-series analysis with the ARIMA model and found the results of the polynomial model to be more realistic and accurate. In the following section, I have shared the code of my analysis. Be sure to read the comments explaining each and every step along the way.
Create the model function
def poly(name, group): # transfrom the date into an integer to be able to fit it into the model group['date_transformed'] = group['date'].map(dt.datetime.toordinal) # Create a range to be able to tell the model later to predict within this range. I want to predict for a range that is 10 points more than half the number of observations in input data. Range = group['date_transformed'].max() + round(len(group)/2) + 10 predict_dates = list(range(group['date_transformed'].max() + 1, Range)) # Build the model # Make sure to transfrom the input data x = group['date_transformed'].values[:,np.newaxis] y = group['vaccination_rate'].values polynomial_features = PolynomialFeatures(degree=2) x_poly = polynomial_features.fit_transform(x) model = LinearRegression() model.fit(x_poly, y) # Test the model and its accuracy y_poly_pred = model.predict(x_poly) rmse = np.sqrt(mean_squared_error(y,y_poly_pred)) r2 = r2_score(y,y_poly_pred) # Save the predictions as a column of the input data group['Pred'] = y_poly_pred group_export = group[['date','vaccination_rate','Pred']].set_index('date') # View results print(name) print('rmse: ', rmse) print('r2: ', r2) return model, polynomial_features, predict_dates, group_export
Model results
Group the data by location (countries).
# Create grouped data for access laterdf_grouped = df.groupby(['iso_code','continent','location'])
Implement the model into each category of the grouped data to get country-wise predictions.
# Dictionaries to save the results of the modeldct_original = {}dct_future = {}# Access each country data seperatelyfor name, group in df_grouped: # Make sure to select countries without NaN values in vaccination_rates group1 = group[group['people_fully_vaccinated'].notna()] # Countries with at least 50 vaccination data points for better predictions if len(group1) > 50: # Save outputs from the function into the following variables predict_dates = poly(name, group1)[2] model = poly(name, group1)[0] polynomial_features = poly(name, group1)[1] group_export = poly(name, group1)[3] group_export['Location'] = name[2] # Future predictions for the range of dates specified in the function. Again, remember to tranform the input Predictions = model.predict(polynomial_features.fit_transform(np.array(predict_dates).reshape(-1,1))) # Putting the predictions and dates into a dataframe Predictions_df = pd.DataFrame({'Future_dates': list(predict_dates),'Predictions': list(Predictions)}) # Converting the transformed dates to original date format Predictions_df = Predictions_df.set_index(Predictions_df['Future_dates'].map(dt.datetime.fromordinal)) # Add country to the dataframe to identify the data Predictions_df['Location'] = name[2] # Save input data predictions and future predictions into dictionaries to access later dct_original[name] = group_export dct_future[name] = Predictions_df # Plot current observed, predicted and future predicted data plt.figure(figsize=(10,5)) plt.xticks(rotation=45) plt.title('Model ' + name[2]) plt.xlabel('Date', fontsize=11) plt.ylabel('Vaccination Rate', fontsize=11) plt.scatter(group_export.index, group_export['vaccination_rate']) plt.plot(group_export['Pred'], color = 'g') plt.plot(Predictions_df[['Predictions']], color = 'm') plt.legend(['Validation', 'Predictions', 'Train'], loc='lower right') plt.show() # View the Actual vs Predicted data and their data count print('Observations in Actual Data = %f, Predicted Observations=%f' % (len(group1), len(Predictions))) print( "\n".join("{} {}".format(x, y) for x, y in zip(predict_dates, Predictions)))
Sample outputs of some of the 40 countries with > 50 vaccination datapoints
From the above prediction for the UK, we can see that the RMSE is pretty low considering the vaccination rates data and the R2 shows a high rate of accuracy. The prediction says that about 30% of the UK could be vaccinated by the beginning of June.
The RMSE for Chile is reasonably low and the R2 suggests a pretty good accuracy. The predictions indicate that potentially 90% of the population could be vaccinated by the beginning of June.
Now for the US predictions, we see that nearly half of the US population could be vaccinated by the beginning of June. Although this might be a reasonable forecast, models with very low RMSE and very high R2 might return overfitted results. Overfitting occurs when the validation lies very close to the actual data but the forecast of unseen data points (test or future data) is unrealistic or far-fetched. In this particular scenario, the model yields good results despite the very high levels of accuracy. Sure, 50% seems like a highly attainable rate given the current rate. However, it is often possible for models with such accuracy and closeness of training and validation points to wind up being overfitted. One way to remedy the overfitting of regression models would be to lower the degree of the polynomial. For instance, for this particular model, we have used a degree of 2, which is the lowest degree for a polynomial model.
# Polynomial degree used before polynomial_features = PolynomialFeatures(degree=2)
Model alternative
Alternatively, if we were to try and attain more generic predictions and avoid possible overfitting, we could consider changing the degree from 2 to 1 which will make it a linear regression model. Looking at the somewhat linear characteristic of the plot, we can also safely say that a linear model for a trend as such, should suffice. So letβs see if the linear model predicts any differently for this particular country. I am just going to go ahead and replace the polynomial model for the US. We will use the same code structure as for the polynomial model, except this time, we will not use βpolynomial_featuresβ.
for name, group in df_grouped: if name[2] == "United States": # Only for the US group1 = group[group['people_fully_vaccinated'].notna()] group1['date_transformed'] = group1['date'].map(dt.datetime.toordinal) # transform date column into integer to be able to build model Range = group1['date_transformed'].max() + round(len(group1)/2) + 10 predict_dates = list(range(group1['date_transformed'].max() + 1, Range)) # create a range of dates to make future predictions x = group1['date_transformed'].values[:,np.newaxis] # input data transformed y = group1['vaccination_rate'].values # input train data model = LinearRegression() model.fit(x, y) # Fitting linear regression y_pred = model.predict(x) group1['Pred'] = y_pred r2 = model.score(x,y) # alternatively, r-squared can also be measured this way rmse = mean_squared_error(y, y_pred, squared=False) group_export = group1[['date','vaccination_rate','Pred']].set_index('date') Predictions = model.predict(np.array(predict_dates).reshape(-1,1)) Predictions_df = pd.DataFrame({'Future_dates': list(predict_dates),'Predictions': list(Predictions)}) Predictions_df = Predictions_df.set_index(Predictions_df['Future_dates'].map(dt.datetime.fromordinal)) plt.xticks(rotation=45) print(name) print('rmse: ', rmse) print('r2: ', r2) plt.scatter(group_export.index, group_export['vaccination_rate']) plt.plot(group_export['Pred'], color = 'g') plt.plot(Predictions_df[['Predictions']], color = 'm') plt.legend(['Validation', 'Predictions', 'Train'], loc='lower right')
The results of the linear model show lower accuracy statistics than that of the polynomial model. The model now no longer shows symptoms of an overfit. The forecast of 30% here is less optimistic in our scenario but the key takeaway is that when there is a possibility of attaining overfitted results, lowering the degree might yield more generic and hence more reliable outcomes of unseen data points.
The above is a Tableau visualization of the final output. Since I set the filter of making predictions only for countries with at least 50 days of current vaccination rates, the predictions are narrowed down only to the coloured countries. This filter can be played around with to get predictions for more countries, however, it might compromise the accuracy.
A comparable visualization drawn out by The Economist boldly highlights the disparity between the rich and the poor with regard to vaccination gains.
While it is often tempting to blindly follow a model-based approach, we must bear in mind that all forecasts are based on assumptions and this one is no exception. This holds especially true for forecasting in the medical, economic, political, social or behavioural context over which we have little to no control. For this particular model, for instance, the following are the limitations:
As mentioned before, the model doesnβt factor in scheduled deliveries by the country which likely will account for improved predictions.There is certainly not enough covid-19 vaccination data out there for a supervised model to be fully reliable. As seen in the geographic visualization of this model, many countries donβt even have 50 observations of vaccination data yet.This model assumes consistency in vaccine roll-outs. However, for many countries, this assumption has proven to be false. The roll-out consistency of a country is certainly affected by the ever-changing laws in the covid era. Consider the ban of Astrazeneca in Denmark for instance [7]. Impacts of such unexpected external factors on the outcome can rarely be factored into a machine learning model.With the many variants that have been discovered, questions about whether vaccination could mean immunity persist. Whether the outcomes of the current predictive models mean immunity, is not known. Hence this study assumes that vaccination rate is simply vaccination rate and not immunity.
As mentioned before, the model doesnβt factor in scheduled deliveries by the country which likely will account for improved predictions.
There is certainly not enough covid-19 vaccination data out there for a supervised model to be fully reliable. As seen in the geographic visualization of this model, many countries donβt even have 50 observations of vaccination data yet.
This model assumes consistency in vaccine roll-outs. However, for many countries, this assumption has proven to be false. The roll-out consistency of a country is certainly affected by the ever-changing laws in the covid era. Consider the ban of Astrazeneca in Denmark for instance [7]. Impacts of such unexpected external factors on the outcome can rarely be factored into a machine learning model.
With the many variants that have been discovered, questions about whether vaccination could mean immunity persist. Whether the outcomes of the current predictive models mean immunity, is not known. Hence this study assumes that vaccination rate is simply vaccination rate and not immunity.
Despite its limitations, it is needless to mention that a good model-based approach is, in many cases, better than blind intuition and guess-games. It may not give us the perfect answers but it certainly can give us an idea of what to expect and help us be better prepared and/or make improved decisions. The ideal outcome is probably the combination of a robust model and a touch of educated intuition.
If you did follow along and manage to acquire your own predictions, great! I hope they are looking as optimistic! Again, hereβs the data and here are the Tableau vizes. Thanks for reading!
[1] D. Gypsyamber and D. David, What is Herd Immunity and How Can We Achieve It With COVID-19? (Apr, 2021), Johns Hopkins Bloomberg School of Public Health
[2] R. Hannah et al., Coronavirus (COVID-19) Testing (Apr, 2021), Our World in Data
[3] L. Li-Lin, T. Ching-Hung, H. Hsiu J & W. Chun-Ying, Covid-19 mortality is negatively associated with test number and government effectiveness (Jul, 2020), Scientific Reports
[4] T. Liji, Countries with older populations have higher SARS-CoV-2 infections and deaths, says study (Feb, 2021), News Medical Life Sciences
[5] WHO, Supporting older people during the COVID-19 pandemic is everyoneβs business, (Apr, 2020), World Health Organization
[6] H. W. Steven, How Are Income and Wealth Linked to Health and Longevity? (Apr, 2015), Urban Institute & Center on Society and Health
[7] BBC, AstraZeneca vaccine: Denmark stops rollout completely (Apr, 2021), BBC News
[8] The EIU, The EIUβs latest vaccine rollout forecasts (Mar, 2021), The Economist
|
[
{
"code": null,
"e": 218,
"s": 172,
"text": "In this article, we are going to walk through"
},
{
"code": null,
"e": 506,
"s": 218,
"text": "Relationships between variables such as a countryβs poverty rates, life expectancy rates, stringency indices and, covid cases and deathsVaccination rates per country and their predictions up until the end of JuneHow I went about the data and the analyses (only the jupyter notebook part)"
},
{
"code": null,
"e": 643,
"s": 506,
"text": "Relationships between variables such as a countryβs poverty rates, life expectancy rates, stringency indices and, covid cases and deaths"
},
{
"code": null,
"e": 720,
"s": 643,
"text": "Vaccination rates per country and their predictions up until the end of June"
},
{
"code": null,
"e": 796,
"s": 720,
"text": "How I went about the data and the analyses (only the jupyter notebook part)"
},
{
"code": null,
"e": 1644,
"s": 796,
"text": "For the past year, covid-19 has captured the worldβs attention. There are so many questions still unanswered about this virus that has caused havoc in the world. So literally any kind of analysis can bring about a better understanding and useful insights for ourselves and potentially the society. Hence Iβm hoping that the following analyses will give readers a better idea of what factors likely influence the rate of infections and deaths from Covid-19 in a given country. Now, bear in mind that this of course doesnβt give us the full picture. For instance, in my perspective, literacy rates, population density, obesity rates, cultural aspects such as social norms, behaviour etc. all play a huge role in the increase of cases or deaths per country but I donβt have all the data and some of such factors canβt even be measured in usable ways."
},
{
"code": null,
"e": 2065,
"s": 1644,
"text": "Getting right to the analysis. Letβs start with the data. I got this amazing dataset from Our World in Data. The description and the source of each column are available here. I have taken the liberty of computing a few columns myself β namely country-wise vaccination rates, testing rates, infection rates and death rates. The scope of analysis using this dataset is incredible and this article covers only a part of it!"
},
{
"code": null,
"e": 2444,
"s": 2065,
"text": "The data comprises of all the above 42 columns where βlocationβ is the country column and each country has data ranging from 1st of Jan 2020 to the 10th of April 2021. While much of the data is available almost from the beginning of this range, we know that testing was only made available much later and vaccinations even more so β late in December for most advanced countries."
},
{
"code": null,
"e": 2729,
"s": 2444,
"text": "Impact of testing rate on the rate of covid infections and deathsImpact of stringency index on the rate of covid infections and deathsImpact of age on covid related deathsImpact of poverty on life expectancy (unrelated to covid)Vaccination rates and predicting future rates by country"
},
{
"code": null,
"e": 2795,
"s": 2729,
"text": "Impact of testing rate on the rate of covid infections and deaths"
},
{
"code": null,
"e": 2865,
"s": 2795,
"text": "Impact of stringency index on the rate of covid infections and deaths"
},
{
"code": null,
"e": 2903,
"s": 2865,
"text": "Impact of age on covid related deaths"
},
{
"code": null,
"e": 2961,
"s": 2903,
"text": "Impact of poverty on life expectancy (unrelated to covid)"
},
{
"code": null,
"e": 3018,
"s": 2961,
"text": "Vaccination rates and predicting future rates by country"
},
{
"code": null,
"e": 3163,
"s": 3018,
"text": "Does aggressive testing have an impact on curbing deaths and infections or does high rates of infections and deaths certainly mean more testing?"
},
{
"code": null,
"e": 3284,
"s": 3163,
"text": "Note: Unfortunately, embedding the interactive Tableau dashboard was rather challenging. The vizes can be followed here."
},
{
"code": null,
"e": 3550,
"s": 3284,
"text": "Above is a tableau visualization of rates of infections and deaths by country, tinted by testing rates. I have considered βMaximumβ as the aggregate as it gives us the most recent observation for each of these columns. For instance, the testing rate is measured by:"
},
{
"code": null,
"e": 3594,
"s": 3550,
"text": "testing_rate = (total_tests/population)*100"
},
{
"code": null,
"e": 3958,
"s": 3594,
"text": "Since each cell of total_tests per country is an aggregated sum of tests per day, max testing_rate would give us the maximum test rate of the country as well as its most recent testing rate. We can see that there is no particularly obvious pattern implying a correlation between testing and either infection or death rates. Letβs take a look at the following viz."
},
{
"code": null,
"e": 4131,
"s": 3958,
"text": "Note that the overshoot of 100% in the testing rate is because each record of testing indicates total tests in a country where 1 person couldβve been tested more than once."
},
{
"code": null,
"e": 4880,
"s": 4131,
"text": "To the left is a scatter plot representing the most recent and the highest rate of infections against the most recent and highest rate of testing by country. Noticeably, although it shows a subtle correlation directing toward a higher rate of infection meaning a higher rate of testing, it doesnβt strongly do so. The same can be said of the scatter plot on the right analyzing the relationship between testing rates and death rates which appears to be even more scattered than the former. Upon hovering on the lower points of the plot, its visibly the rather low-mid-income countries such as Brazil, Peru, Columbia, Indonesia etc. that occupy these points indicating low testing rates in low-mid-income economies. Letβs see the correlations rates:"
},
{
"code": null,
"e": 5855,
"s": 4880,
"text": "Whilst it cannot for certain be determined whether high infections or deaths directly imply more testing, it is certain that factors like the countryβs economic standing in addition could play a role. An interesting study conducted by researchers of Scientific Reports determined that there is indeed a very low correlation between mortality and testing rates while the correlation between testing and infection rates, although above average, is boosted up further in higher income countries according to Our World in Data reports as well as Scientific Reports [2]. This correlation gap could potentially be attributed to the lack of testing resources in low-income countries causing a bias in the over-all analysis. Where there is a lack of testing, there is a lack of knowledge of existing cases. This gap/bias was remedied in their study by splitting the data into subgroups of low, middle and high-income countries and then conducting individual regression analyses [3]."
},
{
"code": null,
"e": 6080,
"s": 5855,
"text": "Does being a βstricterβ country with regard to the implementation of measures in the covid era make the infections or deaths look any better? Or does having high rates of infections and deaths influence the stringency index?"
},
{
"code": null,
"e": 6594,
"s": 6080,
"text": "As defined by Our World in Data, the stringency index is the measure of the strictness of a country with regard to how many covid restrictions are put in place, ranging from 0 to 100, 0 being the lowest. Stringency alone shows a rather low correlation with rates of deaths or infections as the countries indicated by the points is pretty scattered throughout. A very small amount of variance in death and infection rates is explainable by stringency and this can be backed by the following correlation statistics."
},
{
"code": null,
"e": 7537,
"s": 6594,
"text": "Although one would expect that countries get stricter as cases and deaths grow, stringency seems to be rather subjective to a countryβs governing body. The countries lying in the strictest range (close to 100) are from around the globe and not necessarily do all of them share an overwhelmingly high rate of cases/deaths compared to the rest of the world (RoW). There is a lack of literature to back the study of stringency levelβs impact on cases/deaths potentially due to the newness of the measure. It may be possible that countries face stricter measures following a surge of covid cases, however, statistics related to this measure may not be able to represent the reality accurately. As Our World in Data put it, this is because βIt does not measure or imply the appropriateness or effectiveness of a countryβs response. A higher score does not necessarily mean that a countryβs response is βbetterβ than others lower on the index.β [3]"
},
{
"code": null,
"e": 7629,
"s": 7537,
"text": "Do countries with a good percentage of population above 65 years of age see greater deaths?"
},
{
"code": null,
"e": 8214,
"s": 7629,
"text": "Yes, from the above plot it is reasonable to say that there is a certain persistent pattern here i.e. much of the variance in death rates can be explained by whether or not a good percentage of the population lies in the above 65 age range. The point to the bottom right is an outlier where a big chunk of their population of 27% is 65 years and older and yet, they have seen very low deaths compared to the RoW. This point unsurprisingly is Japan. Could this be attributed to their advancements in technology or simply their famous reputation for immunity and generally great health?"
},
{
"code": null,
"e": 8959,
"s": 8214,
"text": "The correlation statistics drawn from python confirm an above-average correlation between deaths and the percentage of population greater than 65 years of age. There have been various studies claiming that age has a vital role to play in covid related mortalities. One such scientific article interestingly claims βseveral researchers have pointed to factors such as different scales and profiles of social interactions within households, endemic infections and median population age as affecting COVID-19 risk and mortalityβ [4]. Needless to explain, older populations face greater risks of infections and deaths from infection as a result of the physiological changes and underlying conditions that are accompanied by ageing, reports WHO [5]."
},
{
"code": null,
"e": 9098,
"s": 8959,
"text": "Albeit unrelated to covid, it is interesting to see how well the poverty rate is correlated to low life expectancy as in the figure below."
},
{
"code": null,
"e": 9655,
"s": 9098,
"text": "Visibly from the chart above, countries living in extreme poverty experience low median life expectancy. The darker tint of blue indicating high rates of poverty lies mostly between the life expectancy range of 50 to 70 years while the majority of countries with populations living in low rates of poverty, experience rich, long lives. It is indeed alarming to see that some countries have life expectancies in as low a range as 50 to 60s. The following figure proves that a vast amount of the variance in life expectancy can be explained by poverty rates."
},
{
"code": null,
"e": 9840,
"s": 9655,
"text": "The above chart indicates pretty strongly that lower rates of poverty explain higher life expectancy. The following correlation statistic confirms the significant negative correlation."
},
{
"code": null,
"e": 10358,
"s": 9840,
"text": "A very articulate report by Urban Institute and Center on Society and Health has explored the details of the role that poverty plays in life expectancy and provided gripping statistics to support inferences such as βPeople with Lower Incomes Report Poorer Health and Have a Higher Risk of Disease and Deathβ [6]. A countless number of elements foster this gap between income and life expectancy ranging from hygiene standards to the ability to seek timely medical attention to the availability of resources and so on."
},
{
"code": null,
"e": 10736,
"s": 10358,
"text": "Now, moving on to the well-awaited analysis of vaccination rates by country. Do note that I am considering a fully vaccinated population for this computation i.e. both first and second doses if applicable. After having studied some of the columns as closely as presented in the above sections, we have obtained a good understanding of the data to do some more complex analyses."
},
{
"code": null,
"e": 11199,
"s": 10736,
"text": "Although not very visible on the above map, the country (independent territory rather) boasting its highest vaccination rate of 87.4% is Gibraltar, located to the south of Spain. Runner up is Isreal which is almost 60% vaccinated. Evidently, the RoW still has a lot of catching up to do. We can see that the US, Morroco, Serbia, Chile and a few others are also slightly ahead of the RoW with around 20% of the population having already acquired the vaccinations."
},
{
"code": null,
"e": 11754,
"s": 11199,
"text": "Now that we have an understanding of the current rates, Iβm going to try and predict the rates of vaccinations two months down the road. Are we about to gain freedom yet? To reach a point where the majority of the restrictions can be lifted, scientists have placed a threshold of 65β70% [1] implying that this percentage of the population of each country must be vaccinated or immune in order for the restrictions to be eased. Iβd like to determine which countries are able to get there by vaccinations in the next two months using polynomial regression."
},
{
"code": null,
"e": 12101,
"s": 11754,
"text": "Note that I am simply going by current and historic rates of vaccination. By no means am I suggesting that the predictions are as good as they get, as in reality, adding in variables such as scheduled vaccine deliveries for each country might give us the ideal results but Iβm just going with what I have here. Without further ado, letβs dive in!"
},
{
"code": null,
"e": 12118,
"s": 12101,
"text": "Import libraries"
},
{
"code": null,
"e": 12736,
"s": 12118,
"text": "import pandas as pdimport numpy as npfrom matplotlib import pyplotimport matplotlib.pyplot as pltfrom matplotlib import rcParamsimport seaborn as snsfrom IPython.display import displayfrom sklearn import linear_modelfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import PolynomialFeaturesfrom sklearn.metrics import r2_scoreimport statsmodels.formula.api as smffrom statsmodels.regression.linear_model import OLSfrom sklearn.linear_model import LinearRegressionimport mathfrom math import sqrtfrom sklearn.metrics import mean_squared_errorfrom random import randomimport datetime as dt"
},
{
"code": null,
"e": 12766,
"s": 12736,
"text": "Prepare and Analyse Dataframe"
},
{
"code": null,
"e": 13646,
"s": 12766,
"text": "df = pd.read_csv(r'C:\\Users\\Deepika\\OneDrive\\Documents\\Professional\\owid-covid-data.csv') #Keeping only relevant columnsdf = df[['iso_code', 'continent', 'location', 'date', 'total_cases', 'new_cases','total_deaths', 'new_deaths','reproduction_rate', 'icu_patients', 'hosp_patients','new_tests', 'total_tests','positive_rate', 'tests_per_case', 'tests_units', 'total_vaccinations', 'people_vaccinated', 'people_fully_vaccinated', 'new_vaccinations','stringency_index', 'population', 'population_density', 'median_age', 'aged_65_older', 'aged_70_older', 'gdp_per_capita', 'extreme_poverty', 'cardiovasc_death_rate', 'diabetes_prevalence', 'female_smokers', 'male_smokers', 'handwashing_facilities', 'hospital_beds_per_thousand', 'life_expectancy', 'human_development_index']]#A very important stepdf['date'] = pd.to_datetime(df['date'])"
},
{
"code": null,
"e": 13707,
"s": 13646,
"text": "Creating a function for additional columns and some analysis"
},
{
"code": null,
"e": 15077,
"s": 13707,
"text": "# Creating function for additional columns and some analysesdef analyse_df(df): df['case_rate'] = (df['total_cases']/df['population'])*100 df['death_rate'] = (df['total_deaths']/df['population'])*100 df['test_rate'] = (df['total_tests']/df['population'])*100 df['admissions_rate'] = (df['hosp_patients']/df['population'])*100 df['critical_rate'] = (df['icu_patients']/df['population'])*100 df['vaccination_rate'] = (df['people_fully_vaccinated']/df['population'])*100 print('Columns: ', df.columns) print('Dataframe shape: ', df.shape) print('Date Range', df['date'].min(),df['date'].max()) #get some stats for each country using groupby stats_df = df.groupby('location')[['date','case_rate','death_rate','test_rate','vaccination_rate', 'admissions_rate','critical_rate','stringency_index', 'population']].agg({\"date\":['max', 'count'], 'case_rate':'max','death_rate':'max','test_rate':'max','vaccination_rate':'max', 'admissions_rate':'mean','critical_rate':'mean','stringency_index':'mean','population':'mean'}) display(stats_df) display(df.corr()) sns.heatmap(df.corr(), vmin=-1, vmax=1, center=0,cmap=sns.diverging_palette(20, 220, n=200),square=True) plt.xticks(rotation=45) rcParams['figure.figsize'] = 12,8 return df, stats_df"
},
{
"code": null,
"e": 15098,
"s": 15077,
"text": "Calling the function"
},
{
"code": null,
"e": 15149,
"s": 15098,
"text": "df = analyse_df(df)[0]stats_df = analyse_df(df)[1]"
},
{
"code": null,
"e": 15463,
"s": 15149,
"text": "The above code snippet returns a bunch of stats about some interesting rates in each country and how well or poorly each variable is correlated with another. We then have to save the data frame (as df here) with the newly created columns for further analyses. The below GIF provides a quick peek into this output."
},
{
"code": null,
"e": 15486,
"s": 15463,
"text": "Build Regression Model"
},
{
"code": null,
"e": 15946,
"s": 15486,
"text": "I chose the polynomial model for this particular case as it is the most straightforward way to analyse and predict the upward trending behaviour of the vaccination rates. I did try a more advanced time-series analysis with the ARIMA model and found the results of the polynomial model to be more realistic and accurate. In the following section, I have shared the code of my analysis. Be sure to read the comments explaining each and every step along the way."
},
{
"code": null,
"e": 15972,
"s": 15946,
"text": "Create the model function"
},
{
"code": null,
"e": 17269,
"s": 15972,
"text": "def poly(name, group): # transfrom the date into an integer to be able to fit it into the model group['date_transformed'] = group['date'].map(dt.datetime.toordinal) # Create a range to be able to tell the model later to predict within this range. I want to predict for a range that is 10 points more than half the number of observations in input data. Range = group['date_transformed'].max() + round(len(group)/2) + 10 predict_dates = list(range(group['date_transformed'].max() + 1, Range)) # Build the model # Make sure to transfrom the input data x = group['date_transformed'].values[:,np.newaxis] y = group['vaccination_rate'].values polynomial_features = PolynomialFeatures(degree=2) x_poly = polynomial_features.fit_transform(x) model = LinearRegression() model.fit(x_poly, y) # Test the model and its accuracy y_poly_pred = model.predict(x_poly) rmse = np.sqrt(mean_squared_error(y,y_poly_pred)) r2 = r2_score(y,y_poly_pred) # Save the predictions as a column of the input data group['Pred'] = y_poly_pred group_export = group[['date','vaccination_rate','Pred']].set_index('date') # View results print(name) print('rmse: ', rmse) print('r2: ', r2) return model, polynomial_features, predict_dates, group_export"
},
{
"code": null,
"e": 17283,
"s": 17269,
"text": "Model results"
},
{
"code": null,
"e": 17323,
"s": 17283,
"text": "Group the data by location (countries)."
},
{
"code": null,
"e": 17422,
"s": 17323,
"text": "# Create grouped data for access laterdf_grouped = df.groupby(['iso_code','continent','location'])"
},
{
"code": null,
"e": 17514,
"s": 17422,
"text": "Implement the model into each category of the grouped data to get country-wise predictions."
},
{
"code": null,
"e": 19816,
"s": 17514,
"text": "# Dictionaries to save the results of the modeldct_original = {}dct_future = {}# Access each country data seperatelyfor name, group in df_grouped: # Make sure to select countries without NaN values in vaccination_rates group1 = group[group['people_fully_vaccinated'].notna()] # Countries with at least 50 vaccination data points for better predictions if len(group1) > 50: # Save outputs from the function into the following variables predict_dates = poly(name, group1)[2] model = poly(name, group1)[0] polynomial_features = poly(name, group1)[1] group_export = poly(name, group1)[3] group_export['Location'] = name[2] # Future predictions for the range of dates specified in the function. Again, remember to tranform the input Predictions = model.predict(polynomial_features.fit_transform(np.array(predict_dates).reshape(-1,1))) # Putting the predictions and dates into a dataframe Predictions_df = pd.DataFrame({'Future_dates': list(predict_dates),'Predictions': list(Predictions)}) # Converting the transformed dates to original date format Predictions_df = Predictions_df.set_index(Predictions_df['Future_dates'].map(dt.datetime.fromordinal)) # Add country to the dataframe to identify the data Predictions_df['Location'] = name[2] # Save input data predictions and future predictions into dictionaries to access later dct_original[name] = group_export dct_future[name] = Predictions_df # Plot current observed, predicted and future predicted data plt.figure(figsize=(10,5)) plt.xticks(rotation=45) plt.title('Model ' + name[2]) plt.xlabel('Date', fontsize=11) plt.ylabel('Vaccination Rate', fontsize=11) plt.scatter(group_export.index, group_export['vaccination_rate']) plt.plot(group_export['Pred'], color = 'g') plt.plot(Predictions_df[['Predictions']], color = 'm') plt.legend(['Validation', 'Predictions', 'Train'], loc='lower right') plt.show() # View the Actual vs Predicted data and their data count print('Observations in Actual Data = %f, Predicted Observations=%f' % (len(group1), len(Predictions))) print( \"\\n\".join(\"{} {}\".format(x, y) for x, y in zip(predict_dates, Predictions)))"
},
{
"code": null,
"e": 19892,
"s": 19816,
"text": "Sample outputs of some of the 40 countries with > 50 vaccination datapoints"
},
{
"code": null,
"e": 20141,
"s": 19892,
"text": "From the above prediction for the UK, we can see that the RMSE is pretty low considering the vaccination rates data and the R2 shows a high rate of accuracy. The prediction says that about 30% of the UK could be vaccinated by the beginning of June."
},
{
"code": null,
"e": 20332,
"s": 20141,
"text": "The RMSE for Chile is reasonably low and the R2 suggests a pretty good accuracy. The predictions indicate that potentially 90% of the population could be vaccinated by the beginning of June."
},
{
"code": null,
"e": 21270,
"s": 20332,
"text": "Now for the US predictions, we see that nearly half of the US population could be vaccinated by the beginning of June. Although this might be a reasonable forecast, models with very low RMSE and very high R2 might return overfitted results. Overfitting occurs when the validation lies very close to the actual data but the forecast of unseen data points (test or future data) is unrealistic or far-fetched. In this particular scenario, the model yields good results despite the very high levels of accuracy. Sure, 50% seems like a highly attainable rate given the current rate. However, it is often possible for models with such accuracy and closeness of training and validation points to wind up being overfitted. One way to remedy the overfitting of regression models would be to lower the degree of the polynomial. For instance, for this particular model, we have used a degree of 2, which is the lowest degree for a polynomial model."
},
{
"code": null,
"e": 21353,
"s": 21270,
"text": "# Polynomial degree used before polynomial_features = PolynomialFeatures(degree=2)"
},
{
"code": null,
"e": 21371,
"s": 21353,
"text": "Model alternative"
},
{
"code": null,
"e": 21989,
"s": 21371,
"text": "Alternatively, if we were to try and attain more generic predictions and avoid possible overfitting, we could consider changing the degree from 2 to 1 which will make it a linear regression model. Looking at the somewhat linear characteristic of the plot, we can also safely say that a linear model for a trend as such, should suffice. So letβs see if the linear model predicts any differently for this particular country. I am just going to go ahead and replace the polynomial model for the US. We will use the same code structure as for the polynomial model, except this time, we will not use βpolynomial_featuresβ."
},
{
"code": null,
"e": 23673,
"s": 21989,
"text": "for name, group in df_grouped: if name[2] == \"United States\": # Only for the US group1 = group[group['people_fully_vaccinated'].notna()] group1['date_transformed'] = group1['date'].map(dt.datetime.toordinal) # transform date column into integer to be able to build model Range = group1['date_transformed'].max() + round(len(group1)/2) + 10 predict_dates = list(range(group1['date_transformed'].max() + 1, Range)) # create a range of dates to make future predictions x = group1['date_transformed'].values[:,np.newaxis] # input data transformed y = group1['vaccination_rate'].values # input train data model = LinearRegression() model.fit(x, y) # Fitting linear regression y_pred = model.predict(x) group1['Pred'] = y_pred r2 = model.score(x,y) # alternatively, r-squared can also be measured this way rmse = mean_squared_error(y, y_pred, squared=False) group_export = group1[['date','vaccination_rate','Pred']].set_index('date') Predictions = model.predict(np.array(predict_dates).reshape(-1,1)) Predictions_df = pd.DataFrame({'Future_dates': list(predict_dates),'Predictions': list(Predictions)}) Predictions_df = Predictions_df.set_index(Predictions_df['Future_dates'].map(dt.datetime.fromordinal)) plt.xticks(rotation=45) print(name) print('rmse: ', rmse) print('r2: ', r2) plt.scatter(group_export.index, group_export['vaccination_rate']) plt.plot(group_export['Pred'], color = 'g') plt.plot(Predictions_df[['Predictions']], color = 'm') plt.legend(['Validation', 'Predictions', 'Train'], loc='lower right')"
},
{
"code": null,
"e": 24076,
"s": 23673,
"text": "The results of the linear model show lower accuracy statistics than that of the polynomial model. The model now no longer shows symptoms of an overfit. The forecast of 30% here is less optimistic in our scenario but the key takeaway is that when there is a possibility of attaining overfitted results, lowering the degree might yield more generic and hence more reliable outcomes of unseen data points."
},
{
"code": null,
"e": 24436,
"s": 24076,
"text": "The above is a Tableau visualization of the final output. Since I set the filter of making predictions only for countries with at least 50 days of current vaccination rates, the predictions are narrowed down only to the coloured countries. This filter can be played around with to get predictions for more countries, however, it might compromise the accuracy."
},
{
"code": null,
"e": 24586,
"s": 24436,
"text": "A comparable visualization drawn out by The Economist boldly highlights the disparity between the rich and the poor with regard to vaccination gains."
},
{
"code": null,
"e": 24977,
"s": 24586,
"text": "While it is often tempting to blindly follow a model-based approach, we must bear in mind that all forecasts are based on assumptions and this one is no exception. This holds especially true for forecasting in the medical, economic, political, social or behavioural context over which we have little to no control. For this particular model, for instance, the following are the limitations:"
},
{
"code": null,
"e": 26039,
"s": 24977,
"text": "As mentioned before, the model doesnβt factor in scheduled deliveries by the country which likely will account for improved predictions.There is certainly not enough covid-19 vaccination data out there for a supervised model to be fully reliable. As seen in the geographic visualization of this model, many countries donβt even have 50 observations of vaccination data yet.This model assumes consistency in vaccine roll-outs. However, for many countries, this assumption has proven to be false. The roll-out consistency of a country is certainly affected by the ever-changing laws in the covid era. Consider the ban of Astrazeneca in Denmark for instance [7]. Impacts of such unexpected external factors on the outcome can rarely be factored into a machine learning model.With the many variants that have been discovered, questions about whether vaccination could mean immunity persist. Whether the outcomes of the current predictive models mean immunity, is not known. Hence this study assumes that vaccination rate is simply vaccination rate and not immunity."
},
{
"code": null,
"e": 26176,
"s": 26039,
"text": "As mentioned before, the model doesnβt factor in scheduled deliveries by the country which likely will account for improved predictions."
},
{
"code": null,
"e": 26414,
"s": 26176,
"text": "There is certainly not enough covid-19 vaccination data out there for a supervised model to be fully reliable. As seen in the geographic visualization of this model, many countries donβt even have 50 observations of vaccination data yet."
},
{
"code": null,
"e": 26814,
"s": 26414,
"text": "This model assumes consistency in vaccine roll-outs. However, for many countries, this assumption has proven to be false. The roll-out consistency of a country is certainly affected by the ever-changing laws in the covid era. Consider the ban of Astrazeneca in Denmark for instance [7]. Impacts of such unexpected external factors on the outcome can rarely be factored into a machine learning model."
},
{
"code": null,
"e": 27104,
"s": 26814,
"text": "With the many variants that have been discovered, questions about whether vaccination could mean immunity persist. Whether the outcomes of the current predictive models mean immunity, is not known. Hence this study assumes that vaccination rate is simply vaccination rate and not immunity."
},
{
"code": null,
"e": 27508,
"s": 27104,
"text": "Despite its limitations, it is needless to mention that a good model-based approach is, in many cases, better than blind intuition and guess-games. It may not give us the perfect answers but it certainly can give us an idea of what to expect and help us be better prepared and/or make improved decisions. The ideal outcome is probably the combination of a robust model and a touch of educated intuition."
},
{
"code": null,
"e": 27697,
"s": 27508,
"text": "If you did follow along and manage to acquire your own predictions, great! I hope they are looking as optimistic! Again, hereβs the data and here are the Tableau vizes. Thanks for reading!"
},
{
"code": null,
"e": 27853,
"s": 27697,
"text": "[1] D. Gypsyamber and D. David, What is Herd Immunity and How Can We Achieve It With COVID-19? (Apr, 2021), Johns Hopkins Bloomberg School of Public Health"
},
{
"code": null,
"e": 27937,
"s": 27853,
"text": "[2] R. Hannah et al., Coronavirus (COVID-19) Testing (Apr, 2021), Our World in Data"
},
{
"code": null,
"e": 28115,
"s": 27937,
"text": "[3] L. Li-Lin, T. Ching-Hung, H. Hsiu J & W. Chun-Ying, Covid-19 mortality is negatively associated with test number and government effectiveness (Jul, 2020), Scientific Reports"
},
{
"code": null,
"e": 28258,
"s": 28115,
"text": "[4] T. Liji, Countries with older populations have higher SARS-CoV-2 infections and deaths, says study (Feb, 2021), News Medical Life Sciences"
},
{
"code": null,
"e": 28383,
"s": 28258,
"text": "[5] WHO, Supporting older people during the COVID-19 pandemic is everyoneβs business, (Apr, 2020), World Health Organization"
},
{
"code": null,
"e": 28519,
"s": 28383,
"text": "[6] H. W. Steven, How Are Income and Wealth Linked to Health and Longevity? (Apr, 2015), Urban Institute & Center on Society and Health"
},
{
"code": null,
"e": 28604,
"s": 28519,
"text": "[7] BBC, AstraZeneca vaccine: Denmark stops rollout completely (Apr, 2021), BBC News"
}
] |
C library function - atan2()
|
The C library function double atan2(double y, double x) returns the arc tangent in radians of y/x based on the signs of both values to determine the correct quadrant.
Following is the declaration for atan2() function.
double atan2(double y, double x)
x β This is the floating point value representing an x-coordinate.
x β This is the floating point value representing an x-coordinate.
y β This is the floating point value representing a y-coordinate.
y β This is the floating point value representing a y-coordinate.
This function returns the principal arc tangent of y/x, in the interval [-pi,+pi] radians.
The following example shows the usage of atan2() function.
#include <stdio.h>
#include <math.h>
#define PI 3.14159265
int main () {
double x, y, ret, val;
x = -7.0;
y = 7.0;
val = 180.0 / PI;
ret = atan2 (y,x) * val;
printf("The arc tangent of x = %lf, y = %lf ", x, y);
printf("is %lf degrees\n", ret);
return(0);
}
Let us compile and run the above program that will produce the following result β
The arc tangent of x = -7.000000, y = 7.000000 is 135.000000 degrees
12 Lectures
2 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
12 Lectures
2 hours
Richa Maheshwari
20 Lectures
3.5 hours
Vandana Annavaram
44 Lectures
1 hours
Amit Diwan
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2174,
"s": 2007,
"text": "The C library function double atan2(double y, double x) returns the arc tangent in radians of y/x based on the signs of both values to determine the correct quadrant."
},
{
"code": null,
"e": 2225,
"s": 2174,
"text": "Following is the declaration for atan2() function."
},
{
"code": null,
"e": 2258,
"s": 2225,
"text": "double atan2(double y, double x)"
},
{
"code": null,
"e": 2325,
"s": 2258,
"text": "x β This is the floating point value representing an x-coordinate."
},
{
"code": null,
"e": 2392,
"s": 2325,
"text": "x β This is the floating point value representing an x-coordinate."
},
{
"code": null,
"e": 2458,
"s": 2392,
"text": "y β This is the floating point value representing a y-coordinate."
},
{
"code": null,
"e": 2524,
"s": 2458,
"text": "y β This is the floating point value representing a y-coordinate."
},
{
"code": null,
"e": 2615,
"s": 2524,
"text": "This function returns the principal arc tangent of y/x, in the interval [-pi,+pi] radians."
},
{
"code": null,
"e": 2674,
"s": 2615,
"text": "The following example shows the usage of atan2() function."
},
{
"code": null,
"e": 2963,
"s": 2674,
"text": "#include <stdio.h>\n#include <math.h>\n\n#define PI 3.14159265\n\nint main () {\n double x, y, ret, val;\n\n x = -7.0;\n y = 7.0;\n val = 180.0 / PI;\n\n ret = atan2 (y,x) * val;\n printf(\"The arc tangent of x = %lf, y = %lf \", x, y);\n printf(\"is %lf degrees\\n\", ret);\n \n return(0);\n}"
},
{
"code": null,
"e": 3045,
"s": 2963,
"text": "Let us compile and run the above program that will produce the following result β"
},
{
"code": null,
"e": 3115,
"s": 3045,
"text": "The arc tangent of x = -7.000000, y = 7.000000 is 135.000000 degrees\n"
},
{
"code": null,
"e": 3148,
"s": 3115,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3163,
"s": 3148,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3198,
"s": 3163,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3213,
"s": 3198,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3248,
"s": 3213,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3262,
"s": 3248,
"text": " Asif Hussain"
},
{
"code": null,
"e": 3295,
"s": 3262,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3313,
"s": 3295,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 3348,
"s": 3313,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3367,
"s": 3348,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 3400,
"s": 3367,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3412,
"s": 3400,
"text": " Amit Diwan"
},
{
"code": null,
"e": 3419,
"s": 3412,
"text": " Print"
},
{
"code": null,
"e": 3430,
"s": 3419,
"text": " Add Notes"
}
] |
Python | Single Point Crossover in Genetic Algorithm - GeeksforGeeks
|
13 Oct, 2019
Single Point Crossover in Genetic Algorithm is a form of crossover in which two-parent chromosome are selected and a random/given point is selected and the genes/data are interchanged between them after the given/selected point for example
Examples:
P1: 000011110011
P2: 101010101010
Point: 4
After Crossover:
C1: 000010101010
C2: 101011110011
The problem is to select a random point for the crossover of two given parents and generate at least five generations of children from the given pair of a chromosome.
# library to generate a random numberimport random # function for implementing the single-point crossoverdef crossover(l, q): # converting the string to list for performing the crossover l = list(l) q = list(q) # generating the random number to perform crossover k = random.randint(0, 15) print("Crossover point :", k) # interchanging the genes for i in range(k, len(s)): l[i], q[i] = q[i], l[i] l = ''.join(l) q = ''.join(q) print(l) print(q, "\n\n") return l, q # patent chromosomes: s = '1100110110110011'p = '1000110011011111'print("Parents")print("P1 :", s)print("P2 :", p, "\n") # function calling and storing the off springs for # next generation crossoverfor i in range(5): print("Generation ", i+1, "Childrens :") s, p = crossover(s, p)
Parents
P1 : 1100110110110011
P2 : 1000110011011111
Generation 1 Childrens :
Crossover point : 2
1100110011011111
1000110110110011
Generation 2 Childrens :
Crossover point : 7
1100110110110011
1000110011011111
Generation 3 Childrens :
Crossover point : 0
1000110011011111
1100110110110011
Generation 4 Childrens :
Crossover point : 7
1000110110110011
1100110011011111
Generation 5 Childrens :
Crossover point : 2
1000110011011111
1100110110110011
Artificial Intelligence
Genetic Algorithms
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Decision Tree
Decision Tree Introduction with example
Python | Decision tree implementation
Support Vector Machine Algorithm
ML | Underfitting and Overfitting
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 24492,
"s": 24464,
"text": "\n13 Oct, 2019"
},
{
"code": null,
"e": 24732,
"s": 24492,
"text": "Single Point Crossover in Genetic Algorithm is a form of crossover in which two-parent chromosome are selected and a random/given point is selected and the genes/data are interchanged between them after the given/selected point for example"
},
{
"code": null,
"e": 24742,
"s": 24732,
"text": "Examples:"
},
{
"code": null,
"e": 24839,
"s": 24742,
"text": "P1: 000011110011 \nP2: 101010101010\n\nPoint: 4\nAfter Crossover:\nC1: 000010101010\nC2: 101011110011\n"
},
{
"code": null,
"e": 25006,
"s": 24839,
"text": "The problem is to select a random point for the crossover of two given parents and generate at least five generations of children from the given pair of a chromosome."
},
{
"code": "# library to generate a random numberimport random # function for implementing the single-point crossoverdef crossover(l, q): # converting the string to list for performing the crossover l = list(l) q = list(q) # generating the random number to perform crossover k = random.randint(0, 15) print(\"Crossover point :\", k) # interchanging the genes for i in range(k, len(s)): l[i], q[i] = q[i], l[i] l = ''.join(l) q = ''.join(q) print(l) print(q, \"\\n\\n\") return l, q # patent chromosomes: s = '1100110110110011'p = '1000110011011111'print(\"Parents\")print(\"P1 :\", s)print(\"P2 :\", p, \"\\n\") # function calling and storing the off springs for # next generation crossoverfor i in range(5): print(\"Generation \", i+1, \"Childrens :\") s, p = crossover(s, p)",
"e": 25804,
"s": 25006,
"text": null
},
{
"code": null,
"e": 26271,
"s": 25804,
"text": "Parents\nP1 : 1100110110110011\nP2 : 1000110011011111 \n\nGeneration 1 Childrens :\nCrossover point : 2\n1100110011011111\n1000110110110011 \n\n\nGeneration 2 Childrens :\nCrossover point : 7\n1100110110110011\n1000110011011111 \n\n\nGeneration 3 Childrens :\nCrossover point : 0\n1000110011011111\n1100110110110011 \n\n\nGeneration 4 Childrens :\nCrossover point : 7\n1000110110110011\n1100110011011111 \n\n\nGeneration 5 Childrens :\nCrossover point : 2\n1000110011011111\n1100110110110011\n"
},
{
"code": null,
"e": 26295,
"s": 26271,
"text": "Artificial Intelligence"
},
{
"code": null,
"e": 26314,
"s": 26295,
"text": "Genetic Algorithms"
},
{
"code": null,
"e": 26331,
"s": 26314,
"text": "Machine Learning"
},
{
"code": null,
"e": 26338,
"s": 26331,
"text": "Python"
},
{
"code": null,
"e": 26355,
"s": 26338,
"text": "Machine Learning"
},
{
"code": null,
"e": 26453,
"s": 26355,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26467,
"s": 26453,
"text": "Decision Tree"
},
{
"code": null,
"e": 26507,
"s": 26467,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 26545,
"s": 26507,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 26578,
"s": 26545,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 26612,
"s": 26578,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 26640,
"s": 26612,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 26690,
"s": 26640,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 26712,
"s": 26690,
"text": "Python map() function"
}
] |
What does the Double Star operator mean in Python? - GeeksforGeeks
|
26 Nov, 2020
Double Star or (**) is one of the Arithmetic Operator (Like +, -, *, **, /, //, %) in Python Language. It is also known as Power Operator.
Arithmetic operators follow the same precedence rules as in mathematics, and they are: exponential is performed first, multiplication and division are performed next ,followed by addition and subtraction.
Arithmetic operators priorities order in Decreasing Mode:
() >> ** >> * >> / >> // >> % >> + >> -
As Exponentiation Operator
For numeric data types, double-asterisk (**) is defined as an Exponentiation Operator:
Example:
Python3
# Python code to Demonstrate the Exponential Operactor a = 2b = 5 # using double asterisk operatorc = a**bprint(c) # using double asterisk operatorz = 2 * (4 ** 2) + 3 * (4 ** 2 - 10)print(z)
Output:
32
50
As arguments in functions and methods
In a function definition, the double asterisk is also known **kwargs. They used to pass a keyword, variable-length argument dictionary to a function. The two asterisks (**) are the important element here, as the word kwargs is conventionally used, though not enforced by the language.
First, letβs simply print out the **kwargs arguments that we pass to a function. Weβll create a short function to do this:
Python3
# Python Program to create a function to get a dictionary of names.# Here, we will start with a dictionary of three names def function(**kwargs): for key, value in kwargs.items(): print("The value of {} is {}".format(key, value)) function(name_1="Shrey", name_2="Rohan", name_3="Ayush")
Output:
The value of name_1 is Shrey
The value of name_2 is Rohan
The value of name_3 is Ayush
Now here is another example where we will pass additional arguments to the function to show that **kwargs will accept any number of arguments:
Python3
# Python Program to create a function to get a dictionary of as many names# you want to include in your Dictionary def function(**kwargs): for key, value in kwargs.items(): print("The value of {} is {}".format(key, value)) function( name_1="Ayush", name_2="Aman", name_3="Harman", name_4="Babber", name_5="Striver",)
Output:
The value of name_1 is Ayush
The value of name_2 is Aman
The value of name_3 is Harman
The value of name_4 is Babber
The value of name_5 is Striver
Using **kwargs provides us with the flexibility to use keyword arguments in our program. When we use **kwargs as a parameter, we donβt need to know how many arguments we would eventually like to pass to a function. Creating functions that accept **kwargs are best used in situations where you expect that the number of inputs within the argument list will remain relatively small.
Python-Operators
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
|
[
{
"code": null,
"e": 23925,
"s": 23897,
"text": "\n26 Nov, 2020"
},
{
"code": null,
"e": 24064,
"s": 23925,
"text": "Double Star or (**) is one of the Arithmetic Operator (Like +, -, *, **, /, //, %) in Python Language. It is also known as Power Operator."
},
{
"code": null,
"e": 24269,
"s": 24064,
"text": "Arithmetic operators follow the same precedence rules as in mathematics, and they are: exponential is performed first, multiplication and division are performed next ,followed by addition and subtraction."
},
{
"code": null,
"e": 24327,
"s": 24269,
"text": "Arithmetic operators priorities order in Decreasing Mode:"
},
{
"code": null,
"e": 24390,
"s": 24327,
"text": "() >> ** >> * >> / >> // >> % >> + >> -\n"
},
{
"code": null,
"e": 24417,
"s": 24390,
"text": "As Exponentiation Operator"
},
{
"code": null,
"e": 24504,
"s": 24417,
"text": "For numeric data types, double-asterisk (**) is defined as an Exponentiation Operator:"
},
{
"code": null,
"e": 24513,
"s": 24504,
"text": "Example:"
},
{
"code": null,
"e": 24521,
"s": 24513,
"text": "Python3"
},
{
"code": "# Python code to Demonstrate the Exponential Operactor a = 2b = 5 # using double asterisk operatorc = a**bprint(c) # using double asterisk operatorz = 2 * (4 ** 2) + 3 * (4 ** 2 - 10)print(z)",
"e": 24718,
"s": 24521,
"text": null
},
{
"code": null,
"e": 24726,
"s": 24718,
"text": "Output:"
},
{
"code": null,
"e": 24732,
"s": 24726,
"text": "32\n50"
},
{
"code": null,
"e": 24770,
"s": 24732,
"text": "As arguments in functions and methods"
},
{
"code": null,
"e": 25056,
"s": 24770,
"text": "In a function definition, the double asterisk is also known **kwargs. They used to pass a keyword, variable-length argument dictionary to a function. The two asterisks (**) are the important element here, as the word kwargs is conventionally used, though not enforced by the language."
},
{
"code": null,
"e": 25179,
"s": 25056,
"text": "First, letβs simply print out the **kwargs arguments that we pass to a function. Weβll create a short function to do this:"
},
{
"code": null,
"e": 25187,
"s": 25179,
"text": "Python3"
},
{
"code": "# Python Program to create a function to get a dictionary of names.# Here, we will start with a dictionary of three names def function(**kwargs): for key, value in kwargs.items(): print(\"The value of {} is {}\".format(key, value)) function(name_1=\"Shrey\", name_2=\"Rohan\", name_3=\"Ayush\")",
"e": 25490,
"s": 25187,
"text": null
},
{
"code": null,
"e": 25498,
"s": 25490,
"text": "Output:"
},
{
"code": null,
"e": 25585,
"s": 25498,
"text": "The value of name_1 is Shrey\nThe value of name_2 is Rohan\nThe value of name_3 is Ayush"
},
{
"code": null,
"e": 25728,
"s": 25585,
"text": "Now here is another example where we will pass additional arguments to the function to show that **kwargs will accept any number of arguments:"
},
{
"code": null,
"e": 25736,
"s": 25728,
"text": "Python3"
},
{
"code": "# Python Program to create a function to get a dictionary of as many names# you want to include in your Dictionary def function(**kwargs): for key, value in kwargs.items(): print(\"The value of {} is {}\".format(key, value)) function( name_1=\"Ayush\", name_2=\"Aman\", name_3=\"Harman\", name_4=\"Babber\", name_5=\"Striver\",)",
"e": 26084,
"s": 25736,
"text": null
},
{
"code": null,
"e": 26092,
"s": 26084,
"text": "Output:"
},
{
"code": null,
"e": 26240,
"s": 26092,
"text": "The value of name_1 is Ayush\nThe value of name_2 is Aman\nThe value of name_3 is Harman\nThe value of name_4 is Babber\nThe value of name_5 is Striver"
},
{
"code": null,
"e": 26621,
"s": 26240,
"text": "Using **kwargs provides us with the flexibility to use keyword arguments in our program. When we use **kwargs as a parameter, we donβt need to know how many arguments we would eventually like to pass to a function. Creating functions that accept **kwargs are best used in situations where you expect that the number of inputs within the argument list will remain relatively small."
},
{
"code": null,
"e": 26638,
"s": 26621,
"text": "Python-Operators"
},
{
"code": null,
"e": 26662,
"s": 26638,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 26669,
"s": 26662,
"text": "Python"
},
{
"code": null,
"e": 26688,
"s": 26669,
"text": "Technical Scripter"
},
{
"code": null,
"e": 26786,
"s": 26688,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26795,
"s": 26786,
"text": "Comments"
},
{
"code": null,
"e": 26808,
"s": 26795,
"text": "Old Comments"
},
{
"code": null,
"e": 26840,
"s": 26808,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26896,
"s": 26840,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26938,
"s": 26896,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26980,
"s": 26938,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27016,
"s": 26980,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 27038,
"s": 27016,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27077,
"s": 27038,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27104,
"s": 27077,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27135,
"s": 27104,
"text": "Python | os.path.join() method"
}
] |
C program to sort an array by using merge sort
|
An array is a group of related data items which shareβs a common name. A particular value in an array is identified with the help of its "index number".
The syntax for declaring an array is as follows β
datatype array_name [size];
For example,
float marks [50]
It declares βmarksβ to be an array containing 50 float elements.
int number[10]
It declares the βnumberβ as an array to contain a maximum of 10 integer constants.
Each element is identified by using an "array index".
Accessing array elements is easy by using the array index.
The logic we use for merge sort is as follows β
void MergeSort(int *array, int left, int right){
int middle = (left+right)/2;
if(left<right){
//Sorting the left part
MergeSort(array, left, middle);
//Sorting the right part
MergeSort(array, middle + 1, right);
// Merge the two parts
Merge(array, left, middle, right);
}
}
The logic for merging all the elements is as follows β
void Merge(int *array, int left, int middle, int right){
int tmp[right - left + 1];
int pos = 0, leftposition = left, rightposition = middle + 1;
while (leftposition <= middle && rightposition <= right){
if (array[leftposition] < array[rightposition]){
tmp[pos++] = array[leftposition++];
}else{
tmp[pos++] = array[rightposition++];
}
}
while (leftposition <= middle)
tmp[pos++] = array[leftposition++];
while (rightposition <= right)
tmp[pos++] = array[rightposition++];
int i;
for (i = 0; i < pos; i++){
array[i + left] = tmp[i];
}
return;
}
Following is the C program to merge sort β
Live Demo
#include <stdio.h>
void Merge(int * , int , int , int );
void MergeSort(int *array, int left, int right){
int middle = (left+right)/2;
if(left<right){
//Sorting the left part
MergeSort(array, left, middle);
//Sorting the right part
MergeSort(array, middle + 1, right);
// Merge the two parts
Merge(array, left, middle, right);
}
}
void Merge(int *array, int left, int middle, int right){
int tmp[right - left + 1];
int pos = 0, leftposition = left, rightposition = middle + 1;
while (leftposition <= middle && rightposition <= right){
if (array[leftposition] < array[rightposition]){
tmp[pos++] = array[leftposition++];
}
else{
tmp[pos++] = array[rightposition++];
}
}
while (leftposition <= middle)
tmp[pos++] = array[leftposition++];
while (rightposition <= right)
tmp[pos++] = array[rightposition++];
int i;
for (i = 0; i < pos; i++){
array[i + left] = tmp[i];
}
return;
}
int main(){
int size;
printf("\n enter size of array:");
scanf("%d", &size);
int array[size];
int i, j, k;
printf("\n enter the elements in an array:");
for (i = 0; i < size; i++){
scanf("%d", &array[i]);
}
MergeSort(array, 0, size - 1);//calling sort function
for (i = 0; i< size; i++){
printf("%d ", array[i]);
}
printf("\n");
return 0;
}
When the above program is executed, it produces the following result β
enter size of array:10
enter the elements in an array:
2
-10
34
-3
45
67
-89
34
23
67
-89 -10 -3 2 23 34 34 45 67 67
|
[
{
"code": null,
"e": 1215,
"s": 1062,
"text": "An array is a group of related data items which shareβs a common name. A particular value in an array is identified with the help of its \"index number\"."
},
{
"code": null,
"e": 1265,
"s": 1215,
"text": "The syntax for declaring an array is as follows β"
},
{
"code": null,
"e": 1293,
"s": 1265,
"text": "datatype array_name [size];"
},
{
"code": null,
"e": 1306,
"s": 1293,
"text": "For example,"
},
{
"code": null,
"e": 1323,
"s": 1306,
"text": "float marks [50]"
},
{
"code": null,
"e": 1388,
"s": 1323,
"text": "It declares βmarksβ to be an array containing 50 float elements."
},
{
"code": null,
"e": 1403,
"s": 1388,
"text": "int number[10]"
},
{
"code": null,
"e": 1486,
"s": 1403,
"text": "It declares the βnumberβ as an array to contain a maximum of 10 integer constants."
},
{
"code": null,
"e": 1540,
"s": 1486,
"text": "Each element is identified by using an \"array index\"."
},
{
"code": null,
"e": 1599,
"s": 1540,
"text": "Accessing array elements is easy by using the array index."
},
{
"code": null,
"e": 1647,
"s": 1599,
"text": "The logic we use for merge sort is as follows β"
},
{
"code": null,
"e": 1966,
"s": 1647,
"text": "void MergeSort(int *array, int left, int right){\n int middle = (left+right)/2;\n if(left<right){\n //Sorting the left part\n MergeSort(array, left, middle);\n //Sorting the right part\n MergeSort(array, middle + 1, right);\n // Merge the two parts\n Merge(array, left, middle, right);\n }\n}"
},
{
"code": null,
"e": 2021,
"s": 1966,
"text": "The logic for merging all the elements is as follows β"
},
{
"code": null,
"e": 2649,
"s": 2021,
"text": "void Merge(int *array, int left, int middle, int right){\n int tmp[right - left + 1];\n int pos = 0, leftposition = left, rightposition = middle + 1;\n while (leftposition <= middle && rightposition <= right){\n if (array[leftposition] < array[rightposition]){\n tmp[pos++] = array[leftposition++];\n }else{\n tmp[pos++] = array[rightposition++];\n }\n }\n while (leftposition <= middle)\n tmp[pos++] = array[leftposition++];\n while (rightposition <= right)\n tmp[pos++] = array[rightposition++];\n int i;\n for (i = 0; i < pos; i++){\n array[i + left] = tmp[i];\n }\n return;\n}"
},
{
"code": null,
"e": 2692,
"s": 2649,
"text": "Following is the C program to merge sort β"
},
{
"code": null,
"e": 2703,
"s": 2692,
"text": " Live Demo"
},
{
"code": null,
"e": 4106,
"s": 2703,
"text": "#include <stdio.h>\nvoid Merge(int * , int , int , int );\nvoid MergeSort(int *array, int left, int right){\n int middle = (left+right)/2;\n if(left<right){\n //Sorting the left part\n MergeSort(array, left, middle);\n //Sorting the right part\n MergeSort(array, middle + 1, right);\n // Merge the two parts\n Merge(array, left, middle, right);\n }\n}\nvoid Merge(int *array, int left, int middle, int right){\n int tmp[right - left + 1];\n int pos = 0, leftposition = left, rightposition = middle + 1;\n while (leftposition <= middle && rightposition <= right){\n if (array[leftposition] < array[rightposition]){\n tmp[pos++] = array[leftposition++];\n }\n else{\n tmp[pos++] = array[rightposition++];\n }\n }\n while (leftposition <= middle)\n tmp[pos++] = array[leftposition++];\n while (rightposition <= right)\n tmp[pos++] = array[rightposition++];\n int i;\n for (i = 0; i < pos; i++){\n array[i + left] = tmp[i];\n }\n return;\n}\nint main(){\n int size;\n printf(\"\\n enter size of array:\");\n scanf(\"%d\", &size);\n int array[size];\n int i, j, k;\n printf(\"\\n enter the elements in an array:\");\n for (i = 0; i < size; i++){\n scanf(\"%d\", &array[i]);\n }\n MergeSort(array, 0, size - 1);//calling sort function\n for (i = 0; i< size; i++){\n printf(\"%d \", array[i]);\n }\n printf(\"\\n\");\n return 0;\n}"
},
{
"code": null,
"e": 4177,
"s": 4106,
"text": "When the above program is executed, it produces the following result β"
},
{
"code": null,
"e": 4294,
"s": 4177,
"text": "enter size of array:10\nenter the elements in an array:\n2\n-10\n34\n-3\n45\n67\n-89\n34\n23\n67\n-89 -10 -3 2 23 34 34 45 67 67"
}
] |
Factorial of Large Number Using boost multiprecision Library - GeeksforGeeks
|
28 Jan, 2018
We have given a large number now we can easily find out the factorial of this large number using boost multiprevision Library.Boost library has included a new multiprecision library in the current 1.53.0 release for C++ programmers who need more precision than 64 bits.
Examples:
Input : 100
Output : 933262154439441526816992388562667004-
907159682643816214685929638952175999-
932299156089414639761565182862536979-
208272237582511852109168640000000000-
00000000000000
Input :50
Output : 3041409320171337804361260816606476884-
4377641568960512000000000000
// CPP program to find factorial of large // number using boost library.#include <bits/stdc++.h>#include <boost/multiprecision/cpp_int.hpp>using boost::multiprecision::cpp_int;using namespace std; cpp_int Factorial(int number){ cpp_int num = 1; for (int i = 1; i <= number; i++) num = num * i; return num;} int main(){ int number = 100; cpp_int fact = Factorial(number); cout << fact << endl; return 0;}
Output:-
933262154439441526816992388562667004-
907159682643816214685929638952175999-
932299156089414639761565182862536979-
208272237582511852109168640000000000-
00000000000000
cpp-boost
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Classes and Objects
Operator Overloading in C++
Socket Programming in C/C++
Constructors in C++
Virtual Function in C++
Multidimensional Arrays in C / C++
Templates in C++ with Examples
Copy Constructor in C++
Object Oriented Programming in C++
Polymorphism in C++
|
[
{
"code": null,
"e": 24794,
"s": 24766,
"text": "\n28 Jan, 2018"
},
{
"code": null,
"e": 25064,
"s": 24794,
"text": "We have given a large number now we can easily find out the factorial of this large number using boost multiprevision Library.Boost library has included a new multiprecision library in the current 1.53.0 release for C++ programmers who need more precision than 64 bits."
},
{
"code": null,
"e": 25074,
"s": 25064,
"text": "Examples:"
},
{
"code": null,
"e": 25399,
"s": 25074,
"text": "Input : 100\nOutput : 933262154439441526816992388562667004-\n 907159682643816214685929638952175999-\n 932299156089414639761565182862536979-\n 208272237582511852109168640000000000-\n 00000000000000\n\n\n\nInput :50\nOutput : 3041409320171337804361260816606476884-\n 4377641568960512000000000000\n"
},
{
"code": "// CPP program to find factorial of large // number using boost library.#include <bits/stdc++.h>#include <boost/multiprecision/cpp_int.hpp>using boost::multiprecision::cpp_int;using namespace std; cpp_int Factorial(int number){ cpp_int num = 1; for (int i = 1; i <= number; i++) num = num * i; return num;} int main(){ int number = 100; cpp_int fact = Factorial(number); cout << fact << endl; return 0;}",
"e": 25833,
"s": 25399,
"text": null
},
{
"code": null,
"e": 25842,
"s": 25833,
"text": "Output:-"
},
{
"code": null,
"e": 26045,
"s": 25842,
"text": "933262154439441526816992388562667004-\n 907159682643816214685929638952175999-\n 932299156089414639761565182862536979-\n 208272237582511852109168640000000000-\n 00000000000000"
},
{
"code": null,
"e": 26055,
"s": 26045,
"text": "cpp-boost"
},
{
"code": null,
"e": 26059,
"s": 26055,
"text": "C++"
},
{
"code": null,
"e": 26063,
"s": 26059,
"text": "CPP"
},
{
"code": null,
"e": 26161,
"s": 26063,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26185,
"s": 26161,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 26213,
"s": 26185,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 26241,
"s": 26213,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 26261,
"s": 26241,
"text": "Constructors in C++"
},
{
"code": null,
"e": 26285,
"s": 26261,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 26320,
"s": 26285,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 26351,
"s": 26320,
"text": "Templates in C++ with Examples"
},
{
"code": null,
"e": 26375,
"s": 26351,
"text": "Copy Constructor in C++"
},
{
"code": null,
"e": 26410,
"s": 26375,
"text": "Object Oriented Programming in C++"
}
] |
Modular multiplicative inverse - GeeksforGeeks
|
19 Feb, 2022
Given two integers βaβ and βmβ, find modular multiplicative inverse of βaβ under modulo βmβ.The modular multiplicative inverse is an integer βxβ such that.
a x β
1 (mod m)
The value of x should be in { 1, 2, ... m-1}, i.e., in the range of integer modulo m. ( Note that x cannot be 0 as a*0 mod m will never be 1 )The multiplicative inverse of βa modulo mβ exists if and only if a and m are relatively prime (i.e., if gcd(a, m) = 1).
Examples:
Input: a = 3, m = 11
Output: 4
Since (4*3) mod 11 = 1, 4 is modulo inverse of 3(under 11).
One might think, 15 also as a valid output as "(15*3) mod 11"
is also 1, but 15 is not in ring {1, 2, ... 10}, so not
valid.
Input: a = 10, m = 17
Output: 12
Since (10*12) mod 17 = 1, 12 is modulo inverse of 10(under 17).
Method 1 (Naive) A Naive method is to try all numbers from 1 to m. For every number x, check if (a*x)%m is 1.
Below is the implementation of this method.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find modular// inverse of a under modulo m#include <iostream>using namespace std; // A naive method to find modular// multiplicative inverse of 'a'// under modulo 'm'int modInverse(int a, int m){ for (int x = 1; x < m; x++) if (((a%m) * (x%m)) % m == 1) return x;} // Driver codeint main(){ int a = 3, m = 11; // Function call cout << modInverse(a, m); return 0;}
// Java program to find modular inverse// of a under modulo mimport java.io.*; class GFG { // A naive method to find modulor // multiplicative inverse of 'a' // under modulo 'm' static int modInverse(int a, int m) { for (int x = 1; x < m; x++) if (((a%m) * (x%m)) % m == 1) return x; return 1; } // Driver Code public static void main(String args[]) { int a = 3, m = 11; // Function call System.out.println(modInverse(a, m)); }} /*This code is contributed by Nikita Tiwari.*/
# Python3 program to find modular# inverse of a under modulo m # A naive method to find modulor# multiplicative inverse of 'a'# under modulo 'm' def modInverse(a, m): for x in range(1, m): if (((a%m) * (x%m)) % m == 1): return x return -1 # Driver Codea = 3m = 11 # Function callprint(modInverse(a, m)) # This code is contributed by Nikita Tiwari.
// C# program to find modular inverse// of a under modulo musing System; class GFG { // A naive method to find modulor // multiplicative inverse of 'a' // under modulo 'm' static int modInverse(int a, int m) { for (int x = 1; x < m; x++) if (((a%m) * (x%m)) % m == 1) return x; return 1; } // Driver Code public static void Main() { int a = 3, m = 11; // Function call Console.WriteLine(modInverse(a, m)); }} // This code is contributed by anuj_67.
<β
php// PHP program to find modular// inverse of a under modulo m // A naive method to find modulor// multiplicative inverse of// 'a' under modulo 'm'function modInverse( $a, $m){ for ($x = 1; $x < $m; $x++) if ((($a%$m) * ($x%$m)) % $m == 1) return $x;} // Driver Code $a = 3; $m = 11; // Function call echo modInverse($a, $m); // This code is contributed by anuj_67.β
>
<script> // Javascript program to find modular// inverse of a under modulo m // A naive method to find modulor// multiplicative inverse of// 'a' under modulo 'm'function modInverse(a, m){ for(let x = 1; x < m; x++) if (((a % m) * (x % m)) % m == 1) return x;} // Driver Codelet a = 3;let m = 11; // Function calldocument.write(modInverse(a, m)); // This code is contributed by _saurabh_jaiswal. </script>
4
Time Complexity: O(m)
Auxiliary Space: O(1)
Method 2 ( Works when m and a are coprime or gcd(a,m)=1 ) The idea is to use Extended Euclidean algorithms that takes two integers βaβ and βbβ, finds their gcd and also find βxβ and βyβ such that
ax + by = gcd(a, b)
To find multiplicative inverse of βaβ under βmβ, we put b = m in above formula. Since we know that a and m are relatively prime, we can put value of gcd as 1.
ax + my = 1
If we take modulo m on both sides, we get
ax + my β
1 (mod m)
We can remove the second term on left side as βmy (mod m)β would always be 0 for an integer y.
ax β
1 (mod m)
So the βxβ that we can find using Extended Euclid Algorithm is the multiplicative inverse of βaβ
Below is the implementation of the above algorithm.
C++
C
PHP
// C++ program to find multiplicative modulo// inverse using Extended Euclid algorithm.#include <iostream>using namespace std; // Function for extended Euclidean Algorithmint gcdExtended(int a, int b, int* x, int* y); // Function to find modulo inverse of avoid modInverse(int a, int m){ int x, y; int g = gcdExtended(a, m, &x, &y); if (g != 1) cout << "Inverse doesn't exist"; else { // m is added to handle negative x int res = (x % m + m) % m; cout << "Modular multiplicative inverse is " << res; }} // Function for extended Euclidean Algorithmint gcdExtended(int a, int b, int* x, int* y){ // Base Case if (a == 0) { *x = 0, *y = 1; return b; } // To store results of recursive call int x1, y1; int gcd = gcdExtended(b % a, a, &x1, &y1); // Update x and y using results of recursive // call *x = y1 - (b / a) * x1; *y = x1; return gcd;} // Driver Codeint main(){ int a = 3, m = 11; // Function call modInverse(a, m); return 0;} // This code is contributed by khushboogoyal499
// C program to find multiplicative modulo inverse using// Extended Euclid algorithm.#include <stdio.h> // C function for extended Euclidean Algorithmint gcdExtended(int a, int b, int* x, int* y); // Function to find modulo inverse of avoid modInverse(int a, int m){ int x, y; int g = gcdExtended(a, m, &x, &y); if (g != 1) printf("Inverse doesn't exist"); else { // m is added to handle negative x int res = (x % m + m) % m; printf("Modular multiplicative inverse is %d", res); }} // C function for extended Euclidean Algorithmint gcdExtended(int a, int b, int* x, int* y){ // Base Case if (a == 0) { *x = 0, *y = 1; return b; } int x1, y1; // To store results of recursive call int gcd = gcdExtended(b % a, a, &x1, &y1); // Update x and y using results of recursive // call *x = y1 - (b / a) * x1; *y = x1; return gcd;} // Driver Codeint main(){ int a = 3, m = 11; // Function call modInverse(a, m); return 0;}
<β
php// PHP program to find multiplicative modulo// inverse using Extended Euclid algorithm.// Function to find modulo inverse of afunction modInverse($a, $m){ $x = 0; $y = 0; $g = gcdExtended($a, $m, $x, $y); if ($g != 1) echo "Inverse doesn't exist"; else { // m is added to handle negative x $res = ($x % $m + $m) % $m; echo "Modular multiplicative " . "inverse is " . $res; }} // function for extended Euclidean Algorithmfunction gcdExtended($a, $b, &$x, &$y){ // Base Case if ($a == 0) { $x = 0; $y = 1; return $b; } $x1; $y1; // To store results of recursive call $gcd = gcdExtended($b%$a, $a, $x1, $y1); // Update x and y using results of // recursive call $x = $y1 - (int)($b/$a) * $x1; $y = $x1; return $gcd;} // Driver Code$a = 3;$m = 11; // Function callmodInverse($a, $m); // This code is contributed by chandan_jnuβ
>
Modular multiplicative inverse is 4
Time Complexity: O(log m)
Auxiliary Space: O(log m) because of the internal recursion stack.
Iterative Implementation:
C++
C
Java
Python3
C#
PHP
Javascript
// Iterative C++ program to find modular// inverse using extended Euclid algorithm#include <bits/stdc++.h>using namespace std; // Returns modulo inverse of a with respect// to m using extended Euclid Algorithm// Assumption: a and m are coprimes, i.e.,// gcd(a, m) = 1int modInverse(int a, int m){ int m0 = m; int y = 0, x = 1; if (m == 1) return 0; while (a > 1) { // q is quotient int q = a / m; int t = m; // m is remainder now, process same as // Euclid's algo m = a % m, a = t; t = y; // Update y and x y = x - q * y; x = t; } // Make x positive if (x < 0) x += m0; return x;} // Driver Codeint main(){ int a = 3, m = 11; // Function call cout << "Modular multiplicative inverse is "<< modInverse(a, m); return 0;}// this code is contributed by shivanisinghss2110
// Iterative C program to find modular// inverse using extended Euclid algorithm#include <stdio.h> // Returns modulo inverse of a with respect// to m using extended Euclid Algorithm// Assumption: a and m are coprimes, i.e.,// gcd(a, m) = 1int modInverse(int a, int m){ int m0 = m; int y = 0, x = 1; if (m == 1) return 0; while (a > 1) { // q is quotient int q = a / m; int t = m; // m is remainder now, process same as // Euclid's algo m = a % m, a = t; t = y; // Update y and x y = x - q * y; x = t; } // Make x positive if (x < 0) x += m0; return x;} // Driver Codeint main(){ int a = 3, m = 11; // Function call printf("Modular multiplicative inverse is %d\n", modInverse(a, m)); return 0;}
// Iterative Java program to find modular// inverse using extended Euclid algorithm class GFG { // Returns modulo inverse of a with // respect to m using extended Euclid // Algorithm Assumption: a and m are // coprimes, i.e., gcd(a, m) = 1 static int modInverse(int a, int m) { int m0 = m; int y = 0, x = 1; if (m == 1) return 0; while (a > 1) { // q is quotient int q = a / m; int t = m; // m is remainder now, process // same as Euclid's algo m = a % m; a = t; t = y; // Update x and y y = x - q * y; x = t; } // Make x positive if (x < 0) x += m0; return x; } // Driver code public static void main(String args[]) { int a = 3, m = 11; // Function call System.out.println("Modular multiplicative " + "inverse is " + modInverse(a, m)); }} /*This code is contributed by Nikita Tiwari.*/
# Iterative Python 3 program to find# modular inverse using extended# Euclid algorithm # Returns modulo inverse of a with# respect to m using extended Euclid# Algorithm Assumption: a and m are# coprimes, i.e., gcd(a, m) = 1 def modInverse(a, m): m0 = m y = 0 x = 1 if (m == 1): return 0 while (a > 1): # q is quotient q = a // m t = m # m is remainder now, process # same as Euclid's algo m = a % m a = t t = y # Update x and y y = x - q * y x = t # Make x positive if (x < 0): x = x + m0 return x # Driver codea = 3m = 11 # Function callprint("Modular multiplicative inverse is", modInverse(a, m)) # This code is contributed by Nikita tiwari.
// Iterative C# program to find modular// inverse using extended Euclid algorithmusing System;class GFG { // Returns modulo inverse of a with // respect to m using extended Euclid // Algorithm Assumption: a and m are // coprimes, i.e., gcd(a, m) = 1 static int modInverse(int a, int m) { int m0 = m; int y = 0, x = 1; if (m == 1) return 0; while (a > 1) { // q is quotient int q = a / m; int t = m; // m is remainder now, process // same as Euclid's algo m = a % m; a = t; t = y; // Update x and y y = x - q * y; x = t; } // Make x positive if (x < 0) x += m0; return x; } // Driver Code public static void Main() { int a = 3, m = 11; // Function call Console.WriteLine("Modular multiplicative " + "inverse is " + modInverse(a, m)); }} // This code is contributed by anuj_67.
<β
php// Iterative PHP program to find modular// inverse using extended Euclid algorithm // Returns modulo inverse of a with respect// to m using extended Euclid Algorithm// Assumption: a and m are coprimes, i.e.,// gcd(a, m) = 1function modInverse($a, $m){ $m0 = $m; $y = 0; $x = 1; if ($m == 1) return 0; while ($a > 1) { // q is quotient $q = (int) ($a / $m); $t = $m; // m is remainder now, // process same as // Euclid's algo $m = $a % $m; $a = $t; $t = $y; // Update y and x $y = $x - $q * $y; $x = $t; } // Make x positive if ($x < 0) $x += $m0; return $x;} // Driver Code $a = 3; $m = 11; // Function call echo "Modular multiplicative inverse is\n", modInverse($a, $m); // This code is contributed by Anuj_67β
>
<script> // Iterative Javascript program to find modular// inverse using extended Euclid algorithm // Returns modulo inverse of a with respect// to m using extended Euclid Algorithm// Assumption: a and m are coprimes, i.e.,// gcd(a, m) = 1function modInverse(a, m){ let m0 = m; let y = 0; let x = 1; if (m == 1) return 0; while (a > 1) { // q is quotient let q = parseInt(a / m); let t = m; // m is remainder now, // process same as // Euclid's algo m = a % m; a = t; t = y; // Update y and x y = x - q * y; x = t; } // Make x positive if (x < 0) x += m0; return x;} // Driver Codelet a = 3;let m = 11; // Function calldocument.write(`Modular multiplicative inverse is ${modInverse(a, m)}`); // This code is contributed by _saurabh_jaiswal </script>
Modular multiplicative inverse is 4
Time Complexity: O(log m)
Auxiliary Space: O(1)
Method 3 (Works when m is prime) If we know m is prime, then we can also use Fermatsβs little theorem to find the inverse.
am-1 β
1 (mod m)
If we multiply both sides with a-1, we get
a-1 β
a m-2 (mod m)
Below is the implementation of the above idea.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find modular inverse of a under modulo m// This program works only if m is prime.#include <iostream>using namespace std; // To find GCD of a and bint gcd(int a, int b); // To compute x raised to power y under modulo mint power(int x, unsigned int y, unsigned int m); // Function to find modular inverse of a under modulo m// Assumption: m is primevoid modInverse(int a, int m){ int g = gcd(a, m); if (g != 1) cout << "Inverse doesn't exist"; else { // If a and m are relatively prime, then modulo // inverse is a^(m-2) mode m cout << "Modular multiplicative inverse is " << power(a, m - 2, m); }} // To compute x^y under modulo mint power(int x, unsigned int y, unsigned int m){ if (y == 0) return 1; int p = power(x, y / 2, m) % m; p = (p * p) % m; return (y % 2 == 0) ? p : (x * p) % m;} // Function to return gcd of a and bint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Driver codeint main(){ int a = 3, m = 11; // Function call modInverse(a, m); return 0;}
// Java program to find modular// inverse of a under modulo m// This program works only if// m is prime.import java.io.*; class GFG { // Function to find modular inverse of a // under modulo m Assumption: m is prime static void modInverse(int a, int m) { int g = gcd(a, m); if (g != 1) System.out.println("Inverse doesn't exist"); else { // If a and m are relatively prime, then modulo // inverse is a^(m-2) mode m System.out.println( "Modular multiplicative inverse is " + power(a, m - 2, m)); } } static int power(int x, int y, int m) { if (y == 0) return 1; int p = power(x, y / 2, m) % m; p = (int)((p * (long)p) % m); if (y % 2 == 0) return p; else return (int)((x * (long)p) % m); } // Function to return gcd of a and b static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // Driver Code public static void main(String args[]) { int a = 3, m = 11; // Function call modInverse(a, m); }} // This code is contributed by Nikita Tiwari.
# Python3 program to find modular# inverse of a under modulo m # This program works only if m is prime. # Function to find modular# inverse of a under modulo m# Assumption: m is prime def modInverse(a, m): g = gcd(a, m) if (g != 1): print("Inverse doesn't exist") else: # If a and m are relatively prime, # then modulo inverse is a^(m-2) mode m print("Modular multiplicative inverse is ", power(a, m - 2, m)) # To compute x^y under modulo m def power(x, y, m): if (y == 0): return 1 p = power(x, y // 2, m) % m p = (p * p) % m if(y % 2 == 0): return p else: return ((x * p) % m) # Function to return gcd of a and b def gcd(a, b): if (a == 0): return b return gcd(b % a, a) # Driver Codea = 3m = 11 # Function callmodInverse(a, m) # This code is contributed by Nikita Tiwari.
// C# program to find modular// inverse of a under modulo m// This program works only if// m is prime.using System;class GFG { // Function to find modular // inverse of a under modulo // m Assumption: m is prime static void modInverse(int a, int m) { int g = gcd(a, m); if (g != 1) Console.Write("Inverse doesn't exist"); else { // If a and m are relatively // prime, then modulo inverse // is a^(m-2) mode m Console.Write( "Modular multiplicative inverse is " + power(a, m - 2, m)); } } // To compute x^y under // modulo m static int power(int x, int y, int m) { if (y == 0) return 1; int p = power(x, y / 2, m) % m; p = (p * p) % m; if (y % 2 == 0) return p; else return (x * p) % m; } // Function to return // gcd of a and b static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // Driver Code public static void Main() { int a = 3, m = 11; // Function call modInverse(a, m); }} // This code is contributed by nitin mittal.
<β
php// PHP program to find modular// inverse of a under modulo m// This program works only if m// is prime. // Function to find modular inverse// of a under modulo m// Assumption: m is primefunction modInverse( $a, $m){ $g = gcd($a, $m); if ($g != 1) echo "Inverse doesn't exist"; else { // If a and m are relatively // prime, then modulo inverse // is a^(m-2) mode m echo "Modular multiplicative inverse is " , power($a, $m - 2, $m); }} // To compute x^y under modulo mfunction power( $x, $y, $m){ if ($y == 0) return 1; $p = power($x, $y / 2, $m) % $m; $p = ($p * $p) % $m; return ($y % 2 == 0)? $p : ($x * $p) % $m;} // Function to return gcd of a and bfunction gcd($a, $b){ if ($a == 0) return $b; return gcd($b % $a, $a);} // Driver Code$a = 3;$m = 11; // Function callmodInverse($a, $m); // This code is contributed by anuj_67.β
>
<script>// Javascript program to find modular inverse of a under modulo m// This program works only if m is prime. // Function to find modular inverse of a under modulo m// Assumption: m is primefunction modInverse(a, m){ let g = gcd(a, m); if (g != 1) document.write("Inverse doesn't exist"); else { // If a and m are relatively prime, then modulo // inverse is a^(m-2) mode m document.write("Modular multiplicative inverse is " + power(a, m - 2, m)); }} // To compute x^y under modulo mfunction power(x, y, m){ if (y == 0) return 1; let p = power(x, parseInt(y / 2), m) % m; p = (p * p) % m; return (y % 2 == 0) ? p : (x * p) % m;} // Function to return gcd of a and bfunction gcd(a, b){ if (a == 0) return b; return gcd(b % a, a);} // Driver codelet a = 3, m = 11; // Function callmodInverse(a, m); // This code is contributed by subham348.</script>
Modular multiplicative inverse is 4
Time Complexity: O(log m)
Auxiliary Space: O(log m) because of the internal recursion stack.
We have discussed three methods to find multiplicative inverse modulo m. 1) Naive Method, O(m) 2) Extended Eulerβs GCD algorithm, O(Log m) [Works when a and m are coprime] 3) Fermatβs Little theorem, O(Log m) [Works when βmβ is prime]
Applications: Computation of the modular multiplicative inverse is an essential step in RSA public-key encryption method.
References: https://en.wikipedia.org/wiki/Modular_multiplicative_inverse http://e-maxx.ru/algo/reverse_elementThis article is contributed by Ankur. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
vt_m
nitin mittal
Chandan_Kumar
raunak_m17
olivebadger
_emperor
derekallen105
oshosmart
sudhanshu751
nitin_19520
nagulansridhar
_saurabh_jaiswal
subham348
khushboogoyal499
shivanisinghss2110
anikakapoor
prophet1999
Modular Arithmetic
number-theory
Mathematical
number-theory
Mathematical
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Modulo Operator (%) in C/C++ with Examples
Find all factors of a natural number | Set 1
Modulo 10^9+7 (1000000007)
Program to find sum of elements in a given array
The Knight's tour problem | Backtracking-1
Program for factorial of a number
Minimum number of jumps to reach end
Operators in C / C++
Find minimum number of coins that make a given value
Write a program to reverse digits of a number
|
[
{
"code": null,
"e": 24159,
"s": 24131,
"text": "\n19 Feb, 2022"
},
{
"code": null,
"e": 24316,
"s": 24159,
"text": "Given two integers βaβ and βmβ, find modular multiplicative inverse of βaβ under modulo βmβ.The modular multiplicative inverse is an integer βxβ such that. "
},
{
"code": null,
"e": 24332,
"s": 24316,
"text": "a x β
1 (mod m)"
},
{
"code": null,
"e": 24594,
"s": 24332,
"text": "The value of x should be in { 1, 2, ... m-1}, i.e., in the range of integer modulo m. ( Note that x cannot be 0 as a*0 mod m will never be 1 )The multiplicative inverse of βa modulo mβ exists if and only if a and m are relatively prime (i.e., if gcd(a, m) = 1)."
},
{
"code": null,
"e": 24605,
"s": 24594,
"text": "Examples: "
},
{
"code": null,
"e": 24923,
"s": 24605,
"text": "Input: a = 3, m = 11\nOutput: 4\nSince (4*3) mod 11 = 1, 4 is modulo inverse of 3(under 11).\nOne might think, 15 also as a valid output as \"(15*3) mod 11\" \nis also 1, but 15 is not in ring {1, 2, ... 10}, so not \nvalid.\n\nInput: a = 10, m = 17\nOutput: 12\nSince (10*12) mod 17 = 1, 12 is modulo inverse of 10(under 17)."
},
{
"code": null,
"e": 25034,
"s": 24923,
"text": "Method 1 (Naive) A Naive method is to try all numbers from 1 to m. For every number x, check if (a*x)%m is 1. "
},
{
"code": null,
"e": 25079,
"s": 25034,
"text": "Below is the implementation of this method. "
},
{
"code": null,
"e": 25083,
"s": 25079,
"text": "C++"
},
{
"code": null,
"e": 25088,
"s": 25083,
"text": "Java"
},
{
"code": null,
"e": 25096,
"s": 25088,
"text": "Python3"
},
{
"code": null,
"e": 25099,
"s": 25096,
"text": "C#"
},
{
"code": null,
"e": 25103,
"s": 25099,
"text": "PHP"
},
{
"code": null,
"e": 25114,
"s": 25103,
"text": "Javascript"
},
{
"code": "// C++ program to find modular// inverse of a under modulo m#include <iostream>using namespace std; // A naive method to find modular// multiplicative inverse of 'a'// under modulo 'm'int modInverse(int a, int m){ for (int x = 1; x < m; x++) if (((a%m) * (x%m)) % m == 1) return x;} // Driver codeint main(){ int a = 3, m = 11; // Function call cout << modInverse(a, m); return 0;}",
"e": 25532,
"s": 25114,
"text": null
},
{
"code": "// Java program to find modular inverse// of a under modulo mimport java.io.*; class GFG { // A naive method to find modulor // multiplicative inverse of 'a' // under modulo 'm' static int modInverse(int a, int m) { for (int x = 1; x < m; x++) if (((a%m) * (x%m)) % m == 1) return x; return 1; } // Driver Code public static void main(String args[]) { int a = 3, m = 11; // Function call System.out.println(modInverse(a, m)); }} /*This code is contributed by Nikita Tiwari.*/",
"e": 26114,
"s": 25532,
"text": null
},
{
"code": "# Python3 program to find modular# inverse of a under modulo m # A naive method to find modulor# multiplicative inverse of 'a'# under modulo 'm' def modInverse(a, m): for x in range(1, m): if (((a%m) * (x%m)) % m == 1): return x return -1 # Driver Codea = 3m = 11 # Function callprint(modInverse(a, m)) # This code is contributed by Nikita Tiwari.",
"e": 26493,
"s": 26114,
"text": null
},
{
"code": "// C# program to find modular inverse// of a under modulo musing System; class GFG { // A naive method to find modulor // multiplicative inverse of 'a' // under modulo 'm' static int modInverse(int a, int m) { for (int x = 1; x < m; x++) if (((a%m) * (x%m)) % m == 1) return x; return 1; } // Driver Code public static void Main() { int a = 3, m = 11; // Function call Console.WriteLine(modInverse(a, m)); }} // This code is contributed by anuj_67.",
"e": 27051,
"s": 26493,
"text": null
},
{
"code": "<β
php// PHP program to find modular// inverse of a under modulo m // A naive method to find modulor// multiplicative inverse of// 'a' under modulo 'm'function modInverse( $a, $m){ for ($x = 1; $x < $m; $x++) if ((($a%$m) * ($x%$m)) % $m == 1) return $x;} // Driver Code $a = 3; $m = 11; // Function call echo modInverse($a, $m); // This code is contributed by anuj_67.β
>",
"e": 27465,
"s": 27051,
"text": null
},
{
"code": "<script> // Javascript program to find modular// inverse of a under modulo m // A naive method to find modulor// multiplicative inverse of// 'a' under modulo 'm'function modInverse(a, m){ for(let x = 1; x < m; x++) if (((a % m) * (x % m)) % m == 1) return x;} // Driver Codelet a = 3;let m = 11; // Function calldocument.write(modInverse(a, m)); // This code is contributed by _saurabh_jaiswal. </script>",
"e": 27891,
"s": 27465,
"text": null
},
{
"code": null,
"e": 27893,
"s": 27891,
"text": "4"
},
{
"code": null,
"e": 27915,
"s": 27893,
"text": "Time Complexity: O(m)"
},
{
"code": null,
"e": 27937,
"s": 27915,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 28134,
"s": 27937,
"text": "Method 2 ( Works when m and a are coprime or gcd(a,m)=1 ) The idea is to use Extended Euclidean algorithms that takes two integers βaβ and βbβ, finds their gcd and also find βxβ and βyβ such that "
},
{
"code": null,
"e": 28154,
"s": 28134,
"text": "ax + by = gcd(a, b)"
},
{
"code": null,
"e": 28313,
"s": 28154,
"text": "To find multiplicative inverse of βaβ under βmβ, we put b = m in above formula. Since we know that a and m are relatively prime, we can put value of gcd as 1."
},
{
"code": null,
"e": 28325,
"s": 28313,
"text": "ax + my = 1"
},
{
"code": null,
"e": 28367,
"s": 28325,
"text": "If we take modulo m on both sides, we get"
},
{
"code": null,
"e": 28387,
"s": 28367,
"text": "ax + my β
1 (mod m)"
},
{
"code": null,
"e": 28483,
"s": 28387,
"text": "We can remove the second term on left side as βmy (mod m)β would always be 0 for an integer y. "
},
{
"code": null,
"e": 28499,
"s": 28483,
"text": "ax β
1 (mod m)"
},
{
"code": null,
"e": 28596,
"s": 28499,
"text": "So the βxβ that we can find using Extended Euclid Algorithm is the multiplicative inverse of βaβ"
},
{
"code": null,
"e": 28650,
"s": 28596,
"text": "Below is the implementation of the above algorithm. "
},
{
"code": null,
"e": 28654,
"s": 28650,
"text": "C++"
},
{
"code": null,
"e": 28656,
"s": 28654,
"text": "C"
},
{
"code": null,
"e": 28660,
"s": 28656,
"text": "PHP"
},
{
"code": "// C++ program to find multiplicative modulo// inverse using Extended Euclid algorithm.#include <iostream>using namespace std; // Function for extended Euclidean Algorithmint gcdExtended(int a, int b, int* x, int* y); // Function to find modulo inverse of avoid modInverse(int a, int m){ int x, y; int g = gcdExtended(a, m, &x, &y); if (g != 1) cout << \"Inverse doesn't exist\"; else { // m is added to handle negative x int res = (x % m + m) % m; cout << \"Modular multiplicative inverse is \" << res; }} // Function for extended Euclidean Algorithmint gcdExtended(int a, int b, int* x, int* y){ // Base Case if (a == 0) { *x = 0, *y = 1; return b; } // To store results of recursive call int x1, y1; int gcd = gcdExtended(b % a, a, &x1, &y1); // Update x and y using results of recursive // call *x = y1 - (b / a) * x1; *y = x1; return gcd;} // Driver Codeint main(){ int a = 3, m = 11; // Function call modInverse(a, m); return 0;} // This code is contributed by khushboogoyal499",
"e": 29772,
"s": 28660,
"text": null
},
{
"code": "// C program to find multiplicative modulo inverse using// Extended Euclid algorithm.#include <stdio.h> // C function for extended Euclidean Algorithmint gcdExtended(int a, int b, int* x, int* y); // Function to find modulo inverse of avoid modInverse(int a, int m){ int x, y; int g = gcdExtended(a, m, &x, &y); if (g != 1) printf(\"Inverse doesn't exist\"); else { // m is added to handle negative x int res = (x % m + m) % m; printf(\"Modular multiplicative inverse is %d\", res); }} // C function for extended Euclidean Algorithmint gcdExtended(int a, int b, int* x, int* y){ // Base Case if (a == 0) { *x = 0, *y = 1; return b; } int x1, y1; // To store results of recursive call int gcd = gcdExtended(b % a, a, &x1, &y1); // Update x and y using results of recursive // call *x = y1 - (b / a) * x1; *y = x1; return gcd;} // Driver Codeint main(){ int a = 3, m = 11; // Function call modInverse(a, m); return 0;}",
"e": 30796,
"s": 29772,
"text": null
},
{
"code": "<β
php// PHP program to find multiplicative modulo// inverse using Extended Euclid algorithm.// Function to find modulo inverse of afunction modInverse($a, $m){ $x = 0; $y = 0; $g = gcdExtended($a, $m, $x, $y); if ($g != 1) echo \"Inverse doesn't exist\"; else { // m is added to handle negative x $res = ($x % $m + $m) % $m; echo \"Modular multiplicative \" . \"inverse is \" . $res; }} // function for extended Euclidean Algorithmfunction gcdExtended($a, $b, &$x, &$y){ // Base Case if ($a == 0) { $x = 0; $y = 1; return $b; } $x1; $y1; // To store results of recursive call $gcd = gcdExtended($b%$a, $a, $x1, $y1); // Update x and y using results of // recursive call $x = $y1 - (int)($b/$a) * $x1; $y = $x1; return $gcd;} // Driver Code$a = 3;$m = 11; // Function callmodInverse($a, $m); // This code is contributed by chandan_jnuβ
>",
"e": 31753,
"s": 30796,
"text": null
},
{
"code": null,
"e": 31789,
"s": 31753,
"text": "Modular multiplicative inverse is 4"
},
{
"code": null,
"e": 31815,
"s": 31789,
"text": "Time Complexity: O(log m)"
},
{
"code": null,
"e": 31884,
"s": 31815,
"text": "Auxiliary Space: O(log m) because of the internal recursion stack."
},
{
"code": null,
"e": 31912,
"s": 31884,
"text": " Iterative Implementation: "
},
{
"code": null,
"e": 31916,
"s": 31912,
"text": "C++"
},
{
"code": null,
"e": 31918,
"s": 31916,
"text": "C"
},
{
"code": null,
"e": 31923,
"s": 31918,
"text": "Java"
},
{
"code": null,
"e": 31931,
"s": 31923,
"text": "Python3"
},
{
"code": null,
"e": 31934,
"s": 31931,
"text": "C#"
},
{
"code": null,
"e": 31938,
"s": 31934,
"text": "PHP"
},
{
"code": null,
"e": 31949,
"s": 31938,
"text": "Javascript"
},
{
"code": "// Iterative C++ program to find modular// inverse using extended Euclid algorithm#include <bits/stdc++.h>using namespace std; // Returns modulo inverse of a with respect// to m using extended Euclid Algorithm// Assumption: a and m are coprimes, i.e.,// gcd(a, m) = 1int modInverse(int a, int m){ int m0 = m; int y = 0, x = 1; if (m == 1) return 0; while (a > 1) { // q is quotient int q = a / m; int t = m; // m is remainder now, process same as // Euclid's algo m = a % m, a = t; t = y; // Update y and x y = x - q * y; x = t; } // Make x positive if (x < 0) x += m0; return x;} // Driver Codeint main(){ int a = 3, m = 11; // Function call cout << \"Modular multiplicative inverse is \"<< modInverse(a, m); return 0;}// this code is contributed by shivanisinghss2110",
"e": 32844,
"s": 31949,
"text": null
},
{
"code": "// Iterative C program to find modular// inverse using extended Euclid algorithm#include <stdio.h> // Returns modulo inverse of a with respect// to m using extended Euclid Algorithm// Assumption: a and m are coprimes, i.e.,// gcd(a, m) = 1int modInverse(int a, int m){ int m0 = m; int y = 0, x = 1; if (m == 1) return 0; while (a > 1) { // q is quotient int q = a / m; int t = m; // m is remainder now, process same as // Euclid's algo m = a % m, a = t; t = y; // Update y and x y = x - q * y; x = t; } // Make x positive if (x < 0) x += m0; return x;} // Driver Codeint main(){ int a = 3, m = 11; // Function call printf(\"Modular multiplicative inverse is %d\\n\", modInverse(a, m)); return 0;}",
"e": 33675,
"s": 32844,
"text": null
},
{
"code": "// Iterative Java program to find modular// inverse using extended Euclid algorithm class GFG { // Returns modulo inverse of a with // respect to m using extended Euclid // Algorithm Assumption: a and m are // coprimes, i.e., gcd(a, m) = 1 static int modInverse(int a, int m) { int m0 = m; int y = 0, x = 1; if (m == 1) return 0; while (a > 1) { // q is quotient int q = a / m; int t = m; // m is remainder now, process // same as Euclid's algo m = a % m; a = t; t = y; // Update x and y y = x - q * y; x = t; } // Make x positive if (x < 0) x += m0; return x; } // Driver code public static void main(String args[]) { int a = 3, m = 11; // Function call System.out.println(\"Modular multiplicative \" + \"inverse is \" + modInverse(a, m)); }} /*This code is contributed by Nikita Tiwari.*/",
"e": 34785,
"s": 33675,
"text": null
},
{
"code": "# Iterative Python 3 program to find# modular inverse using extended# Euclid algorithm # Returns modulo inverse of a with# respect to m using extended Euclid# Algorithm Assumption: a and m are# coprimes, i.e., gcd(a, m) = 1 def modInverse(a, m): m0 = m y = 0 x = 1 if (m == 1): return 0 while (a > 1): # q is quotient q = a // m t = m # m is remainder now, process # same as Euclid's algo m = a % m a = t t = y # Update x and y y = x - q * y x = t # Make x positive if (x < 0): x = x + m0 return x # Driver codea = 3m = 11 # Function callprint(\"Modular multiplicative inverse is\", modInverse(a, m)) # This code is contributed by Nikita tiwari.",
"e": 35559,
"s": 34785,
"text": null
},
{
"code": "// Iterative C# program to find modular// inverse using extended Euclid algorithmusing System;class GFG { // Returns modulo inverse of a with // respect to m using extended Euclid // Algorithm Assumption: a and m are // coprimes, i.e., gcd(a, m) = 1 static int modInverse(int a, int m) { int m0 = m; int y = 0, x = 1; if (m == 1) return 0; while (a > 1) { // q is quotient int q = a / m; int t = m; // m is remainder now, process // same as Euclid's algo m = a % m; a = t; t = y; // Update x and y y = x - q * y; x = t; } // Make x positive if (x < 0) x += m0; return x; } // Driver Code public static void Main() { int a = 3, m = 11; // Function call Console.WriteLine(\"Modular multiplicative \" + \"inverse is \" + modInverse(a, m)); }} // This code is contributed by anuj_67.",
"e": 36654,
"s": 35559,
"text": null
},
{
"code": "<β
php// Iterative PHP program to find modular// inverse using extended Euclid algorithm // Returns modulo inverse of a with respect// to m using extended Euclid Algorithm// Assumption: a and m are coprimes, i.e.,// gcd(a, m) = 1function modInverse($a, $m){ $m0 = $m; $y = 0; $x = 1; if ($m == 1) return 0; while ($a > 1) { // q is quotient $q = (int) ($a / $m); $t = $m; // m is remainder now, // process same as // Euclid's algo $m = $a % $m; $a = $t; $t = $y; // Update y and x $y = $x - $q * $y; $x = $t; } // Make x positive if ($x < 0) $x += $m0; return $x;} // Driver Code $a = 3; $m = 11; // Function call echo \"Modular multiplicative inverse is\\n\", modInverse($a, $m); // This code is contributed by Anuj_67β
>",
"e": 37559,
"s": 36654,
"text": null
},
{
"code": "<script> // Iterative Javascript program to find modular// inverse using extended Euclid algorithm // Returns modulo inverse of a with respect// to m using extended Euclid Algorithm// Assumption: a and m are coprimes, i.e.,// gcd(a, m) = 1function modInverse(a, m){ let m0 = m; let y = 0; let x = 1; if (m == 1) return 0; while (a > 1) { // q is quotient let q = parseInt(a / m); let t = m; // m is remainder now, // process same as // Euclid's algo m = a % m; a = t; t = y; // Update y and x y = x - q * y; x = t; } // Make x positive if (x < 0) x += m0; return x;} // Driver Codelet a = 3;let m = 11; // Function calldocument.write(`Modular multiplicative inverse is ${modInverse(a, m)}`); // This code is contributed by _saurabh_jaiswal </script>",
"e": 38456,
"s": 37559,
"text": null
},
{
"code": null,
"e": 38492,
"s": 38456,
"text": "Modular multiplicative inverse is 4"
},
{
"code": null,
"e": 38518,
"s": 38492,
"text": "Time Complexity: O(log m)"
},
{
"code": null,
"e": 38540,
"s": 38518,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 38666,
"s": 38540,
"text": " Method 3 (Works when m is prime) If we know m is prime, then we can also use Fermatsβs little theorem to find the inverse. "
},
{
"code": null,
"e": 38683,
"s": 38666,
"text": "am-1 β
1 (mod m)"
},
{
"code": null,
"e": 38727,
"s": 38683,
"text": "If we multiply both sides with a-1, we get "
},
{
"code": null,
"e": 38747,
"s": 38727,
"text": "a-1 β
a m-2 (mod m)"
},
{
"code": null,
"e": 38795,
"s": 38747,
"text": "Below is the implementation of the above idea. "
},
{
"code": null,
"e": 38799,
"s": 38795,
"text": "C++"
},
{
"code": null,
"e": 38804,
"s": 38799,
"text": "Java"
},
{
"code": null,
"e": 38812,
"s": 38804,
"text": "Python3"
},
{
"code": null,
"e": 38815,
"s": 38812,
"text": "C#"
},
{
"code": null,
"e": 38819,
"s": 38815,
"text": "PHP"
},
{
"code": null,
"e": 38830,
"s": 38819,
"text": "Javascript"
},
{
"code": "// C++ program to find modular inverse of a under modulo m// This program works only if m is prime.#include <iostream>using namespace std; // To find GCD of a and bint gcd(int a, int b); // To compute x raised to power y under modulo mint power(int x, unsigned int y, unsigned int m); // Function to find modular inverse of a under modulo m// Assumption: m is primevoid modInverse(int a, int m){ int g = gcd(a, m); if (g != 1) cout << \"Inverse doesn't exist\"; else { // If a and m are relatively prime, then modulo // inverse is a^(m-2) mode m cout << \"Modular multiplicative inverse is \" << power(a, m - 2, m); }} // To compute x^y under modulo mint power(int x, unsigned int y, unsigned int m){ if (y == 0) return 1; int p = power(x, y / 2, m) % m; p = (p * p) % m; return (y % 2 == 0) ? p : (x * p) % m;} // Function to return gcd of a and bint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Driver codeint main(){ int a = 3, m = 11; // Function call modInverse(a, m); return 0;}",
"e": 39934,
"s": 38830,
"text": null
},
{
"code": "// Java program to find modular// inverse of a under modulo m// This program works only if// m is prime.import java.io.*; class GFG { // Function to find modular inverse of a // under modulo m Assumption: m is prime static void modInverse(int a, int m) { int g = gcd(a, m); if (g != 1) System.out.println(\"Inverse doesn't exist\"); else { // If a and m are relatively prime, then modulo // inverse is a^(m-2) mode m System.out.println( \"Modular multiplicative inverse is \" + power(a, m - 2, m)); } } static int power(int x, int y, int m) { if (y == 0) return 1; int p = power(x, y / 2, m) % m; p = (int)((p * (long)p) % m); if (y % 2 == 0) return p; else return (int)((x * (long)p) % m); } // Function to return gcd of a and b static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // Driver Code public static void main(String args[]) { int a = 3, m = 11; // Function call modInverse(a, m); }} // This code is contributed by Nikita Tiwari.",
"e": 41183,
"s": 39934,
"text": null
},
{
"code": "# Python3 program to find modular# inverse of a under modulo m # This program works only if m is prime. # Function to find modular# inverse of a under modulo m# Assumption: m is prime def modInverse(a, m): g = gcd(a, m) if (g != 1): print(\"Inverse doesn't exist\") else: # If a and m are relatively prime, # then modulo inverse is a^(m-2) mode m print(\"Modular multiplicative inverse is \", power(a, m - 2, m)) # To compute x^y under modulo m def power(x, y, m): if (y == 0): return 1 p = power(x, y // 2, m) % m p = (p * p) % m if(y % 2 == 0): return p else: return ((x * p) % m) # Function to return gcd of a and b def gcd(a, b): if (a == 0): return b return gcd(b % a, a) # Driver Codea = 3m = 11 # Function callmodInverse(a, m) # This code is contributed by Nikita Tiwari.",
"e": 42070,
"s": 41183,
"text": null
},
{
"code": "// C# program to find modular// inverse of a under modulo m// This program works only if// m is prime.using System;class GFG { // Function to find modular // inverse of a under modulo // m Assumption: m is prime static void modInverse(int a, int m) { int g = gcd(a, m); if (g != 1) Console.Write(\"Inverse doesn't exist\"); else { // If a and m are relatively // prime, then modulo inverse // is a^(m-2) mode m Console.Write( \"Modular multiplicative inverse is \" + power(a, m - 2, m)); } } // To compute x^y under // modulo m static int power(int x, int y, int m) { if (y == 0) return 1; int p = power(x, y / 2, m) % m; p = (p * p) % m; if (y % 2 == 0) return p; else return (x * p) % m; } // Function to return // gcd of a and b static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // Driver Code public static void Main() { int a = 3, m = 11; // Function call modInverse(a, m); }} // This code is contributed by nitin mittal.",
"e": 43320,
"s": 42070,
"text": null
},
{
"code": "<β
php// PHP program to find modular// inverse of a under modulo m// This program works only if m// is prime. // Function to find modular inverse// of a under modulo m// Assumption: m is primefunction modInverse( $a, $m){ $g = gcd($a, $m); if ($g != 1) echo \"Inverse doesn't exist\"; else { // If a and m are relatively // prime, then modulo inverse // is a^(m-2) mode m echo \"Modular multiplicative inverse is \" , power($a, $m - 2, $m); }} // To compute x^y under modulo mfunction power( $x, $y, $m){ if ($y == 0) return 1; $p = power($x, $y / 2, $m) % $m; $p = ($p * $p) % $m; return ($y % 2 == 0)? $p : ($x * $p) % $m;} // Function to return gcd of a and bfunction gcd($a, $b){ if ($a == 0) return $b; return gcd($b % $a, $a);} // Driver Code$a = 3;$m = 11; // Function callmodInverse($a, $m); // This code is contributed by anuj_67.β
>",
"e": 44276,
"s": 43320,
"text": null
},
{
"code": "<script>// Javascript program to find modular inverse of a under modulo m// This program works only if m is prime. // Function to find modular inverse of a under modulo m// Assumption: m is primefunction modInverse(a, m){ let g = gcd(a, m); if (g != 1) document.write(\"Inverse doesn't exist\"); else { // If a and m are relatively prime, then modulo // inverse is a^(m-2) mode m document.write(\"Modular multiplicative inverse is \" + power(a, m - 2, m)); }} // To compute x^y under modulo mfunction power(x, y, m){ if (y == 0) return 1; let p = power(x, parseInt(y / 2), m) % m; p = (p * p) % m; return (y % 2 == 0) ? p : (x * p) % m;} // Function to return gcd of a and bfunction gcd(a, b){ if (a == 0) return b; return gcd(b % a, a);} // Driver codelet a = 3, m = 11; // Function callmodInverse(a, m); // This code is contributed by subham348.</script>",
"e": 45217,
"s": 44276,
"text": null
},
{
"code": null,
"e": 45253,
"s": 45217,
"text": "Modular multiplicative inverse is 4"
},
{
"code": null,
"e": 45279,
"s": 45253,
"text": "Time Complexity: O(log m)"
},
{
"code": null,
"e": 45349,
"s": 45279,
"text": "Auxiliary Space: O(log m) because of the internal recursion stack."
},
{
"code": null,
"e": 45584,
"s": 45349,
"text": "We have discussed three methods to find multiplicative inverse modulo m. 1) Naive Method, O(m) 2) Extended Eulerβs GCD algorithm, O(Log m) [Works when a and m are coprime] 3) Fermatβs Little theorem, O(Log m) [Works when βmβ is prime]"
},
{
"code": null,
"e": 45706,
"s": 45584,
"text": "Applications: Computation of the modular multiplicative inverse is an essential step in RSA public-key encryption method."
},
{
"code": null,
"e": 45978,
"s": 45706,
"text": "References: https://en.wikipedia.org/wiki/Modular_multiplicative_inverse http://e-maxx.ru/algo/reverse_elementThis article is contributed by Ankur. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 45983,
"s": 45978,
"text": "vt_m"
},
{
"code": null,
"e": 45996,
"s": 45983,
"text": "nitin mittal"
},
{
"code": null,
"e": 46010,
"s": 45996,
"text": "Chandan_Kumar"
},
{
"code": null,
"e": 46021,
"s": 46010,
"text": "raunak_m17"
},
{
"code": null,
"e": 46033,
"s": 46021,
"text": "olivebadger"
},
{
"code": null,
"e": 46042,
"s": 46033,
"text": "_emperor"
},
{
"code": null,
"e": 46056,
"s": 46042,
"text": "derekallen105"
},
{
"code": null,
"e": 46066,
"s": 46056,
"text": "oshosmart"
},
{
"code": null,
"e": 46079,
"s": 46066,
"text": "sudhanshu751"
},
{
"code": null,
"e": 46091,
"s": 46079,
"text": "nitin_19520"
},
{
"code": null,
"e": 46106,
"s": 46091,
"text": "nagulansridhar"
},
{
"code": null,
"e": 46123,
"s": 46106,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 46133,
"s": 46123,
"text": "subham348"
},
{
"code": null,
"e": 46150,
"s": 46133,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 46169,
"s": 46150,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 46181,
"s": 46169,
"text": "anikakapoor"
},
{
"code": null,
"e": 46193,
"s": 46181,
"text": "prophet1999"
},
{
"code": null,
"e": 46212,
"s": 46193,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 46226,
"s": 46212,
"text": "number-theory"
},
{
"code": null,
"e": 46239,
"s": 46226,
"text": "Mathematical"
},
{
"code": null,
"e": 46253,
"s": 46239,
"text": "number-theory"
},
{
"code": null,
"e": 46266,
"s": 46253,
"text": "Mathematical"
},
{
"code": null,
"e": 46285,
"s": 46266,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 46383,
"s": 46285,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 46392,
"s": 46383,
"text": "Comments"
},
{
"code": null,
"e": 46405,
"s": 46392,
"text": "Old Comments"
},
{
"code": null,
"e": 46448,
"s": 46405,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 46493,
"s": 46448,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 46520,
"s": 46493,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 46569,
"s": 46520,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 46612,
"s": 46569,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 46646,
"s": 46612,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 46683,
"s": 46646,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 46704,
"s": 46683,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 46757,
"s": 46704,
"text": "Find minimum number of coins that make a given value"
}
] |
Clearing input buffer in C/C++
|
The function fflush(stdin) is used to flush or clear the output buffer of the stream. When it is used after the scanf(), it flushes the input buffer also. It returns zero if successful, otherwise returns EOF and feof error indicator is set.
Here is the syntax of fflush(stdin) to clear the input buffer in C language,
int fflush(FILE *stream);
Here is an example of fflush(stdin) to clear the input buffer in C language,
Live Demo
#include <stdio.h>
#include<stdlib.h>
int main() {
char s[20];
printf("Enter the string : \n", s);
scanf("%s\n", s);
printf("The entered string : %s", s);
fflush(stdin);
return 0;
}
Here is the output
Enter the string : helloworld
The entered string : helloworld
|
[
{
"code": null,
"e": 1303,
"s": 1062,
"text": "The function fflush(stdin) is used to flush or clear the output buffer of the stream. When it is used after the scanf(), it flushes the input buffer also. It returns zero if successful, otherwise returns EOF and feof error indicator is set."
},
{
"code": null,
"e": 1380,
"s": 1303,
"text": "Here is the syntax of fflush(stdin) to clear the input buffer in C language,"
},
{
"code": null,
"e": 1406,
"s": 1380,
"text": "int fflush(FILE *stream);"
},
{
"code": null,
"e": 1483,
"s": 1406,
"text": "Here is an example of fflush(stdin) to clear the input buffer in C language,"
},
{
"code": null,
"e": 1494,
"s": 1483,
"text": " Live Demo"
},
{
"code": null,
"e": 1702,
"s": 1494,
"text": "#include <stdio.h>\n#include<stdlib.h>\n\nint main() {\n char s[20];\n\n printf(\"Enter the string : \\n\", s);\n scanf(\"%s\\n\", s);\n printf(\"The entered string : %s\", s);\n \n fflush(stdin);\n return 0;\n}"
},
{
"code": null,
"e": 1721,
"s": 1702,
"text": "Here is the output"
},
{
"code": null,
"e": 1783,
"s": 1721,
"text": "Enter the string : helloworld\nThe entered string : helloworld"
}
] |
Composition vs Aggregation in C#
|
Under Composition, if the parent object is deleted, then the child object also loses its status. Composition is a special type of Aggregation and gives a part-of relationship.
For example, A Car has an engine. If the car is destroyed, the engine is destroyed as well.
public class Engine {
. . .
}
public class Car {
Engine eng = new Engine();
.......
}
Aggregation is a directional relation between objects in C#. It is the relationship between objects.
For example, Employee and Address
An Employee is associated with a single Department, whereas a Department can have more than one employee. Let us see an example of Employee and Address.
public class Address {
. . .
}
public class Employee {
private Address addr;
public Employee (Address addr) {
this.addr = addr;
}
. . .
}
|
[
{
"code": null,
"e": 1238,
"s": 1062,
"text": "Under Composition, if the parent object is deleted, then the child object also loses its status. Composition is a special type of Aggregation and gives a part-of relationship."
},
{
"code": null,
"e": 1330,
"s": 1238,
"text": "For example, A Car has an engine. If the car is destroyed, the engine is destroyed as well."
},
{
"code": null,
"e": 1425,
"s": 1330,
"text": "public class Engine {\n . . .\n}\npublic class Car {\n Engine eng = new Engine();\n .......\n}"
},
{
"code": null,
"e": 1526,
"s": 1425,
"text": "Aggregation is a directional relation between objects in C#. It is the relationship between objects."
},
{
"code": null,
"e": 1560,
"s": 1526,
"text": "For example, Employee and Address"
},
{
"code": null,
"e": 1713,
"s": 1560,
"text": "An Employee is associated with a single Department, whereas a Department can have more than one employee. Let us see an example of Employee and Address."
},
{
"code": null,
"e": 1872,
"s": 1713,
"text": "public class Address {\n . . .\n}\npublic class Employee {\n private Address addr;\n public Employee (Address addr) {\n this.addr = addr;\n }\n . . .\n}"
}
] |
Detecting faces with Python and OpenCV Face Detection Neural Network | by Himasha Abeywickrama | Towards Data Science
|
Now, we all know that Artificial Intelligence is becoming more and more real and its filling the gaps between capabilities of humans and machines day by day. Itβs not just a fancy word anymore. It has had many advancements over the years in many fields and one of such areas is the domain of Computer Vision.
When it comes to Computer Vision, itβs goal is to train the machines to view and recognize the world as humans do. And also gather knowledge large enough to perform Image and video recognition, Image Analysis and Classification, Media Recreation, Natural Language Processing and etc.
The advancement in Computer Vision has been implemented and perfected gradually with time, primarily over one particular algorithm, a Convolutional Neural Network (CNNs or ConvNets), which is a special type of feed-forward network which is used mostly to analyze visual imagery. Convolutional Neural Networks are very similar to ordinary neural networks but are made up of neurons that have learnable weights and biases.
ConvNets perform better than the other deep neural network architectures because of their unique process. Instead of looking at the image one pixel at a time, ConvNets group several pixels together so they can understand a temporal pattern. In another way, ConvNets can βseeβ group of pixels forming a line or curve. Because of the deep nature of Deep Neural Networks, in the next level they will see not the group of pixels, but groups of lines and curves forming some shapes. And so on until they form a complete picture.
However, CNNs require large datasets and a lot of computational time to train. Some could take even 2β3 weeks across multiple GPUs. There are many things you need to learn if you want to understand CNNs, from the very basic things, like a kernel, pooling layers, and so on. But nowadays, you can just dive and use many open source projects for this technology.
This is actually true because of the technology called Transfer Learning. Transfer Learning is a very practical and powerful technique which utilizes a trained model instead of training the network from scratch. Transfer learning utilizes a trained model on a different dataset, and adapts it to the problem that weβre trying to solve.
In order to build our application, we will follow the transfer learning technique and use a trained model, which was trained using the Caffe framework, a deep learning framework made with expression, speed and modularity in mind. Caffe comes with a repository that is used by researchers and machine learning practitioners to share their trained models. This library is called Model Zoo. You can read all about it by going through their documentation.
The python code, trained caffe model and the prototxt file, which includes the text description of the network and some example images to use with our application are available in the github repository if you want to take a look.
In our application, we will be using the following libraries :
OpenCV, which supports a lot of algorithms related to Computer Vision and Machine Learning and not to mention itβs built in Deep Neural Network which we will be using in our application.Numpy, which is a package used for scientific computing with python.OS, which provides a portable way of using operating system dependent functionality
OpenCV, which supports a lot of algorithms related to Computer Vision and Machine Learning and not to mention itβs built in Deep Neural Network which we will be using in our application.
Numpy, which is a package used for scientific computing with python.
OS, which provides a portable way of using operating system dependent functionality
So, in order to install them, you can run the following commands in a Command Prompt window. pip install opencv-python to install OpenCV, pip install numpy to install Numpy and you donβt have to specifically install the OS library as it comes with your Python installation, but you still must import it.
First, letβs create a file called faceDetection.py and import our libraries.
#import librariesimport os import cv2import numpy
Now, we will get the absolute path of the working directory, where we will be putting all our images,
#import librariesimport os import cv2import numpy#get the absolute path of the working directorydir_path = os.path.dirname(os.path.realpath(__file__))
Now, we will create a folder called βOutputβ to place our final images if it doesnβt already exist.
#import librariesimport os import cv2import numpy#get the absolute path of the working directorydir_path = os.path.dirname(os.path.realpath(__file__))#create the Output folder if it doesn't already existif not os.path.exists('Output'): os.makedirs('Output')
After that, we will load our pre-trained model and the prototxt file from the current working directory.
#import librariesimport os import cv2import numpy#get the absolute path of the working directorydir_path = os.path.dirname(os.path.realpath(__file__))#create the Output folder if it doesn't already existif not os.path.exists('Output'): os.makedirs('Output')#Reads the network model stored in Caffe framework's format.model = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'weights.caffemodel')
Then, we will loop through the files available in the current folder to check if there are files with the extensions, .png, .jpg and .jpeg.
#import librariesimport os import cv2import numpy#get the absolute path of the working directorydir_path = os.path.dirname(os.path.realpath(__file__))#create the Output folder if it doesn't already existif not os.path.exists('Output'): os.makedirs('Output')#Reads the network model stored in Caffe framework's format.model = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'weights.caffemodel')for file in os.listdir(dir_path): #split the file name and the extension into two variales filename, file_extension = os.path.splitext(file) #check if the file extension is .png,.jpeg or .jpg if (file_extension in ['.png','.jpg','.jpeg']):
If an image with the above extensions is found, we will read the image using OpenCV and get itβs height and width by accessing the image.shape tuple and taking the first two elements to draw the rectangle around the face later.
#import librariesimport os import cv2import numpy#get the absolute path of the working directorydir_path = os.path.dirname(os.path.realpath(__file__))#create the Output folder if it doesn't already existif not os.path.exists('Output'): os.makedirs('Output')#Reads the network model stored in Caffe framework's format.model = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'weights.caffemodel')for file in os.listdir(dir_path): #split the file name and the extension into two variales filename, file_extension = os.path.splitext(file) #check if the file extension is .png,.jpeg or .jpg if (file_extension in ['.png','.jpg','.jpeg']): #read the image using cv2 image = cv2.imread(file) #accessing the image.shape tuple and taking the elements (h, w) = image.shape[:2]
And then, we will get our blob using the cv2.dnn.blobFromImage function by giving the image as the input. With cv2.dnn.blobFromImage function we resize image to 300x300 dimension, 1.0 is scale factor and here we use default value so there is no scaling, after that is spatial size that Convolutional Neural Network expects, last values are mean subtraction values in tuple and they are RGB means, and at the end, function returns a βblobβ which is our input image after resizing, mean subtraction and normalizing.
After that, we will input the blob into the model and get the detections using model.foreward function.
#import librariesimport os import cv2import numpy#get the absolute path of the working directorydir_path = os.path.dirname(os.path.realpath(__file__))#create the Output folder if it doesn't already existif not os.path.exists('Output'): os.makedirs('Output')#Reads the network model stored in Caffe framework's format.model = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'weights.caffemodel')for file in os.listdir(dir_path): #split the file name and the extension into two variales filename, file_extension = os.path.splitext(file) #check if the file extension is .png,.jpeg or .jpg if (file_extension in ['.png','.jpg','.jpeg']): #read the image using cv2 image = cv2.imread(file) #accessing the image.shape tuple and taking the elements (h, w) = image.shape[:2] #get our blob which is our input image blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0)) #input the blob into the model and get back the detections model.setInput(blob) detections = model.forward()
Then, we will iterate through all of the faces detected and extract their start and end points. We will extract confidence and compare it to the confidence threshold so we can filter out detections that are weak. If the algorithm is more than 16.5% confident that the detection is a face, we will show a green rectangle on it.
#import librariesimport os import cv2import numpy#get the absolute path of the working directorydir_path = os.path.dirname(os.path.realpath(__file__))#create the Output folder if it doesn't already existif not os.path.exists('Output'): os.makedirs('Output')#Reads the network model stored in Caffe framework's format.model = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'weights.caffemodel')for file in os.listdir(dir_path): #split the file name and the extension into two variales filename, file_extension = os.path.splitext(file) #check if the file extension is .png,.jpeg or .jpg if (file_extension in ['.png','.jpg','.jpeg']): #read the image using cv2 image = cv2.imread(file) #accessing the image.shape tuple and taking the elements (h, w) = image.shape[:2] #get our blob which is our input image blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0)) #input the blob into the model and get back the detections model.setInput(blob) detections = model.forward() #Iterate over all of the faces detected and extract their start and end points count = 0 for i in range(0, detections.shape[2]): box = detections[0, 0, i, 3:7] * numpy.array([w, h, w, h]) (startX, startY, endX, endY) = box.astype("int") confidence = detections[0, 0, i, 2] #if the algorithm is more than 16.5% confident that the detection is a face, show a rectangle around it if (confidence > 0.165): cv2.rectangle(image, (startX, startY), (endX, endY), (0, 255, 0), 2) count = count + 1
Finally, we will save the output image in the Output folder we created and print out a success message to let the user know that itβs done.
#import librariesimport os import cv2import numpy#get the absolute path of the working directorydir_path = os.path.dirname(os.path.realpath(__file__))#create the Output folder if it doesn't already existif not os.path.exists('Output'): os.makedirs('Output')#Reads the network model stored in Caffe framework's format.model = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'weights.caffemodel')for file in os.listdir(dir_path): #split the file name and the extension into two variales filename, file_extension = os.path.splitext(file)#check if the file extension is .png,.jpeg or .jpg if (file_extension in ['.png','.jpg','.jpeg']): #read the image using cv2 image = cv2.imread(file)#accessing the image.shape tuple and taking the elements (h, w) = image.shape[:2]#get our blob which is our input image blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0))#input the blob into the model and get back the detections model.setInput(blob) detections = model.forward() #Iterate over all of the faces detected and extract their start and end points count = 0 for i in range(0, detections.shape[2]): box = detections[0, 0, i, 3:7] * numpy.array([w, h, w, h]) (startX, startY, endX, endY) = box.astype("int")confidence = detections[0, 0, i, 2] #if the algorithm is more than 16.5% confident that the detection is a face, show a rectangle around it if (confidence > 0.165): cv2.rectangle(image, (startX, startY), (endX, endY), (0, 255, 0), 2) count = count + 1 #save the modified image to the Output folder cv2.imwrite('Output/' + file, image) #print out a success message print("Face detection complete for image "+ file + " ("+ str(count) +") faces found!")
I hope you enjoyed the results! Now, you can always play around with the code a little bit to get an idea about what each and every function does. OpenCV provides a great documentation and tutorials if you wanna read and get more information too.
In this article, we walked through,
The concept of Convolutional Neural Networks and how we can save lot of time and effort with Transfer Learning and pre-trained models.Caffe models and how we are going to use a pre-trained Caffe model to implement our application.installing required libraries and setting up the environment.
The concept of Convolutional Neural Networks and how we can save lot of time and effort with Transfer Learning and pre-trained models.
Caffe models and how we are going to use a pre-trained Caffe model to implement our application.
installing required libraries and setting up the environment.
And finally, we implemented a python program which can detect using an image.
If you have any questions, please feel free to leave a comment below. Thanks!
|
[
{
"code": null,
"e": 481,
"s": 172,
"text": "Now, we all know that Artificial Intelligence is becoming more and more real and its filling the gaps between capabilities of humans and machines day by day. Itβs not just a fancy word anymore. It has had many advancements over the years in many fields and one of such areas is the domain of Computer Vision."
},
{
"code": null,
"e": 765,
"s": 481,
"text": "When it comes to Computer Vision, itβs goal is to train the machines to view and recognize the world as humans do. And also gather knowledge large enough to perform Image and video recognition, Image Analysis and Classification, Media Recreation, Natural Language Processing and etc."
},
{
"code": null,
"e": 1186,
"s": 765,
"text": "The advancement in Computer Vision has been implemented and perfected gradually with time, primarily over one particular algorithm, a Convolutional Neural Network (CNNs or ConvNets), which is a special type of feed-forward network which is used mostly to analyze visual imagery. Convolutional Neural Networks are very similar to ordinary neural networks but are made up of neurons that have learnable weights and biases."
},
{
"code": null,
"e": 1710,
"s": 1186,
"text": "ConvNets perform better than the other deep neural network architectures because of their unique process. Instead of looking at the image one pixel at a time, ConvNets group several pixels together so they can understand a temporal pattern. In another way, ConvNets can βseeβ group of pixels forming a line or curve. Because of the deep nature of Deep Neural Networks, in the next level they will see not the group of pixels, but groups of lines and curves forming some shapes. And so on until they form a complete picture."
},
{
"code": null,
"e": 2071,
"s": 1710,
"text": "However, CNNs require large datasets and a lot of computational time to train. Some could take even 2β3 weeks across multiple GPUs. There are many things you need to learn if you want to understand CNNs, from the very basic things, like a kernel, pooling layers, and so on. But nowadays, you can just dive and use many open source projects for this technology."
},
{
"code": null,
"e": 2407,
"s": 2071,
"text": "This is actually true because of the technology called Transfer Learning. Transfer Learning is a very practical and powerful technique which utilizes a trained model instead of training the network from scratch. Transfer learning utilizes a trained model on a different dataset, and adapts it to the problem that weβre trying to solve."
},
{
"code": null,
"e": 2859,
"s": 2407,
"text": "In order to build our application, we will follow the transfer learning technique and use a trained model, which was trained using the Caffe framework, a deep learning framework made with expression, speed and modularity in mind. Caffe comes with a repository that is used by researchers and machine learning practitioners to share their trained models. This library is called Model Zoo. You can read all about it by going through their documentation."
},
{
"code": null,
"e": 3089,
"s": 2859,
"text": "The python code, trained caffe model and the prototxt file, which includes the text description of the network and some example images to use with our application are available in the github repository if you want to take a look."
},
{
"code": null,
"e": 3152,
"s": 3089,
"text": "In our application, we will be using the following libraries :"
},
{
"code": null,
"e": 3490,
"s": 3152,
"text": "OpenCV, which supports a lot of algorithms related to Computer Vision and Machine Learning and not to mention itβs built in Deep Neural Network which we will be using in our application.Numpy, which is a package used for scientific computing with python.OS, which provides a portable way of using operating system dependent functionality"
},
{
"code": null,
"e": 3677,
"s": 3490,
"text": "OpenCV, which supports a lot of algorithms related to Computer Vision and Machine Learning and not to mention itβs built in Deep Neural Network which we will be using in our application."
},
{
"code": null,
"e": 3746,
"s": 3677,
"text": "Numpy, which is a package used for scientific computing with python."
},
{
"code": null,
"e": 3830,
"s": 3746,
"text": "OS, which provides a portable way of using operating system dependent functionality"
},
{
"code": null,
"e": 4134,
"s": 3830,
"text": "So, in order to install them, you can run the following commands in a Command Prompt window. pip install opencv-python to install OpenCV, pip install numpy to install Numpy and you donβt have to specifically install the OS library as it comes with your Python installation, but you still must import it."
},
{
"code": null,
"e": 4211,
"s": 4134,
"text": "First, letβs create a file called faceDetection.py and import our libraries."
},
{
"code": null,
"e": 4263,
"s": 4211,
"text": "#import librariesimport os import cv2import numpy"
},
{
"code": null,
"e": 4365,
"s": 4263,
"text": "Now, we will get the absolute path of the working directory, where we will be putting all our images,"
},
{
"code": null,
"e": 4518,
"s": 4365,
"text": "#import librariesimport os import cv2import numpy#get the absolute path of the working directorydir_path = os.path.dirname(os.path.realpath(__file__))"
},
{
"code": null,
"e": 4618,
"s": 4518,
"text": "Now, we will create a folder called βOutputβ to place our final images if it doesnβt already exist."
},
{
"code": null,
"e": 4880,
"s": 4618,
"text": "#import librariesimport os import cv2import numpy#get the absolute path of the working directorydir_path = os.path.dirname(os.path.realpath(__file__))#create the Output folder if it doesn't already existif not os.path.exists('Output'): os.makedirs('Output')"
},
{
"code": null,
"e": 4985,
"s": 4880,
"text": "After that, we will load our pre-trained model and the prototxt file from the current working directory."
},
{
"code": null,
"e": 5380,
"s": 4985,
"text": "#import librariesimport os import cv2import numpy#get the absolute path of the working directorydir_path = os.path.dirname(os.path.realpath(__file__))#create the Output folder if it doesn't already existif not os.path.exists('Output'): os.makedirs('Output')#Reads the network model stored in Caffe framework's format.model = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'weights.caffemodel')"
},
{
"code": null,
"e": 5520,
"s": 5380,
"text": "Then, we will loop through the files available in the current folder to check if there are files with the extensions, .png, .jpg and .jpeg."
},
{
"code": null,
"e": 6159,
"s": 5520,
"text": "#import librariesimport os import cv2import numpy#get the absolute path of the working directorydir_path = os.path.dirname(os.path.realpath(__file__))#create the Output folder if it doesn't already existif not os.path.exists('Output'): os.makedirs('Output')#Reads the network model stored in Caffe framework's format.model = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'weights.caffemodel')for file in os.listdir(dir_path): #split the file name and the extension into two variales filename, file_extension = os.path.splitext(file) #check if the file extension is .png,.jpeg or .jpg if (file_extension in ['.png','.jpg','.jpeg']):"
},
{
"code": null,
"e": 6387,
"s": 6159,
"text": "If an image with the above extensions is found, we will read the image using OpenCV and get itβs height and width by accessing the image.shape tuple and taking the first two elements to draw the rectangle around the face later."
},
{
"code": null,
"e": 7170,
"s": 6387,
"text": "#import librariesimport os import cv2import numpy#get the absolute path of the working directorydir_path = os.path.dirname(os.path.realpath(__file__))#create the Output folder if it doesn't already existif not os.path.exists('Output'): os.makedirs('Output')#Reads the network model stored in Caffe framework's format.model = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'weights.caffemodel')for file in os.listdir(dir_path): #split the file name and the extension into two variales filename, file_extension = os.path.splitext(file) #check if the file extension is .png,.jpeg or .jpg if (file_extension in ['.png','.jpg','.jpeg']): #read the image using cv2 image = cv2.imread(file) #accessing the image.shape tuple and taking the elements (h, w) = image.shape[:2]"
},
{
"code": null,
"e": 7684,
"s": 7170,
"text": "And then, we will get our blob using the cv2.dnn.blobFromImage function by giving the image as the input. With cv2.dnn.blobFromImage function we resize image to 300x300 dimension, 1.0 is scale factor and here we use default value so there is no scaling, after that is spatial size that Convolutional Neural Network expects, last values are mean subtraction values in tuple and they are RGB means, and at the end, function returns a βblobβ which is our input image after resizing, mean subtraction and normalizing."
},
{
"code": null,
"e": 7788,
"s": 7684,
"text": "After that, we will input the blob into the model and get the detections using model.foreward function."
},
{
"code": null,
"e": 8837,
"s": 7788,
"text": "#import librariesimport os import cv2import numpy#get the absolute path of the working directorydir_path = os.path.dirname(os.path.realpath(__file__))#create the Output folder if it doesn't already existif not os.path.exists('Output'): os.makedirs('Output')#Reads the network model stored in Caffe framework's format.model = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'weights.caffemodel')for file in os.listdir(dir_path): #split the file name and the extension into two variales filename, file_extension = os.path.splitext(file) #check if the file extension is .png,.jpeg or .jpg if (file_extension in ['.png','.jpg','.jpeg']): #read the image using cv2 image = cv2.imread(file) #accessing the image.shape tuple and taking the elements (h, w) = image.shape[:2] #get our blob which is our input image blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0)) #input the blob into the model and get back the detections model.setInput(blob) detections = model.forward()"
},
{
"code": null,
"e": 9164,
"s": 8837,
"text": "Then, we will iterate through all of the faces detected and extract their start and end points. We will extract confidence and compare it to the confidence threshold so we can filter out detections that are weak. If the algorithm is more than 16.5% confident that the detection is a face, we will show a green rectangle on it."
},
{
"code": null,
"e": 10755,
"s": 9164,
"text": "#import librariesimport os import cv2import numpy#get the absolute path of the working directorydir_path = os.path.dirname(os.path.realpath(__file__))#create the Output folder if it doesn't already existif not os.path.exists('Output'): os.makedirs('Output')#Reads the network model stored in Caffe framework's format.model = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'weights.caffemodel')for file in os.listdir(dir_path): #split the file name and the extension into two variales filename, file_extension = os.path.splitext(file) #check if the file extension is .png,.jpeg or .jpg if (file_extension in ['.png','.jpg','.jpeg']): #read the image using cv2 image = cv2.imread(file) #accessing the image.shape tuple and taking the elements (h, w) = image.shape[:2] #get our blob which is our input image blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0)) #input the blob into the model and get back the detections model.setInput(blob) detections = model.forward() #Iterate over all of the faces detected and extract their start and end points count = 0 for i in range(0, detections.shape[2]): box = detections[0, 0, i, 3:7] * numpy.array([w, h, w, h]) (startX, startY, endX, endY) = box.astype(\"int\") confidence = detections[0, 0, i, 2] #if the algorithm is more than 16.5% confident that the detection is a face, show a rectangle around it if (confidence > 0.165): cv2.rectangle(image, (startX, startY), (endX, endY), (0, 255, 0), 2) count = count + 1"
},
{
"code": null,
"e": 10895,
"s": 10755,
"text": "Finally, we will save the output image in the Output folder we created and print out a success message to let the user know that itβs done."
},
{
"code": null,
"e": 12677,
"s": 10895,
"text": "#import librariesimport os import cv2import numpy#get the absolute path of the working directorydir_path = os.path.dirname(os.path.realpath(__file__))#create the Output folder if it doesn't already existif not os.path.exists('Output'): os.makedirs('Output')#Reads the network model stored in Caffe framework's format.model = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'weights.caffemodel')for file in os.listdir(dir_path): #split the file name and the extension into two variales filename, file_extension = os.path.splitext(file)#check if the file extension is .png,.jpeg or .jpg if (file_extension in ['.png','.jpg','.jpeg']): #read the image using cv2 image = cv2.imread(file)#accessing the image.shape tuple and taking the elements (h, w) = image.shape[:2]#get our blob which is our input image blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0))#input the blob into the model and get back the detections model.setInput(blob) detections = model.forward() #Iterate over all of the faces detected and extract their start and end points count = 0 for i in range(0, detections.shape[2]): box = detections[0, 0, i, 3:7] * numpy.array([w, h, w, h]) (startX, startY, endX, endY) = box.astype(\"int\")confidence = detections[0, 0, i, 2] #if the algorithm is more than 16.5% confident that the detection is a face, show a rectangle around it if (confidence > 0.165): cv2.rectangle(image, (startX, startY), (endX, endY), (0, 255, 0), 2) count = count + 1 #save the modified image to the Output folder cv2.imwrite('Output/' + file, image) #print out a success message print(\"Face detection complete for image \"+ file + \" (\"+ str(count) +\") faces found!\")"
},
{
"code": null,
"e": 12924,
"s": 12677,
"text": "I hope you enjoyed the results! Now, you can always play around with the code a little bit to get an idea about what each and every function does. OpenCV provides a great documentation and tutorials if you wanna read and get more information too."
},
{
"code": null,
"e": 12960,
"s": 12924,
"text": "In this article, we walked through,"
},
{
"code": null,
"e": 13252,
"s": 12960,
"text": "The concept of Convolutional Neural Networks and how we can save lot of time and effort with Transfer Learning and pre-trained models.Caffe models and how we are going to use a pre-trained Caffe model to implement our application.installing required libraries and setting up the environment."
},
{
"code": null,
"e": 13387,
"s": 13252,
"text": "The concept of Convolutional Neural Networks and how we can save lot of time and effort with Transfer Learning and pre-trained models."
},
{
"code": null,
"e": 13484,
"s": 13387,
"text": "Caffe models and how we are going to use a pre-trained Caffe model to implement our application."
},
{
"code": null,
"e": 13546,
"s": 13484,
"text": "installing required libraries and setting up the environment."
},
{
"code": null,
"e": 13624,
"s": 13546,
"text": "And finally, we implemented a python program which can detect using an image."
}
] |
Flutter - DevTools - GeeksforGeeks
|
15 Jan, 2021
DevTools is a tooling suite for Flutter and Dart developers consisting of layout inspection tools, performance tools, memory tools basically all the debugging tools that you need to be an efficient and effective Flutter developer bundled into a single web suite.
The Flutter DevTools can be used to perform a number of operations. Some of them are listed below:
UI inspection.App state inspection.Diagnose UI junk performance.Diagnose issues with flutter apps.DevTools use for CPU profiling.Network profiling for an app.Source-level debugging of an app.Debug memory issues in a Flutter or Dart or command-line app.View general log and diagnostics information of an app.Analyze your code and app size of the flutter app.
UI inspection.
App state inspection.
Diagnose UI junk performance.
Diagnose issues with flutter apps.
DevTools use for CPU profiling.
Network profiling for an app.
Source-level debugging of an app.
Debug memory issues in a Flutter or Dart or command-line app.
View general log and diagnostics information of an app.
Analyze your code and app size of the flutter app.
1. Install Flutter DevTool in Android Studio
Follow the below steps to install DevTools in your Android Studio:
Step 1: Install the Flutter plugin in Android Studio, if you donβt already have it installed. This can be done using the normal Plugins page in the Android Studio settings. Once settings->plug-ins page is open, you can search flutter in the marketplace and install the plugin.
Step 2: You first run a Flutter app. Ensuring that you have a device connected to the project, and clicking the Run or Debug toolbar buttons.
Step 3: Launch DevTools from the toolbar/menu in your flutter project. Once an app is running successfully, start DevTools implementing the following instruction one by one:
Open DevTools toolbar action from Run view.DevTools toolbar action visible in the Debug view. (if debugging)DevTools action from the More Actions menu in Inspector view in your flutter project.
Open DevTools toolbar action from Run view.
DevTools toolbar action visible in the Debug view. (if debugging)
DevTools action from the More Actions menu in Inspector view in your flutter project.
2. Installing DevTools from VS Code
Follow the below steps to install DevTools from VS Code:
Step 1: To use the DevTools from VS Code firstly install the Dart extension also you need to install the Flutter extension for debugging flutter applications.
Step 2: Launch an application to debug your application. Start debugging in VS Code by clicking Run > Start Debugging (F5).
Step 3: If once debugging started, the Dart Opens DevTools command becomes available in the VS Code command palette:
Screenshot showing Open DevTools command:
When you run your app the first time, you will be prompted to activate or upgrade DevTools. The below image shows an Active DevTools command:
Clicking the Open button to activate the DevTools package for your application. After this, DevTools launches in your browser and automatically connects to your debug session as shown below:
When DevTools is in an active state, youβll see them in the status bar of VS Code.
3. Install DevTools from the command line
If you have flutter on your computer, you can run:
flutter pub global activate devtools
The above command installs or updates DevTools on your machine or computer. Launch the DevTools from the application server. Run the local webserver. To do that runs the following commands:
flutter pub global run devtools
On the command line, the output looks something like this:
Serving DevTools at http://127.0.0.1:9100
Start a Flutter application or a Dart command-line application. The command for flutter app:
cd path/to/flutter/app
flutter run
You need to have a device connected for the flutter run to work. After the app starts, Following message in your terminal:
An Observatory debugger and profiler on Galaxys20 is available
at: http://127.0.0.1:50976/Swm0bjIe0hj=/
Note that this URL, we will use to connect our app to DevTools.
Once All things set up, debugging through DevTools is very simple as opening a Chrome browser window and navigating to the below link:
http://localhost:9100
After DevTools opens, the dialog box pop-up you will get the below Logging view:
Paste the URL, which you already note from running your app (example, http://127.0.0.1:50976/Swm0bjIe0hg=/) into the connect dialog to connect your app to DevTools to debugging.
The Flutter widget inspector is a great tool for visualizing and monitoring the Flutter widget trees of your application. The Flutter framework uses widgets as the core building block for control anything (such as text, buttons, etc.), to layout (such as centering, padding, row, and column. Inspector helps to visualize and explore widget trees, and can be used for the following:
With the help of the inspector, you can easily understand the existing layouts of your app.
Diagnosing layout issues in your application if anyone arises.
The following is an instruction to the features available in the inspectorβs toolbar in flutterβs DevTools:
Select widget mode: Select a widget and click on the button on the device to inspect it.
Refresh tree: This button used to reload the current widget info.
Slow Animations: It is used to slow down animations to enable visual inspection.
Debug Paint: Debug Paint button used to add visual debugging, Which hints to the rendering that displays borders, padding, alignment, and spacers, etc.
Paint Baselines: Use of each RenderBox to paint a line at each of its text baselines in the project.
Repaint Rainbow: Repaint Rainbow allows rotating colors on layers when repainting.
Debug Mode Banner: It is used to display the debug banner even when running a debug build.
Flutter Layout Explorer
The Flutter Layout Explorer allows you to better understand Flutter layouts. It supports the only exploration of flex layouts but it is possible that it will be extended in the future. To use the Layout Explorer, select the following tab to display the Layout Explorer feature.
The Layout Explorer visualizes how to Flex widgets and their children. The explorer identifies the main axis and cross axis and the current alignment in your application when you debugging it. Also, explorer shows layout constraint violations and render overflow errors in your app. During debugging sessions violated layout constraints are colored red, and overflow errors are presented in the standard βyellow-tapeβ pattern, as you might see on a running device in your emulator. All the above and following visualizations aim to understand easily, why overflow errors occur as well as how to fix them.
The timeline view provides us, timing, and performance information for the currently debugging applications. It contains three-part, each part increasing in granularity.
Flutter frames chart.Timeline events chart.CPU profiler.
Flutter frames chart.
Timeline events chart.
CPU profiler.
Also, the timeline view supports importing and exporting of timeline data files.
This frame chart contains Flutterβs frame information for your application. Every single bar in the chart represents a single Flutter frame. The bars, which are color-coded to highlight the different portions of work that occur when rendering a Flutter frame as shown below:
Selecting a bar from the above chart centers the flame chart below on the timeline events corresponding to the selected Flutter frame which is colored blue in the chart as shown below:
The UI executes Dart code in the Dart VM. It includes code from your application and Flutter framework. When you create an app and display a scene, this thread creates a layer tree, device-agnostic painting commands, and sends the layer tree to the raster thread which will be rendered on the device.
The raster thread (called GPU thread), executes graphics code from Flutter Engine. This thread takes the layer tree and displays it with the help of the GPU. It cannot directly access the raster thread or its data.
Whenever a frame becomes janky, the jank frame visible with a red overlay. A frame is janky when it takes more than ~16 ms to complete (for 60 FPS devices) whenever this target is missed UI dropped frames. Achieving frame rendering rate of 60 FPS, every frame must render in ~16 ms or less.
The timeline events chart displays all event trace from the application. The Flutter framework shows timeline events as it works to build frames, draw scenes, and track other activities. All events show up here in the Timeline.
The Flame chart shows CPU samples for the selected frame event (such as Layout etc.). This profiler should be viewed as a top-down stack trace, where the top-most stack frame calls the one below it, and the width of each stack frame represents the amount of time it consumed the CPU during the inspection or debugging as shown below:
The call tree displays the method trace for the CPU profile. This table of call tree is a top-down representation of the profile which means that a method can be expanded to describe its callees.
Total time: Time the method spent executing the code with its callees.
Self time: Time the method spent to executing its own code.
Method: Name or identity of the called method.
Source: File path for the method call site in your machine.
An image of the same is shown below:
The bottom-up view displays the method trace for the CPU profile but, accordingly to name, it is a bottom-up representation of the profile. This means that every top-level method in the table is actually the last method in the call stack for a given CPU sample.
The allocated object in any application created using a class constructor (like using new MyClass() or MyClass()) live in a portion of memory known as the heap. Memory page in DevTools lets you peek at how an isolate is using memory at a given time. With the help of Monitor Allocations and Reset options, anyone can analyze accumulator counts. The accumulators can be used to study the rate of memory allocations for any dart app, if you suspect your application is leaking memory or has other bugs relating to memory allocation you can easily figure out it on the memory page. Memory profiling contains six parts:
Chart of Memory overviewChart for Android-only memoryEvent timelineMonitoring and setting up of Dart total instances, size, and accumulator monitoring to detect memory leaks in applicationsSnapshots of all live memory class instances, sentinels, etc.
Chart of Memory overview
Chart for Android-only memory
Event timeline
Monitoring and setting up of Dart total instances, size, and accumulator monitoring to detect memory leaks in applications
Snapshots of all live memory class instances, sentinels, etc.
A time-series graph is used to visualize the state of the Flutter memory at successive intervals of time over your application. Every data point on the chart corresponds to the time stamp (x-axis) of measured quantities and (y-axis) of the heap. Example, usage, capacity, external, garbage collection, resident set size, and many more.
The performance view provides us feature to record and profile a session from your Dart or Flutter application. If you are running a Flutter application, please build a profile build to analyze the performance of your application.
The network view allows you for inspecting web socket traffic like HTTP and HTTPS from your Dart or Flutter application. Screenshot of the network screen:
Some examples of filter queries:
my-endpoint m:get t:json s:200
https s:404
DevTools contains a fully originated source-level debugger which is supporting breakpoints, stepping, and variable inspection. When anyone opens their debugger tab, they should see the source for the main entry-point for your app loaded in the debugger. For browsing around more of your application sources, click Libraries (top right) or use an alternate method the hotkey command β + P / ctrl + P. This will open the libraries window and allow you to search for other source files from your application.
In addition, the Resume button continues regular execution of the application in which you worked on.
The app size tool frees you to analyze the total size of your app and can view a single snapshot of βsize informationβ using the Analysis tab, or compare two different snapshots of βsize informationβ, which contains size data for Dart code of your application. The flutter compiler attempts to optimize your appβs size by removing pieces of code that are unused or unreachable(garbage code) in your application.
In the analysis tab you can view the hierarchical structure of the size data using the treemap and table, view code attribution data (i.e. why a piece of code is included in your compiled application) using the dominator tree and call graph.
Whenever you open the Analysis tab, instructions to load an app size file. Drag and drop an app size file into the dialogbox and click to button βAnalyze Sizeβ.
The diff tab provides us to compare two snapshots of size information, two size information files you are comparing should be generated from two different versions of the same app, for example, the size file generated before and after changes to your application code can visualize the difference between the two data sets using the tree-map and table.
Flutter
Picked
Technical Scripter 2020
Dart
Flutter
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
ListView Class in Flutter
Flutter - Flexible Widget
Flutter - Stack Widget
What is widgets in Flutter?
Flutter - Custom Bottom Navigation Bar
Flutter Tutorial
Flutter - Flexible Widget
Flutter - Stack Widget
Flutter - BorderRadius Widget
|
[
{
"code": null,
"e": 24036,
"s": 24008,
"text": "\n15 Jan, 2021"
},
{
"code": null,
"e": 24299,
"s": 24036,
"text": "DevTools is a tooling suite for Flutter and Dart developers consisting of layout inspection tools, performance tools, memory tools basically all the debugging tools that you need to be an efficient and effective Flutter developer bundled into a single web suite."
},
{
"code": null,
"e": 24398,
"s": 24299,
"text": "The Flutter DevTools can be used to perform a number of operations. Some of them are listed below:"
},
{
"code": null,
"e": 24756,
"s": 24398,
"text": "UI inspection.App state inspection.Diagnose UI junk performance.Diagnose issues with flutter apps.DevTools use for CPU profiling.Network profiling for an app.Source-level debugging of an app.Debug memory issues in a Flutter or Dart or command-line app.View general log and diagnostics information of an app.Analyze your code and app size of the flutter app."
},
{
"code": null,
"e": 24771,
"s": 24756,
"text": "UI inspection."
},
{
"code": null,
"e": 24793,
"s": 24771,
"text": "App state inspection."
},
{
"code": null,
"e": 24823,
"s": 24793,
"text": "Diagnose UI junk performance."
},
{
"code": null,
"e": 24858,
"s": 24823,
"text": "Diagnose issues with flutter apps."
},
{
"code": null,
"e": 24890,
"s": 24858,
"text": "DevTools use for CPU profiling."
},
{
"code": null,
"e": 24920,
"s": 24890,
"text": "Network profiling for an app."
},
{
"code": null,
"e": 24954,
"s": 24920,
"text": "Source-level debugging of an app."
},
{
"code": null,
"e": 25016,
"s": 24954,
"text": "Debug memory issues in a Flutter or Dart or command-line app."
},
{
"code": null,
"e": 25072,
"s": 25016,
"text": "View general log and diagnostics information of an app."
},
{
"code": null,
"e": 25123,
"s": 25072,
"text": "Analyze your code and app size of the flutter app."
},
{
"code": null,
"e": 25168,
"s": 25123,
"text": "1. Install Flutter DevTool in Android Studio"
},
{
"code": null,
"e": 25235,
"s": 25168,
"text": "Follow the below steps to install DevTools in your Android Studio:"
},
{
"code": null,
"e": 25512,
"s": 25235,
"text": "Step 1: Install the Flutter plugin in Android Studio, if you donβt already have it installed. This can be done using the normal Plugins page in the Android Studio settings. Once settings->plug-ins page is open, you can search flutter in the marketplace and install the plugin."
},
{
"code": null,
"e": 25654,
"s": 25512,
"text": "Step 2: You first run a Flutter app. Ensuring that you have a device connected to the project, and clicking the Run or Debug toolbar buttons."
},
{
"code": null,
"e": 25829,
"s": 25654,
"text": "Step 3: Launch DevTools from the toolbar/menu in your flutter project. Once an app is running successfully, start DevTools implementing the following instruction one by one:"
},
{
"code": null,
"e": 26023,
"s": 25829,
"text": "Open DevTools toolbar action from Run view.DevTools toolbar action visible in the Debug view. (if debugging)DevTools action from the More Actions menu in Inspector view in your flutter project."
},
{
"code": null,
"e": 26067,
"s": 26023,
"text": "Open DevTools toolbar action from Run view."
},
{
"code": null,
"e": 26133,
"s": 26067,
"text": "DevTools toolbar action visible in the Debug view. (if debugging)"
},
{
"code": null,
"e": 26219,
"s": 26133,
"text": "DevTools action from the More Actions menu in Inspector view in your flutter project."
},
{
"code": null,
"e": 26255,
"s": 26219,
"text": "2. Installing DevTools from VS Code"
},
{
"code": null,
"e": 26312,
"s": 26255,
"text": "Follow the below steps to install DevTools from VS Code:"
},
{
"code": null,
"e": 26471,
"s": 26312,
"text": "Step 1: To use the DevTools from VS Code firstly install the Dart extension also you need to install the Flutter extension for debugging flutter applications."
},
{
"code": null,
"e": 26595,
"s": 26471,
"text": "Step 2: Launch an application to debug your application. Start debugging in VS Code by clicking Run > Start Debugging (F5)."
},
{
"code": null,
"e": 26712,
"s": 26595,
"text": "Step 3: If once debugging started, the Dart Opens DevTools command becomes available in the VS Code command palette:"
},
{
"code": null,
"e": 26754,
"s": 26712,
"text": "Screenshot showing Open DevTools command:"
},
{
"code": null,
"e": 26897,
"s": 26754,
"text": " When you run your app the first time, you will be prompted to activate or upgrade DevTools. The below image shows an Active DevTools command:"
},
{
"code": null,
"e": 27088,
"s": 26897,
"text": "Clicking the Open button to activate the DevTools package for your application. After this, DevTools launches in your browser and automatically connects to your debug session as shown below:"
},
{
"code": null,
"e": 27171,
"s": 27088,
"text": "When DevTools is in an active state, youβll see them in the status bar of VS Code."
},
{
"code": null,
"e": 27213,
"s": 27171,
"text": "3. Install DevTools from the command line"
},
{
"code": null,
"e": 27264,
"s": 27213,
"text": "If you have flutter on your computer, you can run:"
},
{
"code": null,
"e": 27301,
"s": 27264,
"text": "flutter pub global activate devtools"
},
{
"code": null,
"e": 27491,
"s": 27301,
"text": "The above command installs or updates DevTools on your machine or computer. Launch the DevTools from the application server. Run the local webserver. To do that runs the following commands:"
},
{
"code": null,
"e": 27526,
"s": 27491,
"text": "flutter pub global run devtools "
},
{
"code": null,
"e": 27585,
"s": 27526,
"text": "On the command line, the output looks something like this:"
},
{
"code": null,
"e": 27627,
"s": 27585,
"text": "Serving DevTools at http://127.0.0.1:9100"
},
{
"code": null,
"e": 27720,
"s": 27627,
"text": "Start a Flutter application or a Dart command-line application. The command for flutter app:"
},
{
"code": null,
"e": 27755,
"s": 27720,
"text": "cd path/to/flutter/app\nflutter run"
},
{
"code": null,
"e": 27878,
"s": 27755,
"text": "You need to have a device connected for the flutter run to work. After the app starts, Following message in your terminal:"
},
{
"code": null,
"e": 27982,
"s": 27878,
"text": "An Observatory debugger and profiler on Galaxys20 is available\nat: http://127.0.0.1:50976/Swm0bjIe0hj=/"
},
{
"code": null,
"e": 28046,
"s": 27982,
"text": "Note that this URL, we will use to connect our app to DevTools."
},
{
"code": null,
"e": 28181,
"s": 28046,
"text": "Once All things set up, debugging through DevTools is very simple as opening a Chrome browser window and navigating to the below link:"
},
{
"code": null,
"e": 28203,
"s": 28181,
"text": "http://localhost:9100"
},
{
"code": null,
"e": 28284,
"s": 28203,
"text": "After DevTools opens, the dialog box pop-up you will get the below Logging view:"
},
{
"code": null,
"e": 28462,
"s": 28284,
"text": "Paste the URL, which you already note from running your app (example, http://127.0.0.1:50976/Swm0bjIe0hg=/) into the connect dialog to connect your app to DevTools to debugging."
},
{
"code": null,
"e": 28844,
"s": 28462,
"text": "The Flutter widget inspector is a great tool for visualizing and monitoring the Flutter widget trees of your application. The Flutter framework uses widgets as the core building block for control anything (such as text, buttons, etc.), to layout (such as centering, padding, row, and column. Inspector helps to visualize and explore widget trees, and can be used for the following:"
},
{
"code": null,
"e": 28936,
"s": 28844,
"text": "With the help of the inspector, you can easily understand the existing layouts of your app."
},
{
"code": null,
"e": 28999,
"s": 28936,
"text": "Diagnosing layout issues in your application if anyone arises."
},
{
"code": null,
"e": 29107,
"s": 28999,
"text": "The following is an instruction to the features available in the inspectorβs toolbar in flutterβs DevTools:"
},
{
"code": null,
"e": 29196,
"s": 29107,
"text": "Select widget mode: Select a widget and click on the button on the device to inspect it."
},
{
"code": null,
"e": 29262,
"s": 29196,
"text": "Refresh tree: This button used to reload the current widget info."
},
{
"code": null,
"e": 29343,
"s": 29262,
"text": "Slow Animations: It is used to slow down animations to enable visual inspection."
},
{
"code": null,
"e": 29495,
"s": 29343,
"text": "Debug Paint: Debug Paint button used to add visual debugging, Which hints to the rendering that displays borders, padding, alignment, and spacers, etc."
},
{
"code": null,
"e": 29596,
"s": 29495,
"text": "Paint Baselines: Use of each RenderBox to paint a line at each of its text baselines in the project."
},
{
"code": null,
"e": 29679,
"s": 29596,
"text": "Repaint Rainbow: Repaint Rainbow allows rotating colors on layers when repainting."
},
{
"code": null,
"e": 29770,
"s": 29679,
"text": "Debug Mode Banner: It is used to display the debug banner even when running a debug build."
},
{
"code": null,
"e": 29794,
"s": 29770,
"text": "Flutter Layout Explorer"
},
{
"code": null,
"e": 30072,
"s": 29794,
"text": "The Flutter Layout Explorer allows you to better understand Flutter layouts. It supports the only exploration of flex layouts but it is possible that it will be extended in the future. To use the Layout Explorer, select the following tab to display the Layout Explorer feature."
},
{
"code": null,
"e": 30677,
"s": 30072,
"text": "The Layout Explorer visualizes how to Flex widgets and their children. The explorer identifies the main axis and cross axis and the current alignment in your application when you debugging it. Also, explorer shows layout constraint violations and render overflow errors in your app. During debugging sessions violated layout constraints are colored red, and overflow errors are presented in the standard βyellow-tapeβ pattern, as you might see on a running device in your emulator. All the above and following visualizations aim to understand easily, why overflow errors occur as well as how to fix them."
},
{
"code": null,
"e": 30847,
"s": 30677,
"text": "The timeline view provides us, timing, and performance information for the currently debugging applications. It contains three-part, each part increasing in granularity."
},
{
"code": null,
"e": 30904,
"s": 30847,
"text": "Flutter frames chart.Timeline events chart.CPU profiler."
},
{
"code": null,
"e": 30926,
"s": 30904,
"text": "Flutter frames chart."
},
{
"code": null,
"e": 30949,
"s": 30926,
"text": "Timeline events chart."
},
{
"code": null,
"e": 30963,
"s": 30949,
"text": "CPU profiler."
},
{
"code": null,
"e": 31046,
"s": 30963,
"text": " Also, the timeline view supports importing and exporting of timeline data files. "
},
{
"code": null,
"e": 31321,
"s": 31046,
"text": "This frame chart contains Flutterβs frame information for your application. Every single bar in the chart represents a single Flutter frame. The bars, which are color-coded to highlight the different portions of work that occur when rendering a Flutter frame as shown below:"
},
{
"code": null,
"e": 31506,
"s": 31321,
"text": "Selecting a bar from the above chart centers the flame chart below on the timeline events corresponding to the selected Flutter frame which is colored blue in the chart as shown below:"
},
{
"code": null,
"e": 31807,
"s": 31506,
"text": "The UI executes Dart code in the Dart VM. It includes code from your application and Flutter framework. When you create an app and display a scene, this thread creates a layer tree, device-agnostic painting commands, and sends the layer tree to the raster thread which will be rendered on the device."
},
{
"code": null,
"e": 32022,
"s": 31807,
"text": "The raster thread (called GPU thread), executes graphics code from Flutter Engine. This thread takes the layer tree and displays it with the help of the GPU. It cannot directly access the raster thread or its data."
},
{
"code": null,
"e": 32313,
"s": 32022,
"text": "Whenever a frame becomes janky, the jank frame visible with a red overlay. A frame is janky when it takes more than ~16 ms to complete (for 60 FPS devices) whenever this target is missed UI dropped frames. Achieving frame rendering rate of 60 FPS, every frame must render in ~16 ms or less."
},
{
"code": null,
"e": 32541,
"s": 32313,
"text": "The timeline events chart displays all event trace from the application. The Flutter framework shows timeline events as it works to build frames, draw scenes, and track other activities. All events show up here in the Timeline."
},
{
"code": null,
"e": 32875,
"s": 32541,
"text": "The Flame chart shows CPU samples for the selected frame event (such as Layout etc.). This profiler should be viewed as a top-down stack trace, where the top-most stack frame calls the one below it, and the width of each stack frame represents the amount of time it consumed the CPU during the inspection or debugging as shown below:"
},
{
"code": null,
"e": 33071,
"s": 32875,
"text": "The call tree displays the method trace for the CPU profile. This table of call tree is a top-down representation of the profile which means that a method can be expanded to describe its callees."
},
{
"code": null,
"e": 33142,
"s": 33071,
"text": "Total time: Time the method spent executing the code with its callees."
},
{
"code": null,
"e": 33202,
"s": 33142,
"text": "Self time: Time the method spent to executing its own code."
},
{
"code": null,
"e": 33249,
"s": 33202,
"text": "Method: Name or identity of the called method."
},
{
"code": null,
"e": 33309,
"s": 33249,
"text": "Source: File path for the method call site in your machine."
},
{
"code": null,
"e": 33346,
"s": 33309,
"text": "An image of the same is shown below:"
},
{
"code": null,
"e": 33608,
"s": 33346,
"text": "The bottom-up view displays the method trace for the CPU profile but, accordingly to name, it is a bottom-up representation of the profile. This means that every top-level method in the table is actually the last method in the call stack for a given CPU sample."
},
{
"code": null,
"e": 34224,
"s": 33608,
"text": "The allocated object in any application created using a class constructor (like using new MyClass() or MyClass()) live in a portion of memory known as the heap. Memory page in DevTools lets you peek at how an isolate is using memory at a given time. With the help of Monitor Allocations and Reset options, anyone can analyze accumulator counts. The accumulators can be used to study the rate of memory allocations for any dart app, if you suspect your application is leaking memory or has other bugs relating to memory allocation you can easily figure out it on the memory page. Memory profiling contains six parts:"
},
{
"code": null,
"e": 34475,
"s": 34224,
"text": "Chart of Memory overviewChart for Android-only memoryEvent timelineMonitoring and setting up of Dart total instances, size, and accumulator monitoring to detect memory leaks in applicationsSnapshots of all live memory class instances, sentinels, etc."
},
{
"code": null,
"e": 34500,
"s": 34475,
"text": "Chart of Memory overview"
},
{
"code": null,
"e": 34530,
"s": 34500,
"text": "Chart for Android-only memory"
},
{
"code": null,
"e": 34545,
"s": 34530,
"text": "Event timeline"
},
{
"code": null,
"e": 34668,
"s": 34545,
"text": "Monitoring and setting up of Dart total instances, size, and accumulator monitoring to detect memory leaks in applications"
},
{
"code": null,
"e": 34730,
"s": 34668,
"text": "Snapshots of all live memory class instances, sentinels, etc."
},
{
"code": null,
"e": 35067,
"s": 34730,
"text": "A time-series graph is used to visualize the state of the Flutter memory at successive intervals of time over your application. Every data point on the chart corresponds to the time stamp (x-axis) of measured quantities and (y-axis) of the heap. Example, usage, capacity, external, garbage collection, resident set size, and many more."
},
{
"code": null,
"e": 35298,
"s": 35067,
"text": "The performance view provides us feature to record and profile a session from your Dart or Flutter application. If you are running a Flutter application, please build a profile build to analyze the performance of your application."
},
{
"code": null,
"e": 35453,
"s": 35298,
"text": "The network view allows you for inspecting web socket traffic like HTTP and HTTPS from your Dart or Flutter application. Screenshot of the network screen:"
},
{
"code": null,
"e": 35486,
"s": 35453,
"text": "Some examples of filter queries:"
},
{
"code": null,
"e": 35529,
"s": 35486,
"text": "my-endpoint m:get t:json s:200\nhttps s:404"
},
{
"code": null,
"e": 36036,
"s": 35529,
"text": "DevTools contains a fully originated source-level debugger which is supporting breakpoints, stepping, and variable inspection. When anyone opens their debugger tab, they should see the source for the main entry-point for your app loaded in the debugger. For browsing around more of your application sources, click Libraries (top right) or use an alternate method the hotkey command β + P / ctrl + P. This will open the libraries window and allow you to search for other source files from your application. "
},
{
"code": null,
"e": 36138,
"s": 36036,
"text": "In addition, the Resume button continues regular execution of the application in which you worked on."
},
{
"code": null,
"e": 36551,
"s": 36138,
"text": "The app size tool frees you to analyze the total size of your app and can view a single snapshot of βsize informationβ using the Analysis tab, or compare two different snapshots of βsize informationβ, which contains size data for Dart code of your application. The flutter compiler attempts to optimize your appβs size by removing pieces of code that are unused or unreachable(garbage code) in your application."
},
{
"code": null,
"e": 36794,
"s": 36551,
"text": "In the analysis tab you can view the hierarchical structure of the size data using the treemap and table, view code attribution data (i.e. why a piece of code is included in your compiled application) using the dominator tree and call graph."
},
{
"code": null,
"e": 36955,
"s": 36794,
"text": "Whenever you open the Analysis tab, instructions to load an app size file. Drag and drop an app size file into the dialogbox and click to button βAnalyze Sizeβ."
},
{
"code": null,
"e": 37308,
"s": 36955,
"text": "The diff tab provides us to compare two snapshots of size information, two size information files you are comparing should be generated from two different versions of the same app, for example, the size file generated before and after changes to your application code can visualize the difference between the two data sets using the tree-map and table."
},
{
"code": null,
"e": 37316,
"s": 37308,
"text": "Flutter"
},
{
"code": null,
"e": 37323,
"s": 37316,
"text": "Picked"
},
{
"code": null,
"e": 37347,
"s": 37323,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 37352,
"s": 37347,
"text": "Dart"
},
{
"code": null,
"e": 37360,
"s": 37352,
"text": "Flutter"
},
{
"code": null,
"e": 37379,
"s": 37360,
"text": "Technical Scripter"
},
{
"code": null,
"e": 37477,
"s": 37379,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37516,
"s": 37477,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 37542,
"s": 37516,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 37568,
"s": 37542,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 37591,
"s": 37568,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 37619,
"s": 37591,
"text": "What is widgets in Flutter?"
},
{
"code": null,
"e": 37658,
"s": 37619,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 37675,
"s": 37658,
"text": "Flutter Tutorial"
},
{
"code": null,
"e": 37701,
"s": 37675,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 37724,
"s": 37701,
"text": "Flutter - Stack Widget"
}
] |
ExpressJS - Database
|
We keep receiving requests, but end up not storing them anywhere. We need a Database to store the data. For this, we will make use of the NoSQL database called MongoDB.
To install and read about Mongo, follow this link.
In order to use Mongo with Express, we need a client API for node. There are multiple options for us, but for this tutorial, we will stick to mongoose. Mongoose is used for document Modeling in Node for MongoDB. For document modeling, we create a Model (much like a class in document oriented programming), and then we produce documents using this Model (like we create documents of a class in OOP). All our processing will be done on these "documents", then finally, we will write these documents in our database.
Now that you have installed Mongo, let us install Mongoose, the same way we have been installing our other node packages β
npm install --save mongoose
Before we start using mongoose, we have to create a database using the Mongo shell. To create a new database, open your terminal and enter "mongo". A Mongo shell will start, enter the following code β
use my_db
A new database will be created for you. Whenever you open up the mongo shell, it will default to "test" db and you will have to change to your database using the same command as above.
To use Mongoose, we will require it in our index.js file and then connect to the mongodb service running on mongodb://localhost.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my_db');
Now our app is connected to our database, let us create a new Model. This model will act as a collection in our database. To create a new Model, use the following code, before defining any route β
var personSchema = mongoose.Schema({
name: String,
age: Number,
nationality: String
});
var Person = mongoose.model("Person", personSchema);
The above code defines the schema for a person and is used to create a Mongoose Mode Person.
Now, we will create a new html form; this form will help you get the details of a person and save it to our database. To create the form, create a new view file called person.pug in views directory with the following content β
html
head
title Person
body
form(action = "/person", method = "POST")
div
label(for = "name") Name:
input(name = "name")
br
div
label(for = "age") Age:
input(name = "age")
br
div
label(for = "nationality") Nationality:
input(name = "nationality")
br
button(type = "submit") Create new person
Also add a new get route in index.js to render this document β
app.get('/person', function(req, res){
res.render('person');
});
Go to "localhost:3000/person" to check if the form is displaying the correct output. Note that this is just the UI, it is not working yet. The following screenshot shows how the form is displayed β
We will now define a post route handler at '/person' which will handle this request
app.post('/person', function(req, res){
var personInfo = req.body; //Get the parsed information
if(!personInfo.name || !personInfo.age || !personInfo.nationality){
res.render('show_message', {
message: "Sorry, you provided worng info", type: "error"});
} else {
var newPerson = new Person({
name: personInfo.name,
age: personInfo.age,
nationality: personInfo.nationality
});
newPerson.save(function(err, Person){
if(err)
res.render('show_message', {message: "Database error", type: "error"});
else
res.render('show_message', {
message: "New person added", type: "success", person: personInfo});
});
}
});
In the above code, if we receive any empty field or do not receive any field, we will send an error response. But if we receive a well-formed document, then we create a newPerson document from Person model and save it to our DB using the newPerson.save() function. This is defined in Mongoose and accepts a callback as argument. This callback has 2 arguments β error and response. These arguments will render the show_message view.
To show the response from this route, we will also need to create a show_message view. Create a new view with the following code β
html
head
title Person
body
if(type == "error")
h3(style = "color:red") #{message}
else
h3 New person,
name: #{person.name},
age: #{person.age} and
nationality: #{person.nationality} added!
We will receive the following response on successfully submitting the form(show_message.pug) β
We now have an interface to create persons.
Mongoose provides a lot of functions for retrieving documents, we will focus on 3 of those. All these functions also take a callback as the last parameter, and just like the save function, their arguments are error and response. The three functions are as follows β
This function finds all the documents matching the fields in conditions object. Same operators used in Mongo also work in mongoose. For example,
Person.find(function(err, response){
console.log(response);
});
This will fetch all the documents from the person's collection.
Person.find({name: "Ayush", age: 20},
function(err, response){
console.log(response);
});
This will fetch all documents where field name is "Ayush" and age is 20.
We can also provide projection we need, i.e., the fields we need. For example, if we want only the names of people whose nationality is "Indian", we use β
Person.find({nationality: "Indian"}, "name", function(err, response){
console.log(response);
});
This function always fetches a single, most relevant document. It has the same exact arguments as Model.find().
This function takes in the _id(defined by mongo) as the first argument, an optional projection string and a callback to handle the response. For example,
Person.findById("507f1f77bcf86cd799439011", function(err, response){
console.log(response);
});
Let us now create a route to view all people records β
var express = require('express');
var app = express();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my_db');
var personSchema = mongoose.Schema({
name: String,
age: Number,
nationality: String
});
var Person = mongoose.model("Person", personSchema);
app.get('/people', function(req, res){
Person.find(function(err, response){
res.json(response);
});
});
app.listen(3000);
Mongoose provides 3 functions to update documents. The functions are described below β
This function takes a conditions and updates an object as input and applies the changes to all the documents matching the conditions in the collection. For example, following code will update the nationality "American" in all Person documents β
Person.update({age: 25}, {nationality: "American"}, function(err, response){
console.log(response);
});
It finds one document based on the query and updates that according to the second argument. It also takes a callback as last argument. Let us perform the following example to understand the function
Person.findOneAndUpdate({name: "Ayush"}, {age: 40}, function(err, response) {
console.log(response);
});
This function updates a single document identified by its id. For example,
Person.findByIdAndUpdate("507f1f77bcf86cd799439011", {name: "James"},
function(err, response){
console.log(response);
});
Let us now create a route to update people. This will be a PUT route with the id as a parameter and details in the payload.
var express = require('express');
var app = express();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my_db');
var personSchema = mongoose.Schema({
name: String,
age: Number,
nationality: String
});
var Person = mongoose.model("Person", personSchema);
app.put('/people/:id', function(req, res){
Person.findByIdAndUpdate(req.params.id, req.body, function(err, response){
if(err) res.json({message: "Error in updating person with id " + req.params.id});
res.json(response);
});
});
app.listen(3000);
To test this route, enter the following in your terminal (replace the id with an id from your created people) β
curl -X PUT --data "name = James&age = 20&nationality = American
"http://localhost:3000/people/507f1f77bcf86cd799439011
This will update the document associated with the id provided in the route with the above details.
We have covered Create, Read and Update, now we will see how Mongoose can be used to Delete documents. We have 3 functions here, exactly like update.
This function takes a condition object as input and removes all documents matching the conditions. For example, if we need to remove all people aged 20, use the following syntax β
Person.remove({age:20});
This functions removes a single, most relevant document according to conditions object. Let us execute the following code to understand the same.
Person.findOneAndRemove({name: "Ayush"});
This function removes a single document identified by its id. For example,
Person.findByIdAndRemove("507f1f77bcf86cd799439011");
Let us now create a route to delete people from our database.
var express = require('express');
var app = express();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my_db');
var personSchema = mongoose.Schema({
name: String,
age: Number,
nationality: String
});
var Person = mongoose.model("Person", personSchema);
app.delete('/people/:id', function(req, res){
Person.findByIdAndRemove(req.params.id, function(err, response){
if(err) res.json({message: "Error in deleting record id " + req.params.id});
else res.json({message: "Person with id " + req.params.id + " removed."});
});
});
app.listen(3000);
To check the output, use the following curl command β
curl -X DELETE http://localhost:3000/people/507f1f77bcf86cd799439011
This will remove the person with given id producing the following message β
{message: "Person with id 507f1f77bcf86cd799439011 removed."}
This wraps up how we can create simple CRUD applications using MongoDB, Mongoose and Express. To explore Mongoose further, read the API docs.
16 Lectures
1 hours
Anadi Sharma
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2230,
"s": 2061,
"text": "We keep receiving requests, but end up not storing them anywhere. We need a Database to store the data. For this, we will make use of the NoSQL database called MongoDB."
},
{
"code": null,
"e": 2281,
"s": 2230,
"text": "To install and read about Mongo, follow this link."
},
{
"code": null,
"e": 2796,
"s": 2281,
"text": "In order to use Mongo with Express, we need a client API for node. There are multiple options for us, but for this tutorial, we will stick to mongoose. Mongoose is used for document Modeling in Node for MongoDB. For document modeling, we create a Model (much like a class in document oriented programming), and then we produce documents using this Model (like we create documents of a class in OOP). All our processing will be done on these \"documents\", then finally, we will write these documents in our database."
},
{
"code": null,
"e": 2919,
"s": 2796,
"text": "Now that you have installed Mongo, let us install Mongoose, the same way we have been installing our other node packages β"
},
{
"code": null,
"e": 2948,
"s": 2919,
"text": "npm install --save mongoose\n"
},
{
"code": null,
"e": 3149,
"s": 2948,
"text": "Before we start using mongoose, we have to create a database using the Mongo shell. To create a new database, open your terminal and enter \"mongo\". A Mongo shell will start, enter the following code β"
},
{
"code": null,
"e": 3160,
"s": 3149,
"text": "use my_db\n"
},
{
"code": null,
"e": 3345,
"s": 3160,
"text": "A new database will be created for you. Whenever you open up the mongo shell, it will default to \"test\" db and you will have to change to your database using the same command as above."
},
{
"code": null,
"e": 3474,
"s": 3345,
"text": "To use Mongoose, we will require it in our index.js file and then connect to the mongodb service running on mongodb://localhost."
},
{
"code": null,
"e": 3558,
"s": 3474,
"text": "var mongoose = require('mongoose');\nmongoose.connect('mongodb://localhost/my_db');\n"
},
{
"code": null,
"e": 3755,
"s": 3558,
"text": "Now our app is connected to our database, let us create a new Model. This model will act as a collection in our database. To create a new Model, use the following code, before defining any route β"
},
{
"code": null,
"e": 3905,
"s": 3755,
"text": "var personSchema = mongoose.Schema({\n name: String,\n age: Number,\n nationality: String\n});\nvar Person = mongoose.model(\"Person\", personSchema);"
},
{
"code": null,
"e": 3998,
"s": 3905,
"text": "The above code defines the schema for a person and is used to create a Mongoose Mode Person."
},
{
"code": null,
"e": 4225,
"s": 3998,
"text": "Now, we will create a new html form; this form will help you get the details of a person and save it to our database. To create the form, create a new view file called person.pug in views directory with the following content β"
},
{
"code": null,
"e": 4629,
"s": 4225,
"text": "html\nhead\n title Person\n body\n form(action = \"/person\", method = \"POST\")\n div\n label(for = \"name\") Name: \n input(name = \"name\")\n br\n div\n label(for = \"age\") Age: \n input(name = \"age\")\n br\n div\n label(for = \"nationality\") Nationality: \n input(name = \"nationality\")\n br\n button(type = \"submit\") Create new person\n"
},
{
"code": null,
"e": 4692,
"s": 4629,
"text": "Also add a new get route in index.js to render this document β"
},
{
"code": null,
"e": 4760,
"s": 4692,
"text": "app.get('/person', function(req, res){\n res.render('person');\n});"
},
{
"code": null,
"e": 4958,
"s": 4760,
"text": "Go to \"localhost:3000/person\" to check if the form is displaying the correct output. Note that this is just the UI, it is not working yet. The following screenshot shows how the form is displayed β"
},
{
"code": null,
"e": 5042,
"s": 4958,
"text": "We will now define a post route handler at '/person' which will handle this request"
},
{
"code": null,
"e": 5789,
"s": 5042,
"text": "app.post('/person', function(req, res){\n var personInfo = req.body; //Get the parsed information\n \n if(!personInfo.name || !personInfo.age || !personInfo.nationality){\n res.render('show_message', {\n message: \"Sorry, you provided worng info\", type: \"error\"});\n } else {\n var newPerson = new Person({\n name: personInfo.name,\n age: personInfo.age,\n nationality: personInfo.nationality\n });\n\t\t\n newPerson.save(function(err, Person){\n if(err)\n res.render('show_message', {message: \"Database error\", type: \"error\"});\n else\n res.render('show_message', {\n message: \"New person added\", type: \"success\", person: personInfo});\n });\n }\n});"
},
{
"code": null,
"e": 6221,
"s": 5789,
"text": "In the above code, if we receive any empty field or do not receive any field, we will send an error response. But if we receive a well-formed document, then we create a newPerson document from Person model and save it to our DB using the newPerson.save() function. This is defined in Mongoose and accepts a callback as argument. This callback has 2 arguments β error and response. These arguments will render the show_message view."
},
{
"code": null,
"e": 6352,
"s": 6221,
"text": "To show the response from this route, we will also need to create a show_message view. Create a new view with the following code β"
},
{
"code": null,
"e": 6624,
"s": 6352,
"text": "html\n head\n title Person\n body\n if(type == \"error\")\n h3(style = \"color:red\") #{message}\n else\n h3 New person, \n name: #{person.name}, \n age: #{person.age} and \n nationality: #{person.nationality} added!\n"
},
{
"code": null,
"e": 6719,
"s": 6624,
"text": "We will receive the following response on successfully submitting the form(show_message.pug) β"
},
{
"code": null,
"e": 6763,
"s": 6719,
"text": "We now have an interface to create persons."
},
{
"code": null,
"e": 7029,
"s": 6763,
"text": "Mongoose provides a lot of functions for retrieving documents, we will focus on 3 of those. All these functions also take a callback as the last parameter, and just like the save function, their arguments are error and response. The three functions are as follows β"
},
{
"code": null,
"e": 7174,
"s": 7029,
"text": "This function finds all the documents matching the fields in conditions object. Same operators used in Mongo also work in mongoose. For example,"
},
{
"code": null,
"e": 7241,
"s": 7174,
"text": "Person.find(function(err, response){\n console.log(response);\n});"
},
{
"code": null,
"e": 7305,
"s": 7241,
"text": "This will fetch all the documents from the person's collection."
},
{
"code": null,
"e": 7405,
"s": 7305,
"text": "Person.find({name: \"Ayush\", age: 20}, \n function(err, response){\n console.log(response);\n});"
},
{
"code": null,
"e": 7478,
"s": 7405,
"text": "This will fetch all documents where field name is \"Ayush\" and age is 20."
},
{
"code": null,
"e": 7633,
"s": 7478,
"text": "We can also provide projection we need, i.e., the fields we need. For example, if we want only the names of people whose nationality is \"Indian\", we use β"
},
{
"code": null,
"e": 7733,
"s": 7633,
"text": "Person.find({nationality: \"Indian\"}, \"name\", function(err, response){\n console.log(response);\n});"
},
{
"code": null,
"e": 7845,
"s": 7733,
"text": "This function always fetches a single, most relevant document. It has the same exact arguments as Model.find()."
},
{
"code": null,
"e": 7999,
"s": 7845,
"text": "This function takes in the _id(defined by mongo) as the first argument, an optional projection string and a callback to handle the response. For example,"
},
{
"code": null,
"e": 8098,
"s": 7999,
"text": "Person.findById(\"507f1f77bcf86cd799439011\", function(err, response){\n console.log(response);\n});"
},
{
"code": null,
"e": 8153,
"s": 8098,
"text": "Let us now create a route to view all people records β"
},
{
"code": null,
"e": 8580,
"s": 8153,
"text": "var express = require('express');\nvar app = express();\n\nvar mongoose = require('mongoose');\nmongoose.connect('mongodb://localhost/my_db');\n\nvar personSchema = mongoose.Schema({\n name: String,\n age: Number,\n nationality: String\n});\n\nvar Person = mongoose.model(\"Person\", personSchema);\n\napp.get('/people', function(req, res){\n Person.find(function(err, response){\n res.json(response);\n });\n});\n\napp.listen(3000);"
},
{
"code": null,
"e": 8667,
"s": 8580,
"text": "Mongoose provides 3 functions to update documents. The functions are described below β"
},
{
"code": null,
"e": 8912,
"s": 8667,
"text": "This function takes a conditions and updates an object as input and applies the changes to all the documents matching the conditions in the collection. For example, following code will update the nationality \"American\" in all Person documents β"
},
{
"code": null,
"e": 9019,
"s": 8912,
"text": "Person.update({age: 25}, {nationality: \"American\"}, function(err, response){\n console.log(response);\n});"
},
{
"code": null,
"e": 9218,
"s": 9019,
"text": "It finds one document based on the query and updates that according to the second argument. It also takes a callback as last argument. Let us perform the following example to understand the function"
},
{
"code": null,
"e": 9326,
"s": 9218,
"text": "Person.findOneAndUpdate({name: \"Ayush\"}, {age: 40}, function(err, response) {\n console.log(response);\n});"
},
{
"code": null,
"e": 9401,
"s": 9326,
"text": "This function updates a single document identified by its id. For example,"
},
{
"code": null,
"e": 9533,
"s": 9401,
"text": "Person.findByIdAndUpdate(\"507f1f77bcf86cd799439011\", {name: \"James\"}, \n function(err, response){\n console.log(response);\n});"
},
{
"code": null,
"e": 9657,
"s": 9533,
"text": "Let us now create a route to update people. This will be a PUT route with the id as a parameter and details in the payload."
},
{
"code": null,
"e": 10214,
"s": 9657,
"text": "var express = require('express');\nvar app = express();\n\nvar mongoose = require('mongoose');\nmongoose.connect('mongodb://localhost/my_db');\n\nvar personSchema = mongoose.Schema({\n name: String,\n age: Number,\n nationality: String\n});\n\nvar Person = mongoose.model(\"Person\", personSchema);\n\napp.put('/people/:id', function(req, res){\n Person.findByIdAndUpdate(req.params.id, req.body, function(err, response){\n if(err) res.json({message: \"Error in updating person with id \" + req.params.id});\n res.json(response);\n });\n});\n\napp.listen(3000);"
},
{
"code": null,
"e": 10326,
"s": 10214,
"text": "To test this route, enter the following in your terminal (replace the id with an id from your created people) β"
},
{
"code": null,
"e": 10447,
"s": 10326,
"text": "curl -X PUT --data \"name = James&age = 20&nationality = American\n\"http://localhost:3000/people/507f1f77bcf86cd799439011\n"
},
{
"code": null,
"e": 10546,
"s": 10447,
"text": "This will update the document associated with the id provided in the route with the above details."
},
{
"code": null,
"e": 10696,
"s": 10546,
"text": "We have covered Create, Read and Update, now we will see how Mongoose can be used to Delete documents. We have 3 functions here, exactly like update."
},
{
"code": null,
"e": 10876,
"s": 10696,
"text": "This function takes a condition object as input and removes all documents matching the conditions. For example, if we need to remove all people aged 20, use the following syntax β"
},
{
"code": null,
"e": 10902,
"s": 10876,
"text": "Person.remove({age:20});\n"
},
{
"code": null,
"e": 11048,
"s": 10902,
"text": "This functions removes a single, most relevant document according to conditions object. Let us execute the following code to understand the same."
},
{
"code": null,
"e": 11091,
"s": 11048,
"text": "Person.findOneAndRemove({name: \"Ayush\"});\n"
},
{
"code": null,
"e": 11166,
"s": 11091,
"text": "This function removes a single document identified by its id. For example,"
},
{
"code": null,
"e": 11220,
"s": 11166,
"text": "Person.findByIdAndRemove(\"507f1f77bcf86cd799439011\");"
},
{
"code": null,
"e": 11282,
"s": 11220,
"text": "Let us now create a route to delete people from our database."
},
{
"code": null,
"e": 11882,
"s": 11282,
"text": "var express = require('express');\nvar app = express();\n\nvar mongoose = require('mongoose');\nmongoose.connect('mongodb://localhost/my_db');\n\nvar personSchema = mongoose.Schema({\n name: String,\n age: Number,\n nationality: String\n});\n\nvar Person = mongoose.model(\"Person\", personSchema);\n\napp.delete('/people/:id', function(req, res){\n Person.findByIdAndRemove(req.params.id, function(err, response){\n if(err) res.json({message: \"Error in deleting record id \" + req.params.id});\n else res.json({message: \"Person with id \" + req.params.id + \" removed.\"});\n });\n});\n\napp.listen(3000);"
},
{
"code": null,
"e": 11937,
"s": 11882,
"text": "To check the output, use the following curl command β "
},
{
"code": null,
"e": 12007,
"s": 11937,
"text": "curl -X DELETE http://localhost:3000/people/507f1f77bcf86cd799439011\n"
},
{
"code": null,
"e": 12083,
"s": 12007,
"text": "This will remove the person with given id producing the following message β"
},
{
"code": null,
"e": 12146,
"s": 12083,
"text": "{message: \"Person with id 507f1f77bcf86cd799439011 removed.\"}\n"
},
{
"code": null,
"e": 12288,
"s": 12146,
"text": "This wraps up how we can create simple CRUD applications using MongoDB, Mongoose and Express. To explore Mongoose further, read the API docs."
},
{
"code": null,
"e": 12321,
"s": 12288,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 12335,
"s": 12321,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 12342,
"s": 12335,
"text": " Print"
},
{
"code": null,
"e": 12353,
"s": 12342,
"text": " Add Notes"
}
] |
Easy way to re-order columns in MySQL?
|
To re-order columns in MySQL, use the ALTER TABLE MODIFY COLUMN. The syntax is as follows -
ALTER TABLE yourTableName MODIFY COLUMN yourColumnName data type after yourColumnName.
To understand the above syntax, let us first create a table. The query to create a table is as follows.
mysql> create table reOrderColumn
-> (
-> ProductId int,
-> DeliveryDate datetime,
-> ProductName varchar(100)
-> );
Query OK, 0 rows affected (0.76 sec)
Now check the description of the table. The query is as follows.
mysql> desc reOrderColumn;
The following is the output.
+--------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| ProductId | int(11) | YES | | NULL | |
| DeliveryDate | datetime | YES | | NULL | |
| ProductName | varchar(100) | YES | | NULL | |
+--------------+--------------+------+-----+---------+-------+
3 rows in set (0.10 sec)
Now re-order the column using ALTER MODIFY command. I will reorder the DeliveryDate column after the ProductName column. The query is as follows.
mysql> alter table reOrderColumn modify column DeliveryDate datetime after ProductName;
Query OK, 0 rows affected (1.61 sec)
Records: 0 Duplicates: 0 Warnings: 0
Let us now check the column have been reordered or not. The query is as follows.
mysql> desc reOrderColumn;
The following is the output displaying the columns have been reordered.
+--------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| ProductId | int(11) | YES | | NULL | |
| ProductName | varchar(100) | YES | | NULL | |
| DeliveryDate | datetime | YES | | NULL | |
+--------------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1154,
"s": 1062,
"text": "To re-order columns in MySQL, use the ALTER TABLE MODIFY COLUMN. The syntax is as follows -"
},
{
"code": null,
"e": 1241,
"s": 1154,
"text": "ALTER TABLE yourTableName MODIFY COLUMN yourColumnName data type after yourColumnName."
},
{
"code": null,
"e": 1345,
"s": 1241,
"text": "To understand the above syntax, let us first create a table. The query to create a table is as follows."
},
{
"code": null,
"e": 1499,
"s": 1345,
"text": "mysql> create table reOrderColumn\n-> (\n-> ProductId int,\n-> DeliveryDate datetime,\n-> ProductName varchar(100)\n-> );\nQuery OK, 0 rows affected (0.76 sec)"
},
{
"code": null,
"e": 1564,
"s": 1499,
"text": "Now check the description of the table. The query is as follows."
},
{
"code": null,
"e": 1591,
"s": 1564,
"text": "mysql> desc reOrderColumn;"
},
{
"code": null,
"e": 1620,
"s": 1591,
"text": "The following is the output."
},
{
"code": null,
"e": 2016,
"s": 1620,
"text": "+--------------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+--------------+--------------+------+-----+---------+-------+\n| ProductId | int(11) | YES | | NULL | |\n| DeliveryDate | datetime | YES | | NULL | |\n| ProductName | varchar(100) | YES | | NULL | |\n+--------------+--------------+------+-----+---------+-------+\n3 rows in set (0.10 sec)"
},
{
"code": null,
"e": 2162,
"s": 2016,
"text": "Now re-order the column using ALTER MODIFY command. I will reorder the DeliveryDate column after the ProductName column. The query is as follows."
},
{
"code": null,
"e": 2324,
"s": 2162,
"text": "mysql> alter table reOrderColumn modify column DeliveryDate datetime after ProductName;\nQuery OK, 0 rows affected (1.61 sec)\nRecords: 0 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 2405,
"s": 2324,
"text": "Let us now check the column have been reordered or not. The query is as follows."
},
{
"code": null,
"e": 2432,
"s": 2405,
"text": "mysql> desc reOrderColumn;"
},
{
"code": null,
"e": 2504,
"s": 2432,
"text": "The following is the output displaying the columns have been reordered."
},
{
"code": null,
"e": 2900,
"s": 2504,
"text": "+--------------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+--------------+--------------+------+-----+---------+-------+\n| ProductId | int(11) | YES | | NULL | |\n| ProductName | varchar(100) | YES | | NULL | |\n| DeliveryDate | datetime | YES | | NULL | |\n+--------------+--------------+------+-----+---------+-------+\n3 rows in set (0.00 sec)"
}
] |
Biopython - PDB Module
|
Biopython provides Bio.PDB module to manipulate polypeptide structures. The PDB (Protein Data Bank) is the largest protein structure resource available online. It hosts a lot of distinct protein structures, including protein-protein, protein-DNA, protein-RNA complexes.
In order to load the PDB, type the below command β
from Bio.PDB import *
The PDB distributes protein structures in three different formats β
The XML-based file format which is not supported by Biopython
The pdb file format, which is a specially formatted text file
PDBx/mmCIF files format
PDB files distributed by the Protein Data Bank may contain formatting errors that make them ambiguous or difficult to parse. The Bio.PDB module attempts to deal with these errors automatically.
The Bio.PDB module implements two different parsers, one is mmCIF format and second one is pdb format.
Let us learn how to parser each of the format in detail β
Let us download an example database in mmCIF format from pdb server using the below command β
>>> pdbl = PDBList()
>>> pdbl.retrieve_pdb_file('2FAT', pdir = '.', file_format = 'mmCif')
This will download the specified file (2fat.cif) from the server and store it in the current working directory.
Here, PDBList provides options to list and download files from online PDB FTP server. retrieve_pdb_file method needs the name of the file to be downloaded without extension. retrieve_pdb_file also have option to specify download directory, pdir and format of the file, file_format. The possible values of file format are as follows β
βmmCifβ (default, PDBx/mmCif file)
βpdbβ (format PDB)
βxmlβ (PMDML/XML format)
βmmtfβ (highly compressed)
βbundleβ (PDB formatted archive for large structure)
To load a cif file, use Bio.MMCIF.MMCIFParser as specified below β
>>> parser = MMCIFParser(QUIET = True)
>>> data = parser.get_structure("2FAT", "2FAT.cif")
Here, QUIET suppresses the warning during parsing the file. get_structure will parse the file and return the structure with id as 2FAT (first argument).
After running the above command, it parses the file and prints possible warning, if available.
Now, check the structure using the below command β
>>> data
<Structure id = 2FAT>
To get the type, use type method as specified below,
>>> print(type(data))
<class 'Bio.PDB.Structure.Structure'>
We have successfully parsed the file and got the structure of the protein. We will learn the details of the protein structure and how to get it in the later chapter.
Let us download an example database in PDB format from pdb server using the below command β
>>> pdbl = PDBList()
>>> pdbl.retrieve_pdb_file('2FAT', pdir = '.', file_format = 'pdb')
This will download the specified file (pdb2fat.ent) from the server and store it in the current working directory.
To load a pdb file, use Bio.PDB.PDBParser as specified below β
>>> parser = PDBParser(PERMISSIVE = True, QUIET = True)
>>> data = parser.get_structure("2fat","pdb2fat.ent")
Here, get_structure is similar to MMCIFParser. PERMISSIVE option try to parse the protein data as flexible as possible.
Now, check the structure and its type with the code snippet given below β
>>> data
<Structure id = 2fat>
>>> print(type(data))
<class 'Bio.PDB.Structure.Structure'>
Well, the header structure stores the dictionary information. To perform this, type the below command β
>>> print(data.header.keys()) dict_keys([
'name', 'head', 'deposition_date', 'release_date', 'structure_method', 'resolution',
'structure_reference', 'journal_reference', 'author', 'compound', 'source',
'keywords', 'journal'])
>>>
To get the name, use the following code β
>>> print(data.header["name"])
an anti-urokinase plasminogen activator receptor (upar) antibody: crystal
structure and binding epitope
>>>
You can also check the date and resolution with the below code β
>>> print(data.header["release_date"]) 2006-11-14
>>> print(data.header["resolution"]) 1.77
PDB structure is composed of a single model, containing two chains.
chain L, containing number of residues
chain H, containing number of residues
Each residue is composed of multiple atoms, each having a 3D position represented by (x, y, z) coordinates.
Let us learn how to get the structure of the atom in detail in the below section β
The Structure.get_models() method returns an iterator over the models. It is defined below β
>>> model = data.get_models()
>>> model
<generator object get_models at 0x103fa1c80>
>>> models = list(model)
>>> models [<Model id = 0>]
>>> type(models[0])
<class 'Bio.PDB.Model.Model'>
Here, a Model describes exactly one 3D conformation. It contains one or more chains.
The Model.get_chain() method returns an iterator over the chains. It is defined below β
>>> chains = list(models[0].get_chains())
>>> chains
[<Chain id = L>, <Chain id = H>]
>>> type(chains[0])
<class 'Bio.PDB.Chain.Chain'>
Here, Chain describes a proper polypeptide structure, i.e., a consecutive sequence of bound residues.
The Chain.get_residues() method returns an iterator over the residues. It is defined below β
>>> residue = list(chains[0].get_residues())
>>> len(residue)
293
>>> residue1 = list(chains[1].get_residues())
>>> len(residue1)
311
Well, Residue holds the atoms that belong to an amino acid.
The Residue.get_atom() returns an iterator over the atoms as defined below β
>>> atoms = list(residue[0].get_atoms())
>>> atoms
[<Atom N>, <Atom CA>, <Atom C>, <Atom Ov, <Atom CB>, <Atom CG>, <Atom OD1>, <Atom OD2>]
An atom holds the 3D coordinate of an atom and it is called a Vector. It is defined below
>>> atoms[0].get_vector()
<Vector 18.49, 73.26, 44.16>
It represents x, y and z co-ordinate values.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2376,
"s": 2106,
"text": "Biopython provides Bio.PDB module to manipulate polypeptide structures. The PDB (Protein Data Bank) is the largest protein structure resource available online. It hosts a lot of distinct protein structures, including protein-protein, protein-DNA, protein-RNA complexes."
},
{
"code": null,
"e": 2427,
"s": 2376,
"text": "In order to load the PDB, type the below command β"
},
{
"code": null,
"e": 2450,
"s": 2427,
"text": "from Bio.PDB import *\n"
},
{
"code": null,
"e": 2518,
"s": 2450,
"text": "The PDB distributes protein structures in three different formats β"
},
{
"code": null,
"e": 2580,
"s": 2518,
"text": "The XML-based file format which is not supported by Biopython"
},
{
"code": null,
"e": 2642,
"s": 2580,
"text": "The pdb file format, which is a specially formatted text file"
},
{
"code": null,
"e": 2666,
"s": 2642,
"text": "PDBx/mmCIF files format"
},
{
"code": null,
"e": 2860,
"s": 2666,
"text": "PDB files distributed by the Protein Data Bank may contain formatting errors that make them ambiguous or difficult to parse. The Bio.PDB module attempts to deal with these errors automatically."
},
{
"code": null,
"e": 2963,
"s": 2860,
"text": "The Bio.PDB module implements two different parsers, one is mmCIF format and second one is pdb format."
},
{
"code": null,
"e": 3021,
"s": 2963,
"text": "Let us learn how to parser each of the format in detail β"
},
{
"code": null,
"e": 3115,
"s": 3021,
"text": "Let us download an example database in mmCIF format from pdb server using the below command β"
},
{
"code": null,
"e": 3207,
"s": 3115,
"text": ">>> pdbl = PDBList() \n>>> pdbl.retrieve_pdb_file('2FAT', pdir = '.', file_format = 'mmCif')"
},
{
"code": null,
"e": 3319,
"s": 3207,
"text": "This will download the specified file (2fat.cif) from the server and store it in the current working directory."
},
{
"code": null,
"e": 3653,
"s": 3319,
"text": "Here, PDBList provides options to list and download files from online PDB FTP server. retrieve_pdb_file method needs the name of the file to be downloaded without extension. retrieve_pdb_file also have option to specify download directory, pdir and format of the file, file_format. The possible values of file format are as follows β"
},
{
"code": null,
"e": 3688,
"s": 3653,
"text": "βmmCifβ (default, PDBx/mmCif file)"
},
{
"code": null,
"e": 3707,
"s": 3688,
"text": "βpdbβ (format PDB)"
},
{
"code": null,
"e": 3732,
"s": 3707,
"text": "βxmlβ (PMDML/XML format)"
},
{
"code": null,
"e": 3759,
"s": 3732,
"text": "βmmtfβ (highly compressed)"
},
{
"code": null,
"e": 3812,
"s": 3759,
"text": "βbundleβ (PDB formatted archive for large structure)"
},
{
"code": null,
"e": 3879,
"s": 3812,
"text": "To load a cif file, use Bio.MMCIF.MMCIFParser as specified below β"
},
{
"code": null,
"e": 3971,
"s": 3879,
"text": ">>> parser = MMCIFParser(QUIET = True) \n>>> data = parser.get_structure(\"2FAT\", \"2FAT.cif\")"
},
{
"code": null,
"e": 4124,
"s": 3971,
"text": "Here, QUIET suppresses the warning during parsing the file. get_structure will parse the file and return the structure with id as 2FAT (first argument)."
},
{
"code": null,
"e": 4219,
"s": 4124,
"text": "After running the above command, it parses the file and prints possible warning, if available."
},
{
"code": null,
"e": 4270,
"s": 4219,
"text": "Now, check the structure using the below command β"
},
{
"code": null,
"e": 4418,
"s": 4270,
"text": ">>> data \n<Structure id = 2FAT>\n\nTo get the type, use type method as specified below,\n\n>>> print(type(data)) \n<class 'Bio.PDB.Structure.Structure'>"
},
{
"code": null,
"e": 4584,
"s": 4418,
"text": "We have successfully parsed the file and got the structure of the protein. We will learn the details of the protein structure and how to get it in the later chapter."
},
{
"code": null,
"e": 4676,
"s": 4584,
"text": "Let us download an example database in PDB format from pdb server using the below command β"
},
{
"code": null,
"e": 4766,
"s": 4676,
"text": ">>> pdbl = PDBList() \n>>> pdbl.retrieve_pdb_file('2FAT', pdir = '.', file_format = 'pdb')"
},
{
"code": null,
"e": 4881,
"s": 4766,
"text": "This will download the specified file (pdb2fat.ent) from the server and store it in the current working directory."
},
{
"code": null,
"e": 4944,
"s": 4881,
"text": "To load a pdb file, use Bio.PDB.PDBParser as specified below β"
},
{
"code": null,
"e": 5055,
"s": 4944,
"text": ">>> parser = PDBParser(PERMISSIVE = True, QUIET = True) \n>>> data = parser.get_structure(\"2fat\",\"pdb2fat.ent\")"
},
{
"code": null,
"e": 5175,
"s": 5055,
"text": "Here, get_structure is similar to MMCIFParser. PERMISSIVE option try to parse the protein data as flexible as possible."
},
{
"code": null,
"e": 5249,
"s": 5175,
"text": "Now, check the structure and its type with the code snippet given below β"
},
{
"code": null,
"e": 5343,
"s": 5249,
"text": ">>> data \n<Structure id = 2fat> \n>>> print(type(data)) \n<class 'Bio.PDB.Structure.Structure'>"
},
{
"code": null,
"e": 5447,
"s": 5343,
"text": "Well, the header structure stores the dictionary information. To perform this, type the below command β"
},
{
"code": null,
"e": 5690,
"s": 5447,
"text": ">>> print(data.header.keys()) dict_keys([\n 'name', 'head', 'deposition_date', 'release_date', 'structure_method', 'resolution', \n 'structure_reference', 'journal_reference', 'author', 'compound', 'source', \n 'keywords', 'journal']) \n>>>"
},
{
"code": null,
"e": 5732,
"s": 5690,
"text": "To get the name, use the following code β"
},
{
"code": null,
"e": 5873,
"s": 5732,
"text": ">>> print(data.header[\"name\"]) \nan anti-urokinase plasminogen activator receptor (upar) antibody: crystal \nstructure and binding epitope\n>>>"
},
{
"code": null,
"e": 5938,
"s": 5873,
"text": "You can also check the date and resolution with the below code β"
},
{
"code": null,
"e": 6031,
"s": 5938,
"text": ">>> print(data.header[\"release_date\"]) 2006-11-14 \n>>> print(data.header[\"resolution\"]) 1.77"
},
{
"code": null,
"e": 6099,
"s": 6031,
"text": "PDB structure is composed of a single model, containing two chains."
},
{
"code": null,
"e": 6138,
"s": 6099,
"text": "chain L, containing number of residues"
},
{
"code": null,
"e": 6177,
"s": 6138,
"text": "chain H, containing number of residues"
},
{
"code": null,
"e": 6285,
"s": 6177,
"text": "Each residue is composed of multiple atoms, each having a 3D position represented by (x, y, z) coordinates."
},
{
"code": null,
"e": 6368,
"s": 6285,
"text": "Let us learn how to get the structure of the atom in detail in the below section β"
},
{
"code": null,
"e": 6461,
"s": 6368,
"text": "The Structure.get_models() method returns an iterator over the models. It is defined below β"
},
{
"code": null,
"e": 6655,
"s": 6461,
"text": ">>> model = data.get_models() \n>>> model \n<generator object get_models at 0x103fa1c80> \n>>> models = list(model) \n>>> models [<Model id = 0>] \n>>> type(models[0]) \n<class 'Bio.PDB.Model.Model'>"
},
{
"code": null,
"e": 6740,
"s": 6655,
"text": "Here, a Model describes exactly one 3D conformation. It contains one or more chains."
},
{
"code": null,
"e": 6828,
"s": 6740,
"text": "The Model.get_chain() method returns an iterator over the chains. It is defined below β"
},
{
"code": null,
"e": 6968,
"s": 6828,
"text": ">>> chains = list(models[0].get_chains()) \n>>> chains \n[<Chain id = L>, <Chain id = H>] \n>>> type(chains[0]) \n<class 'Bio.PDB.Chain.Chain'>"
},
{
"code": null,
"e": 7070,
"s": 6968,
"text": "Here, Chain describes a proper polypeptide structure, i.e., a consecutive sequence of bound residues."
},
{
"code": null,
"e": 7163,
"s": 7070,
"text": "The Chain.get_residues() method returns an iterator over the residues. It is defined below β"
},
{
"code": null,
"e": 7301,
"s": 7163,
"text": ">>> residue = list(chains[0].get_residues())\n>>> len(residue) \n293 \n>>> residue1 = list(chains[1].get_residues()) \n>>> len(residue1) \n311"
},
{
"code": null,
"e": 7361,
"s": 7301,
"text": "Well, Residue holds the atoms that belong to an amino acid."
},
{
"code": null,
"e": 7438,
"s": 7361,
"text": "The Residue.get_atom() returns an iterator over the atoms as defined below β"
},
{
"code": null,
"e": 7579,
"s": 7438,
"text": ">>> atoms = list(residue[0].get_atoms()) \n>>> atoms \n[<Atom N>, <Atom CA>, <Atom C>, <Atom Ov, <Atom CB>, <Atom CG>, <Atom OD1>, <Atom OD2>]"
},
{
"code": null,
"e": 7669,
"s": 7579,
"text": "An atom holds the 3D coordinate of an atom and it is called a Vector. It is defined below"
},
{
"code": null,
"e": 7725,
"s": 7669,
"text": ">>> atoms[0].get_vector() \n<Vector 18.49, 73.26, 44.16>"
},
{
"code": null,
"e": 7770,
"s": 7725,
"text": "It represents x, y and z co-ordinate values."
},
{
"code": null,
"e": 7777,
"s": 7770,
"text": " Print"
},
{
"code": null,
"e": 7788,
"s": 7777,
"text": " Add Notes"
}
] |
Flutter - Writing Android Specific Code
|
Flutter provides a general framework to access platform specific feature. This enables the developer to extend the functionality of the Flutter framework using platform specific code. Platform specific functionality like camera, battery level, browser, etc., can be accessed easily through the framework.
The general idea of accessing the platform specific code is through simple messaging protocol. Flutter code, Client and the platform code and Host binds to a common Message Channel. Client sends message to the Host through the Message Channel. Host listens on the Message Channel, receives the message and does the necessary functionality and finally, returns the result to the Client through Message Channel.
The platform specific code architecture is shown in the block diagram given below β
The messaging protocol uses a standard message codec (StandardMessageCodec class) that supports binary serialization of JSON-like values such as numbers, strings, boolean, etc., The serialization and de-serialization works transparently between the client and the host.
Let us write a simple application to open a browser using Android SDK and understand how
Create a new Flutter application in Android studio, flutter_browser_app
Create a new Flutter application in Android studio, flutter_browser_app
Replace main.dart code with below code β
Replace main.dart code with below code β
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatelessWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(this.title),
),
body: Center(
child: RaisedButton(
child: Text('Open Browser'),
onPressed: null,
),
),
);
}
}
Here, we have created a new button to open the browser and set its onPressed method as null.
Here, we have created a new button to open the browser and set its onPressed method as null.
Now, import the following packages β
Now, import the following packages β
import 'dart:async';
import 'package:flutter/services.dart';
Here, services.dart include the functionality to invoke platform specific code.
Here, services.dart include the functionality to invoke platform specific code.
Create a new message channel in the MyHomePage widget.
Create a new message channel in the MyHomePage widget.
static const platform = const
MethodChannel('flutterapp.tutorialspoint.com/browser');
Write a method, _openBrowser to invoke platform specific method, openBrowser method through message channel.
Write a method, _openBrowser to invoke platform specific method, openBrowser method through message channel.
Future<void> _openBrowser() async {
try {
final int result = await platform.invokeMethod(
'openBrowser', <String, String>{
'url': "https://flutter.dev"
}
);
}
on PlatformException catch (e) {
// Unable to open the browser
print(e);
}
}
Here, we have used platform.invokeMethod to invoke openBrowser (explained in coming steps). openBrowser has an argument, url to open a specific url.
Change the value of onPressed property of the RaisedButton from null to _openBrowser.
Change the value of onPressed property of the RaisedButton from null to _openBrowser.
onPressed: _openBrowser,
Open MainActivity.java (inside the android folder) and import the required library β
Open MainActivity.java (inside the android folder) and import the required library β
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugins.GeneratedPluginRegistrant;
Write a method, openBrowser to open a browser
Write a method, openBrowser to open a browser
private void openBrowser(MethodCall call, Result result, String url) {
Activity activity = this;
if (activity == null) {
result.error("ACTIVITY_NOT_AVAILABLE",
"Browser cannot be opened without foreground
activity", null);
return;
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
activity.startActivity(intent);
result.success((Object) true);
}
Now, set channel name in the MainActivity class β
Now, set channel name in the MainActivity class β
private static final String CHANNEL = "flutterapp.tutorialspoint.com/browser";
Write android specific code to set message handling in the onCreate method β
Write android specific code to set message handling in the onCreate method β
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
new MethodCallHandler() {
@Override
public void onMethodCall(MethodCall call, Result result) {
String url = call.argument("url");
if (call.method.equals("openBrowser")) {
openBrowser(call, result, url);
} else {
result.notImplemented();
}
}
});
Here, we have created a message channel using MethodChannel class and used MethodCallHandler class to handle the message. onMethodCall is the actual method responsible for calling the correct platform specific code by the checking the message. onMethodCall method extracts the url from message and then invokes the openBrowser only when the method call is openBrowser. Otherwise, it returns notImplemented method.
The complete source code of the application is as follows β
main.dart
MainActivity.java
package com.tutorialspoint.flutterapp.flutter_browser_app;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity {
private static final String CHANNEL = "flutterapp.tutorialspoint.com/browser";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
new MethodCallHandler() {
@Override
public void onMethodCall(MethodCall call, Result result) {
String url = call.argument("url");
if (call.method.equals("openBrowser")) {
openBrowser(call, result, url);
} else {
result.notImplemented();
}
}
}
);
}
private void openBrowser(MethodCall call, Result result, String url) {
Activity activity = this; if (activity == null) {
result.error(
"ACTIVITY_NOT_AVAILABLE", "Browser cannot be opened without foreground activity", null
);
return;
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
activity.startActivity(intent);
result.success((Object) true);
}
}
main.dart
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(
title: 'Flutter Demo Home Page'
),
);
}
}
class MyHomePage extends StatelessWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
static const platform = const MethodChannel('flutterapp.tutorialspoint.com/browser');
Future<void> _openBrowser() async {
try {
final int result = await platform.invokeMethod('openBrowser', <String, String>{
'url': "https://flutter.dev"
});
}
on PlatformException catch (e) {
// Unable to open the browser print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(this.title),
),
body: Center(
child: RaisedButton(
child: Text('Open Browser'),
onPressed: _openBrowser,
),
),
);
}
}
Run the application and click the Open Browser button and you can see that the browser is launched. The Browser app - Home page is as shown in the screenshot here β
34 Lectures
4 hours
Sriyank Siddhartha
117 Lectures
10 hours
Frahaan Hussain
27 Lectures
1 hours
Skillbakerystudios
17 Lectures
51 mins
Harsh Kumar Khatri
17 Lectures
1.5 hours
Pramila Rawat
85 Lectures
16.5 hours
Rahul Agarwal
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2523,
"s": 2218,
"text": "Flutter provides a general framework to access platform specific feature. This enables the developer to extend the functionality of the Flutter framework using platform specific code. Platform specific functionality like camera, battery level, browser, etc., can be accessed easily through the framework."
},
{
"code": null,
"e": 2933,
"s": 2523,
"text": "The general idea of accessing the platform specific code is through simple messaging protocol. Flutter code, Client and the platform code and Host binds to a common Message Channel. Client sends message to the Host through the Message Channel. Host listens on the Message Channel, receives the message and does the necessary functionality and finally, returns the result to the Client through Message Channel."
},
{
"code": null,
"e": 3017,
"s": 2933,
"text": "The platform specific code architecture is shown in the block diagram given below β"
},
{
"code": null,
"e": 3287,
"s": 3017,
"text": "The messaging protocol uses a standard message codec (StandardMessageCodec class) that supports binary serialization of JSON-like values such as numbers, strings, boolean, etc., The serialization and de-serialization works transparently between the client and the host."
},
{
"code": null,
"e": 3376,
"s": 3287,
"text": "Let us write a simple application to open a browser using Android SDK and understand how"
},
{
"code": null,
"e": 3448,
"s": 3376,
"text": "Create a new Flutter application in Android studio, flutter_browser_app"
},
{
"code": null,
"e": 3520,
"s": 3448,
"text": "Create a new Flutter application in Android studio, flutter_browser_app"
},
{
"code": null,
"e": 3561,
"s": 3520,
"text": "Replace main.dart code with below code β"
},
{
"code": null,
"e": 3602,
"s": 3561,
"text": "Replace main.dart code with below code β"
},
{
"code": null,
"e": 4449,
"s": 3602,
"text": "import 'package:flutter/material.dart'; \nvoid main() => runApp(MyApp()); \nclass MyApp extends StatelessWidget { \n @override \n Widget build(BuildContext context) {\n return MaterialApp(\n title: 'Flutter Demo', \n theme: ThemeData( \n primarySwatch: Colors.blue, \n ), \n home: MyHomePage(title: 'Flutter Demo Home Page'),\n );\n }\n}\nclass MyHomePage extends StatelessWidget { \n MyHomePage({Key key, this.title}) : super(key: key); \n final String title; \n \n @override \n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(\n title: Text(this.title), \n ), \n body: Center(\n child: RaisedButton( \n child: Text('Open Browser'), \n onPressed: null, \n ), \n ), \n ); \n }\n}"
},
{
"code": null,
"e": 4542,
"s": 4449,
"text": "Here, we have created a new button to open the browser and set its onPressed method as null."
},
{
"code": null,
"e": 4635,
"s": 4542,
"text": "Here, we have created a new button to open the browser and set its onPressed method as null."
},
{
"code": null,
"e": 4672,
"s": 4635,
"text": "Now, import the following packages β"
},
{
"code": null,
"e": 4709,
"s": 4672,
"text": "Now, import the following packages β"
},
{
"code": null,
"e": 4772,
"s": 4709,
"text": "import 'dart:async'; \nimport 'package:flutter/services.dart';\n"
},
{
"code": null,
"e": 4852,
"s": 4772,
"text": "Here, services.dart include the functionality to invoke platform specific code."
},
{
"code": null,
"e": 4932,
"s": 4852,
"text": "Here, services.dart include the functionality to invoke platform specific code."
},
{
"code": null,
"e": 4987,
"s": 4932,
"text": "Create a new message channel in the MyHomePage widget."
},
{
"code": null,
"e": 5042,
"s": 4987,
"text": "Create a new message channel in the MyHomePage widget."
},
{
"code": null,
"e": 5129,
"s": 5042,
"text": "static const platform = const \nMethodChannel('flutterapp.tutorialspoint.com/browser');"
},
{
"code": null,
"e": 5238,
"s": 5129,
"text": "Write a method, _openBrowser to invoke platform specific method, openBrowser method through message channel."
},
{
"code": null,
"e": 5347,
"s": 5238,
"text": "Write a method, _openBrowser to invoke platform specific method, openBrowser method through message channel."
},
{
"code": null,
"e": 5657,
"s": 5347,
"text": "Future<void> _openBrowser() async { \n try {\n final int result = await platform.invokeMethod(\n 'openBrowser', <String, String>{ \n 'url': \"https://flutter.dev\" \n }\n ); \n } \n on PlatformException catch (e) { \n // Unable to open the browser \n print(e); \n }\n}"
},
{
"code": null,
"e": 5806,
"s": 5657,
"text": "Here, we have used platform.invokeMethod to invoke openBrowser (explained in coming steps). openBrowser has an argument, url to open a specific url."
},
{
"code": null,
"e": 5892,
"s": 5806,
"text": "Change the value of onPressed property of the RaisedButton from null to _openBrowser."
},
{
"code": null,
"e": 5978,
"s": 5892,
"text": "Change the value of onPressed property of the RaisedButton from null to _openBrowser."
},
{
"code": null,
"e": 6004,
"s": 5978,
"text": "onPressed: _openBrowser,\n"
},
{
"code": null,
"e": 6089,
"s": 6004,
"text": "Open MainActivity.java (inside the android folder) and import the required library β"
},
{
"code": null,
"e": 6174,
"s": 6089,
"text": "Open MainActivity.java (inside the android folder) and import the required library β"
},
{
"code": null,
"e": 6596,
"s": 6174,
"text": "import android.app.Activity; \nimport android.content.Intent; \nimport android.net.Uri; \nimport android.os.Bundle; \n\nimport io.flutter.app.FlutterActivity; \nimport io.flutter.plugin.common.MethodCall; \nimport io.flutter.plugin.common.MethodChannel; \nimport io.flutter.plugin.common.MethodChannel.MethodCallHandler; \nimport io.flutter.plugin.common.MethodChannel.Result; \nimport io.flutter.plugins.GeneratedPluginRegistrant;"
},
{
"code": null,
"e": 6642,
"s": 6596,
"text": "Write a method, openBrowser to open a browser"
},
{
"code": null,
"e": 6688,
"s": 6642,
"text": "Write a method, openBrowser to open a browser"
},
{
"code": null,
"e": 7127,
"s": 6688,
"text": "private void openBrowser(MethodCall call, Result result, String url) { \n Activity activity = this; \n if (activity == null) { \n result.error(\"ACTIVITY_NOT_AVAILABLE\", \n \"Browser cannot be opened without foreground \n activity\", null); \n return; \n } \n Intent intent = new Intent(Intent.ACTION_VIEW); \n intent.setData(Uri.parse(url)); \n \n activity.startActivity(intent); \n result.success((Object) true); \n}"
},
{
"code": null,
"e": 7177,
"s": 7127,
"text": "Now, set channel name in the MainActivity class β"
},
{
"code": null,
"e": 7227,
"s": 7177,
"text": "Now, set channel name in the MainActivity class β"
},
{
"code": null,
"e": 7307,
"s": 7227,
"text": "private static final String CHANNEL = \"flutterapp.tutorialspoint.com/browser\";\n"
},
{
"code": null,
"e": 7384,
"s": 7307,
"text": "Write android specific code to set message handling in the onCreate method β"
},
{
"code": null,
"e": 7461,
"s": 7384,
"text": "Write android specific code to set message handling in the onCreate method β"
},
{
"code": null,
"e": 7837,
"s": 7461,
"text": "new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler( \n new MethodCallHandler() { \n @Override \n public void onMethodCall(MethodCall call, Result result) { \n String url = call.argument(\"url\"); \n if (call.method.equals(\"openBrowser\")) {\n openBrowser(call, result, url); \n } else { \n result.notImplemented(); \n } \n } \n});"
},
{
"code": null,
"e": 8251,
"s": 7837,
"text": "Here, we have created a message channel using MethodChannel class and used MethodCallHandler class to handle the message. onMethodCall is the actual method responsible for calling the correct platform specific code by the checking the message. onMethodCall method extracts the url from message and then invokes the openBrowser only when the method call is openBrowser. Otherwise, it returns notImplemented method."
},
{
"code": null,
"e": 8311,
"s": 8251,
"text": "The complete source code of the application is as follows β"
},
{
"code": null,
"e": 8321,
"s": 8311,
"text": "main.dart"
},
{
"code": null,
"e": 8339,
"s": 8321,
"text": "MainActivity.java"
},
{
"code": null,
"e": 9969,
"s": 8339,
"text": "package com.tutorialspoint.flutterapp.flutter_browser_app; \n\nimport android.app.Activity; \nimport android.content.Intent; \nimport android.net.Uri; \nimport android.os.Bundle; \nimport io.flutter.app.FlutterActivity; \nimport io.flutter.plugin.common.MethodCall; \nimport io.flutter.plugin.common.MethodChannel.Result; \nimport io.flutter.plugins.GeneratedPluginRegistrant; \n\npublic class MainActivity extends FlutterActivity { \n private static final String CHANNEL = \"flutterapp.tutorialspoint.com/browser\"; \n @Override \n protected void onCreate(Bundle savedInstanceState) { \n super.onCreate(savedInstanceState); \n GeneratedPluginRegistrant.registerWith(this); \n new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(\n new MethodCallHandler() {\n @Override \n public void onMethodCall(MethodCall call, Result result) {\n String url = call.argument(\"url\"); \n if (call.method.equals(\"openBrowser\")) { \n openBrowser(call, result, url); \n } else { \n result.notImplemented(); \n }\n }\n }\n ); \n }\n private void openBrowser(MethodCall call, Result result, String url) {\n Activity activity = this; if (activity == null) {\n result.error(\n \"ACTIVITY_NOT_AVAILABLE\", \"Browser cannot be opened without foreground activity\", null\n ); \n return; \n } \n Intent intent = new Intent(Intent.ACTION_VIEW); \n intent.setData(Uri.parse(url)); \n activity.startActivity(intent); \n result.success((Object) true); \n }\n}"
},
{
"code": null,
"e": 9979,
"s": 9969,
"text": "main.dart"
},
{
"code": null,
"e": 11315,
"s": 9979,
"text": "import 'package:flutter/material.dart'; \nimport 'dart:async'; \nimport 'package:flutter/services.dart'; \n\nvoid main() => runApp(MyApp()); \nclass MyApp extends StatelessWidget {\n @override \n Widget build(BuildContext context) {\n return MaterialApp(\n title: 'Flutter Demo', \n theme: ThemeData( \n primarySwatch: Colors.blue, \n ), \n home: MyHomePage(\n title: 'Flutter Demo Home Page'\n ), \n ); \n }\n}\nclass MyHomePage extends StatelessWidget {\n MyHomePage({Key key, this.title}) : super(key: key); \n final String title; \n static const platform = const MethodChannel('flutterapp.tutorialspoint.com/browser'); \n Future<void> _openBrowser() async {\n try {\n final int result = await platform.invokeMethod('openBrowser', <String, String>{ \n 'url': \"https://flutter.dev\" \n });\n }\n on PlatformException catch (e) { \n // Unable to open the browser print(e); \n } \n }\n @override \n Widget build(BuildContext context) {\n return Scaffold( \n appBar: AppBar( \n title: Text(this.title), \n ), \n body: Center(\n child: RaisedButton( \n child: Text('Open Browser'), \n onPressed: _openBrowser, \n ), \n ),\n );\n }\n}"
},
{
"code": null,
"e": 11480,
"s": 11315,
"text": "Run the application and click the Open Browser button and you can see that the browser is launched. The Browser app - Home page is as shown in the screenshot here β"
},
{
"code": null,
"e": 11513,
"s": 11480,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 11533,
"s": 11513,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 11568,
"s": 11533,
"text": "\n 117 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 11585,
"s": 11568,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 11618,
"s": 11585,
"text": "\n 27 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 11638,
"s": 11618,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 11670,
"s": 11638,
"text": "\n 17 Lectures \n 51 mins\n"
},
{
"code": null,
"e": 11690,
"s": 11670,
"text": " Harsh Kumar Khatri"
},
{
"code": null,
"e": 11725,
"s": 11690,
"text": "\n 17 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 11740,
"s": 11725,
"text": " Pramila Rawat"
},
{
"code": null,
"e": 11776,
"s": 11740,
"text": "\n 85 Lectures \n 16.5 hours \n"
},
{
"code": null,
"e": 11791,
"s": 11776,
"text": " Rahul Agarwal"
},
{
"code": null,
"e": 11798,
"s": 11791,
"text": " Print"
},
{
"code": null,
"e": 11809,
"s": 11798,
"text": " Add Notes"
}
] |
fork() and memory shared b/w processes created using it - GeeksforGeeks
|
28 Jun, 2021
Prerequisite : fork() in C.
So when we do a fork() what are the sections the two process actually share ?Is the heap memory per process ?Are the global variables shared ?Will malloc return the same address to both ?
Let us run below program and take look at the output of it to clear the questions above .
// C program to demonstrate working of fork()#include <unistd.h>#include <sys/types.h>#include <errno.h>#include <stdio.h>#include <sys/wait.h>#include <stdlib.h> int globalVar; /* A global variable*/ int main(void){ int localVar = 0; int* p = (int*) malloc(2); pid_t childPID = fork(); // Putting value at allocated address *p = 0; if (childPID >= 0) // fork was successful { if (childPID == 0) // child process { printf("\n Child Process Initial Value :: localVar" " = %d, globalVar = %d", localVar, globalVar); localVar++; globalVar++; int c = 500; printf("\n Child Process :: localVar = %d, " "globalVar = %d", localVar, globalVar); printf("\n Address of malloced mem child = %p " "and value is %d", p, *p); printf("\n lets change the value pointed my malloc"); *p = 50; printf("\n Address of malloced mem child = %p " "and value is %d", p, *p); printf("\n lets change the value pointed my " "malloc in child"); *p = 200; printf("\n Address of malloced mem child = %p " "and value is %d\n\n\n", p, *p); } else // Parent process { printf("\n Parent process Initial Value :: " "localVar = %d, globalVar = %d", localVar, globalVar); localVar = 10; globalVar = 20; printf("\n Parent process :: localVar = %d," " globalVar = %d", localVar, globalVar); printf("\n Address of malloced mem parent= %p " "and value is %d", p, *p); *p = 100; printf("\n Address of malloced mem parent= %p " "and value is %d", p, *p); printf("\n lets change the value pointed my" " malloc in child"); *p = 400; printf("\n Address of malloced mem child = %p" " and value is %d \n", p, *p); } } else // fork failed { printf("\n Fork failed, quitting!!!!!!\n"); return 1; } return 0;}
Parent process Initial Value :: localVar = 0, globalVar = 0
Parent process :: localVar = 10, globalVar = 20
Address of malloced mem parent= 0x1bb5010 and value is 0
Address of malloced mem parent= 0x1bb5010 and value is 100
lets change the value pointed my malloc in child
Address of malloced mem child = 0x1bb5010 and value is 400
Child Process Initial Value :: localVar = 0, globalVar = 0
Child Process :: localVar = 1, globalVar = 1
Address of malloced mem child = 0x1bb5010 and value is 0
lets change the value pointed my malloc
Address of malloced mem child = 0x1bb5010 and value is 50
lets change the value pointed my malloc in child
Address of malloced mem child = 0x1bb5010 and value is 200
Explanation ::
So each process child and parent both have their own copy of globalVariable and localvar otherwise if they had shared it, we would have got βChild Process Initial Value :: localVar = [10], globalVariable[20] β in child process which was assigned in parent process which executed first but we didnβt.Though address of memory returned by malloc is same but in actual they are pointing to or mapped to different physical address otherwise when parent assigned value of 100 at memory address 0x1535010 the same 100 we should have got in child but we got 0.This article is contributed by Abhilash Kumar Jaiswal . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes
arrow_drop_upSave
So each process child and parent both have their own copy of globalVariable and localvar otherwise if they had shared it, we would have got βChild Process Initial Value :: localVar = [10], globalVariable[20] β in child process which was assigned in parent process which executed first but we didnβt.
Though address of memory returned by malloc is same but in actual they are pointing to or mapped to different physical address otherwise when parent assigned value of 100 at memory address 0x1535010 the same 100 we should have got in child but we got 0.This article is contributed by Abhilash Kumar Jaiswal . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes
arrow_drop_upSave
This article is contributed by Abhilash Kumar Jaiswal . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
system-programming
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
Arrow operator -> in C/C++ with Examples
'this' pointer in C++
How to split a string in C/C++, Python and Java?
Smart Pointers in C++ and How to Use Them
How to dynamically allocate a 2D array in C?
UDP Server-Client implementation in C
Input-output system calls in C | Create, Open, Close, Read, Write
|
[
{
"code": null,
"e": 23843,
"s": 23815,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 23871,
"s": 23843,
"text": "Prerequisite : fork() in C."
},
{
"code": null,
"e": 24059,
"s": 23871,
"text": "So when we do a fork() what are the sections the two process actually share ?Is the heap memory per process ?Are the global variables shared ?Will malloc return the same address to both ?"
},
{
"code": null,
"e": 24149,
"s": 24059,
"text": "Let us run below program and take look at the output of it to clear the questions above ."
},
{
"code": "// C program to demonstrate working of fork()#include <unistd.h>#include <sys/types.h>#include <errno.h>#include <stdio.h>#include <sys/wait.h>#include <stdlib.h> int globalVar; /* A global variable*/ int main(void){ int localVar = 0; int* p = (int*) malloc(2); pid_t childPID = fork(); // Putting value at allocated address *p = 0; if (childPID >= 0) // fork was successful { if (childPID == 0) // child process { printf(\"\\n Child Process Initial Value :: localVar\" \" = %d, globalVar = %d\", localVar, globalVar); localVar++; globalVar++; int c = 500; printf(\"\\n Child Process :: localVar = %d, \" \"globalVar = %d\", localVar, globalVar); printf(\"\\n Address of malloced mem child = %p \" \"and value is %d\", p, *p); printf(\"\\n lets change the value pointed my malloc\"); *p = 50; printf(\"\\n Address of malloced mem child = %p \" \"and value is %d\", p, *p); printf(\"\\n lets change the value pointed my \" \"malloc in child\"); *p = 200; printf(\"\\n Address of malloced mem child = %p \" \"and value is %d\\n\\n\\n\", p, *p); } else // Parent process { printf(\"\\n Parent process Initial Value :: \" \"localVar = %d, globalVar = %d\", localVar, globalVar); localVar = 10; globalVar = 20; printf(\"\\n Parent process :: localVar = %d,\" \" globalVar = %d\", localVar, globalVar); printf(\"\\n Address of malloced mem parent= %p \" \"and value is %d\", p, *p); *p = 100; printf(\"\\n Address of malloced mem parent= %p \" \"and value is %d\", p, *p); printf(\"\\n lets change the value pointed my\" \" malloc in child\"); *p = 400; printf(\"\\n Address of malloced mem child = %p\" \" and value is %d \\n\", p, *p); } } else // fork failed { printf(\"\\n Fork failed, quitting!!!!!!\\n\"); return 1; } return 0;}",
"e": 26412,
"s": 24149,
"text": null
},
{
"code": null,
"e": 27127,
"s": 26412,
"text": " Parent process Initial Value :: localVar = 0, globalVar = 0\n Parent process :: localVar = 10, globalVar = 20\n Address of malloced mem parent= 0x1bb5010 and value is 0\n Address of malloced mem parent= 0x1bb5010 and value is 100\n lets change the value pointed my malloc in child\n Address of malloced mem child = 0x1bb5010 and value is 400 \n\n Child Process Initial Value :: localVar = 0, globalVar = 0\n Child Process :: localVar = 1, globalVar = 1\n Address of malloced mem child = 0x1bb5010 and value is 0\n lets change the value pointed my malloc\n Address of malloced mem child = 0x1bb5010 and value is 50\n lets change the value pointed my malloc in child\n Address of malloced mem child = 0x1bb5010 and value is 200\n"
},
{
"code": null,
"e": 27142,
"s": 27127,
"text": "Explanation ::"
},
{
"code": null,
"e": 28160,
"s": 27142,
"text": "So each process child and parent both have their own copy of globalVariable and localvar otherwise if they had shared it, we would have got βChild Process Initial Value :: localVar = [10], globalVariable[20] β in child process which was assigned in parent process which executed first but we didnβt.Though address of memory returned by malloc is same but in actual they are pointing to or mapped to different physical address otherwise when parent assigned value of 100 at memory address 0x1535010 the same 100 we should have got in child but we got 0.This article is contributed by Abhilash Kumar Jaiswal . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 28460,
"s": 28160,
"text": "So each process child and parent both have their own copy of globalVariable and localvar otherwise if they had shared it, we would have got βChild Process Initial Value :: localVar = [10], globalVariable[20] β in child process which was assigned in parent process which executed first but we didnβt."
},
{
"code": null,
"e": 29179,
"s": 28460,
"text": "Though address of memory returned by malloc is same but in actual they are pointing to or mapped to different physical address otherwise when parent assigned value of 100 at memory address 0x1535010 the same 100 we should have got in child but we got 0.This article is contributed by Abhilash Kumar Jaiswal . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 29486,
"s": 29179,
"text": "This article is contributed by Abhilash Kumar Jaiswal . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 29611,
"s": 29486,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 29630,
"s": 29611,
"text": "system-programming"
},
{
"code": null,
"e": 29641,
"s": 29630,
"text": "C Language"
},
{
"code": null,
"e": 29739,
"s": 29641,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29748,
"s": 29739,
"text": "Comments"
},
{
"code": null,
"e": 29761,
"s": 29748,
"text": "Old Comments"
},
{
"code": null,
"e": 29799,
"s": 29761,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 29825,
"s": 29799,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 29845,
"s": 29825,
"text": "Multithreading in C"
},
{
"code": null,
"e": 29886,
"s": 29845,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 29908,
"s": 29886,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 29957,
"s": 29908,
"text": "How to split a string in C/C++, Python and Java?"
},
{
"code": null,
"e": 29999,
"s": 29957,
"text": "Smart Pointers in C++ and How to Use Them"
},
{
"code": null,
"e": 30044,
"s": 29999,
"text": "How to dynamically allocate a 2D array in C?"
},
{
"code": null,
"e": 30082,
"s": 30044,
"text": "UDP Server-Client implementation in C"
}
] |
Javascript Program To Find Length Of The Longest Substring Without Repeating Characters - GeeksforGeeks
|
20 Dec, 2021
Given a string str, find the length of the longest substring without repeating characters.
For βABDEFGABEFβ, the longest substring are βBDEFGAβ and βDEFGABβ, with length 6.
For βBBBBβ the longest substring is βBβ, with length 1.
For βGEEKSFORGEEKSβ, there are two longest substrings shown in the below diagrams, with length 7
The desired time complexity is O(n) where n is the length of the string.
Method 1 (Simple : O(n3)): We can consider all substrings one by one and check for each substring whether it contains all unique characters or not. There will be n*(n+1)/2 substrings. Whether a substring contains all unique characters or not can be checked in linear time by scanning it from left to right and keeping a map of visited characters. Time complexity of this solution would be O(n^3).
Javascript
<script> // JavaScript program to find the length of the// longest substring without repeating// characters// This function returns true if all characters in// str[i..j] are distinct, otherwise returns falsefunction areDistinct(str, i, j){ // Note : Default values in visited are false var visited = new [26]; for(var k = i; k <= j; k++) { if (visited[str.charAt(k) - 'a'] == true) return false; visited[str.charAt(k) - 'a'] = true; } return true;} // Returns length of the longest substring// with all distinct characters.function longestUniqueSubsttr(str){ var n = str.length(); // Result var res = 0; for(var i = 0; i < n; i++) for(var j = i; j < n; j++) if (areDistinct(str, i, j)) res = Math.max(res, j - i + 1); return res;} // Driver code var str = "geeksforgeeks"; document.write("The input string is " + str); var len = longestUniqueSubsttr(str); document.write("The length of the longest " + "non-repeating character " + "substring is " + len); // This code is contributed by shivanisinghss2110. </script>
The input string is geeksforgeeks
The length of the longest non-repeating character substring is 7
Method 2 (Better : O(n2)) The idea is to use window sliding. Whenever we see repetition, we remove the previous occurrence and slide the window.
Javascript
<script> // JavaScript program to find the length of the // longest substring without repeating// characters function longestUniqueSubsttr(str){ var n = str.length(); // Result var res = 0; for(var i = 0; i < n; i++) { // Note : Default values in visited are false var visited = new [256]; for(var j = i; j < n; j++) { // If current character is visited // Break the loop if (visited[str.charAt(j)] == true) break; // Else update the result if // this window is larger, and mark // current character as visited. else { res = Math.max(res, j - i + 1); visited[str.charAt(j)] = true; } } // Remove the first character of previous // window visited[str.charAt(i)] = false; } return res;} // Driver code var str = "geeksforgeeks"; document.write("The input string is " + str); var len = longestUniqueSubsttr(str); document.write("The length of the longest " + "non-repeating character " + "substring is " + len); // This code is contributed by shivanisinghss2110 </script>
The input string is geeksforgeeks
The length of the longest non-repeating character substring is 7
Method 4 (Linear Time): Let us talk about the linear time solution now. This solution uses extra space to store the last indexes of already visited characters. The idea is to scan the string from left to right, keep track of the maximum length Non-Repeating Character Substring seen so far in res. When we traverse the string, to know the length of current window we need two indexes. 1) Ending index ( j ) : We consider current index as ending index. 2) Starting index ( i ) : It is same as previous window if current character was not present in the previous window. To check if the current character was present in the previous window or not, we store last index of every character in an array lasIndex[]. If lastIndex[str[j]] + 1 is more than previous start, then we updated the start index i. Else we keep same i.
Below is the implementation of the above approach :
Javascript
<script> // JavaScript program to find the length of the longest substring// without repeating charactersvar NO_OF_CHARS = 256; function longestUniqueSubsttr(str) { var n = str.length(); var res = 0; // result // last index of all characters is initialized // as -1 var lastIndex = new [NO_OF_CHARS]; Arrays.fill(lastIndex, -1); // Initialize start of current window var i = 0; // Move end of current window for (var j = 0; j < n; j++) { // Find the last index of str[j] // Update i (starting index of current window) // as maximum of current value of i and last // index plus 1 i = Math.max(i, lastIndex[str.charAt(j)] + 1); // Update result if we get a larger window res = Math.max(res, j - i + 1); // Update last index of j. lastIndex[str.charAt(j)] = j; } return res; } /* Driver program to test above function */ var str = "geeksforgeeks"; document.write("The input string is " + str); var len = longestUniqueSubsttr(str); document.write("The length of the longest non repeating character is " + len); // This code is contributed by shivanisinghss2110 </script>
The input string is geeksforgeeks
The length of the longest non-repeating character substring is 7
Time Complexity: O(n + d) where n is length of the input string and d is number of characters in input string alphabet. For example, if string consists of lowercase English characters then value of d is 26. Auxiliary Space: O(d)
Please refer complete article on Length of the longest substring without repeating characters for more details!
Amazon
Housing.com
Microsoft
Morgan Stanley
Strings
Morgan Stanley
Amazon
Microsoft
Housing.com
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 String Coding Problems for Interviews
VigeneΜre Cipher
How to Append a Character to a String in C
Convert character array to string in C++
Naive algorithm for Pattern Searching
Return maximum occurring character in an input string
Hill Cipher
sprintf() in C
A Program to check if strings are rotations of each other or not
Print all the duplicates in the input string
|
[
{
"code": null,
"e": 24437,
"s": 24409,
"text": "\n20 Dec, 2021"
},
{
"code": null,
"e": 24529,
"s": 24437,
"text": "Given a string str, find the length of the longest substring without repeating characters. "
},
{
"code": null,
"e": 24611,
"s": 24529,
"text": "For βABDEFGABEFβ, the longest substring are βBDEFGAβ and βDEFGABβ, with length 6."
},
{
"code": null,
"e": 24667,
"s": 24611,
"text": "For βBBBBβ the longest substring is βBβ, with length 1."
},
{
"code": null,
"e": 24764,
"s": 24667,
"text": "For βGEEKSFORGEEKSβ, there are two longest substrings shown in the below diagrams, with length 7"
},
{
"code": null,
"e": 24837,
"s": 24764,
"text": "The desired time complexity is O(n) where n is the length of the string."
},
{
"code": null,
"e": 25234,
"s": 24837,
"text": "Method 1 (Simple : O(n3)): We can consider all substrings one by one and check for each substring whether it contains all unique characters or not. There will be n*(n+1)/2 substrings. Whether a substring contains all unique characters or not can be checked in linear time by scanning it from left to right and keeping a map of visited characters. Time complexity of this solution would be O(n^3)."
},
{
"code": null,
"e": 25245,
"s": 25234,
"text": "Javascript"
},
{
"code": "<script> // JavaScript program to find the length of the// longest substring without repeating// characters// This function returns true if all characters in// str[i..j] are distinct, otherwise returns falsefunction areDistinct(str, i, j){ // Note : Default values in visited are false var visited = new [26]; for(var k = i; k <= j; k++) { if (visited[str.charAt(k) - 'a'] == true) return false; visited[str.charAt(k) - 'a'] = true; } return true;} // Returns length of the longest substring// with all distinct characters.function longestUniqueSubsttr(str){ var n = str.length(); // Result var res = 0; for(var i = 0; i < n; i++) for(var j = i; j < n; j++) if (areDistinct(str, i, j)) res = Math.max(res, j - i + 1); return res;} // Driver code var str = \"geeksforgeeks\"; document.write(\"The input string is \" + str); var len = longestUniqueSubsttr(str); document.write(\"The length of the longest \" + \"non-repeating character \" + \"substring is \" + len); // This code is contributed by shivanisinghss2110. </script>",
"e": 26475,
"s": 25245,
"text": null
},
{
"code": null,
"e": 26574,
"s": 26475,
"text": "The input string is geeksforgeeks\nThe length of the longest non-repeating character substring is 7"
},
{
"code": null,
"e": 26719,
"s": 26574,
"text": "Method 2 (Better : O(n2)) The idea is to use window sliding. Whenever we see repetition, we remove the previous occurrence and slide the window."
},
{
"code": null,
"e": 26730,
"s": 26719,
"text": "Javascript"
},
{
"code": "<script> // JavaScript program to find the length of the // longest substring without repeating// characters function longestUniqueSubsttr(str){ var n = str.length(); // Result var res = 0; for(var i = 0; i < n; i++) { // Note : Default values in visited are false var visited = new [256]; for(var j = i; j < n; j++) { // If current character is visited // Break the loop if (visited[str.charAt(j)] == true) break; // Else update the result if // this window is larger, and mark // current character as visited. else { res = Math.max(res, j - i + 1); visited[str.charAt(j)] = true; } } // Remove the first character of previous // window visited[str.charAt(i)] = false; } return res;} // Driver code var str = \"geeksforgeeks\"; document.write(\"The input string is \" + str); var len = longestUniqueSubsttr(str); document.write(\"The length of the longest \" + \"non-repeating character \" + \"substring is \" + len); // This code is contributed by shivanisinghss2110 </script>",
"e": 28037,
"s": 26730,
"text": null
},
{
"code": null,
"e": 28136,
"s": 28037,
"text": "The input string is geeksforgeeks\nThe length of the longest non-repeating character substring is 7"
},
{
"code": null,
"e": 28957,
"s": 28136,
"text": "Method 4 (Linear Time): Let us talk about the linear time solution now. This solution uses extra space to store the last indexes of already visited characters. The idea is to scan the string from left to right, keep track of the maximum length Non-Repeating Character Substring seen so far in res. When we traverse the string, to know the length of current window we need two indexes. 1) Ending index ( j ) : We consider current index as ending index. 2) Starting index ( i ) : It is same as previous window if current character was not present in the previous window. To check if the current character was present in the previous window or not, we store last index of every character in an array lasIndex[]. If lastIndex[str[j]] + 1 is more than previous start, then we updated the start index i. Else we keep same i. "
},
{
"code": null,
"e": 29009,
"s": 28957,
"text": "Below is the implementation of the above approach :"
},
{
"code": null,
"e": 29020,
"s": 29009,
"text": "Javascript"
},
{
"code": "<script> // JavaScript program to find the length of the longest substring// without repeating charactersvar NO_OF_CHARS = 256; function longestUniqueSubsttr(str) { var n = str.length(); var res = 0; // result // last index of all characters is initialized // as -1 var lastIndex = new [NO_OF_CHARS]; Arrays.fill(lastIndex, -1); // Initialize start of current window var i = 0; // Move end of current window for (var j = 0; j < n; j++) { // Find the last index of str[j] // Update i (starting index of current window) // as maximum of current value of i and last // index plus 1 i = Math.max(i, lastIndex[str.charAt(j)] + 1); // Update result if we get a larger window res = Math.max(res, j - i + 1); // Update last index of j. lastIndex[str.charAt(j)] = j; } return res; } /* Driver program to test above function */ var str = \"geeksforgeeks\"; document.write(\"The input string is \" + str); var len = longestUniqueSubsttr(str); document.write(\"The length of the longest non repeating character is \" + len); // This code is contributed by shivanisinghss2110 </script>",
"e": 30333,
"s": 29020,
"text": null
},
{
"code": null,
"e": 30432,
"s": 30333,
"text": "The input string is geeksforgeeks\nThe length of the longest non-repeating character substring is 7"
},
{
"code": null,
"e": 30662,
"s": 30432,
"text": "Time Complexity: O(n + d) where n is length of the input string and d is number of characters in input string alphabet. For example, if string consists of lowercase English characters then value of d is 26. Auxiliary Space: O(d) "
},
{
"code": null,
"e": 30774,
"s": 30662,
"text": "Please refer complete article on Length of the longest substring without repeating characters for more details!"
},
{
"code": null,
"e": 30781,
"s": 30774,
"text": "Amazon"
},
{
"code": null,
"e": 30793,
"s": 30781,
"text": "Housing.com"
},
{
"code": null,
"e": 30803,
"s": 30793,
"text": "Microsoft"
},
{
"code": null,
"e": 30818,
"s": 30803,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 30826,
"s": 30818,
"text": "Strings"
},
{
"code": null,
"e": 30841,
"s": 30826,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 30848,
"s": 30841,
"text": "Amazon"
},
{
"code": null,
"e": 30858,
"s": 30848,
"text": "Microsoft"
},
{
"code": null,
"e": 30870,
"s": 30858,
"text": "Housing.com"
},
{
"code": null,
"e": 30878,
"s": 30870,
"text": "Strings"
},
{
"code": null,
"e": 30976,
"s": 30878,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30985,
"s": 30976,
"text": "Comments"
},
{
"code": null,
"e": 30998,
"s": 30985,
"text": "Old Comments"
},
{
"code": null,
"e": 31043,
"s": 30998,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 31060,
"s": 31043,
"text": "VigeneΜre Cipher"
},
{
"code": null,
"e": 31103,
"s": 31060,
"text": "How to Append a Character to a String in C"
},
{
"code": null,
"e": 31144,
"s": 31103,
"text": "Convert character array to string in C++"
},
{
"code": null,
"e": 31182,
"s": 31144,
"text": "Naive algorithm for Pattern Searching"
},
{
"code": null,
"e": 31236,
"s": 31182,
"text": "Return maximum occurring character in an input string"
},
{
"code": null,
"e": 31248,
"s": 31236,
"text": "Hill Cipher"
},
{
"code": null,
"e": 31263,
"s": 31248,
"text": "sprintf() in C"
},
{
"code": null,
"e": 31328,
"s": 31263,
"text": "A Program to check if strings are rotations of each other or not"
}
] |
Neural Networks with Memory. Understanding RNN, LSTM under 5 minutes | by Ramya Vidiyala | Towards Data Science
|
We always heard that Neural Networks (NNs)are inspired by biological neural networks. This huge representation was done in a fantastic way.
Figure 1 shows the anatomy of a single neuron. The central part is called the cell body where the nucleus resides. There are various wires which pass the stimulus to the cell body and few wires which send the output to the other neurons. The thickness of the dendrites implies the weight/bias/power of the stimulus. Many neurons with various cell bodies are stacked up which forms the biological neural network.
This same structure is implemented in Neural Networks. The input is passed through an activation function with weighted edges. The output is generated which can be passed to another activation function. Many activation functions can be stacked up, each of these is called a layer. And in a layer, we can have multiple neurons.
These activation functions can be as simple as a sigmoid function
Various types and sizes of data can be handled
Multiple functions can be easily configured
Non-linear data can be efficiently handled
The main difference between the functioning of neural networks and the biological neural network is memory. While both the human brain and neural networks have the ability to read and write from the memory available, the brain can create/store the memory as well. Researchers identified that this key difference is the major roadblock for todayβs AI systems to reach human-level intelligence.
Researchers at DeepMind aimed to build a differentiable computer, by putting together a neural network and linking it to external memory. The neural network would act as a CPU with a memory attached. Such differentiable computers aim to learn programs (algorithms) from input and output data.
The neural networks are used when the amount of data is huge. For example, text data has an enormous amount of dimensions or the image data which is split into a huge number of pixels.
A movie consists of a sequence of scenes. When we watch a particular scene, we donβt try to understand it in isolation, but rather in connection with previous scenes. In a similar fashion, a machine learning model has to understand the text by utilizing already-learned text, just like in a human neural network.
In traditional machine learning models, we cannot store a modelβs previous stages. However, Recurrent Neural Networks (commonly called RNN) can do this for us. Letβs take a closer look at RNNs below.
An RNN has a repeating module that takes input from the previous stage and gives its output as input to the next stage. However, in RNNs we can only retain information from the most recent stage. Thatβs where LSTM comes to the picture.
To learn long-term dependencies, our network needs memorization power. LSTMs are a special case of RNNs which can do that. They have the same chain-like structure as RNNs, but with a different repeating module structure.
LSTM has a wide range of applications in Sequence-to-Sequence modeling tasks like Speech Recognition, Text Summarization, Video Classification, and so on.
To understand how these networks can be adopted in real-life applications in a quick glance, do check the article below.
towardsdatascience.com
A spam detection model can be achieved by converting text data into vectors, creating an LSTM model, and fitting the model with the vectors.
To implement these complete neural networks, Keras and TensorFlow made it simple.
We are implementing a Bidirectional LSTM with the ReLU activation function.
#Importing necessary librariesimport tensorflow as tffrom keras.layers import LSTM, Activation, Bidirectional#Addding Bi-directional LSTMmodel.add(Bidirectional(tf.keras.layers.LSTM(64)))#Relu allows converging quickly and allows backpropagationmodel.add(Dense(16, activation='relu'))model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
Creating each layer is just a single line of code.
In this article, we learned how neural networks are linked to biological neural networks and the working of neural networks with memory (namely, RNN, LSTM).
Thanks for the read. I am going to write more beginner-friendly posts in the future too. Follow me up on Medium to be informed about them. I welcome feedback and can be reached out on Twitter ramya_vidiyala and LinkedIn RamyaVidiyala. Happy learning!
|
[
{
"code": null,
"e": 312,
"s": 172,
"text": "We always heard that Neural Networks (NNs)are inspired by biological neural networks. This huge representation was done in a fantastic way."
},
{
"code": null,
"e": 724,
"s": 312,
"text": "Figure 1 shows the anatomy of a single neuron. The central part is called the cell body where the nucleus resides. There are various wires which pass the stimulus to the cell body and few wires which send the output to the other neurons. The thickness of the dendrites implies the weight/bias/power of the stimulus. Many neurons with various cell bodies are stacked up which forms the biological neural network."
},
{
"code": null,
"e": 1051,
"s": 724,
"text": "This same structure is implemented in Neural Networks. The input is passed through an activation function with weighted edges. The output is generated which can be passed to another activation function. Many activation functions can be stacked up, each of these is called a layer. And in a layer, we can have multiple neurons."
},
{
"code": null,
"e": 1117,
"s": 1051,
"text": "These activation functions can be as simple as a sigmoid function"
},
{
"code": null,
"e": 1164,
"s": 1117,
"text": "Various types and sizes of data can be handled"
},
{
"code": null,
"e": 1208,
"s": 1164,
"text": "Multiple functions can be easily configured"
},
{
"code": null,
"e": 1251,
"s": 1208,
"text": "Non-linear data can be efficiently handled"
},
{
"code": null,
"e": 1644,
"s": 1251,
"text": "The main difference between the functioning of neural networks and the biological neural network is memory. While both the human brain and neural networks have the ability to read and write from the memory available, the brain can create/store the memory as well. Researchers identified that this key difference is the major roadblock for todayβs AI systems to reach human-level intelligence."
},
{
"code": null,
"e": 1937,
"s": 1644,
"text": "Researchers at DeepMind aimed to build a differentiable computer, by putting together a neural network and linking it to external memory. The neural network would act as a CPU with a memory attached. Such differentiable computers aim to learn programs (algorithms) from input and output data."
},
{
"code": null,
"e": 2122,
"s": 1937,
"text": "The neural networks are used when the amount of data is huge. For example, text data has an enormous amount of dimensions or the image data which is split into a huge number of pixels."
},
{
"code": null,
"e": 2435,
"s": 2122,
"text": "A movie consists of a sequence of scenes. When we watch a particular scene, we donβt try to understand it in isolation, but rather in connection with previous scenes. In a similar fashion, a machine learning model has to understand the text by utilizing already-learned text, just like in a human neural network."
},
{
"code": null,
"e": 2635,
"s": 2435,
"text": "In traditional machine learning models, we cannot store a modelβs previous stages. However, Recurrent Neural Networks (commonly called RNN) can do this for us. Letβs take a closer look at RNNs below."
},
{
"code": null,
"e": 2871,
"s": 2635,
"text": "An RNN has a repeating module that takes input from the previous stage and gives its output as input to the next stage. However, in RNNs we can only retain information from the most recent stage. Thatβs where LSTM comes to the picture."
},
{
"code": null,
"e": 3092,
"s": 2871,
"text": "To learn long-term dependencies, our network needs memorization power. LSTMs are a special case of RNNs which can do that. They have the same chain-like structure as RNNs, but with a different repeating module structure."
},
{
"code": null,
"e": 3247,
"s": 3092,
"text": "LSTM has a wide range of applications in Sequence-to-Sequence modeling tasks like Speech Recognition, Text Summarization, Video Classification, and so on."
},
{
"code": null,
"e": 3368,
"s": 3247,
"text": "To understand how these networks can be adopted in real-life applications in a quick glance, do check the article below."
},
{
"code": null,
"e": 3391,
"s": 3368,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3532,
"s": 3391,
"text": "A spam detection model can be achieved by converting text data into vectors, creating an LSTM model, and fitting the model with the vectors."
},
{
"code": null,
"e": 3614,
"s": 3532,
"text": "To implement these complete neural networks, Keras and TensorFlow made it simple."
},
{
"code": null,
"e": 3690,
"s": 3614,
"text": "We are implementing a Bidirectional LSTM with the ReLU activation function."
},
{
"code": null,
"e": 4056,
"s": 3690,
"text": "#Importing necessary librariesimport tensorflow as tffrom keras.layers import LSTM, Activation, Bidirectional#Addding Bi-directional LSTMmodel.add(Bidirectional(tf.keras.layers.LSTM(64)))#Relu allows converging quickly and allows backpropagationmodel.add(Dense(16, activation='relu'))model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])"
},
{
"code": null,
"e": 4107,
"s": 4056,
"text": "Creating each layer is just a single line of code."
},
{
"code": null,
"e": 4264,
"s": 4107,
"text": "In this article, we learned how neural networks are linked to biological neural networks and the working of neural networks with memory (namely, RNN, LSTM)."
}
] |
7 things to quickly improve your Data Analysis in Python | by Peter Nistrup | Towards Data Science
|
Take your Data Analysis to the next level!
Turning a blind eye to the completely obvious risk of sounding like a broken record I just want to voice yet another giant thank you to everyone whoβs been reading and sharing my last two articles: Python tricks 101, what every new programmer should know and Exploring your data with just 1 line of Python. Here I was, thinking that the βPython tricks 101...β article had been successful and then you go ahead and blow any expectations away once more.So, to quote myself:
βThanks and lets get on with it!β
For this article I thought it would be nice to create a list of things Iβve learned that have sped up or improved my average day-to-day data analysis. So without any further ado, hereβs a list of what weβll be covering in the article:
Pandas ProfilingPlotting Pandas data using Cufflinks & PlotlyIPython Magic CommandsFancy formatting in JupyterJupyter shortcutsMultiple outputs per cell in Jupyter (or IPython)Instantly create slideshows of your Jupyter Notebook
Pandas Profiling
Plotting Pandas data using Cufflinks & Plotly
IPython Magic Commands
Fancy formatting in Jupyter
Jupyter shortcuts
Multiple outputs per cell in Jupyter (or IPython)
Instantly create slideshows of your Jupyter Notebook
If these sound like something you might enjoy learning about, keep scrolling.
Note that this will be quite a long one. Still, Iβve tried my best to be as concise and as to-the-point as possible. I hope you enjoy!
This should be no surprise to those of you whoβve been following me. The benefits of this tool are obvious. The animation below is the results of calling the simple method df.profile_report(), take a look at the resulting report yourself:
Using this tool is simple a matter of installing and importing the Pandas Profiling package.
I wont spend too much time on this one since Iβve already written a small article on the subject, so if you want to know more about this gem of a package, then please read my article about Pandas Profiling here:
towardsdatascience.com
Most of us whoβre quote-unquote βexperiencedβ Data Scientist or Data Analysts, will be quite familiar with the integration between matplotlib and pandas. Namely the fact that you can make quick plots of a simple pd.DataFrame or pd.Series by simply calling the .plot() method:
Now this is all fine and dandy, but how about an interactive, pan-able, zoom-able, scale-able plot instead? Cufflinks to the rescue! (courtesy of Plotly)
To install Cufflinks in your environment simply run ! pip install cufflinks --upgrade in your favorite terminal and youβre ready to go. Take a look at the following:
Notice that the only thing that changed above is the imports and the setting of cf.go_offline() for Cufflinks. Other than that itβs simply a matter of changing your .plot() method to .iplot() .
Other methods like .scatter_matrix() can give you some really nice visualisation as well:
I urge anyone that works with a lot of data visualisation to take a look at the documentation for both Cufflinks and Plotly to discover more methods for yourselves!
The βMagicsβ of IPython are basically a series of enhancements that IPython has layered on-top of the standard Python syntax. Magic commands come in two flavors: line magics, which are denoted by a single % prefix and operate on a single line of input, and cell magics, which are denoted by a double %% prefix and operate on multiple lines of input. Below are just a few of the useful functionalities provided by the βMagicsβ:
Why not start with some good-old self-help? If youβre to remember just one Magic Command it should probably be this one. Executing the %lsmagic command will grant you a full list of all available Magic Commands:
This is probably the Magic Command I use the most.
Most of us have tried it: You find yourself executing a code-block that keeps breaking and you β in pure desperation β write 20 print()-statements to output the contents of each variable. Then, when you finally fix the issue, you have to go back and delete all the printing functionality again.
But not anymore! Simply execute the %debug command after encountering a problem and execute whatever part of the code you want:
So whatβs happening above?
We have a function that takes a list as input and squares all even number.We run our function but something breaks. Weβre not told at what!We use the %debug command to tab into the function at the time it broke.We ask the debugger to tell us the value of x as well as the type(x).The failure is obvious. Weβre passing '6' as a string!
We have a function that takes a list as input and squares all even number.
We run our function but something breaks. Weβre not told at what!
We use the %debug command to tab into the function at the time it broke.
We ask the debugger to tell us the value of x as well as the type(x).
The failure is obvious. Weβre passing '6' as a string!
This is highly useful for more complex functions as Iβm sure you can imagine!
This one is pretty cool as well. Letβs say for the sake of argument, that you spend a while cleaning some data in a notebook, now you want to test some functionality in another notebook so you have to either implement the functionality in the same notebook or save your data and load it in the other notebook right? Not with %store ! Simply store the variable and retrieve it in whatever other notebook you want:
%store [variable] stores the variable.%store -r [variable] reads/retrieves a stored variable.
Ever assigned some value to a variable but forgot the variable name? Maybe you accidentally deleted the cells responsibility for assigning the value to the variable? With %who you get a list of all globally assigned variables:
With this little command you get all the timing information you might need. Simply apply the %%time command to any piece of executable code you want and youβll get an output like this:
And this will be the last one Iβll talk about in this article. This one is especially useful for when youβve written some complicated function or class in your notebook that you want to save in its own file, separate from the notebook. Simply prefix the cell of your function or class with the %%writefile command followed by a filename to save it:
As you can see, we can simply save the function weβve created to a βutils.pyβ file and then weβre free to import it in whatever fashion we want. In other notebooks as well! (As long as theyβre in the same directory of the utils.py file)
This one is super cool! Basically Jupyter allows for some HTML / CSS formatting in the markdown cells. These are the once I use the most:
The blue and stylish one:
<div class="alert alert-block alert-info"> This is <b>fancy</b>!</div>
The red and slightly panic-inducing one:
<div class="alert alert-block alert-danger"> This is <b>baaaaad</b>!</div>
The green and calming one:
<div class="alert alert-block alert-success"> This is <b>gooood</b>!</div>
Take a look at them in action here:
These are quite nice for when you want to present some findings in a Notebook format!
Accessing and learning the keyboard shortcuts, you can use the command palette: Ctrl + Shift + P . This brings up a list of all functionalities of the notebook. The following is an excerpt of the most basic commands:
Esc : This will take you into command mode. This is also the mode in which you can navigate your notebook using the arrow-keys.
While in command mode:
A and B : Inserts a new cell [A]bove or [B]elow the current cell.
M : Changes the current cell to [M]arkdown.
Y : Changes the current cell to code. (y tho?)
D,D : [D]efinetly [D]eletes the current cell.
Enter : Takes you back into edit mode for the current cell.
While in edit mode:
Shift + Tab : Shows you the Docstring (documentation) for the the object you typed in the current cell β keep pressing the shortcut to cycle through modes of documentation.
Ctrl + Shift + - : Splits the current cell from where your cursor is.
Esc + F : Find and replace on your code excluding outputs.
Esc + O : Toggles cell output.
Selecting Multiple Cells:
Shift + Down and Shift + Up : Selects the next sell in a downwards or upwards direction. I think you can use the power of deduction to find out which is which.
Shift + M : Merges the selected cells.
As a side-note, remember that once cells are selected, you can delete / copy / cut / paste / run them as a batch.
This one is great. Have you ever wanted to display the .head() and the .tail() of a pandas DataFrame but you you gave up halfway-through because it was too much of a hassle to create the additional code-cell to run the .tail() method? Fear no more, now you can display all the outputs you want using the following lines of code:
from IPython.core.interactiveshell import InteractiveShellInteractiveShell.ast_node_interactivity = "all"
Now lo and behold, the power of multiple outputs:
With RISE you can instantly turn your Jupyter Notebook into a slideshow with a single keystroke. Best of all, the notebook is still active, so you can perform live coding while presenting! Take a look:
To use this brilliant tool, simple install RISE either by virtue of conda or pip depending on your environment:
conda install -c conda-forge rise/// OR ///pip install RISE
Now youβll be able to create fancy slides from your notebook by simply clicking the new button:
Thanks for reading. I would urge anyone to explore each point in more detail on your own to find out exactly what and how you want to apply them to your own workflows.
If you want to see and learn more, be sure to follow me on Mediumπ and Twitter π¦
|
[
{
"code": null,
"e": 215,
"s": 172,
"text": "Take your Data Analysis to the next level!"
},
{
"code": null,
"e": 687,
"s": 215,
"text": "Turning a blind eye to the completely obvious risk of sounding like a broken record I just want to voice yet another giant thank you to everyone whoβs been reading and sharing my last two articles: Python tricks 101, what every new programmer should know and Exploring your data with just 1 line of Python. Here I was, thinking that the βPython tricks 101...β article had been successful and then you go ahead and blow any expectations away once more.So, to quote myself:"
},
{
"code": null,
"e": 721,
"s": 687,
"text": "βThanks and lets get on with it!β"
},
{
"code": null,
"e": 956,
"s": 721,
"text": "For this article I thought it would be nice to create a list of things Iβve learned that have sped up or improved my average day-to-day data analysis. So without any further ado, hereβs a list of what weβll be covering in the article:"
},
{
"code": null,
"e": 1185,
"s": 956,
"text": "Pandas ProfilingPlotting Pandas data using Cufflinks & PlotlyIPython Magic CommandsFancy formatting in JupyterJupyter shortcutsMultiple outputs per cell in Jupyter (or IPython)Instantly create slideshows of your Jupyter Notebook"
},
{
"code": null,
"e": 1202,
"s": 1185,
"text": "Pandas Profiling"
},
{
"code": null,
"e": 1248,
"s": 1202,
"text": "Plotting Pandas data using Cufflinks & Plotly"
},
{
"code": null,
"e": 1271,
"s": 1248,
"text": "IPython Magic Commands"
},
{
"code": null,
"e": 1299,
"s": 1271,
"text": "Fancy formatting in Jupyter"
},
{
"code": null,
"e": 1317,
"s": 1299,
"text": "Jupyter shortcuts"
},
{
"code": null,
"e": 1367,
"s": 1317,
"text": "Multiple outputs per cell in Jupyter (or IPython)"
},
{
"code": null,
"e": 1420,
"s": 1367,
"text": "Instantly create slideshows of your Jupyter Notebook"
},
{
"code": null,
"e": 1498,
"s": 1420,
"text": "If these sound like something you might enjoy learning about, keep scrolling."
},
{
"code": null,
"e": 1633,
"s": 1498,
"text": "Note that this will be quite a long one. Still, Iβve tried my best to be as concise and as to-the-point as possible. I hope you enjoy!"
},
{
"code": null,
"e": 1872,
"s": 1633,
"text": "This should be no surprise to those of you whoβve been following me. The benefits of this tool are obvious. The animation below is the results of calling the simple method df.profile_report(), take a look at the resulting report yourself:"
},
{
"code": null,
"e": 1965,
"s": 1872,
"text": "Using this tool is simple a matter of installing and importing the Pandas Profiling package."
},
{
"code": null,
"e": 2177,
"s": 1965,
"text": "I wont spend too much time on this one since Iβve already written a small article on the subject, so if you want to know more about this gem of a package, then please read my article about Pandas Profiling here:"
},
{
"code": null,
"e": 2200,
"s": 2177,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2476,
"s": 2200,
"text": "Most of us whoβre quote-unquote βexperiencedβ Data Scientist or Data Analysts, will be quite familiar with the integration between matplotlib and pandas. Namely the fact that you can make quick plots of a simple pd.DataFrame or pd.Series by simply calling the .plot() method:"
},
{
"code": null,
"e": 2630,
"s": 2476,
"text": "Now this is all fine and dandy, but how about an interactive, pan-able, zoom-able, scale-able plot instead? Cufflinks to the rescue! (courtesy of Plotly)"
},
{
"code": null,
"e": 2796,
"s": 2630,
"text": "To install Cufflinks in your environment simply run ! pip install cufflinks --upgrade in your favorite terminal and youβre ready to go. Take a look at the following:"
},
{
"code": null,
"e": 2990,
"s": 2796,
"text": "Notice that the only thing that changed above is the imports and the setting of cf.go_offline() for Cufflinks. Other than that itβs simply a matter of changing your .plot() method to .iplot() ."
},
{
"code": null,
"e": 3080,
"s": 2990,
"text": "Other methods like .scatter_matrix() can give you some really nice visualisation as well:"
},
{
"code": null,
"e": 3245,
"s": 3080,
"text": "I urge anyone that works with a lot of data visualisation to take a look at the documentation for both Cufflinks and Plotly to discover more methods for yourselves!"
},
{
"code": null,
"e": 3672,
"s": 3245,
"text": "The βMagicsβ of IPython are basically a series of enhancements that IPython has layered on-top of the standard Python syntax. Magic commands come in two flavors: line magics, which are denoted by a single % prefix and operate on a single line of input, and cell magics, which are denoted by a double %% prefix and operate on multiple lines of input. Below are just a few of the useful functionalities provided by the βMagicsβ:"
},
{
"code": null,
"e": 3884,
"s": 3672,
"text": "Why not start with some good-old self-help? If youβre to remember just one Magic Command it should probably be this one. Executing the %lsmagic command will grant you a full list of all available Magic Commands:"
},
{
"code": null,
"e": 3935,
"s": 3884,
"text": "This is probably the Magic Command I use the most."
},
{
"code": null,
"e": 4230,
"s": 3935,
"text": "Most of us have tried it: You find yourself executing a code-block that keeps breaking and you β in pure desperation β write 20 print()-statements to output the contents of each variable. Then, when you finally fix the issue, you have to go back and delete all the printing functionality again."
},
{
"code": null,
"e": 4358,
"s": 4230,
"text": "But not anymore! Simply execute the %debug command after encountering a problem and execute whatever part of the code you want:"
},
{
"code": null,
"e": 4385,
"s": 4358,
"text": "So whatβs happening above?"
},
{
"code": null,
"e": 4720,
"s": 4385,
"text": "We have a function that takes a list as input and squares all even number.We run our function but something breaks. Weβre not told at what!We use the %debug command to tab into the function at the time it broke.We ask the debugger to tell us the value of x as well as the type(x).The failure is obvious. Weβre passing '6' as a string!"
},
{
"code": null,
"e": 4795,
"s": 4720,
"text": "We have a function that takes a list as input and squares all even number."
},
{
"code": null,
"e": 4861,
"s": 4795,
"text": "We run our function but something breaks. Weβre not told at what!"
},
{
"code": null,
"e": 4934,
"s": 4861,
"text": "We use the %debug command to tab into the function at the time it broke."
},
{
"code": null,
"e": 5004,
"s": 4934,
"text": "We ask the debugger to tell us the value of x as well as the type(x)."
},
{
"code": null,
"e": 5059,
"s": 5004,
"text": "The failure is obvious. Weβre passing '6' as a string!"
},
{
"code": null,
"e": 5137,
"s": 5059,
"text": "This is highly useful for more complex functions as Iβm sure you can imagine!"
},
{
"code": null,
"e": 5550,
"s": 5137,
"text": "This one is pretty cool as well. Letβs say for the sake of argument, that you spend a while cleaning some data in a notebook, now you want to test some functionality in another notebook so you have to either implement the functionality in the same notebook or save your data and load it in the other notebook right? Not with %store ! Simply store the variable and retrieve it in whatever other notebook you want:"
},
{
"code": null,
"e": 5644,
"s": 5550,
"text": "%store [variable] stores the variable.%store -r [variable] reads/retrieves a stored variable."
},
{
"code": null,
"e": 5871,
"s": 5644,
"text": "Ever assigned some value to a variable but forgot the variable name? Maybe you accidentally deleted the cells responsibility for assigning the value to the variable? With %who you get a list of all globally assigned variables:"
},
{
"code": null,
"e": 6056,
"s": 5871,
"text": "With this little command you get all the timing information you might need. Simply apply the %%time command to any piece of executable code you want and youβll get an output like this:"
},
{
"code": null,
"e": 6405,
"s": 6056,
"text": "And this will be the last one Iβll talk about in this article. This one is especially useful for when youβve written some complicated function or class in your notebook that you want to save in its own file, separate from the notebook. Simply prefix the cell of your function or class with the %%writefile command followed by a filename to save it:"
},
{
"code": null,
"e": 6642,
"s": 6405,
"text": "As you can see, we can simply save the function weβve created to a βutils.pyβ file and then weβre free to import it in whatever fashion we want. In other notebooks as well! (As long as theyβre in the same directory of the utils.py file)"
},
{
"code": null,
"e": 6780,
"s": 6642,
"text": "This one is super cool! Basically Jupyter allows for some HTML / CSS formatting in the markdown cells. These are the once I use the most:"
},
{
"code": null,
"e": 6806,
"s": 6780,
"text": "The blue and stylish one:"
},
{
"code": null,
"e": 6880,
"s": 6806,
"text": "<div class=\"alert alert-block alert-info\"> This is <b>fancy</b>!</div>"
},
{
"code": null,
"e": 6921,
"s": 6880,
"text": "The red and slightly panic-inducing one:"
},
{
"code": null,
"e": 6999,
"s": 6921,
"text": "<div class=\"alert alert-block alert-danger\"> This is <b>baaaaad</b>!</div>"
},
{
"code": null,
"e": 7026,
"s": 6999,
"text": "The green and calming one:"
},
{
"code": null,
"e": 7104,
"s": 7026,
"text": "<div class=\"alert alert-block alert-success\"> This is <b>gooood</b>!</div>"
},
{
"code": null,
"e": 7140,
"s": 7104,
"text": "Take a look at them in action here:"
},
{
"code": null,
"e": 7226,
"s": 7140,
"text": "These are quite nice for when you want to present some findings in a Notebook format!"
},
{
"code": null,
"e": 7443,
"s": 7226,
"text": "Accessing and learning the keyboard shortcuts, you can use the command palette: Ctrl + Shift + P . This brings up a list of all functionalities of the notebook. The following is an excerpt of the most basic commands:"
},
{
"code": null,
"e": 7571,
"s": 7443,
"text": "Esc : This will take you into command mode. This is also the mode in which you can navigate your notebook using the arrow-keys."
},
{
"code": null,
"e": 7594,
"s": 7571,
"text": "While in command mode:"
},
{
"code": null,
"e": 7660,
"s": 7594,
"text": "A and B : Inserts a new cell [A]bove or [B]elow the current cell."
},
{
"code": null,
"e": 7704,
"s": 7660,
"text": "M : Changes the current cell to [M]arkdown."
},
{
"code": null,
"e": 7751,
"s": 7704,
"text": "Y : Changes the current cell to code. (y tho?)"
},
{
"code": null,
"e": 7797,
"s": 7751,
"text": "D,D : [D]efinetly [D]eletes the current cell."
},
{
"code": null,
"e": 7857,
"s": 7797,
"text": "Enter : Takes you back into edit mode for the current cell."
},
{
"code": null,
"e": 7877,
"s": 7857,
"text": "While in edit mode:"
},
{
"code": null,
"e": 8050,
"s": 7877,
"text": "Shift + Tab : Shows you the Docstring (documentation) for the the object you typed in the current cell β keep pressing the shortcut to cycle through modes of documentation."
},
{
"code": null,
"e": 8120,
"s": 8050,
"text": "Ctrl + Shift + - : Splits the current cell from where your cursor is."
},
{
"code": null,
"e": 8179,
"s": 8120,
"text": "Esc + F : Find and replace on your code excluding outputs."
},
{
"code": null,
"e": 8210,
"s": 8179,
"text": "Esc + O : Toggles cell output."
},
{
"code": null,
"e": 8236,
"s": 8210,
"text": "Selecting Multiple Cells:"
},
{
"code": null,
"e": 8396,
"s": 8236,
"text": "Shift + Down and Shift + Up : Selects the next sell in a downwards or upwards direction. I think you can use the power of deduction to find out which is which."
},
{
"code": null,
"e": 8435,
"s": 8396,
"text": "Shift + M : Merges the selected cells."
},
{
"code": null,
"e": 8549,
"s": 8435,
"text": "As a side-note, remember that once cells are selected, you can delete / copy / cut / paste / run them as a batch."
},
{
"code": null,
"e": 8878,
"s": 8549,
"text": "This one is great. Have you ever wanted to display the .head() and the .tail() of a pandas DataFrame but you you gave up halfway-through because it was too much of a hassle to create the additional code-cell to run the .tail() method? Fear no more, now you can display all the outputs you want using the following lines of code:"
},
{
"code": null,
"e": 8984,
"s": 8878,
"text": "from IPython.core.interactiveshell import InteractiveShellInteractiveShell.ast_node_interactivity = \"all\""
},
{
"code": null,
"e": 9034,
"s": 8984,
"text": "Now lo and behold, the power of multiple outputs:"
},
{
"code": null,
"e": 9236,
"s": 9034,
"text": "With RISE you can instantly turn your Jupyter Notebook into a slideshow with a single keystroke. Best of all, the notebook is still active, so you can perform live coding while presenting! Take a look:"
},
{
"code": null,
"e": 9348,
"s": 9236,
"text": "To use this brilliant tool, simple install RISE either by virtue of conda or pip depending on your environment:"
},
{
"code": null,
"e": 9408,
"s": 9348,
"text": "conda install -c conda-forge rise/// OR ///pip install RISE"
},
{
"code": null,
"e": 9504,
"s": 9408,
"text": "Now youβll be able to create fancy slides from your notebook by simply clicking the new button:"
},
{
"code": null,
"e": 9672,
"s": 9504,
"text": "Thanks for reading. I would urge anyone to explore each point in more detail on your own to find out exactly what and how you want to apply them to your own workflows."
}
] |
Semaphore in C#
|
The semaphore class lets you set a limit on the number of threads that have access to a critical section. The class is used to control access to a pool of resources. System.Threading.Semaphore is the namespace for Semaphore because it has all the methods and properties required to implement Semaphore.
For using a semaphore in C#, you just need to instantiate an instance of a Semaphore object. It has minimum of two arguments β
β
MSDN
Let us now see an example:
Here, we have used the following Semaphore constructor that initializes a new instance of the Semaphore class, specifying the maximum number of concurrent entries and optionally reserving some entries.
static Semaphore semaphore = new Semaphore(2, 2);
Live Demo
using System;
using System.Threading;
namespace Program
{
class Demo
{
static Thread[] t = new Thread[5];
static Semaphore semaphore = new Semaphore(2, 2);
static void DoSomething()
{
Console.WriteLine("{0} = waiting", Thread.CurrentThread.Name);
semaphore.WaitOne();
Console.WriteLine("{0} begins!", Thread.CurrentThread.Name);
Thread.Sleep(1000);
Console.WriteLine("{0} releasing...", Thread.CurrentThread.Name);
semaphore.Release();
}
static void Main(string[] args)
{
for (int j = 0; j < 5; j++)
{
t[j] = new Thread(DoSomething);
t[j].Name = "thread number " + j;
t[j].Start();
}
Console.Read();
}
}
}
The following is the output
thread number 2 = waiting
thread number 0 = waiting
thread number 3 = waiting
thread number 1 = waiting
thread number 4 = waiting
thread number 2 begins!
thread number 1 begins!
thread number 2 releasing...
thread number 1 releasing...
thread number 4 begins!
thread number 3 begins!
thread number 4 releasing...
thread number 0 begins!
thread number 3 releasing...
thread number 0 releasing...
|
[
{
"code": null,
"e": 1365,
"s": 1062,
"text": "The semaphore class lets you set a limit on the number of threads that have access to a critical section. The class is used to control access to a pool of resources. System.Threading.Semaphore is the namespace for Semaphore because it has all the methods and properties required to implement Semaphore."
},
{
"code": null,
"e": 1492,
"s": 1365,
"text": "For using a semaphore in C#, you just need to instantiate an instance of a Semaphore object. It has minimum of two arguments β"
},
{
"code": null,
"e": 1494,
"s": 1492,
"text": "β"
},
{
"code": null,
"e": 1499,
"s": 1494,
"text": "MSDN"
},
{
"code": null,
"e": 1526,
"s": 1499,
"text": "Let us now see an example:"
},
{
"code": null,
"e": 1728,
"s": 1526,
"text": "Here, we have used the following Semaphore constructor that initializes a new instance of the Semaphore class, specifying the maximum number of concurrent entries and optionally reserving some entries."
},
{
"code": null,
"e": 1778,
"s": 1728,
"text": "static Semaphore semaphore = new Semaphore(2, 2);"
},
{
"code": null,
"e": 1789,
"s": 1778,
"text": " Live Demo"
},
{
"code": null,
"e": 2575,
"s": 1789,
"text": "using System;\nusing System.Threading;\nnamespace Program\n{\nclass Demo\n {\n static Thread[] t = new Thread[5];\n static Semaphore semaphore = new Semaphore(2, 2);\n static void DoSomething()\n {\n Console.WriteLine(\"{0} = waiting\", Thread.CurrentThread.Name);\n semaphore.WaitOne();\n Console.WriteLine(\"{0} begins!\", Thread.CurrentThread.Name);\n Thread.Sleep(1000);\n Console.WriteLine(\"{0} releasing...\", Thread.CurrentThread.Name);\n semaphore.Release();\n }\n static void Main(string[] args)\n {\n for (int j = 0; j < 5; j++)\n {\n t[j] = new Thread(DoSomething);\n t[j].Name = \"thread number \" + j;\n t[j].Start();\n }\n Console.Read();\n }\n }\n}"
},
{
"code": null,
"e": 2603,
"s": 2575,
"text": "The following is the output"
},
{
"code": null,
"e": 2998,
"s": 2603,
"text": "thread number 2 = waiting\nthread number 0 = waiting\nthread number 3 = waiting\nthread number 1 = waiting\nthread number 4 = waiting\nthread number 2 begins!\nthread number 1 begins!\nthread number 2 releasing...\nthread number 1 releasing...\nthread number 4 begins!\nthread number 3 begins!\nthread number 4 releasing...\nthread number 0 begins!\nthread number 3 releasing...\nthread number 0 releasing..."
}
] |
DynamoDB - Error Handling
|
On unsuccessful processing of a request, DynamoDB throws an error. Each error consists of the following components: HTTP status code, exception name, and message. Error management rests on your SDK, which propagates errors, or your own code.
Exceptions fall into different HTTP header status codes. The 4xx and 5xx hold errors related to request issues and AWS.
A selection of exceptions in the HTTP 4xx category are as follows β
AccessDeniedException β The client failed to sign the request correctly.
AccessDeniedException β The client failed to sign the request correctly.
ConditionalCheckFailedException β A condition evaluated to false.
ConditionalCheckFailedException β A condition evaluated to false.
IncompleteSignatureException β The request included an incomplete signature.
IncompleteSignatureException β The request included an incomplete signature.
Exceptions in the HTTP 5xx category are as follows β
Internal Server Error
Service Unavailable
Errors come from a variety of sources such as servers, switches, load balancers, and other pieces of structures and systems. Common solutions consist of simple retries, which supports reliability. All SDKs include this logic automatically, and you can set retry parameters to suit your application needs.
For example β Java offers a maxErrorRetry value to stop retries.
Amazon recommends using a backoff solution in addition to retries in order to control flow. This consists of progressively increasing wait periods between retries and eventually stopping after a fairly short period. Note SDKs perform automatic retries, but not exponential backoff.
The following program is an example of the retry backoff β
public enum Results {
SUCCESS,
NOT_READY,
THROTTLED,
SERVER_ERROR
}
public static void DoAndWaitExample() {
try {
// asynchronous operation.
long token = asyncOperation();
int retries = 0;
boolean retry = false;
do {
long waitTime = Math.min(getWaitTime(retries), MAX_WAIT_INTERVAL);
System.out.print(waitTime + "\n");
// Pause for result
Thread.sleep(waitTime);
// Get result
Results result = getAsyncOperationResult(token);
if (Results.SUCCESS == result) {
retry = false;
} else if (Results.NOT_READY == result) {
retry = true;
} else if (Results.THROTTLED == result) {
retry = true;
} else if (Results.SERVER_ERROR == result) {
retry = true;
} else {
// stop on other error
retry = false;
}
} while (retry && (retries++ < MAX_RETRIES));
}
catch (Exception ex) {
}
}
public static long getWaitTime(int retryCount) {
long waitTime = ((long) Math.pow(3, retryCount) * 100L);
return waitTime;
}
16 Lectures
1.5 hours
Harshit Srivastava
49 Lectures
3.5 hours
Niyazi Erdogan
48 Lectures
3 hours
Niyazi Erdogan
13 Lectures
1 hours
Harshit Srivastava
45 Lectures
4 hours
Pranjal Srivastava, Harshit Srivastava
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2633,
"s": 2391,
"text": "On unsuccessful processing of a request, DynamoDB throws an error. Each error consists of the following components: HTTP status code, exception name, and message. Error management rests on your SDK, which propagates errors, or your own code."
},
{
"code": null,
"e": 2753,
"s": 2633,
"text": "Exceptions fall into different HTTP header status codes. The 4xx and 5xx hold errors related to request issues and AWS."
},
{
"code": null,
"e": 2821,
"s": 2753,
"text": "A selection of exceptions in the HTTP 4xx category are as follows β"
},
{
"code": null,
"e": 2894,
"s": 2821,
"text": "AccessDeniedException β The client failed to sign the request correctly."
},
{
"code": null,
"e": 2967,
"s": 2894,
"text": "AccessDeniedException β The client failed to sign the request correctly."
},
{
"code": null,
"e": 3033,
"s": 2967,
"text": "ConditionalCheckFailedException β A condition evaluated to false."
},
{
"code": null,
"e": 3099,
"s": 3033,
"text": "ConditionalCheckFailedException β A condition evaluated to false."
},
{
"code": null,
"e": 3176,
"s": 3099,
"text": "IncompleteSignatureException β The request included an incomplete signature."
},
{
"code": null,
"e": 3253,
"s": 3176,
"text": "IncompleteSignatureException β The request included an incomplete signature."
},
{
"code": null,
"e": 3306,
"s": 3253,
"text": "Exceptions in the HTTP 5xx category are as follows β"
},
{
"code": null,
"e": 3328,
"s": 3306,
"text": "Internal Server Error"
},
{
"code": null,
"e": 3348,
"s": 3328,
"text": "Service Unavailable"
},
{
"code": null,
"e": 3653,
"s": 3348,
"text": "Errors come from a variety of sources such as servers, switches, load balancers, and other pieces of structures and systems. Common solutions consist of simple retries, which supports reliability. All SDKs include this logic automatically, and you can set retry parameters to suit your application needs."
},
{
"code": null,
"e": 3718,
"s": 3653,
"text": "For example β Java offers a maxErrorRetry value to stop retries."
},
{
"code": null,
"e": 4000,
"s": 3718,
"text": "Amazon recommends using a backoff solution in addition to retries in order to control flow. This consists of progressively increasing wait periods between retries and eventually stopping after a fairly short period. Note SDKs perform automatic retries, but not exponential backoff."
},
{
"code": null,
"e": 4059,
"s": 4000,
"text": "The following program is an example of the retry backoff β"
},
{
"code": null,
"e": 5297,
"s": 4059,
"text": "public enum Results { \n SUCCESS, \n NOT_READY, \n THROTTLED, \n SERVER_ERROR \n}\npublic static void DoAndWaitExample() { \n try {\n // asynchronous operation. \n long token = asyncOperation(); \n int retries = 0; \n boolean retry = false; \n \n do { \n long waitTime = Math.min(getWaitTime(retries), MAX_WAIT_INTERVAL); \n System.out.print(waitTime + \"\\n\"); \n \n // Pause for result \n Thread.sleep(waitTime); \n \n // Get result \n Results result = getAsyncOperationResult(token); \n \n if (Results.SUCCESS == result) { \n retry = false; \n } else if (Results.NOT_READY == result) { \n retry = true; \n } else if (Results.THROTTLED == result) { \n retry = true; \n } else if (Results.SERVER_ERROR == result) { \n retry = true; \n } else { \n \n // stop on other error \n retry = false; \n } \n } while (retry && (retries++ < MAX_RETRIES)); \n }\n catch (Exception ex) { \n } \n}\npublic static long getWaitTime(int retryCount) { \n long waitTime = ((long) Math.pow(3, retryCount) * 100L); \n return waitTime; \n}"
},
{
"code": null,
"e": 5332,
"s": 5297,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5352,
"s": 5332,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 5387,
"s": 5352,
"text": "\n 49 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5403,
"s": 5387,
"text": " Niyazi Erdogan"
},
{
"code": null,
"e": 5436,
"s": 5403,
"text": "\n 48 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5452,
"s": 5436,
"text": " Niyazi Erdogan"
},
{
"code": null,
"e": 5485,
"s": 5452,
"text": "\n 13 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5505,
"s": 5485,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 5538,
"s": 5505,
"text": "\n 45 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5578,
"s": 5538,
"text": " Pranjal Srivastava, Harshit Srivastava"
},
{
"code": null,
"e": 5585,
"s": 5578,
"text": " Print"
},
{
"code": null,
"e": 5596,
"s": 5585,
"text": " Add Notes"
}
] |
Multivariable time series forecasting using Stateless Neural Networks | by Arjeus A. Guevarra | Towards Data Science
|
Forecasting with multiple variables that aids a target variable with stateless deep learning.
Time series. Datasets that have a time element with them. Such data allow us to think about the combination of 2 properties of time series:
Seasonality β Patterns in data that tends to repeat over and over at a specific length of time.Trend β This is similar to regression, where we are capturing the global pattern of the series.The relevance of data tends to center at present time, meaning past and data close to present time is of greater influence and accuracy of future predictions is better when closer to present data (principle of entropy).
Seasonality β Patterns in data that tends to repeat over and over at a specific length of time.
Trend β This is similar to regression, where we are capturing the global pattern of the series.
The relevance of data tends to center at present time, meaning past and data close to present time is of greater influence and accuracy of future predictions is better when closer to present data (principle of entropy).
Such a combination is what makes time series special. The data at a point in time depends on the previous data. Intuitively, this is the cause and effect nature of events, such as the words that youβre reading makes sense based on the previous words.
Normally, machine learning only captures the trend, which makes training a typical machine learning model over time series expensive.
Normally forecasting a single variable involves creating a model that is a function of previous time data. This is known as autoregression of single variable.
The image above is a sample of an autoregression formula. [1]
We will not dive into the details of the formula, but notice the ff variables:
βdependent variable. The value of data at present time.
βindependent variable. Note that previous data are given values to the variables.
The rest are additional parameters and variables that refine the accuracy of the model.
But what if we have additional hypothetical variables that are correlated with the target variable? These could increase the accuracy of the target variable that we need through proper modelling.
When you think of time series, you immediately think of LSTMs, GRUs and other recurrent neural networks. But in this case we refuse to do this and instead rely on feedforward neural networks. Why is it? Letβs illustrate the two and why I chose to follow the latter:
Recurrent neural networks β These are graphs whose output is fed back to the input. As inference is being done, the output of the network are stored as states, ready to be inferred on the next time step.
Recurrent neural networks β These are graphs whose output is fed back to the input. As inference is being done, the output of the network are stored as states, ready to be inferred on the next time step.
The recurrent network attempts to predict the next timestep through the following:
At β Actual input value at time t.Xt β The previous state of the RNN or the modelled prediction
At β Actual input value at time t.
Xt β The previous state of the RNN or the modelled prediction
With the variables above, the network achieves its predictive power by minimizing the error between the modelled data and actual data. However, notice that as the RNN passes through different temporal data, the error of predictive model increases.
LSTMs and GRUs appear to solve this problem, as it contains gates that accepts or forgets previous data that are considered irrelevant. However, these gates and data transformations cannot specifically be controlled into a critical aspect of time series analysis: how various timestates relate to one another.
In the image below, the timestep becomes a vector to a cell with an activation function. Thus, the relationship of the timesteps are captured vs the target future step.
We can then move to the implementation proper for the specifics of the pipeline and the model designed.
The complete code implementation is located on Github at https://github.com/arjay55/time_series_stateless.git
I. Libraries
The libraries mainly consist of the ff:
pandas β for data preparationScikit-learn (sklearn) and scipyβ for external loss function and for scalingseaborn β for heatmap visualizationskopt β an optimization module which includes Bayesian optimization. We will use this for hyperparameter tuning during training.TensorFlow β an open-source library for deep learning. We used the latest version, tensorflow-beta1.
pandas β for data preparation
Scikit-learn (sklearn) and scipyβ for external loss function and for scaling
seaborn β for heatmap visualization
skopt β an optimization module which includes Bayesian optimization. We will use this for hyperparameter tuning during training.
TensorFlow β an open-source library for deep learning. We used the latest version, tensorflow-beta1.
II. Data Preparation
We will only load the normalized dataset for data privacy.
First, we load the normalized dataset.
Upon examining the DataFrame, we have 3 columns1. mutual_unit β this is the trust fund units, convertible to the currency of investment. The higher its value, the more returns you have on your investment.2. stock_exchange β this is the index for an aggregate of stock prices from various companies in a company.3. inflation β inflation rate of a given country.
These variables are chosen as they are representative characteristics of financial status of a given country.
Note that the inflation column has a lot empty or null values. One technique is to fill the data with assumed values:1. Linear interpolation in the upper and lowermost indices of the dataset.2. ARIMA based extrapolation beyond the furthest indices. Why? It is easier to model the outer portions using 2 forecasting steps only.
We saved the file to a csv for consumption of another programming language, R. I chose to use this as its βauto-arimaβ function is popular and mature compared to Python equivalent.
We will have 2 outputs:1. backasted[2] values to x steps β βbackastedβ means forecasting backwards, or simply reversing the time series and performing forecasting.2. forecasted values to y steps β the usual forecasting.
The x and y values are determined by function get_outernan and fill_data fills the missing data with assumed values.
In Rstudio, we load the interpolated inflation dataset and perform simple ARIMA:
In forecasting, regular ARIMA is done
In βbackcastingβ, notice the use rev() function prior to timeseries ts() function to transform data to timeseries.
The get get_outernan function returned values (6,15), where it is the number of steps to backcast and forecast respectively.
III. Data Exploration
Now that we have prepared the data for analysis, we can start exploring them to examine its data quality and simplify the data using domain expertise.
First, letβs refine our objective. Remember that we are intending to forecast a single variable. That variable is the mutual_unit. We have 3 variables
Our intent is to forecast the mutual_unit variable with the aid of helper variables, which are stock_exchange and inflation.
Letβs plot the three variables:
Upon examining the graphs, there may be some correlation between the mutual_unit and stock_exchange. For inflation, the values have a pivot from going up to going down.
As an additional analysis letβs perform a timestep vs timestep correlation analysis. Weβll use a heatmap to review the correlations.
On the first snip (correl.py), it produces a heatmap.
We can see that mutual_unit has high levels of correlation:
Note: As of the time of this writing, it appears that inflation has negative correlation with the mutual_unit. This could be that the unit goes higher to recover from the increase in inflation. You could try reducing the time window of interest and it may increase the model accuracy.
In our model, we need to specify the weights of the variables. This is the 2nd part of the code (correl2). Since we are using stock_exchange and inflation as helper variables, their weight will have these effects:
Higher weights mean higher correlation with the target variable.Lower weights is the opposite of the above. If higher weights are specified, then the noise of the variable will overfit or make the target variable less accurate.
Higher weights mean higher correlation with the target variable.
Lower weights is the opposite of the above. If higher weights are specified, then the noise of the variable will overfit or make the target variable less accurate.
To be set as weights for our model. The correlations are scaled as follows:
ABS(VARIABLEx)/SUM(ABS(VARIABLES))
where VARIABLEx is the correlation coeff. divided by the sum of the variableβs correlation coeffs. Note that absolute values are taken prior to other computations.
Note that the three have about the same proportion as they have correlations versus mutual_unit.
This is the part where we apply machine learning to make predictions! This is not magical of course, the process is still stochastic and mathematical. It is just its information processing techniques that make its prediction impressive.
The type of prediction we make is regression, where we are predicting continuous values. In regression, we model continuous values. In classification, we model discrete values. In the image below, a certain metric is represented in two types. In discrete or classification, the values are mild, moderate or severe. In the right axis, the metric is represented as continuous values.
Our data is a time series, therefore, apart from its feature values, there is a forward moving time. While our dataset contains trend and seasonality, it is important to truncate the dataset into a rolling window. Why? Because using the entire history may overfit the model.
In our case, 1 month of window may suffice, or 4 business weeks. This assumption means that most of the properties can be modeled using this window.
Note: From this point I will mention the function that are used in the implementations below.
We also need to define the scope of rolling window. In our case, we will assume 3 months of training data to characterize the model.
Weβll now split the train and test datasets:
The code above shows the creation of train and test dataset. The result is a TimeseriesGenerator that already creates the rolling window datasets.
We are splitting the train/test dataset by 80%/20%. Note that the test data has batch size of only 1, where as we will encounter later, the test set will be compared 1 by 1 to form the validation error.
The training window size is 20.
The model is of Sequential in nature, meaning the layers are stacked into a single input/single output without any branching.
The model starts from βdenseβ then ending at the βdense_2β layer.
The 1st layer (βdenseβ) is simply a dot multiplication, which is equivalent to linear vector autoregression (VAR), with adjustable number of parameters for added complexity. It does not contain stochastic parameters.The 2nd layer (βdense_1β) is an additional layer to learn further nonlinearities.The Next layers are namely, a. Dropout layer βlayer that randomly disconnects certain weights during training. This helps the network learn nonlinearities in logical forms while reducing overfitting.b. Flatten layer β layer that permutes the previous hidden layer into the output layer. The output dimension is equal to the target variableβs dimension.
The 1st layer (βdenseβ) is simply a dot multiplication, which is equivalent to linear vector autoregression (VAR), with adjustable number of parameters for added complexity. It does not contain stochastic parameters.
The 2nd layer (βdense_1β) is an additional layer to learn further nonlinearities.
The Next layers are namely, a. Dropout layer βlayer that randomly disconnects certain weights during training. This helps the network learn nonlinearities in logical forms while reducing overfitting.b. Flatten layer β layer that permutes the previous hidden layer into the output layer. The output dimension is equal to the target variableβs dimension.
Function: train_evaluate()
Recall that recurrent networks only model the current and the next timestep. What if we only want an autoregressive model that characterizes the next timestep with the previous timesteps? (See Figure above, βFeedforward network that relates various timesteps vs the next timestepβ). Weβll then a stateless network as it simplifies the model.
Another important characteristic is input masking. Recall that our input shape has 20 timesteps. We will not use these shape as input layer shape:
Using all timesteps may introduce overfitting.As we are training as rolling window to capture the seasonality, we will use input skips to capture the seasonality at different scales.Further timesteps have lesser relevance to present value.
Using all timesteps may introduce overfitting.
As we are training as rolling window to capture the seasonality, we will use input skips to capture the seasonality at different scales.
Further timesteps have lesser relevance to present value.
With these, we only have 11 inputs at input layer. You can try different combinations to mask.
Hyperparameters are mainly the adjustable arguments when instantiating or training a model.
As an example, the gist above instantiates a βDenseβ layer. Those that are parts of the kwargs dictionary are hyperparameters:
The βinput_layerβ is the number of neurons created. Adjusting these will directly affect the modelβs capacity to adjust to nonlinearities (underfit or overfit).The βuni_regβ applies L1 regularization to that layer. Higher parameter values will adjust more slowly, reducing the risk of overfitting.
The βinput_layerβ is the number of neurons created. Adjusting these will directly affect the modelβs capacity to adjust to nonlinearities (underfit or overfit).
The βuni_regβ applies L1 regularization to that layer. Higher parameter values will adjust more slowly, reducing the risk of overfitting.
Here are the modelβs hyperparameters:
The gist above is created using the library called βskopt.spaceβ, where you specify the ranges and categories to optimize.
Afterwards, we wrap the entire pipeline into a function and run the optimization function command. This is the reason we created a large function called
train_evaluate(normalized_data, est_period,loss_func,param_record, **kwargs)
It contains model creation, validation process, etc. Feel free to study it.
Now, to the hyperparameter optimization command.
We are optimizing the parameters using Bayesian optimization of Gaussian Probabilities. It essentially maps a probabilistic model of the optimization space. An assumption on navigating space between exploitation (suspected value) and exploration(creating real data points) [4]
Testing this autoregressive problem has a lot of components:
Test sets during training
Test sets during training
these are the test values where features at X(t+1) are predicted
2. Iterative prediction for multi-step prediction
First, letβs remind ourselves of our target variable, mutual_unit .
In order to perform the validation of this variable, the 3 variables need to be predicted at X(t+1). The input data are pushed to the left, then the latest timestep data are replaced with the predicted data. The process are iterated to achieve the iteration at multi-steps.
The function that does this is
validation()
The validation function does the iterative forecast and is compared with the corresponding test data. Note that only mutual_unit is only held out and compared.
Now, the vectors y_pred and y_true are future values. Entropy or unpredictability increases as time steps are forecasted further. Therefore we will introduce a discount factor to these values. In our application, the discount factor is 0.9.
After this, the mean absolute error is computed. This will be the main validation metric as measure of the modelβs performance.
This MAE will serve as metric for Early stopping.
Early stopping is applied to our validation metric (MAE) to mitigate the risk overfitting. It stops once the validation error begins to increase.However, it has the risk of not full reaching full optimality as the validation value is assumed to be convex, as once the inflection point of the error is founded, training is halted.
I used a hand-coded Early stopper and not an API from TensorFlow due to a customized validation computation plus it is easier to code it rather to find an appropriate API. The object name is
class CustomEarlyStopper: def __init__(self, patience=3, delta=1e-4): ...
It has similar parameters like patience and delta, which acts as a tolerance to increases in validation error.
Letβs take a look between predicted and actual values. Notice the predicted values have a positive offset above the predict value.
We are now preparing the model for inferential use.
Using the final parameters, we reoptimize the model to reach the same validation error during hyperparameter tuning. These can be obtained through loading the optimization object.
Using the final parameters, we reoptimize the model to reach the same validation error during hyperparameter tuning. These can be obtained through loading the optimization object.
In the notebook, you can notice the functions jump() and load() to make persistent(save to disk). The functions are placed to facilitate usage of objects upon system interruption.
Note: You can refactor the code so that the model optimized with the best hyperparameters are made persistent(user) so as to avoid re-training as above.
2. After this, capture the last training loss of the last optimal training. Note that this is the training loss to apply and NOT validation loss. This technique can also be refactored.
3. Finally, we have to train the model using the entire dataset. To reduce the risk of overfitting, weβll get the previous training loss from the last trained model. Weβll stop the model training once the target training loss is achieved.
Thank you for reading and hope you learned about the basics of time series forecasting, from data preparation to modelling. I had fun sharing this experience in as much as having fun learning, discovering and applying deep learning on simple time series forecasting.
[1] Autoregressive model, Wikipedia
[2] βRob J Hyndmanβ, Backcasting in R (2014)
[3] Vector autoregression, Wikipedia
[4] Gilles Louppe, Manoj Kumar, Bayesian optimization with skopt (2016)
|
[
{
"code": null,
"e": 266,
"s": 172,
"text": "Forecasting with multiple variables that aids a target variable with stateless deep learning."
},
{
"code": null,
"e": 406,
"s": 266,
"text": "Time series. Datasets that have a time element with them. Such data allow us to think about the combination of 2 properties of time series:"
},
{
"code": null,
"e": 816,
"s": 406,
"text": "Seasonality β Patterns in data that tends to repeat over and over at a specific length of time.Trend β This is similar to regression, where we are capturing the global pattern of the series.The relevance of data tends to center at present time, meaning past and data close to present time is of greater influence and accuracy of future predictions is better when closer to present data (principle of entropy)."
},
{
"code": null,
"e": 912,
"s": 816,
"text": "Seasonality β Patterns in data that tends to repeat over and over at a specific length of time."
},
{
"code": null,
"e": 1008,
"s": 912,
"text": "Trend β This is similar to regression, where we are capturing the global pattern of the series."
},
{
"code": null,
"e": 1228,
"s": 1008,
"text": "The relevance of data tends to center at present time, meaning past and data close to present time is of greater influence and accuracy of future predictions is better when closer to present data (principle of entropy)."
},
{
"code": null,
"e": 1479,
"s": 1228,
"text": "Such a combination is what makes time series special. The data at a point in time depends on the previous data. Intuitively, this is the cause and effect nature of events, such as the words that youβre reading makes sense based on the previous words."
},
{
"code": null,
"e": 1613,
"s": 1479,
"text": "Normally, machine learning only captures the trend, which makes training a typical machine learning model over time series expensive."
},
{
"code": null,
"e": 1772,
"s": 1613,
"text": "Normally forecasting a single variable involves creating a model that is a function of previous time data. This is known as autoregression of single variable."
},
{
"code": null,
"e": 1834,
"s": 1772,
"text": "The image above is a sample of an autoregression formula. [1]"
},
{
"code": null,
"e": 1913,
"s": 1834,
"text": "We will not dive into the details of the formula, but notice the ff variables:"
},
{
"code": null,
"e": 1969,
"s": 1913,
"text": "βdependent variable. The value of data at present time."
},
{
"code": null,
"e": 2051,
"s": 1969,
"text": "βindependent variable. Note that previous data are given values to the variables."
},
{
"code": null,
"e": 2139,
"s": 2051,
"text": "The rest are additional parameters and variables that refine the accuracy of the model."
},
{
"code": null,
"e": 2335,
"s": 2139,
"text": "But what if we have additional hypothetical variables that are correlated with the target variable? These could increase the accuracy of the target variable that we need through proper modelling."
},
{
"code": null,
"e": 2601,
"s": 2335,
"text": "When you think of time series, you immediately think of LSTMs, GRUs and other recurrent neural networks. But in this case we refuse to do this and instead rely on feedforward neural networks. Why is it? Letβs illustrate the two and why I chose to follow the latter:"
},
{
"code": null,
"e": 2805,
"s": 2601,
"text": "Recurrent neural networks β These are graphs whose output is fed back to the input. As inference is being done, the output of the network are stored as states, ready to be inferred on the next time step."
},
{
"code": null,
"e": 3009,
"s": 2805,
"text": "Recurrent neural networks β These are graphs whose output is fed back to the input. As inference is being done, the output of the network are stored as states, ready to be inferred on the next time step."
},
{
"code": null,
"e": 3092,
"s": 3009,
"text": "The recurrent network attempts to predict the next timestep through the following:"
},
{
"code": null,
"e": 3188,
"s": 3092,
"text": "At β Actual input value at time t.Xt β The previous state of the RNN or the modelled prediction"
},
{
"code": null,
"e": 3223,
"s": 3188,
"text": "At β Actual input value at time t."
},
{
"code": null,
"e": 3285,
"s": 3223,
"text": "Xt β The previous state of the RNN or the modelled prediction"
},
{
"code": null,
"e": 3533,
"s": 3285,
"text": "With the variables above, the network achieves its predictive power by minimizing the error between the modelled data and actual data. However, notice that as the RNN passes through different temporal data, the error of predictive model increases."
},
{
"code": null,
"e": 3843,
"s": 3533,
"text": "LSTMs and GRUs appear to solve this problem, as it contains gates that accepts or forgets previous data that are considered irrelevant. However, these gates and data transformations cannot specifically be controlled into a critical aspect of time series analysis: how various timestates relate to one another."
},
{
"code": null,
"e": 4012,
"s": 3843,
"text": "In the image below, the timestep becomes a vector to a cell with an activation function. Thus, the relationship of the timesteps are captured vs the target future step."
},
{
"code": null,
"e": 4116,
"s": 4012,
"text": "We can then move to the implementation proper for the specifics of the pipeline and the model designed."
},
{
"code": null,
"e": 4226,
"s": 4116,
"text": "The complete code implementation is located on Github at https://github.com/arjay55/time_series_stateless.git"
},
{
"code": null,
"e": 4239,
"s": 4226,
"text": "I. Libraries"
},
{
"code": null,
"e": 4279,
"s": 4239,
"text": "The libraries mainly consist of the ff:"
},
{
"code": null,
"e": 4648,
"s": 4279,
"text": "pandas β for data preparationScikit-learn (sklearn) and scipyβ for external loss function and for scalingseaborn β for heatmap visualizationskopt β an optimization module which includes Bayesian optimization. We will use this for hyperparameter tuning during training.TensorFlow β an open-source library for deep learning. We used the latest version, tensorflow-beta1."
},
{
"code": null,
"e": 4678,
"s": 4648,
"text": "pandas β for data preparation"
},
{
"code": null,
"e": 4755,
"s": 4678,
"text": "Scikit-learn (sklearn) and scipyβ for external loss function and for scaling"
},
{
"code": null,
"e": 4791,
"s": 4755,
"text": "seaborn β for heatmap visualization"
},
{
"code": null,
"e": 4920,
"s": 4791,
"text": "skopt β an optimization module which includes Bayesian optimization. We will use this for hyperparameter tuning during training."
},
{
"code": null,
"e": 5021,
"s": 4920,
"text": "TensorFlow β an open-source library for deep learning. We used the latest version, tensorflow-beta1."
},
{
"code": null,
"e": 5042,
"s": 5021,
"text": "II. Data Preparation"
},
{
"code": null,
"e": 5101,
"s": 5042,
"text": "We will only load the normalized dataset for data privacy."
},
{
"code": null,
"e": 5140,
"s": 5101,
"text": "First, we load the normalized dataset."
},
{
"code": null,
"e": 5501,
"s": 5140,
"text": "Upon examining the DataFrame, we have 3 columns1. mutual_unit β this is the trust fund units, convertible to the currency of investment. The higher its value, the more returns you have on your investment.2. stock_exchange β this is the index for an aggregate of stock prices from various companies in a company.3. inflation β inflation rate of a given country."
},
{
"code": null,
"e": 5611,
"s": 5501,
"text": "These variables are chosen as they are representative characteristics of financial status of a given country."
},
{
"code": null,
"e": 5938,
"s": 5611,
"text": "Note that the inflation column has a lot empty or null values. One technique is to fill the data with assumed values:1. Linear interpolation in the upper and lowermost indices of the dataset.2. ARIMA based extrapolation beyond the furthest indices. Why? It is easier to model the outer portions using 2 forecasting steps only."
},
{
"code": null,
"e": 6119,
"s": 5938,
"text": "We saved the file to a csv for consumption of another programming language, R. I chose to use this as its βauto-arimaβ function is popular and mature compared to Python equivalent."
},
{
"code": null,
"e": 6339,
"s": 6119,
"text": "We will have 2 outputs:1. backasted[2] values to x steps β βbackastedβ means forecasting backwards, or simply reversing the time series and performing forecasting.2. forecasted values to y steps β the usual forecasting."
},
{
"code": null,
"e": 6456,
"s": 6339,
"text": "The x and y values are determined by function get_outernan and fill_data fills the missing data with assumed values."
},
{
"code": null,
"e": 6537,
"s": 6456,
"text": "In Rstudio, we load the interpolated inflation dataset and perform simple ARIMA:"
},
{
"code": null,
"e": 6575,
"s": 6537,
"text": "In forecasting, regular ARIMA is done"
},
{
"code": null,
"e": 6690,
"s": 6575,
"text": "In βbackcastingβ, notice the use rev() function prior to timeseries ts() function to transform data to timeseries."
},
{
"code": null,
"e": 6815,
"s": 6690,
"text": "The get get_outernan function returned values (6,15), where it is the number of steps to backcast and forecast respectively."
},
{
"code": null,
"e": 6837,
"s": 6815,
"text": "III. Data Exploration"
},
{
"code": null,
"e": 6988,
"s": 6837,
"text": "Now that we have prepared the data for analysis, we can start exploring them to examine its data quality and simplify the data using domain expertise."
},
{
"code": null,
"e": 7139,
"s": 6988,
"text": "First, letβs refine our objective. Remember that we are intending to forecast a single variable. That variable is the mutual_unit. We have 3 variables"
},
{
"code": null,
"e": 7264,
"s": 7139,
"text": "Our intent is to forecast the mutual_unit variable with the aid of helper variables, which are stock_exchange and inflation."
},
{
"code": null,
"e": 7296,
"s": 7264,
"text": "Letβs plot the three variables:"
},
{
"code": null,
"e": 7465,
"s": 7296,
"text": "Upon examining the graphs, there may be some correlation between the mutual_unit and stock_exchange. For inflation, the values have a pivot from going up to going down."
},
{
"code": null,
"e": 7598,
"s": 7465,
"text": "As an additional analysis letβs perform a timestep vs timestep correlation analysis. Weβll use a heatmap to review the correlations."
},
{
"code": null,
"e": 7652,
"s": 7598,
"text": "On the first snip (correl.py), it produces a heatmap."
},
{
"code": null,
"e": 7712,
"s": 7652,
"text": "We can see that mutual_unit has high levels of correlation:"
},
{
"code": null,
"e": 7997,
"s": 7712,
"text": "Note: As of the time of this writing, it appears that inflation has negative correlation with the mutual_unit. This could be that the unit goes higher to recover from the increase in inflation. You could try reducing the time window of interest and it may increase the model accuracy."
},
{
"code": null,
"e": 8211,
"s": 7997,
"text": "In our model, we need to specify the weights of the variables. This is the 2nd part of the code (correl2). Since we are using stock_exchange and inflation as helper variables, their weight will have these effects:"
},
{
"code": null,
"e": 8439,
"s": 8211,
"text": "Higher weights mean higher correlation with the target variable.Lower weights is the opposite of the above. If higher weights are specified, then the noise of the variable will overfit or make the target variable less accurate."
},
{
"code": null,
"e": 8504,
"s": 8439,
"text": "Higher weights mean higher correlation with the target variable."
},
{
"code": null,
"e": 8668,
"s": 8504,
"text": "Lower weights is the opposite of the above. If higher weights are specified, then the noise of the variable will overfit or make the target variable less accurate."
},
{
"code": null,
"e": 8744,
"s": 8668,
"text": "To be set as weights for our model. The correlations are scaled as follows:"
},
{
"code": null,
"e": 8779,
"s": 8744,
"text": "ABS(VARIABLEx)/SUM(ABS(VARIABLES))"
},
{
"code": null,
"e": 8943,
"s": 8779,
"text": "where VARIABLEx is the correlation coeff. divided by the sum of the variableβs correlation coeffs. Note that absolute values are taken prior to other computations."
},
{
"code": null,
"e": 9040,
"s": 8943,
"text": "Note that the three have about the same proportion as they have correlations versus mutual_unit."
},
{
"code": null,
"e": 9277,
"s": 9040,
"text": "This is the part where we apply machine learning to make predictions! This is not magical of course, the process is still stochastic and mathematical. It is just its information processing techniques that make its prediction impressive."
},
{
"code": null,
"e": 9659,
"s": 9277,
"text": "The type of prediction we make is regression, where we are predicting continuous values. In regression, we model continuous values. In classification, we model discrete values. In the image below, a certain metric is represented in two types. In discrete or classification, the values are mild, moderate or severe. In the right axis, the metric is represented as continuous values."
},
{
"code": null,
"e": 9934,
"s": 9659,
"text": "Our data is a time series, therefore, apart from its feature values, there is a forward moving time. While our dataset contains trend and seasonality, it is important to truncate the dataset into a rolling window. Why? Because using the entire history may overfit the model."
},
{
"code": null,
"e": 10083,
"s": 9934,
"text": "In our case, 1 month of window may suffice, or 4 business weeks. This assumption means that most of the properties can be modeled using this window."
},
{
"code": null,
"e": 10177,
"s": 10083,
"text": "Note: From this point I will mention the function that are used in the implementations below."
},
{
"code": null,
"e": 10310,
"s": 10177,
"text": "We also need to define the scope of rolling window. In our case, we will assume 3 months of training data to characterize the model."
},
{
"code": null,
"e": 10355,
"s": 10310,
"text": "Weβll now split the train and test datasets:"
},
{
"code": null,
"e": 10502,
"s": 10355,
"text": "The code above shows the creation of train and test dataset. The result is a TimeseriesGenerator that already creates the rolling window datasets."
},
{
"code": null,
"e": 10705,
"s": 10502,
"text": "We are splitting the train/test dataset by 80%/20%. Note that the test data has batch size of only 1, where as we will encounter later, the test set will be compared 1 by 1 to form the validation error."
},
{
"code": null,
"e": 10737,
"s": 10705,
"text": "The training window size is 20."
},
{
"code": null,
"e": 10863,
"s": 10737,
"text": "The model is of Sequential in nature, meaning the layers are stacked into a single input/single output without any branching."
},
{
"code": null,
"e": 10929,
"s": 10863,
"text": "The model starts from βdenseβ then ending at the βdense_2β layer."
},
{
"code": null,
"e": 11579,
"s": 10929,
"text": "The 1st layer (βdenseβ) is simply a dot multiplication, which is equivalent to linear vector autoregression (VAR), with adjustable number of parameters for added complexity. It does not contain stochastic parameters.The 2nd layer (βdense_1β) is an additional layer to learn further nonlinearities.The Next layers are namely, a. Dropout layer βlayer that randomly disconnects certain weights during training. This helps the network learn nonlinearities in logical forms while reducing overfitting.b. Flatten layer β layer that permutes the previous hidden layer into the output layer. The output dimension is equal to the target variableβs dimension."
},
{
"code": null,
"e": 11796,
"s": 11579,
"text": "The 1st layer (βdenseβ) is simply a dot multiplication, which is equivalent to linear vector autoregression (VAR), with adjustable number of parameters for added complexity. It does not contain stochastic parameters."
},
{
"code": null,
"e": 11878,
"s": 11796,
"text": "The 2nd layer (βdense_1β) is an additional layer to learn further nonlinearities."
},
{
"code": null,
"e": 12231,
"s": 11878,
"text": "The Next layers are namely, a. Dropout layer βlayer that randomly disconnects certain weights during training. This helps the network learn nonlinearities in logical forms while reducing overfitting.b. Flatten layer β layer that permutes the previous hidden layer into the output layer. The output dimension is equal to the target variableβs dimension."
},
{
"code": null,
"e": 12258,
"s": 12231,
"text": "Function: train_evaluate()"
},
{
"code": null,
"e": 12600,
"s": 12258,
"text": "Recall that recurrent networks only model the current and the next timestep. What if we only want an autoregressive model that characterizes the next timestep with the previous timesteps? (See Figure above, βFeedforward network that relates various timesteps vs the next timestepβ). Weβll then a stateless network as it simplifies the model."
},
{
"code": null,
"e": 12747,
"s": 12600,
"text": "Another important characteristic is input masking. Recall that our input shape has 20 timesteps. We will not use these shape as input layer shape:"
},
{
"code": null,
"e": 12987,
"s": 12747,
"text": "Using all timesteps may introduce overfitting.As we are training as rolling window to capture the seasonality, we will use input skips to capture the seasonality at different scales.Further timesteps have lesser relevance to present value."
},
{
"code": null,
"e": 13034,
"s": 12987,
"text": "Using all timesteps may introduce overfitting."
},
{
"code": null,
"e": 13171,
"s": 13034,
"text": "As we are training as rolling window to capture the seasonality, we will use input skips to capture the seasonality at different scales."
},
{
"code": null,
"e": 13229,
"s": 13171,
"text": "Further timesteps have lesser relevance to present value."
},
{
"code": null,
"e": 13324,
"s": 13229,
"text": "With these, we only have 11 inputs at input layer. You can try different combinations to mask."
},
{
"code": null,
"e": 13416,
"s": 13324,
"text": "Hyperparameters are mainly the adjustable arguments when instantiating or training a model."
},
{
"code": null,
"e": 13543,
"s": 13416,
"text": "As an example, the gist above instantiates a βDenseβ layer. Those that are parts of the kwargs dictionary are hyperparameters:"
},
{
"code": null,
"e": 13841,
"s": 13543,
"text": "The βinput_layerβ is the number of neurons created. Adjusting these will directly affect the modelβs capacity to adjust to nonlinearities (underfit or overfit).The βuni_regβ applies L1 regularization to that layer. Higher parameter values will adjust more slowly, reducing the risk of overfitting."
},
{
"code": null,
"e": 14002,
"s": 13841,
"text": "The βinput_layerβ is the number of neurons created. Adjusting these will directly affect the modelβs capacity to adjust to nonlinearities (underfit or overfit)."
},
{
"code": null,
"e": 14140,
"s": 14002,
"text": "The βuni_regβ applies L1 regularization to that layer. Higher parameter values will adjust more slowly, reducing the risk of overfitting."
},
{
"code": null,
"e": 14178,
"s": 14140,
"text": "Here are the modelβs hyperparameters:"
},
{
"code": null,
"e": 14301,
"s": 14178,
"text": "The gist above is created using the library called βskopt.spaceβ, where you specify the ranges and categories to optimize."
},
{
"code": null,
"e": 14454,
"s": 14301,
"text": "Afterwards, we wrap the entire pipeline into a function and run the optimization function command. This is the reason we created a large function called"
},
{
"code": null,
"e": 14531,
"s": 14454,
"text": "train_evaluate(normalized_data, est_period,loss_func,param_record, **kwargs)"
},
{
"code": null,
"e": 14607,
"s": 14531,
"text": "It contains model creation, validation process, etc. Feel free to study it."
},
{
"code": null,
"e": 14656,
"s": 14607,
"text": "Now, to the hyperparameter optimization command."
},
{
"code": null,
"e": 14933,
"s": 14656,
"text": "We are optimizing the parameters using Bayesian optimization of Gaussian Probabilities. It essentially maps a probabilistic model of the optimization space. An assumption on navigating space between exploitation (suspected value) and exploration(creating real data points) [4]"
},
{
"code": null,
"e": 14994,
"s": 14933,
"text": "Testing this autoregressive problem has a lot of components:"
},
{
"code": null,
"e": 15020,
"s": 14994,
"text": "Test sets during training"
},
{
"code": null,
"e": 15046,
"s": 15020,
"text": "Test sets during training"
},
{
"code": null,
"e": 15111,
"s": 15046,
"text": "these are the test values where features at X(t+1) are predicted"
},
{
"code": null,
"e": 15161,
"s": 15111,
"text": "2. Iterative prediction for multi-step prediction"
},
{
"code": null,
"e": 15229,
"s": 15161,
"text": "First, letβs remind ourselves of our target variable, mutual_unit ."
},
{
"code": null,
"e": 15503,
"s": 15229,
"text": "In order to perform the validation of this variable, the 3 variables need to be predicted at X(t+1). The input data are pushed to the left, then the latest timestep data are replaced with the predicted data. The process are iterated to achieve the iteration at multi-steps."
},
{
"code": null,
"e": 15534,
"s": 15503,
"text": "The function that does this is"
},
{
"code": null,
"e": 15547,
"s": 15534,
"text": "validation()"
},
{
"code": null,
"e": 15707,
"s": 15547,
"text": "The validation function does the iterative forecast and is compared with the corresponding test data. Note that only mutual_unit is only held out and compared."
},
{
"code": null,
"e": 15948,
"s": 15707,
"text": "Now, the vectors y_pred and y_true are future values. Entropy or unpredictability increases as time steps are forecasted further. Therefore we will introduce a discount factor to these values. In our application, the discount factor is 0.9."
},
{
"code": null,
"e": 16076,
"s": 15948,
"text": "After this, the mean absolute error is computed. This will be the main validation metric as measure of the modelβs performance."
},
{
"code": null,
"e": 16126,
"s": 16076,
"text": "This MAE will serve as metric for Early stopping."
},
{
"code": null,
"e": 16456,
"s": 16126,
"text": "Early stopping is applied to our validation metric (MAE) to mitigate the risk overfitting. It stops once the validation error begins to increase.However, it has the risk of not full reaching full optimality as the validation value is assumed to be convex, as once the inflection point of the error is founded, training is halted."
},
{
"code": null,
"e": 16647,
"s": 16456,
"text": "I used a hand-coded Early stopper and not an API from TensorFlow due to a customized validation computation plus it is easier to code it rather to find an appropriate API. The object name is"
},
{
"code": null,
"e": 16721,
"s": 16647,
"text": "class CustomEarlyStopper:\tdef __init__(self, patience=3, delta=1e-4):\t..."
},
{
"code": null,
"e": 16832,
"s": 16721,
"text": "It has similar parameters like patience and delta, which acts as a tolerance to increases in validation error."
},
{
"code": null,
"e": 16963,
"s": 16832,
"text": "Letβs take a look between predicted and actual values. Notice the predicted values have a positive offset above the predict value."
},
{
"code": null,
"e": 17015,
"s": 16963,
"text": "We are now preparing the model for inferential use."
},
{
"code": null,
"e": 17195,
"s": 17015,
"text": "Using the final parameters, we reoptimize the model to reach the same validation error during hyperparameter tuning. These can be obtained through loading the optimization object."
},
{
"code": null,
"e": 17375,
"s": 17195,
"text": "Using the final parameters, we reoptimize the model to reach the same validation error during hyperparameter tuning. These can be obtained through loading the optimization object."
},
{
"code": null,
"e": 17555,
"s": 17375,
"text": "In the notebook, you can notice the functions jump() and load() to make persistent(save to disk). The functions are placed to facilitate usage of objects upon system interruption."
},
{
"code": null,
"e": 17708,
"s": 17555,
"text": "Note: You can refactor the code so that the model optimized with the best hyperparameters are made persistent(user) so as to avoid re-training as above."
},
{
"code": null,
"e": 17893,
"s": 17708,
"text": "2. After this, capture the last training loss of the last optimal training. Note that this is the training loss to apply and NOT validation loss. This technique can also be refactored."
},
{
"code": null,
"e": 18132,
"s": 17893,
"text": "3. Finally, we have to train the model using the entire dataset. To reduce the risk of overfitting, weβll get the previous training loss from the last trained model. Weβll stop the model training once the target training loss is achieved."
},
{
"code": null,
"e": 18399,
"s": 18132,
"text": "Thank you for reading and hope you learned about the basics of time series forecasting, from data preparation to modelling. I had fun sharing this experience in as much as having fun learning, discovering and applying deep learning on simple time series forecasting."
},
{
"code": null,
"e": 18435,
"s": 18399,
"text": "[1] Autoregressive model, Wikipedia"
},
{
"code": null,
"e": 18480,
"s": 18435,
"text": "[2] βRob J Hyndmanβ, Backcasting in R (2014)"
},
{
"code": null,
"e": 18517,
"s": 18480,
"text": "[3] Vector autoregression, Wikipedia"
}
] |
Alternate XOR operations on sorted array - GeeksforGeeks
|
18 Nov, 2021
Given an array arr[] and two integers X and K. The task is to perform the following operation on array K times:
Sort the array.XOR every alternate element of the sorted array with X i.e. arr[0], arr[2], arr[4], ...
Sort the array.
XOR every alternate element of the sorted array with X i.e. arr[0], arr[2], arr[4], ...
After repeating the above steps K times, print the maximum and the minimum element in the modified array.Examples:
Input: arr[] = {9, 7, 11, 15, 5}, K = 1, X = 2 Output: 7 13 Since the operations has to be performed only once, the sorted array will be {5, 7, 9, 11, 15} Now, apply xor with 2 on alternate elements i.e. 5, 9 and 15. {5 ^ 2, 7, 9 ^ 2, 11, 15 ^ 2} which is equal to {7, 7, 11, 11, 13}Input: arr[] = {605, 986}, K = 548, X = 569 Output: 605 986
Approach: Instead of sorting the array in every iteration, a frequency array can be maintained that will store the frequency of each element in the array. Traversing from 1 to maximum element in the array, the elements can be processed in the sorted order and after every operation, the frequency of the same elements can be adjusted when the alternate elements get XORed with the given integer. Check the programming implementation for more details.Below is the implementation of the above approach:
C++
Java
Python 3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define MAX 100000 // Function to find the maximum and the// minimum elements from the array after// performing the given operation k timesvoid xorOnSortedArray(int arr[], int n, int k, int x){ // To store the current sequence of elements int arr1[MAX + 1] = { 0 }; // To store the next sequence of elements // after xoring with current elements int arr2[MAX + 1] = { 0 }; int xor_val[MAX + 1]; // Store the frequency of elements of arr[] in arr1[] for (int i = 0; i < n; i++) arr1[arr[i]]++; // Storing all precomputed XOR values so that // we don't have to do it again and again // as XOR is a costly operation for (int i = 0; i <= MAX; i++) xor_val[i] = i ^ x; // Perform the operations k times while (k--) { // The value of count decide on how many elements // we have to apply XOR operation int count = 0; for (int i = 0; i <= MAX; i++) { int store = arr1[i]; // If current element is present in // the array to be modified if (arr1[i] > 0) { // Suppose i = m and arr1[i] = num, it means // 'm' appears 'num' times // If the count is even we have to perform // XOR operation on alternate 'm' starting // from the 0th index because count is even // and we have to perform XOR operations // starting with initial 'm' // Hence there will be ceil(num/2) operations on // 'm' that will change 'm' to xor_val[m] i.e. m^x if (count % 2 == 0) { int div = ceil((float)arr1[i] / 2); // Decrease the frequency of 'm' from arr1[] arr1[i] = arr1[i] - div; // Increase the frequency of 'm^x' in arr2[] arr2[xor_val[i]] += div; } // If the count is odd we have to perform // XOR operation on alternate 'm' starting // from the 1st index because count is odd // and we have to leave the 0th 'm' // Hence there will be (num/2) XOR operations on // 'm' that will change 'm' to xor_val[m] i.e. m^x else if (count % 2 != 0) { int div = arr1[i] / 2; arr1[i] = arr1[i] - div; arr2[xor_val[i]] += div; } } // Updating the count by frequency of // the current elements as we have // processed that many elements count = count + store; } // Updating arr1[] which will now store the // next sequence of elements // At this time, arr1[] stores the remaining // 'm' on which XOR was not performed and // arr2[] stores the frequency of 'm^x' i.e. // those 'm' on which operation was performed // Updating arr1[] with frequency of remaining // 'm' & frequency of 'm^x' from arr2[] // With help of arr2[], we prevent sorting of // the array again and again for (int i = 0; i <= MAX; i++) { arr1[i] = arr1[i] + arr2[i]; // Resetting arr2[] for next iteration arr2[i] = 0; } } // Finding the maximum and the minimum element // from the modified array after the operations int min = INT_MAX; int max = INT_MIN; for (int i = 0; i <= MAX; i++) { if (arr1[i] > 0) { if (min > i) min = i; if (max < i) max = i; } } // Printing the max and the min element cout << min << " " << max << endl;} // Driver codeint main(){ int arr[] = { 605, 986 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 548, x = 569; xorOnSortedArray(arr, n, k, x); return 0;}
// Java implementation of the approachclass GFG{ static int MAX = 100000; // Function to find the maximum and the // minimum elements from the array after // performing the given operation k times public static void xorOnSortedArray(int[] arr, int n, int k, int x) { // To store the current sequence of elements int[] arr1 = new int[MAX + 1]; // To store the next sequence of elements // after xoring with current elements int[] arr2 = new int[MAX + 1]; int[] xor_val = new int[MAX + 1]; // Store the frequency of elements // of arr[] in arr1[] for (int i = 0; i < n; i++) arr1[arr[i]]++; // Storing all precomputed XOR values so that // we don't have to do it again and again // as XOR is a costly operation for (int i = 0; i <= MAX; i++) xor_val[i] = i ^ x; // Perform the operations k times while (k-- > 0) { // The value of count decide on how many elements // we have to apply XOR operation int count = 0; for (int i = 0; i <= MAX; i++) { int store = arr1[i]; // If current element is present in // the array to be modified if (arr1[i] > 0) { // Suppose i = m and arr1[i] = num, it means // 'm' appears 'num' times // If the count is even we have to perform // XOR operation on alternate 'm' starting // from the 0th index because count is even // and we have to perform XOR operations // starting with initial 'm' // Hence there will be ceil(num/2) operations on // 'm' that will change 'm' to xor_val[m] i.e. m^x if (count % 2 == 0) { int div = (int) Math.ceil(arr1[i] / 2); // Decrease the frequency of 'm' from arr1[] arr1[i] = arr1[i] - div; // Increase the frequency of 'm^x' in arr2[] arr2[xor_val[i]] += div; } // If the count is odd we have to perform // XOR operation on alternate 'm' starting // from the 1st index because count is odd // and we have to leave the 0th 'm' // Hence there will be (num/2) XOR operations on // 'm' that will change 'm' to xor_val[m] i.e. m^x else if (count % 2 != 0) { int div = arr1[i] / 2; arr1[i] = arr1[i] - div; arr2[xor_val[i]] += div; } } // Updating the count by frequency of // the current elements as we have // processed that many elements count = count + store; } // Updating arr1[] which will now store the // next sequence of elements // At this time, arr1[] stores the remaining // 'm' on which XOR was not performed and // arr2[] stores the frequency of 'm^x' i.e. // those 'm' on which operation was performed // Updating arr1[] with frequency of remaining // 'm' & frequency of 'm^x' from arr2[] // With help of arr2[], we prevent sorting of // the array again and again for (int i = 0; i <= MAX; i++) { arr1[i] = arr1[i] + arr2[i]; // Resetting arr2[] for next iteration arr2[i] = 0; } } // Finding the maximum and the minimum element // from the modified array after the operations int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; for (int i = 0; i <= MAX; i++) { if (arr1[i] > 0) { if (min > i) min = i; if (max < i) max = i; } } // Printing the max and the min element System.out.println(min + " " + max); } // Driver code public static void main(String[] args) { int[] arr = { 605, 986 }; int n = arr.length; int k = 548, x = 569; xorOnSortedArray(arr, n, k, x); }} // This code is contributed by// sanjeev2552
# Python 3 implementation of the approachMAX = 10000import sysfrom math import ceil, floor # Function to find the maximum and the# minimum elements from the array after# performing the given operation k timesdef xorOnSortedArray(arr, n, k, x): # To store the current sequence of elements arr1 = [0 for i in range(MAX + 1)] # To store the next sequence of elements # after xoring with current elements arr2 = [0 for i in range(MAX + 1)] xor_val = [0 for i in range(MAX + 1)] # Store the frequency of elements # of arr[] in arr1[] for i in range(n): arr1[arr[i]] += 1 # Storing all precomputed XOR values # so that we don't have to do it # again and again as XOR is a costly operation for i in range(MAX + 1): xor_val[i] = i ^ x # Perform the operations k times while (k > 0): k -= 1 # The value of count decide on # how many elements we have to # apply XOR operation count = 0 for i in range(MAX + 1): store = arr1[i] # If current element is present in # the array to be modified if (arr1[i] > 0): # Suppose i = m and arr1[i] = num, # it means 'm' appears 'num' times # If the count is even we have to # perform XOR operation on alternate # 'm' starting from the 0th index because # count is even and we have to perform # XOR operations starting with initial 'm' # Hence there will be ceil(num/2) # operations on 'm' that will change # 'm' to xor_val[m] i.e. m^x if (count % 2 == 0): div = arr1[i] // 2 + 1 # Decrease the frequency of # 'm' from arr1[] arr1[i] = arr1[i] - div # Increase the frequency of # 'm^x' in arr2[] arr2[xor_val[i]] += div # If the count is odd we have to perform # XOR operation on alternate 'm' starting # from the 1st index because count is odd # and we have to leave the 0th 'm' # Hence there will be (num/2) XOR operations on # 'm' that will change 'm' to xor_val[m] i.e. m^x elif (count % 2 != 0): div = arr1[i] // 2 arr1[i] = arr1[i] - div arr2[xor_val[i]] += div # Updating the count by frequency of # the current elements as we have # processed that many elements count = count + store # Updating arr1[] which will now store the # next sequence of elements # At this time, arr1[] stores the remaining # 'm' on which XOR was not performed and # arr2[] stores the frequency of 'm^x' i.e. # those 'm' on which operation was performed # Updating arr1[] with frequency of remaining # 'm' & frequency of 'm^x' from arr2[] # With help of arr2[], we prevent sorting of # the array again and again for i in range(MAX+1): arr1[i] = arr1[i] + arr2[i] # Resetting arr2[] for next iteration arr2[i] = 0 # Finding the maximum and the minimum element # from the modified array after the operations mn = sys.maxsize mx = -sys.maxsize-1 for i in range(MAX + 1): if (arr1[i] > 0): if (mn > i): mn = i if (mx < i): mx = i # Printing the max and the min element print(mn,mx) # Driver codeif __name__ == '__main__': arr = [605, 986] n = len(arr) k = 548 x = 569 xorOnSortedArray(arr, n, k, x) # This code is contributed by Surendra_Gangwar
// C# implementation of the approachusing System; class GFG{ static int MAX = 100000; // Function to find the maximum and the // minimum elements from the array after // performing the given operation k times public static void xorOnSortedArray(int[] arr, int n, int k, int x) { // To store the current sequence of elements int[] arr1 = new int[MAX + 1]; // To store the next sequence of elements // after xoring with current elements int[] arr2 = new int[MAX + 1]; int[] xor_val = new int[MAX + 1]; // Store the frequency of elements // of arr[] in arr1[] for (int i = 0; i < n; i++) arr1[arr[i]]++; // Storing all precomputed XOR values so that // we don't have to do it again and again // as XOR is a costly operation for (int i = 0; i <= MAX; i++) xor_val[i] = i ^ x; // Perform the operations k times while (k-- > 0) { // The value of count decides on // how many elements we have to // apply XOR operation int count = 0; for (int i = 0; i <= MAX; i++) { int store = arr1[i]; // If current element is present in // the array to be modified if (arr1[i] > 0) { // Suppose i = m and arr1[i] = num, // it means 'm' appears 'num' times // If the count is even we have to perform // XOR operation on alternate 'm' starting // from the 0th index because count is even // and we have to perform XOR operations // starting with initial 'm' // Hence there will be ceil(num/2) operations on // 'm' that will change 'm' to xor_val[m] i.e. m^x if (count % 2 == 0) { int div = (int) Math.Ceiling((double)(arr1[i] / 2)); // Decrease the frequency of 'm' from arr1[] arr1[i] = arr1[i] - div; // Increase the frequency of 'm^x' in arr2[] arr2[xor_val[i]] += div; } // If the count is odd we have to perform // XOR operation on alternate 'm' starting // from the 1st index because count is odd // and we have to leave the 0th 'm' // Hence there will be (num/2) XOR operations on // 'm' that will change 'm' to xor_val[m] i.e. m^x else if (count % 2 != 0) { int div = arr1[i] / 2; arr1[i] = arr1[i] - div; arr2[xor_val[i]] += div; } } // Updating the count by frequency of // the current elements as we have // processed that many elements count = count + store; } // Updating arr1[] which will now store the // next sequence of elements // At this time, arr1[] stores the remaining // 'm' on which XOR was not performed and // arr2[] stores the frequency of 'm^x' i.e. // those 'm' on which operation was performed // Updating arr1[] with frequency of remaining // 'm' & frequency of 'm^x' from arr2[] // With help of arr2[], we prevent sorting of // the array again and again for (int i = 0; i <= MAX; i++) { arr1[i] = arr1[i] + arr2[i]; // Resetting arr2[] for next iteration arr2[i] = 0; } } // Finding the maximum and the minimum element // from the modified array after the operations int min = int.MaxValue; int max = int.MinValue; for (int i = 0; i <= MAX; i++) { if (arr1[i] > 0) { if (min > i) min = i; if (max < i) max = i; } } // Printing the max and the min element Console.WriteLine(min + " " + max); } // Driver code public static void Main(String[] args) { int[] arr = { 605, 986 }; int n = arr.Length; int k = 548, x = 569; xorOnSortedArray(arr, n, k, x); }} // This code is contributed by Rajput-Ji
<script> // Javascript implementation of the approach const MAX = 100000; // Function to find the maximum and the// minimum elements from the array after// performing the given operation k timesfunction xorOnSortedArray(arr, n, k, x){ // To store the current sequence of elements let arr1 = new Array(MAX + 1).fill(0); // To store the next sequence of elements // after xoring with current elements let arr2 = new Array(MAX + 1).fill(0); let xor_val = new Array(MAX + 1); // Store the frequency of elements of arr[] in arr1[] for (let i = 0; i < n; i++) arr1[arr[i]]++; // Storing all precomputed XOR values so that // we don't have to do it again and again // as XOR is a costly operation for (let i = 0; i <= MAX; i++) xor_val[i] = i ^ x; // Perform the operations k times while (k--) { // The value of count decide on how many elements // we have to apply XOR operation let count = 0; for (let i = 0; i <= MAX; i++) { let store = arr1[i]; // If current element is present in // the array to be modified if (arr1[i] > 0) { // Suppose i = m and arr1[i] = num, it means // 'm' appears 'num' times // If the count is even we have to perform // XOR operation on alternate 'm' starting // from the 0th index because count is even // and we have to perform XOR operations // starting with initial 'm' // Hence there will be ceil(num/2) operations on // 'm' that will change 'm' to xor_val[m] i.e. m^x if (count % 2 == 0) { let div = Math.ceil(arr1[i] / 2); // Decrease the frequency of 'm' from arr1[] arr1[i] = arr1[i] - div; // Increase the frequency of 'm^x' in arr2[] arr2[xor_val[i]] += div; } // If the count is odd we have to perform // XOR operation on alternate 'm' starting // from the 1st index because count is odd // and we have to leave the 0th 'm' // Hence there will be (num/2) XOR operations on // 'm' that will change 'm' to xor_val[m] i.e. m^x else if (count % 2 != 0) { let div = parseInt(arr1[i] / 2); arr1[i] = arr1[i] - div; arr2[xor_val[i]] += div; } } // Updating the count by frequency of // the current elements as we have // processed that many elements count = count + store; } // Updating arr1[] which will now store the // next sequence of elements // At this time, arr1[] stores the remaining // 'm' on which XOR was not performed and // arr2[] stores the frequency of 'm^x' i.e. // those 'm' on which operation was performed // Updating arr1[] with frequency of remaining // 'm' & frequency of 'm^x' from arr2[] // With help of arr2[], we prevent sorting of // the array again and again for (let i = 0; i <= MAX; i++) { arr1[i] = arr1[i] + arr2[i]; // Resetting arr2[] for next iteration arr2[i] = 0; } } // Finding the maximum and the minimum element // from the modified array after the operations let min = Number.MAX_VALUE; let max = Number.MIN_VALUE; for (let i = 0; i <= MAX; i++) { if (arr1[i] > 0) { if (min > i) min = i; if (max < i) max = i; } } // Printing the max and the min element document.write(min + " " + max);} // Driver code let arr = [ 605, 986 ]; let n = arr.length; let k = 548, x = 569; xorOnSortedArray(arr, n, k, x); </script>
605 986
Time Complexity: O(n + k * MAX)
Auxiliary Space: O(MAX)
sanjeev2552
Rajput-Ji
SURENDRA_GANGWAR
rishavmahato348
subhammahato348
Bitwise-XOR
Arrays
Bit Magic
Dynamic Programming
Mathematical
Sorting
Arrays
Dynamic Programming
Mathematical
Bit Magic
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Next Greater Element
Window Sliding Technique
Count pairs with given sum
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Count set bits in an integer
Cyclic Redundancy Check and Modulo-2 Division
|
[
{
"code": null,
"e": 24405,
"s": 24377,
"text": "\n18 Nov, 2021"
},
{
"code": null,
"e": 24519,
"s": 24405,
"text": "Given an array arr[] and two integers X and K. The task is to perform the following operation on array K times: "
},
{
"code": null,
"e": 24622,
"s": 24519,
"text": "Sort the array.XOR every alternate element of the sorted array with X i.e. arr[0], arr[2], arr[4], ..."
},
{
"code": null,
"e": 24638,
"s": 24622,
"text": "Sort the array."
},
{
"code": null,
"e": 24726,
"s": 24638,
"text": "XOR every alternate element of the sorted array with X i.e. arr[0], arr[2], arr[4], ..."
},
{
"code": null,
"e": 24843,
"s": 24726,
"text": "After repeating the above steps K times, print the maximum and the minimum element in the modified array.Examples: "
},
{
"code": null,
"e": 25188,
"s": 24843,
"text": "Input: arr[] = {9, 7, 11, 15, 5}, K = 1, X = 2 Output: 7 13 Since the operations has to be performed only once, the sorted array will be {5, 7, 9, 11, 15} Now, apply xor with 2 on alternate elements i.e. 5, 9 and 15. {5 ^ 2, 7, 9 ^ 2, 11, 15 ^ 2} which is equal to {7, 7, 11, 11, 13}Input: arr[] = {605, 986}, K = 548, X = 569 Output: 605 986 "
},
{
"code": null,
"e": 25692,
"s": 25190,
"text": "Approach: Instead of sorting the array in every iteration, a frequency array can be maintained that will store the frequency of each element in the array. Traversing from 1 to maximum element in the array, the elements can be processed in the sorted order and after every operation, the frequency of the same elements can be adjusted when the alternate elements get XORed with the given integer. Check the programming implementation for more details.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25696,
"s": 25692,
"text": "C++"
},
{
"code": null,
"e": 25701,
"s": 25696,
"text": "Java"
},
{
"code": null,
"e": 25710,
"s": 25701,
"text": "Python 3"
},
{
"code": null,
"e": 25713,
"s": 25710,
"text": "C#"
},
{
"code": null,
"e": 25724,
"s": 25713,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define MAX 100000 // Function to find the maximum and the// minimum elements from the array after// performing the given operation k timesvoid xorOnSortedArray(int arr[], int n, int k, int x){ // To store the current sequence of elements int arr1[MAX + 1] = { 0 }; // To store the next sequence of elements // after xoring with current elements int arr2[MAX + 1] = { 0 }; int xor_val[MAX + 1]; // Store the frequency of elements of arr[] in arr1[] for (int i = 0; i < n; i++) arr1[arr[i]]++; // Storing all precomputed XOR values so that // we don't have to do it again and again // as XOR is a costly operation for (int i = 0; i <= MAX; i++) xor_val[i] = i ^ x; // Perform the operations k times while (k--) { // The value of count decide on how many elements // we have to apply XOR operation int count = 0; for (int i = 0; i <= MAX; i++) { int store = arr1[i]; // If current element is present in // the array to be modified if (arr1[i] > 0) { // Suppose i = m and arr1[i] = num, it means // 'm' appears 'num' times // If the count is even we have to perform // XOR operation on alternate 'm' starting // from the 0th index because count is even // and we have to perform XOR operations // starting with initial 'm' // Hence there will be ceil(num/2) operations on // 'm' that will change 'm' to xor_val[m] i.e. m^x if (count % 2 == 0) { int div = ceil((float)arr1[i] / 2); // Decrease the frequency of 'm' from arr1[] arr1[i] = arr1[i] - div; // Increase the frequency of 'm^x' in arr2[] arr2[xor_val[i]] += div; } // If the count is odd we have to perform // XOR operation on alternate 'm' starting // from the 1st index because count is odd // and we have to leave the 0th 'm' // Hence there will be (num/2) XOR operations on // 'm' that will change 'm' to xor_val[m] i.e. m^x else if (count % 2 != 0) { int div = arr1[i] / 2; arr1[i] = arr1[i] - div; arr2[xor_val[i]] += div; } } // Updating the count by frequency of // the current elements as we have // processed that many elements count = count + store; } // Updating arr1[] which will now store the // next sequence of elements // At this time, arr1[] stores the remaining // 'm' on which XOR was not performed and // arr2[] stores the frequency of 'm^x' i.e. // those 'm' on which operation was performed // Updating arr1[] with frequency of remaining // 'm' & frequency of 'm^x' from arr2[] // With help of arr2[], we prevent sorting of // the array again and again for (int i = 0; i <= MAX; i++) { arr1[i] = arr1[i] + arr2[i]; // Resetting arr2[] for next iteration arr2[i] = 0; } } // Finding the maximum and the minimum element // from the modified array after the operations int min = INT_MAX; int max = INT_MIN; for (int i = 0; i <= MAX; i++) { if (arr1[i] > 0) { if (min > i) min = i; if (max < i) max = i; } } // Printing the max and the min element cout << min << \" \" << max << endl;} // Driver codeint main(){ int arr[] = { 605, 986 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 548, x = 569; xorOnSortedArray(arr, n, k, x); return 0;}",
"e": 29689,
"s": 25724,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ static int MAX = 100000; // Function to find the maximum and the // minimum elements from the array after // performing the given operation k times public static void xorOnSortedArray(int[] arr, int n, int k, int x) { // To store the current sequence of elements int[] arr1 = new int[MAX + 1]; // To store the next sequence of elements // after xoring with current elements int[] arr2 = new int[MAX + 1]; int[] xor_val = new int[MAX + 1]; // Store the frequency of elements // of arr[] in arr1[] for (int i = 0; i < n; i++) arr1[arr[i]]++; // Storing all precomputed XOR values so that // we don't have to do it again and again // as XOR is a costly operation for (int i = 0; i <= MAX; i++) xor_val[i] = i ^ x; // Perform the operations k times while (k-- > 0) { // The value of count decide on how many elements // we have to apply XOR operation int count = 0; for (int i = 0; i <= MAX; i++) { int store = arr1[i]; // If current element is present in // the array to be modified if (arr1[i] > 0) { // Suppose i = m and arr1[i] = num, it means // 'm' appears 'num' times // If the count is even we have to perform // XOR operation on alternate 'm' starting // from the 0th index because count is even // and we have to perform XOR operations // starting with initial 'm' // Hence there will be ceil(num/2) operations on // 'm' that will change 'm' to xor_val[m] i.e. m^x if (count % 2 == 0) { int div = (int) Math.ceil(arr1[i] / 2); // Decrease the frequency of 'm' from arr1[] arr1[i] = arr1[i] - div; // Increase the frequency of 'm^x' in arr2[] arr2[xor_val[i]] += div; } // If the count is odd we have to perform // XOR operation on alternate 'm' starting // from the 1st index because count is odd // and we have to leave the 0th 'm' // Hence there will be (num/2) XOR operations on // 'm' that will change 'm' to xor_val[m] i.e. m^x else if (count % 2 != 0) { int div = arr1[i] / 2; arr1[i] = arr1[i] - div; arr2[xor_val[i]] += div; } } // Updating the count by frequency of // the current elements as we have // processed that many elements count = count + store; } // Updating arr1[] which will now store the // next sequence of elements // At this time, arr1[] stores the remaining // 'm' on which XOR was not performed and // arr2[] stores the frequency of 'm^x' i.e. // those 'm' on which operation was performed // Updating arr1[] with frequency of remaining // 'm' & frequency of 'm^x' from arr2[] // With help of arr2[], we prevent sorting of // the array again and again for (int i = 0; i <= MAX; i++) { arr1[i] = arr1[i] + arr2[i]; // Resetting arr2[] for next iteration arr2[i] = 0; } } // Finding the maximum and the minimum element // from the modified array after the operations int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; for (int i = 0; i <= MAX; i++) { if (arr1[i] > 0) { if (min > i) min = i; if (max < i) max = i; } } // Printing the max and the min element System.out.println(min + \" \" + max); } // Driver code public static void main(String[] args) { int[] arr = { 605, 986 }; int n = arr.length; int k = 548, x = 569; xorOnSortedArray(arr, n, k, x); }} // This code is contributed by// sanjeev2552",
"e": 34289,
"s": 29689,
"text": null
},
{
"code": "# Python 3 implementation of the approachMAX = 10000import sysfrom math import ceil, floor # Function to find the maximum and the# minimum elements from the array after# performing the given operation k timesdef xorOnSortedArray(arr, n, k, x): # To store the current sequence of elements arr1 = [0 for i in range(MAX + 1)] # To store the next sequence of elements # after xoring with current elements arr2 = [0 for i in range(MAX + 1)] xor_val = [0 for i in range(MAX + 1)] # Store the frequency of elements # of arr[] in arr1[] for i in range(n): arr1[arr[i]] += 1 # Storing all precomputed XOR values # so that we don't have to do it # again and again as XOR is a costly operation for i in range(MAX + 1): xor_val[i] = i ^ x # Perform the operations k times while (k > 0): k -= 1 # The value of count decide on # how many elements we have to # apply XOR operation count = 0 for i in range(MAX + 1): store = arr1[i] # If current element is present in # the array to be modified if (arr1[i] > 0): # Suppose i = m and arr1[i] = num, # it means 'm' appears 'num' times # If the count is even we have to # perform XOR operation on alternate # 'm' starting from the 0th index because # count is even and we have to perform # XOR operations starting with initial 'm' # Hence there will be ceil(num/2) # operations on 'm' that will change # 'm' to xor_val[m] i.e. m^x if (count % 2 == 0): div = arr1[i] // 2 + 1 # Decrease the frequency of # 'm' from arr1[] arr1[i] = arr1[i] - div # Increase the frequency of # 'm^x' in arr2[] arr2[xor_val[i]] += div # If the count is odd we have to perform # XOR operation on alternate 'm' starting # from the 1st index because count is odd # and we have to leave the 0th 'm' # Hence there will be (num/2) XOR operations on # 'm' that will change 'm' to xor_val[m] i.e. m^x elif (count % 2 != 0): div = arr1[i] // 2 arr1[i] = arr1[i] - div arr2[xor_val[i]] += div # Updating the count by frequency of # the current elements as we have # processed that many elements count = count + store # Updating arr1[] which will now store the # next sequence of elements # At this time, arr1[] stores the remaining # 'm' on which XOR was not performed and # arr2[] stores the frequency of 'm^x' i.e. # those 'm' on which operation was performed # Updating arr1[] with frequency of remaining # 'm' & frequency of 'm^x' from arr2[] # With help of arr2[], we prevent sorting of # the array again and again for i in range(MAX+1): arr1[i] = arr1[i] + arr2[i] # Resetting arr2[] for next iteration arr2[i] = 0 # Finding the maximum and the minimum element # from the modified array after the operations mn = sys.maxsize mx = -sys.maxsize-1 for i in range(MAX + 1): if (arr1[i] > 0): if (mn > i): mn = i if (mx < i): mx = i # Printing the max and the min element print(mn,mx) # Driver codeif __name__ == '__main__': arr = [605, 986] n = len(arr) k = 548 x = 569 xorOnSortedArray(arr, n, k, x) # This code is contributed by Surendra_Gangwar",
"e": 38143,
"s": 34289,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ static int MAX = 100000; // Function to find the maximum and the // minimum elements from the array after // performing the given operation k times public static void xorOnSortedArray(int[] arr, int n, int k, int x) { // To store the current sequence of elements int[] arr1 = new int[MAX + 1]; // To store the next sequence of elements // after xoring with current elements int[] arr2 = new int[MAX + 1]; int[] xor_val = new int[MAX + 1]; // Store the frequency of elements // of arr[] in arr1[] for (int i = 0; i < n; i++) arr1[arr[i]]++; // Storing all precomputed XOR values so that // we don't have to do it again and again // as XOR is a costly operation for (int i = 0; i <= MAX; i++) xor_val[i] = i ^ x; // Perform the operations k times while (k-- > 0) { // The value of count decides on // how many elements we have to // apply XOR operation int count = 0; for (int i = 0; i <= MAX; i++) { int store = arr1[i]; // If current element is present in // the array to be modified if (arr1[i] > 0) { // Suppose i = m and arr1[i] = num, // it means 'm' appears 'num' times // If the count is even we have to perform // XOR operation on alternate 'm' starting // from the 0th index because count is even // and we have to perform XOR operations // starting with initial 'm' // Hence there will be ceil(num/2) operations on // 'm' that will change 'm' to xor_val[m] i.e. m^x if (count % 2 == 0) { int div = (int) Math.Ceiling((double)(arr1[i] / 2)); // Decrease the frequency of 'm' from arr1[] arr1[i] = arr1[i] - div; // Increase the frequency of 'm^x' in arr2[] arr2[xor_val[i]] += div; } // If the count is odd we have to perform // XOR operation on alternate 'm' starting // from the 1st index because count is odd // and we have to leave the 0th 'm' // Hence there will be (num/2) XOR operations on // 'm' that will change 'm' to xor_val[m] i.e. m^x else if (count % 2 != 0) { int div = arr1[i] / 2; arr1[i] = arr1[i] - div; arr2[xor_val[i]] += div; } } // Updating the count by frequency of // the current elements as we have // processed that many elements count = count + store; } // Updating arr1[] which will now store the // next sequence of elements // At this time, arr1[] stores the remaining // 'm' on which XOR was not performed and // arr2[] stores the frequency of 'm^x' i.e. // those 'm' on which operation was performed // Updating arr1[] with frequency of remaining // 'm' & frequency of 'm^x' from arr2[] // With help of arr2[], we prevent sorting of // the array again and again for (int i = 0; i <= MAX; i++) { arr1[i] = arr1[i] + arr2[i]; // Resetting arr2[] for next iteration arr2[i] = 0; } } // Finding the maximum and the minimum element // from the modified array after the operations int min = int.MaxValue; int max = int.MinValue; for (int i = 0; i <= MAX; i++) { if (arr1[i] > 0) { if (min > i) min = i; if (max < i) max = i; } } // Printing the max and the min element Console.WriteLine(min + \" \" + max); } // Driver code public static void Main(String[] args) { int[] arr = { 605, 986 }; int n = arr.Length; int k = 548, x = 569; xorOnSortedArray(arr, n, k, x); }} // This code is contributed by Rajput-Ji",
"e": 42771,
"s": 38143,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach const MAX = 100000; // Function to find the maximum and the// minimum elements from the array after// performing the given operation k timesfunction xorOnSortedArray(arr, n, k, x){ // To store the current sequence of elements let arr1 = new Array(MAX + 1).fill(0); // To store the next sequence of elements // after xoring with current elements let arr2 = new Array(MAX + 1).fill(0); let xor_val = new Array(MAX + 1); // Store the frequency of elements of arr[] in arr1[] for (let i = 0; i < n; i++) arr1[arr[i]]++; // Storing all precomputed XOR values so that // we don't have to do it again and again // as XOR is a costly operation for (let i = 0; i <= MAX; i++) xor_val[i] = i ^ x; // Perform the operations k times while (k--) { // The value of count decide on how many elements // we have to apply XOR operation let count = 0; for (let i = 0; i <= MAX; i++) { let store = arr1[i]; // If current element is present in // the array to be modified if (arr1[i] > 0) { // Suppose i = m and arr1[i] = num, it means // 'm' appears 'num' times // If the count is even we have to perform // XOR operation on alternate 'm' starting // from the 0th index because count is even // and we have to perform XOR operations // starting with initial 'm' // Hence there will be ceil(num/2) operations on // 'm' that will change 'm' to xor_val[m] i.e. m^x if (count % 2 == 0) { let div = Math.ceil(arr1[i] / 2); // Decrease the frequency of 'm' from arr1[] arr1[i] = arr1[i] - div; // Increase the frequency of 'm^x' in arr2[] arr2[xor_val[i]] += div; } // If the count is odd we have to perform // XOR operation on alternate 'm' starting // from the 1st index because count is odd // and we have to leave the 0th 'm' // Hence there will be (num/2) XOR operations on // 'm' that will change 'm' to xor_val[m] i.e. m^x else if (count % 2 != 0) { let div = parseInt(arr1[i] / 2); arr1[i] = arr1[i] - div; arr2[xor_val[i]] += div; } } // Updating the count by frequency of // the current elements as we have // processed that many elements count = count + store; } // Updating arr1[] which will now store the // next sequence of elements // At this time, arr1[] stores the remaining // 'm' on which XOR was not performed and // arr2[] stores the frequency of 'm^x' i.e. // those 'm' on which operation was performed // Updating arr1[] with frequency of remaining // 'm' & frequency of 'm^x' from arr2[] // With help of arr2[], we prevent sorting of // the array again and again for (let i = 0; i <= MAX; i++) { arr1[i] = arr1[i] + arr2[i]; // Resetting arr2[] for next iteration arr2[i] = 0; } } // Finding the maximum and the minimum element // from the modified array after the operations let min = Number.MAX_VALUE; let max = Number.MIN_VALUE; for (let i = 0; i <= MAX; i++) { if (arr1[i] > 0) { if (min > i) min = i; if (max < i) max = i; } } // Printing the max and the min element document.write(min + \" \" + max);} // Driver code let arr = [ 605, 986 ]; let n = arr.length; let k = 548, x = 569; xorOnSortedArray(arr, n, k, x); </script>",
"e": 46719,
"s": 42771,
"text": null
},
{
"code": null,
"e": 46727,
"s": 46719,
"text": "605 986"
},
{
"code": null,
"e": 46761,
"s": 46729,
"text": "Time Complexity: O(n + k * MAX)"
},
{
"code": null,
"e": 46785,
"s": 46761,
"text": "Auxiliary Space: O(MAX)"
},
{
"code": null,
"e": 46797,
"s": 46785,
"text": "sanjeev2552"
},
{
"code": null,
"e": 46807,
"s": 46797,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 46824,
"s": 46807,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 46840,
"s": 46824,
"text": "rishavmahato348"
},
{
"code": null,
"e": 46856,
"s": 46840,
"text": "subhammahato348"
},
{
"code": null,
"e": 46868,
"s": 46856,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 46875,
"s": 46868,
"text": "Arrays"
},
{
"code": null,
"e": 46885,
"s": 46875,
"text": "Bit Magic"
},
{
"code": null,
"e": 46905,
"s": 46885,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 46918,
"s": 46905,
"text": "Mathematical"
},
{
"code": null,
"e": 46926,
"s": 46918,
"text": "Sorting"
},
{
"code": null,
"e": 46933,
"s": 46926,
"text": "Arrays"
},
{
"code": null,
"e": 46953,
"s": 46933,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 46966,
"s": 46953,
"text": "Mathematical"
},
{
"code": null,
"e": 46976,
"s": 46966,
"text": "Bit Magic"
},
{
"code": null,
"e": 46984,
"s": 46976,
"text": "Sorting"
},
{
"code": null,
"e": 47082,
"s": 46984,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 47091,
"s": 47082,
"text": "Comments"
},
{
"code": null,
"e": 47104,
"s": 47091,
"text": "Old Comments"
},
{
"code": null,
"e": 47125,
"s": 47104,
"text": "Next Greater Element"
},
{
"code": null,
"e": 47150,
"s": 47125,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 47177,
"s": 47150,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 47226,
"s": 47177,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 47264,
"s": 47226,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 47291,
"s": 47264,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 47337,
"s": 47291,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 47405,
"s": 47337,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 47434,
"s": 47405,
"text": "Count set bits in an integer"
}
] |
Equivalent of Java Super Keyword in C#
|
For super keyword in Java, we have the base keyword in C#.
Super keyword in Java refers immediate parent class instance. It is used to differentiate the members of superclass from the members of subclass, if they have same names. It is used to invoke the superclass constructor from subclass.
C# base keyword is used to access the constructors and methods of base class. Use it within instance method, constructor, etc.
Let us see an example of C# base.
Live Demo
using System;
public class Animal {
public string repColor = "brown";
}
public class Reptile: Animal {
string repColor = "green";
public void display() {
Console.WriteLine("Color: "+base.repColor);
Console.WriteLine("Color: "+repColor);
}
}
public class Demo {
public static void Main() {
Reptile rep = new Reptile();
rep.display();
}
}
Color: brown
Color: green
|
[
{
"code": null,
"e": 1121,
"s": 1062,
"text": "For super keyword in Java, we have the base keyword in C#."
},
{
"code": null,
"e": 1355,
"s": 1121,
"text": "Super keyword in Java refers immediate parent class instance. It is used to differentiate the members of superclass from the members of subclass, if they have same names. It is used to invoke the superclass constructor from subclass."
},
{
"code": null,
"e": 1482,
"s": 1355,
"text": "C# base keyword is used to access the constructors and methods of base class. Use it within instance method, constructor, etc."
},
{
"code": null,
"e": 1516,
"s": 1482,
"text": "Let us see an example of C# base."
},
{
"code": null,
"e": 1527,
"s": 1516,
"text": " Live Demo"
},
{
"code": null,
"e": 1906,
"s": 1527,
"text": "using System;\npublic class Animal {\n public string repColor = \"brown\";\n}\npublic class Reptile: Animal {\n string repColor = \"green\";\n public void display() {\n Console.WriteLine(\"Color: \"+base.repColor);\n Console.WriteLine(\"Color: \"+repColor);\n }\n}\npublic class Demo {\n public static void Main() {\n Reptile rep = new Reptile();\n rep.display();\n }\n}"
},
{
"code": null,
"e": 1932,
"s": 1906,
"text": "Color: brown\nColor: green"
}
] |
Matcher replaceAll() method in Java with Examples
|
The java.util.regex.Matcher class represents an engine that performs various match operations. There is no constructor for this class, you can create/obtain an object of this class using the matches() method of the class java.util.regex.Pattern.
The replaceAll() method of this (Matcher) class accepts a string value, replaces all the matched subsequences in the input with the given string value and returns the result.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAllExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
String regex = "[#%&*]";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Creating a Matcher object
Matcher matcher = pattern.matcher(input);
int count =0;
while(matcher.find()) {
count++;
}
//Retrieving Pattern used
System.out.println("The are "+count+" special characters [# % & *] in the given text");
//Replacing all special characters [# % & *] with ! String result = matcher.replaceAll("!");
System.out.println("Replaced all special characters [# % & *] with !: \n"+result);
}
}
Enter input text:
Hello# How # are# you *& welcome to T#utorials%point
The are 7 special characters [# % & *] in the given text
Replaced all special characters [# % & *] with !:
Hello! How ! are! you !! welcome to T!utorials!point
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAllExample {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
//Regular expression to match spaces (one or more)
String regex = "\\s+";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
//Replacing all space characters with single space
String result = matcher.replaceAll(" ");
System.out.print("Text after removing unwanted spaces: \n"+result);
}
}
Enter a String
hello this is a sample text with irregular spaces
Text after removing unwanted spaces:
hello this is a sample text with irregular spaces
|
[
{
"code": null,
"e": 1308,
"s": 1062,
"text": "The java.util.regex.Matcher class represents an engine that performs various match operations. There is no constructor for this class, you can create/obtain an object of this class using the matches() method of the class java.util.regex.Pattern."
},
{
"code": null,
"e": 1483,
"s": 1308,
"text": "The replaceAll() method of this (Matcher) class accepts a string value, replaces all the matched subsequences in the input with the given string value and returns the result."
},
{
"code": null,
"e": 2369,
"s": 1483,
"text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class ReplaceAllExample {\n public static void main(String[] args) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter input text: \");\n String input = sc.nextLine();\n String regex = \"[#%&*]\";\n //Creating a pattern object\n Pattern pattern = Pattern.compile(regex);\n //Creating a Matcher object\n Matcher matcher = pattern.matcher(input);\n int count =0;\n while(matcher.find()) {\n count++;\n }\n //Retrieving Pattern used\n System.out.println(\"The are \"+count+\" special characters [# % & *] in the given text\");\n //Replacing all special characters [# % & *] with ! String result = matcher.replaceAll(\"!\");\n System.out.println(\"Replaced all special characters [# % & *] with !: \\n\"+result);\n }\n}"
},
{
"code": null,
"e": 2600,
"s": 2369,
"text": "Enter input text:\nHello# How # are# you *& welcome to T#utorials%point\nThe are 7 special characters [# % & *] in the given text\nReplaced all special characters [# % & *] with !:\nHello! How ! are! you !! welcome to T!utorials!point"
},
{
"code": null,
"e": 3369,
"s": 2600,
"text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class ReplaceAllExample {\n public static void main(String args[]) {\n //Reading String from user\n System.out.println(\"Enter a String\");\n Scanner sc = new Scanner(System.in);\n String input = sc.nextLine();\n //Regular expression to match spaces (one or more)\n String regex = \"\\\\s+\";\n //Compiling the regular expression\n Pattern pattern = Pattern.compile(regex);\n //Retrieving the matcher object\n Matcher matcher = pattern.matcher(input);\n //Replacing all space characters with single space\n String result = matcher.replaceAll(\" \");\n System.out.print(\"Text after removing unwanted spaces: \\n\"+result);\n }\n}"
},
{
"code": null,
"e": 3521,
"s": 3369,
"text": "Enter a String\nhello this is a sample text with irregular spaces\nText after removing unwanted spaces:\nhello this is a sample text with irregular spaces"
}
] |
Convert array to HashSet in Java
|
Create an array and convert it to List β
Integer[] arr = { 10, 15, 20, 10, 10, 10, 20, 30, 35, 40, 40};
List<Integer> l = Arrays.asList(arr);
Now, let us convert the above array to HashSet β
Set<Integer> s = new HashSet<Integer>(l);
The following is an example to convert array to HashSet β
Live Demo
import java.util.*;
public class Demo {
public static void main(String[] argv) throws Exception {
Integer[] arr = { 10, 15, 20, 10, 10, 10, 20, 30, 35, 40, 40};
List<Integer> l = Arrays.asList(arr);
Set<Integer> s = new HashSet<Integer>(l);
for (Iterator i = s.iterator(); i.hasNext();) {
Object ele = i.next();
System.out.println(ele);
}
}
}
35
20
40
10
30
15
|
[
{
"code": null,
"e": 1103,
"s": 1062,
"text": "Create an array and convert it to List β"
},
{
"code": null,
"e": 1204,
"s": 1103,
"text": "Integer[] arr = { 10, 15, 20, 10, 10, 10, 20, 30, 35, 40, 40};\nList<Integer> l = Arrays.asList(arr);"
},
{
"code": null,
"e": 1253,
"s": 1204,
"text": "Now, let us convert the above array to HashSet β"
},
{
"code": null,
"e": 1295,
"s": 1253,
"text": "Set<Integer> s = new HashSet<Integer>(l);"
},
{
"code": null,
"e": 1353,
"s": 1295,
"text": "The following is an example to convert array to HashSet β"
},
{
"code": null,
"e": 1364,
"s": 1353,
"text": " Live Demo"
},
{
"code": null,
"e": 1761,
"s": 1364,
"text": "import java.util.*;\npublic class Demo {\n public static void main(String[] argv) throws Exception {\n Integer[] arr = { 10, 15, 20, 10, 10, 10, 20, 30, 35, 40, 40};\n List<Integer> l = Arrays.asList(arr);\n Set<Integer> s = new HashSet<Integer>(l);\n for (Iterator i = s.iterator(); i.hasNext();) {\n Object ele = i.next();\n System.out.println(ele);\n }\n }\n}"
},
{
"code": null,
"e": 1779,
"s": 1761,
"text": "35\n20\n40\n10\n30\n15"
}
] |
Input/Output from external file in C/C++, Java and Python for Competitive Programming - GeeksforGeeks
|
06 Jan, 2022
In Competitive Programming, most of the time we need to enter input for checking our code manually. But it would become cumbersome if we have a questions like Graphs, strings, or bulky entry of input data because it will definitely time out or the chances of typing incorrect data would be increased. We can easily get rid of problem by simply saving the test cases to the specified file at the desired location according to our easiness. These are useful in competitions like Facebook Hackercup, Google Codejam. These competitions do not provide the online judge like environment rather than they asked you to upload input and output files.For Input/Output, we basically use these two type of file access modes i.e.,
βrβ: It means read, as it opens the file for input operation but the file must exist at specified location.
βwβ: It means write, as it creates an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file.
C/C++
In C/C++ we can use freopen for standard input and output. The syntax of this function as:-
FILE * freopen(const char * filename, const char * mode, FILE * stream );
filename: It refers to name of the file that we want to open.
mode: Discussed above.
stream: Pointer to a FILE object that identifies the stream to be reopened.
We can also use Symbolic constant ONLINE_JUDGE for debugging purpose. As most of the online judges add this flag at the end of the command line before executing our code. For example in C++11, it would be compiled as
-std = c++0x -O2 -static -s -lm -DONLINE_JUDGE
So we can take advantage of that by using C preprocessor directive.
we can also do the same using ONLINE_JUDGE in java, but as of now it does not work in codechef but works in codeforces.
CPP
Java
// Below is C/C++ code for input/output#include<stdio.h> int main(){#ifndef ONLINE_JUDGE // For getting input from input.txt file freopen("input.txt", "r", stdin); // Printing the Output to output.txt file freopen("output.txt", "w", stdout); #endif return 0;}
// Java code for I/Oimport java.io.*;// this does not works in codechef but works in codeforcesclass GFG { public static void main(String[] args) throws IOException { if (System.getProperty("ONLINE_JUDGE") == null) { // Redirecting the I/O to external files // as ONLINE_JUDGE constant is not defined which // means // the code is not running on an online judge PrintStream ps = new PrintStream(new File("output.txt")); InputStream is = new FileInputStream("input.txt"); System.setIn(is); System.setOut(ps); } }}// This code is contributed by Rahul Mandal
JAVA
In Java, we can use BufferedReader class for the fast Input and PrintWriter class for formatted representation to the output along with FileReader and FileWriter class.
FileReader(String filename): This constructor creates a new FileReader, and instructs the parser to read file from that directory. The file must exist in that specified location.
FileWriter(String fileName): This constructor creates a FileWriter object, to the specified location.
Java
// Java program For handling Input/Outputimport java.io.*;class Main{ public static void main(String[] args) throws IOException { // BufferedReader Class for Fast buffer Input BufferedReader br = new BufferedReader( new FileReader("input.txt")); // PrintWriter class prints formatted representations // of objects to a text-output stream. PrintWriter pw=new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); // Your code goes Here pw.flush(); }}// Thanks to Saurabh Kumar Prajapati for providing this java Code
PYTHON
In python we first import the module sys(system), after that We will use open() function which returns the file object, that are commonly used with two arguments: open(filename, mode).
The first argument is a string containing the filename.
The second argument is another string (mode) containing a few characters describing the way in which the file will be used.
Python
# Below is Python code for input/output import sys# For getting input from input.txt filesys.stdin = open('input.txt', 'r') # Printing the Output to output.txt filesys.stdout = open('output.txt', 'w')
This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
mandalrahul05
abhishek0719kadiyan
Competitive Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Bits manipulation (Important tactics)
Breadth First Traversal ( BFS ) on a 2D array
Remove all occurrences of a character in a string | Recursive approach
Container with Most Water
How to begin with Competitive Programming?
Sequence Alignment problem
String hashing using Polynomial rolling hash function
Shortest path in a directed graph by Dijkstraβs algorithm
Formatted output in Java
|
[
{
"code": null,
"e": 24568,
"s": 24540,
"text": "\n06 Jan, 2022"
},
{
"code": null,
"e": 25288,
"s": 24568,
"text": "In Competitive Programming, most of the time we need to enter input for checking our code manually. But it would become cumbersome if we have a questions like Graphs, strings, or bulky entry of input data because it will definitely time out or the chances of typing incorrect data would be increased. We can easily get rid of problem by simply saving the test cases to the specified file at the desired location according to our easiness. These are useful in competitions like Facebook Hackercup, Google Codejam. These competitions do not provide the online judge like environment rather than they asked you to upload input and output files.For Input/Output, we basically use these two type of file access modes i.e., "
},
{
"code": null,
"e": 25398,
"s": 25288,
"text": "βrβ: It means read, as it opens the file for input operation but the file must exist at specified location. "
},
{
"code": null,
"e": 25589,
"s": 25398,
"text": "βwβ: It means write, as it creates an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file. "
},
{
"code": null,
"e": 25597,
"s": 25591,
"text": "C/C++"
},
{
"code": null,
"e": 25691,
"s": 25597,
"text": "In C/C++ we can use freopen for standard input and output. The syntax of this function as:- "
},
{
"code": null,
"e": 25765,
"s": 25691,
"text": "FILE * freopen(const char * filename, const char * mode, FILE * stream );"
},
{
"code": null,
"e": 25829,
"s": 25767,
"text": "filename: It refers to name of the file that we want to open."
},
{
"code": null,
"e": 25852,
"s": 25829,
"text": "mode: Discussed above."
},
{
"code": null,
"e": 25930,
"s": 25852,
"text": "stream: Pointer to a FILE object that identifies the stream to be reopened. "
},
{
"code": null,
"e": 26149,
"s": 25930,
"text": "We can also use Symbolic constant ONLINE_JUDGE for debugging purpose. As most of the online judges add this flag at the end of the command line before executing our code. For example in C++11, it would be compiled as "
},
{
"code": null,
"e": 26196,
"s": 26149,
"text": "-std = c++0x -O2 -static -s -lm -DONLINE_JUDGE"
},
{
"code": null,
"e": 26265,
"s": 26196,
"text": "So we can take advantage of that by using C preprocessor directive. "
},
{
"code": null,
"e": 26386,
"s": 26265,
"text": "we can also do the same using ONLINE_JUDGE in java, but as of now it does not work in codechef but works in codeforces. "
},
{
"code": null,
"e": 26390,
"s": 26386,
"text": "CPP"
},
{
"code": null,
"e": 26395,
"s": 26390,
"text": "Java"
},
{
"code": "// Below is C/C++ code for input/output#include<stdio.h> int main(){#ifndef ONLINE_JUDGE // For getting input from input.txt file freopen(\"input.txt\", \"r\", stdin); // Printing the Output to output.txt file freopen(\"output.txt\", \"w\", stdout); #endif return 0;}",
"e": 26672,
"s": 26395,
"text": null
},
{
"code": "// Java code for I/Oimport java.io.*;// this does not works in codechef but works in codeforcesclass GFG { public static void main(String[] args) throws IOException { if (System.getProperty(\"ONLINE_JUDGE\") == null) { // Redirecting the I/O to external files // as ONLINE_JUDGE constant is not defined which // means // the code is not running on an online judge PrintStream ps = new PrintStream(new File(\"output.txt\")); InputStream is = new FileInputStream(\"input.txt\"); System.setIn(is); System.setOut(ps); } }}// This code is contributed by Rahul Mandal",
"e": 27380,
"s": 26672,
"text": null
},
{
"code": null,
"e": 27385,
"s": 27380,
"text": "JAVA"
},
{
"code": null,
"e": 27556,
"s": 27385,
"text": "In Java, we can use BufferedReader class for the fast Input and PrintWriter class for formatted representation to the output along with FileReader and FileWriter class. "
},
{
"code": null,
"e": 27735,
"s": 27556,
"text": "FileReader(String filename): This constructor creates a new FileReader, and instructs the parser to read file from that directory. The file must exist in that specified location."
},
{
"code": null,
"e": 27837,
"s": 27735,
"text": "FileWriter(String fileName): This constructor creates a FileWriter object, to the specified location."
},
{
"code": null,
"e": 27844,
"s": 27839,
"text": "Java"
},
{
"code": "// Java program For handling Input/Outputimport java.io.*;class Main{ public static void main(String[] args) throws IOException { // BufferedReader Class for Fast buffer Input BufferedReader br = new BufferedReader( new FileReader(\"input.txt\")); // PrintWriter class prints formatted representations // of objects to a text-output stream. PrintWriter pw=new PrintWriter(new BufferedWriter(new FileWriter(\"output.txt\"))); // Your code goes Here pw.flush(); }}// Thanks to Saurabh Kumar Prajapati for providing this java Code",
"e": 28474,
"s": 27844,
"text": null
},
{
"code": null,
"e": 28481,
"s": 28474,
"text": "PYTHON"
},
{
"code": null,
"e": 28668,
"s": 28481,
"text": "In python we first import the module sys(system), after that We will use open() function which returns the file object, that are commonly used with two arguments: open(filename, mode). "
},
{
"code": null,
"e": 28724,
"s": 28668,
"text": "The first argument is a string containing the filename."
},
{
"code": null,
"e": 28848,
"s": 28724,
"text": "The second argument is another string (mode) containing a few characters describing the way in which the file will be used."
},
{
"code": null,
"e": 28857,
"s": 28850,
"text": "Python"
},
{
"code": "# Below is Python code for input/output import sys# For getting input from input.txt filesys.stdin = open('input.txt', 'r') # Printing the Output to output.txt filesys.stdout = open('output.txt', 'w')",
"e": 29058,
"s": 28857,
"text": null
},
{
"code": null,
"e": 29481,
"s": 29058,
"text": "This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 29495,
"s": 29481,
"text": "mandalrahul05"
},
{
"code": null,
"e": 29515,
"s": 29495,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 29539,
"s": 29515,
"text": "Competitive Programming"
},
{
"code": null,
"e": 29637,
"s": 29539,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29646,
"s": 29637,
"text": "Comments"
},
{
"code": null,
"e": 29659,
"s": 29646,
"text": "Old Comments"
},
{
"code": null,
"e": 29697,
"s": 29659,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 29743,
"s": 29697,
"text": "Breadth First Traversal ( BFS ) on a 2D array"
},
{
"code": null,
"e": 29814,
"s": 29743,
"text": "Remove all occurrences of a character in a string | Recursive approach"
},
{
"code": null,
"e": 29840,
"s": 29814,
"text": "Container with Most Water"
},
{
"code": null,
"e": 29883,
"s": 29840,
"text": "How to begin with Competitive Programming?"
},
{
"code": null,
"e": 29910,
"s": 29883,
"text": "Sequence Alignment problem"
},
{
"code": null,
"e": 29964,
"s": 29910,
"text": "String hashing using Polynomial rolling hash function"
},
{
"code": null,
"e": 30022,
"s": 29964,
"text": "Shortest path in a directed graph by Dijkstraβs algorithm"
}
] |
How can I get the current screen orientation in Android?
|
In some situation, we need to find an android activity orientation. This example demonstrates how to integrate Android Login and registration form.
Step 1 β Create a new project in Android Studio, go to File β New Project and fill all required details to create a new project.
Step 2 β Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:id = "@+id/parent"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:gravity = "center"
android:orientation = "vertical">
<TextView
android:id = "@+id/text"
android:textSize = "28sp"
android:textAlignment = "center"
android:layout_width = "match_parent"
android:layout_height = "wrap_content" />
</LinearLayout>
In the above code, we have taken a text view. According to screen orientation, text view going to update the text.
Step 3 β Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int view = R.layout.activity_main;
TextView textview;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(view);
textview = findViewById(R.id.text);
int orientation = this.getResources().getConfiguration().orientation;
if (orientation = = Configuration.ORIENTATION_PORTRAIT) {
textview.setText("Portrait mode");
} else {
textview.setText("landscape mode");
}
}
}
In the above code, we have taken orientation as integer and comparing with configuring orientation as shown below -
int orientation = this.getResources().getConfiguration().orientation;
if (orientation = = Configuration.ORIENTATION_PORTRAIT) {
textview.setText("Portrait mode");
} else {
textview.setText("landscape mode");
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen β
When user keeps mobile as portrait mode, it will show the result as shown above. Now turn the device to landscape mode, it will show the result as shown below -
Click here to download the project code
|
[
{
"code": null,
"e": 1210,
"s": 1062,
"text": "In some situation, we need to find an android activity orientation. This example demonstrates how to integrate Android Login and registration form."
},
{
"code": null,
"e": 1339,
"s": 1210,
"text": "Step 1 β Create a new project in Android Studio, go to File β New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1404,
"s": 1339,
"text": "Step 2 β Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2012,
"s": 1404,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n android:id = \"@+id/parent\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:gravity = \"center\"\n android:orientation = \"vertical\">\n <TextView\n android:id = \"@+id/text\"\n android:textSize = \"28sp\"\n android:textAlignment = \"center\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2127,
"s": 2012,
"text": "In the above code, we have taken a text view. According to screen orientation, text view going to update the text."
},
{
"code": null,
"e": 2184,
"s": 2127,
"text": "Step 3 β Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3053,
"s": 2184,
"text": "package com.example.andy.myapplication;\nimport android.content.res.Configuration;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n int view = R.layout.activity_main;\n TextView textview;\n @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(view);\n textview = findViewById(R.id.text);\n int orientation = this.getResources().getConfiguration().orientation;\n if (orientation = = Configuration.ORIENTATION_PORTRAIT) {\n textview.setText(\"Portrait mode\");\n } else {\n textview.setText(\"landscape mode\");\n }\n }\n}"
},
{
"code": null,
"e": 3169,
"s": 3053,
"text": "In the above code, we have taken orientation as integer and comparing with configuring orientation as shown below -"
},
{
"code": null,
"e": 3385,
"s": 3169,
"text": "int orientation = this.getResources().getConfiguration().orientation;\nif (orientation = = Configuration.ORIENTATION_PORTRAIT) {\n textview.setText(\"Portrait mode\");\n} else {\n textview.setText(\"landscape mode\");\n}"
},
{
"code": null,
"e": 3732,
"s": 3385,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen β"
},
{
"code": null,
"e": 3893,
"s": 3732,
"text": "When user keeps mobile as portrait mode, it will show the result as shown above. Now turn the device to landscape mode, it will show the result as shown below -"
},
{
"code": null,
"e": 3933,
"s": 3893,
"text": "Click here to download the project code"
}
] |
What is following-sibling in Selenium?
|
We can use the concept of following-sibling in xpath for identifying elements in Selenium. It identifies the siblings of the context node. The siblings should be located at the equal level of the existing node and should have the same parent.
Let us see an example of an element with ul tag having more than one child with li tag. Then let us try to locate the fifth li element (Effective Resume Writing) from the first li element with class attribute sreading.
//li[@class='sreading']/following-sibling::li[4]
Here, we are locating the fifth child of ul tag, but we have provided li[4] since we are locating the fifth child from the first child element.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class FollowingSiblingXpath{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
//identify fifth child from first child
WebElement n = driver.findElement
(By.xpath("//li[@class='sreading']/following-sibling::li[4]"));
String s = n.getText();
System.out.println("Text is: " + s);
driver.quit();
}
}
|
[
{
"code": null,
"e": 1305,
"s": 1062,
"text": "We can use the concept of following-sibling in xpath for identifying elements in Selenium. It identifies the siblings of the context node. The siblings should be located at the equal level of the existing node and should have the same parent."
},
{
"code": null,
"e": 1524,
"s": 1305,
"text": "Let us see an example of an element with ul tag having more than one child with li tag. Then let us try to locate the fifth li element (Effective Resume Writing) from the first li element with class attribute sreading."
},
{
"code": null,
"e": 1573,
"s": 1524,
"text": "//li[@class='sreading']/following-sibling::li[4]"
},
{
"code": null,
"e": 1717,
"s": 1573,
"text": "Here, we are locating the fifth child of ul tag, but we have provided li[4] since we are locating the fifth child from the first child element."
},
{
"code": null,
"e": 2597,
"s": 1717,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class FollowingSiblingXpath{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //URL launch\n driver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\");\n //identify fifth child from first child\n WebElement n = driver.findElement\n (By.xpath(\"//li[@class='sreading']/following-sibling::li[4]\"));\n String s = n.getText();\n System.out.println(\"Text is: \" + s);\n driver.quit();\n }\n}"
}
] |
How to create a Hero Image with CSS?
|
Following is the code to create a hero image with CSS β
Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body,
html {
height: 100%;
margin: 0;
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
*,
*::before,
*::after {
box-sizing: border-box;
}
h1 {
font-size: 60px;
font-weight: bolder;
}
.heroContainer {
background-image: linear-gradient( rgba(185, 255, 243, 0.5), rgba(31, 12, 117, 0.5) ),
url("https://images.pexels.com/photos/670720/pexels-photo-670720.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=1000");
height: 50%;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
position: relative;
}
.heroCaption {
text-align: center;
position: absolute;
top: 20%;
left: 45%;
color: white;
}
.heroCaption button {
border: none;
outline: none;
display: inline-block;
padding: 20px;
color: rgb(255, 255, 255);
opacity: 0.8;
font-size: 20px;
background-color: rgb(47, 151, 21);
text-align: center;
cursor: pointer;
}
.heroCaption button:hover {
opacity: 1;
}
</style>
</head>
<body>
<div class="heroContainer">
<div class="heroCaption">
<h1>I am Shawn</h1>
<h2>And I'm a Web Developer</h2>
<button>Contact Me</button>
</div>
</div>
</body>
</html>
The above code will produce the following output β
|
[
{
"code": null,
"e": 1118,
"s": 1062,
"text": "Following is the code to create a hero image with CSS β"
},
{
"code": null,
"e": 1129,
"s": 1118,
"text": " Live Demo"
},
{
"code": null,
"e": 2402,
"s": 1129,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<style>\nbody,\nhtml {\n height: 100%;\n margin: 0;\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n}\n*,\n*::before,\n*::after {\n box-sizing: border-box;\n}\nh1 {\n font-size: 60px;\n font-weight: bolder;\n}\n.heroContainer {\n background-image: linear-gradient( rgba(185, 255, 243, 0.5), rgba(31, 12, 117, 0.5) ),\n url(\"https://images.pexels.com/photos/670720/pexels-photo-670720.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=1000\");\n height: 50%;\n background-position: center;\n background-repeat: no-repeat;\n background-size: cover;\n position: relative;\n}\n.heroCaption {\n text-align: center;\n position: absolute;\n top: 20%;\n left: 45%;\n color: white;\n}\n.heroCaption button {\n border: none;\n outline: none;\n display: inline-block;\n padding: 20px;\n color: rgb(255, 255, 255);\n opacity: 0.8;\n font-size: 20px;\n background-color: rgb(47, 151, 21);\n text-align: center;\n cursor: pointer;\n}\n.heroCaption button:hover {\n opacity: 1;\n}\n</style>\n</head>\n<body>\n<div class=\"heroContainer\">\n<div class=\"heroCaption\">\n<h1>I am Shawn</h1>\n<h2>And I'm a Web Developer</h2>\n<button>Contact Me</button>\n</div>\n</div>\n</body>\n</html>"
},
{
"code": null,
"e": 2453,
"s": 2402,
"text": "The above code will produce the following output β"
}
] |
React Native - App
|
If you open the default app you can observe that the app.js file looks like
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
export default class App extends React.Component {
render() {
return (
<View style = {styles.container}>
<Text>Open up App.js to start working on your app!</Text>
<Text>Changes you make will automatically reload.</Text>
<Text>Shake your phone to open the developer menu.</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
To display a simple message saying βWelcome to Tutorialspointβ remove the CSS part and insert the message to be printed wrapped by the <text></text> tags inside <view></view> as shown below.
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
export default class App extends React.Component {
render() {
return (
<View>
<Text>Welcome to Tutorialspoint</Text>
</View>
);
}
}
20 Lectures
1.5 hours
Anadi Sharma
61 Lectures
6.5 hours
A To Z Mentor
40 Lectures
4.5 hours
Eduonix Learning Solutions
56 Lectures
12.5 hours
Eduonix Learning Solutions
62 Lectures
4.5 hours
Senol Atac
67 Lectures
4.5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2420,
"s": 2344,
"text": "If you open the default app you can observe that the app.js file looks like"
},
{
"code": null,
"e": 3036,
"s": 2420,
"text": "import React from 'react';\nimport { StyleSheet, Text, View } from 'react-native';\n\nexport default class App extends React.Component {\n render() {\n return (\n <View style = {styles.container}>\n <Text>Open up App.js to start working on your app!</Text>\n <Text>Changes you make will automatically reload.</Text>\n <Text>Shake your phone to open the developer menu.</Text>\n </View>\n );\n }\n}\n\nconst styles = StyleSheet.create({\n container: {\n flex: 1,\n backgroundColor: '#fff',\n alignItems: 'center',\n justifyContent: 'center',\n },\n});"
},
{
"code": null,
"e": 3227,
"s": 3036,
"text": "To display a simple message saying βWelcome to Tutorialspointβ remove the CSS part and insert the message to be printed wrapped by the <text></text> tags inside <view></view> as shown below."
},
{
"code": null,
"e": 3490,
"s": 3227,
"text": "import React from 'react';\nimport { StyleSheet, Text, View } from 'react-native';\n\nexport default class App extends React.Component {\n render() {\n return (\n <View>\n <Text>Welcome to Tutorialspoint</Text>\n </View>\n );\n }\n}"
},
{
"code": null,
"e": 3525,
"s": 3490,
"text": "\n 20 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3539,
"s": 3525,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3574,
"s": 3539,
"text": "\n 61 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3589,
"s": 3574,
"text": " A To Z Mentor"
},
{
"code": null,
"e": 3624,
"s": 3589,
"text": "\n 40 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3652,
"s": 3624,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3688,
"s": 3652,
"text": "\n 56 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 3716,
"s": 3688,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3751,
"s": 3716,
"text": "\n 62 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3763,
"s": 3751,
"text": " Senol Atac"
},
{
"code": null,
"e": 3798,
"s": 3763,
"text": "\n 67 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3810,
"s": 3798,
"text": " Senol Atac"
},
{
"code": null,
"e": 3817,
"s": 3810,
"text": " Print"
},
{
"code": null,
"e": 3828,
"s": 3817,
"text": " Add Notes"
}
] |
AI with Python aΜΒΒ Computer Vision
|
Computer vision is concerned with modeling and replicating human vision using computer software and hardware. In this chapter, you will learn in detail about this.
Computer vision is a discipline that studies how to reconstruct, interrupt and understand a 3d scene from its 2d images, in terms of the properties of the structure present in the scene.
Computer vision is divided into three basic categories as following β
Low-level vision β It includes process image for feature extraction.
Low-level vision β It includes process image for feature extraction.
Intermediate-level vision β It includes object recognition and 3D scene interpretation
Intermediate-level vision β It includes object recognition and 3D scene interpretation
High-level vision β It includes conceptual description of a scene like activity, intention and behavior.
High-level vision β It includes conceptual description of a scene like activity, intention and behavior.
Image processing studies image to image transformation. The input and output of image processing are both images.
Computer vision is the construction of explicit, meaningful descriptions of physical objects from their image. The output of computer vision is a description or an interpretation of structures in 3D scene.
Computer vision finds applications in the following fields β
Robotics
Localization-determine robot location automatically
Localization-determine robot location automatically
Navigation
Navigation
Obstacles avoidance
Obstacles avoidance
Assembly (peg-in-hole, welding, painting)
Assembly (peg-in-hole, welding, painting)
Manipulation (e.g. PUMA robot manipulator)
Manipulation (e.g. PUMA robot manipulator)
Human Robot Interaction (HRI): Intelligent robotics to interact with and serve people
Human Robot Interaction (HRI): Intelligent robotics to interact with and serve people
Medicine
Classification and detection (e.g. lesion or cells classification and tumor detection)
Classification and detection (e.g. lesion or cells classification and tumor detection)
2D/3D segmentation
2D/3D segmentation
3D human organ reconstruction (MRI or ultrasound)
3D human organ reconstruction (MRI or ultrasound)
Vision-guided robotics surgery
Vision-guided robotics surgery
Security
Biometrics (iris, finger print, face recognition)
Surveillance-detecting certain suspicious activities or behaviors
Transportation
Autonomous vehicle
Safety, e.g., driver vigilance monitoring
Industrial Automation Application
Industrial inspection (defect detection)
Assembly
Barcode and package label reading
Object sorting
Document understanding (e.g. OCR)
For Computer vision with Python, you can use a popular library called OpenCV (Open Source Computer Vision). It is a library of programming functions mainly aimed at the real-time computer vision. It is written in C++ and its primary interface is in C++. You can install this package with the help of the following command β
pip install opencv_python-X.X-cp36-cp36m-winX.whl
Here X represents the version of Python installed on your machine as well as the win32 or 64 bit you are having.
If you are using the anaconda environment, then use the following command to install OpenCV β
conda install -c conda-forge opencv
Most of the CV applications need to get the images as input and produce the images as output. In this section, you will learn how to read and write image file with the help of functions provided by OpenCV.
OpenCV provides the following functions for this purpose β
imread() function β This is the function for reading an image. OpenCV imread() supports various image formats like PNG, JPEG, JPG, TIFF, etc.
imread() function β This is the function for reading an image. OpenCV imread() supports various image formats like PNG, JPEG, JPG, TIFF, etc.
imshow() function β This is the function for showing an image in a window. The window automatically fits to the image size. OpenCV imshow() supports various image formats like PNG, JPEG, JPG, TIFF, etc.
imshow() function β This is the function for showing an image in a window. The window automatically fits to the image size. OpenCV imshow() supports various image formats like PNG, JPEG, JPG, TIFF, etc.
imwrite() function β This is the function for writing an image. OpenCV imwrite() supports various image formats like PNG, JPEG, JPG, TIFF, etc.
imwrite() function β This is the function for writing an image. OpenCV imwrite() supports various image formats like PNG, JPEG, JPG, TIFF, etc.
This example shows the Python code for reading an image in one format β showing it in a window and writing the same image in other format. Consider the steps shown below β
Import the OpenCV package as shown β
import cv2
Now, for reading a particular image, use the imread() function β
image = cv2.imread('image_flower.jpg')
For showing the image, use the imshow() function. The name of the window in which you can see the image would be image_flower.
cv2.imshow('image_flower',image)
cv2.destroyAllwindows()
Now, we can write the same image into the other format, say .png by using the imwrite() function β
cv2.imwrite('image_flower.png',image)
The output True means that the image has been successfully written as .png file also in the same folder.
True
Note β The function destroyallWindows() simply destroys all the windows we created.
In OpenCV, the images are not stored by using the conventional RGB color, rather they are stored in the reverse order i.e. in the BGR order. Hence the default color code while reading an image is BGR. The cvtColor() color conversion function in for converting the image from one color code to other.
Consider this example to convert image from BGR to grayscale.
Import the OpenCV package as shown β
import cv2
Now, for reading a particular image, use the imread() function β
image = cv2.imread('image_flower.jpg')
Now, if we see this image using imshow() function, then we can see that this image is in BGR.
cv2.imshow('BGR_Penguins',image)
Now, use cvtColor() function to convert this image to grayscale.
image = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
cv2.imshow('gray_penguins',image)
Humans, after seeing a rough sketch, can easily recognize many object types and their poses. That is why edges play an important role in the life of humans as well as in the applications of computer vision. OpenCV provides very simple and useful function called Canny()for detecting the edges.
The following example shows clear identification of the edges.
Import OpenCV package as shown β
import cv2
import numpy as np
Now, for reading a particular image, use the imread() function.
image = cv2.imread('Penguins.jpg')
Now, use the Canny () function for detecting the edges of the already read image.
cv2.imwrite(βedges_Penguins.jpgβ,cv2.Canny(image,200,300))
Now, for showing the image with edges, use the imshow() function.
cv2.imshow(βedgesβ, cv2.imread(ββedges_Penguins.jpgβ))
This Python program will create an image named edges_penguins.jpg with edge detection.
Face detection is one of the fascinating applications of computer vision which makes it more realistic as well as futuristic. OpenCV has a built-in facility to perform face detection. We are going to use the Haar cascade classifier for face detection.
We need data to use the Haar cascade classifier. You can find this data in our OpenCV package. After installing OpenCv, you can see the folder name haarcascades. There would be .xml files for different application. Now, copy all of them for different use and paste then in a new folder under the current project.
Example
The following is the Python code using Haar Cascade to detect the face of Amitabh Bachan shown in the following image β
Import the OpenCV package as shown β
import cv2
import numpy as np
Now, use the HaarCascadeClassifier for detecting face β
face_detection=
cv2.CascadeClassifier('D:/ProgramData/cascadeclassifier/
haarcascade_frontalface_default.xml')
Now, for reading a particular image, use the imread() function β
img = cv2.imread('AB.jpg')
Now, convert it into grayscale because it would accept gray images β
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Now, using face_detection.detectMultiScale, perform actual face detection
faces = face_detection.detectMultiScale(gray, 1.3, 5)
Now, draw a rectangle around the whole face β
for (x,y,w,h) in faces:
img = cv2.rectangle(img,(x,y),(x+w, y+h),(255,0,0),3)
cv2.imwrite('Face_AB.jpg',img)
This Python program will create an image named Face_AB.jpg with face detection as shown
Eye detection is another fascinating application of computer vision which makes it more realistic as well as futuristic. OpenCV has a built-in facility to perform eye detection. We are going to use the Haar cascade classifier for eye detection.
The following example gives the Python code using Haar Cascade to detect the face of Amitabh Bachan given in the following image β
Import OpenCV package as shown β
import cv2
import numpy as np
Now, use the HaarCascadeClassifier for detecting face β
eye_cascade = cv2.CascadeClassifier('D:/ProgramData/cascadeclassifier/haarcascade_eye.xml')
Now, for reading a particular image, use the imread() function
img = cv2.imread('AB_Eye.jpg')
Now, convert it into grayscale because it would accept grey images β
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Now with the help of eye_cascade.detectMultiScale, perform actual face detection
eyes = eye_cascade.detectMultiScale(gray, 1.03, 5)
Now, draw a rectangle around the whole face β
for (ex,ey,ew,eh) in eyes:
img = cv2.rectangle(img,(ex,ey),(ex+ew, ey+eh),(0,255,0),2)
cv2.imwrite('Eye_AB.jpg',img)
This Python program will create an image named Eye_AB.jpg with eye detection as shown β
78 Lectures
7 hours
Arnab Chakraborty
87 Lectures
9.5 hours
DigiFisk (Programming Is Fun)
10 Lectures
1 hours
Nikoloz Sanakoevi
15 Lectures
54 mins
Mukund Kumar Mishra
11 Lectures
1 hours
Gilad James, PhD
20 Lectures
2 hours
Gilad James, PhD
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2369,
"s": 2205,
"text": "Computer vision is concerned with modeling and replicating human vision using computer software and hardware. In this chapter, you will learn in detail about this."
},
{
"code": null,
"e": 2556,
"s": 2369,
"text": "Computer vision is a discipline that studies how to reconstruct, interrupt and understand a 3d scene from its 2d images, in terms of the properties of the structure present in the scene."
},
{
"code": null,
"e": 2626,
"s": 2556,
"text": "Computer vision is divided into three basic categories as following β"
},
{
"code": null,
"e": 2695,
"s": 2626,
"text": "Low-level vision β It includes process image for feature extraction."
},
{
"code": null,
"e": 2764,
"s": 2695,
"text": "Low-level vision β It includes process image for feature extraction."
},
{
"code": null,
"e": 2851,
"s": 2764,
"text": "Intermediate-level vision β It includes object recognition and 3D scene interpretation"
},
{
"code": null,
"e": 2938,
"s": 2851,
"text": "Intermediate-level vision β It includes object recognition and 3D scene interpretation"
},
{
"code": null,
"e": 3043,
"s": 2938,
"text": "High-level vision β It includes conceptual description of a scene like activity, intention and behavior."
},
{
"code": null,
"e": 3148,
"s": 3043,
"text": "High-level vision β It includes conceptual description of a scene like activity, intention and behavior."
},
{
"code": null,
"e": 3262,
"s": 3148,
"text": "Image processing studies image to image transformation. The input and output of image processing are both images."
},
{
"code": null,
"e": 3468,
"s": 3262,
"text": "Computer vision is the construction of explicit, meaningful descriptions of physical objects from their image. The output of computer vision is a description or an interpretation of structures in 3D scene."
},
{
"code": null,
"e": 3529,
"s": 3468,
"text": "Computer vision finds applications in the following fields β"
},
{
"code": null,
"e": 3538,
"s": 3529,
"text": "Robotics"
},
{
"code": null,
"e": 3590,
"s": 3538,
"text": "Localization-determine robot location automatically"
},
{
"code": null,
"e": 3642,
"s": 3590,
"text": "Localization-determine robot location automatically"
},
{
"code": null,
"e": 3653,
"s": 3642,
"text": "Navigation"
},
{
"code": null,
"e": 3664,
"s": 3653,
"text": "Navigation"
},
{
"code": null,
"e": 3684,
"s": 3664,
"text": "Obstacles avoidance"
},
{
"code": null,
"e": 3704,
"s": 3684,
"text": "Obstacles avoidance"
},
{
"code": null,
"e": 3746,
"s": 3704,
"text": "Assembly (peg-in-hole, welding, painting)"
},
{
"code": null,
"e": 3788,
"s": 3746,
"text": "Assembly (peg-in-hole, welding, painting)"
},
{
"code": null,
"e": 3831,
"s": 3788,
"text": "Manipulation (e.g. PUMA robot manipulator)"
},
{
"code": null,
"e": 3874,
"s": 3831,
"text": "Manipulation (e.g. PUMA robot manipulator)"
},
{
"code": null,
"e": 3960,
"s": 3874,
"text": "Human Robot Interaction (HRI): Intelligent robotics to interact with and serve people"
},
{
"code": null,
"e": 4046,
"s": 3960,
"text": "Human Robot Interaction (HRI): Intelligent robotics to interact with and serve people"
},
{
"code": null,
"e": 4055,
"s": 4046,
"text": "Medicine"
},
{
"code": null,
"e": 4142,
"s": 4055,
"text": "Classification and detection (e.g. lesion or cells classification and tumor detection)"
},
{
"code": null,
"e": 4229,
"s": 4142,
"text": "Classification and detection (e.g. lesion or cells classification and tumor detection)"
},
{
"code": null,
"e": 4248,
"s": 4229,
"text": "2D/3D segmentation"
},
{
"code": null,
"e": 4267,
"s": 4248,
"text": "2D/3D segmentation"
},
{
"code": null,
"e": 4317,
"s": 4267,
"text": "3D human organ reconstruction (MRI or ultrasound)"
},
{
"code": null,
"e": 4367,
"s": 4317,
"text": "3D human organ reconstruction (MRI or ultrasound)"
},
{
"code": null,
"e": 4398,
"s": 4367,
"text": "Vision-guided robotics surgery"
},
{
"code": null,
"e": 4429,
"s": 4398,
"text": "Vision-guided robotics surgery"
},
{
"code": null,
"e": 4438,
"s": 4429,
"text": "Security"
},
{
"code": null,
"e": 4488,
"s": 4438,
"text": "Biometrics (iris, finger print, face recognition)"
},
{
"code": null,
"e": 4554,
"s": 4488,
"text": "Surveillance-detecting certain suspicious activities or behaviors"
},
{
"code": null,
"e": 4569,
"s": 4554,
"text": "Transportation"
},
{
"code": null,
"e": 4588,
"s": 4569,
"text": "Autonomous vehicle"
},
{
"code": null,
"e": 4630,
"s": 4588,
"text": "Safety, e.g., driver vigilance monitoring"
},
{
"code": null,
"e": 4664,
"s": 4630,
"text": "Industrial Automation Application"
},
{
"code": null,
"e": 4705,
"s": 4664,
"text": "Industrial inspection (defect detection)"
},
{
"code": null,
"e": 4714,
"s": 4705,
"text": "Assembly"
},
{
"code": null,
"e": 4748,
"s": 4714,
"text": "Barcode and package label reading"
},
{
"code": null,
"e": 4763,
"s": 4748,
"text": "Object sorting"
},
{
"code": null,
"e": 4797,
"s": 4763,
"text": "Document understanding (e.g. OCR)"
},
{
"code": null,
"e": 5121,
"s": 4797,
"text": "For Computer vision with Python, you can use a popular library called OpenCV (Open Source Computer Vision). It is a library of programming functions mainly aimed at the real-time computer vision. It is written in C++ and its primary interface is in C++. You can install this package with the help of the following command β"
},
{
"code": null,
"e": 5172,
"s": 5121,
"text": "pip install opencv_python-X.X-cp36-cp36m-winX.whl\n"
},
{
"code": null,
"e": 5285,
"s": 5172,
"text": "Here X represents the version of Python installed on your machine as well as the win32 or 64 bit you are having."
},
{
"code": null,
"e": 5379,
"s": 5285,
"text": "If you are using the anaconda environment, then use the following command to install OpenCV β"
},
{
"code": null,
"e": 5416,
"s": 5379,
"text": "conda install -c conda-forge opencv\n"
},
{
"code": null,
"e": 5622,
"s": 5416,
"text": "Most of the CV applications need to get the images as input and produce the images as output. In this section, you will learn how to read and write image file with the help of functions provided by OpenCV."
},
{
"code": null,
"e": 5681,
"s": 5622,
"text": "OpenCV provides the following functions for this purpose β"
},
{
"code": null,
"e": 5823,
"s": 5681,
"text": "imread() function β This is the function for reading an image. OpenCV imread() supports various image formats like PNG, JPEG, JPG, TIFF, etc."
},
{
"code": null,
"e": 5965,
"s": 5823,
"text": "imread() function β This is the function for reading an image. OpenCV imread() supports various image formats like PNG, JPEG, JPG, TIFF, etc."
},
{
"code": null,
"e": 6168,
"s": 5965,
"text": "imshow() function β This is the function for showing an image in a window. The window automatically fits to the image size. OpenCV imshow() supports various image formats like PNG, JPEG, JPG, TIFF, etc."
},
{
"code": null,
"e": 6371,
"s": 6168,
"text": "imshow() function β This is the function for showing an image in a window. The window automatically fits to the image size. OpenCV imshow() supports various image formats like PNG, JPEG, JPG, TIFF, etc."
},
{
"code": null,
"e": 6515,
"s": 6371,
"text": "imwrite() function β This is the function for writing an image. OpenCV imwrite() supports various image formats like PNG, JPEG, JPG, TIFF, etc."
},
{
"code": null,
"e": 6659,
"s": 6515,
"text": "imwrite() function β This is the function for writing an image. OpenCV imwrite() supports various image formats like PNG, JPEG, JPG, TIFF, etc."
},
{
"code": null,
"e": 6831,
"s": 6659,
"text": "This example shows the Python code for reading an image in one format β showing it in a window and writing the same image in other format. Consider the steps shown below β"
},
{
"code": null,
"e": 6868,
"s": 6831,
"text": "Import the OpenCV package as shown β"
},
{
"code": null,
"e": 6879,
"s": 6868,
"text": "import cv2"
},
{
"code": null,
"e": 6944,
"s": 6879,
"text": "Now, for reading a particular image, use the imread() function β"
},
{
"code": null,
"e": 6983,
"s": 6944,
"text": "image = cv2.imread('image_flower.jpg')"
},
{
"code": null,
"e": 7110,
"s": 6983,
"text": "For showing the image, use the imshow() function. The name of the window in which you can see the image would be image_flower."
},
{
"code": null,
"e": 7167,
"s": 7110,
"text": "cv2.imshow('image_flower',image)\ncv2.destroyAllwindows()"
},
{
"code": null,
"e": 7266,
"s": 7167,
"text": "Now, we can write the same image into the other format, say .png by using the imwrite() function β"
},
{
"code": null,
"e": 7304,
"s": 7266,
"text": "cv2.imwrite('image_flower.png',image)"
},
{
"code": null,
"e": 7409,
"s": 7304,
"text": "The output True means that the image has been successfully written as .png file also in the same folder."
},
{
"code": null,
"e": 7415,
"s": 7409,
"text": "True\n"
},
{
"code": null,
"e": 7499,
"s": 7415,
"text": "Note β The function destroyallWindows() simply destroys all the windows we created."
},
{
"code": null,
"e": 7799,
"s": 7499,
"text": "In OpenCV, the images are not stored by using the conventional RGB color, rather they are stored in the reverse order i.e. in the BGR order. Hence the default color code while reading an image is BGR. The cvtColor() color conversion function in for converting the image from one color code to other."
},
{
"code": null,
"e": 7861,
"s": 7799,
"text": "Consider this example to convert image from BGR to grayscale."
},
{
"code": null,
"e": 7898,
"s": 7861,
"text": "Import the OpenCV package as shown β"
},
{
"code": null,
"e": 7909,
"s": 7898,
"text": "import cv2"
},
{
"code": null,
"e": 7974,
"s": 7909,
"text": "Now, for reading a particular image, use the imread() function β"
},
{
"code": null,
"e": 8013,
"s": 7974,
"text": "image = cv2.imread('image_flower.jpg')"
},
{
"code": null,
"e": 8107,
"s": 8013,
"text": "Now, if we see this image using imshow() function, then we can see that this image is in BGR."
},
{
"code": null,
"e": 8140,
"s": 8107,
"text": "cv2.imshow('BGR_Penguins',image)"
},
{
"code": null,
"e": 8205,
"s": 8140,
"text": "Now, use cvtColor() function to convert this image to grayscale."
},
{
"code": null,
"e": 8286,
"s": 8205,
"text": "image = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)\ncv2.imshow('gray_penguins',image)"
},
{
"code": null,
"e": 8580,
"s": 8286,
"text": "Humans, after seeing a rough sketch, can easily recognize many object types and their poses. That is why edges play an important role in the life of humans as well as in the applications of computer vision. OpenCV provides very simple and useful function called Canny()for detecting the edges."
},
{
"code": null,
"e": 8643,
"s": 8580,
"text": "The following example shows clear identification of the edges."
},
{
"code": null,
"e": 8676,
"s": 8643,
"text": "Import OpenCV package as shown β"
},
{
"code": null,
"e": 8706,
"s": 8676,
"text": "import cv2\nimport numpy as np"
},
{
"code": null,
"e": 8770,
"s": 8706,
"text": "Now, for reading a particular image, use the imread() function."
},
{
"code": null,
"e": 8805,
"s": 8770,
"text": "image = cv2.imread('Penguins.jpg')"
},
{
"code": null,
"e": 8887,
"s": 8805,
"text": "Now, use the Canny () function for detecting the edges of the already read image."
},
{
"code": null,
"e": 8946,
"s": 8887,
"text": "cv2.imwrite(βedges_Penguins.jpgβ,cv2.Canny(image,200,300))"
},
{
"code": null,
"e": 9012,
"s": 8946,
"text": "Now, for showing the image with edges, use the imshow() function."
},
{
"code": null,
"e": 9067,
"s": 9012,
"text": "cv2.imshow(βedgesβ, cv2.imread(ββedges_Penguins.jpgβ))"
},
{
"code": null,
"e": 9154,
"s": 9067,
"text": "This Python program will create an image named edges_penguins.jpg with edge detection."
},
{
"code": null,
"e": 9406,
"s": 9154,
"text": "Face detection is one of the fascinating applications of computer vision which makes it more realistic as well as futuristic. OpenCV has a built-in facility to perform face detection. We are going to use the Haar cascade classifier for face detection."
},
{
"code": null,
"e": 9719,
"s": 9406,
"text": "We need data to use the Haar cascade classifier. You can find this data in our OpenCV package. After installing OpenCv, you can see the folder name haarcascades. There would be .xml files for different application. Now, copy all of them for different use and paste then in a new folder under the current project."
},
{
"code": null,
"e": 9727,
"s": 9719,
"text": "Example"
},
{
"code": null,
"e": 9847,
"s": 9727,
"text": "The following is the Python code using Haar Cascade to detect the face of Amitabh Bachan shown in the following image β"
},
{
"code": null,
"e": 9884,
"s": 9847,
"text": "Import the OpenCV package as shown β"
},
{
"code": null,
"e": 9914,
"s": 9884,
"text": "import cv2\nimport numpy as np"
},
{
"code": null,
"e": 9970,
"s": 9914,
"text": "Now, use the HaarCascadeClassifier for detecting face β"
},
{
"code": null,
"e": 10081,
"s": 9970,
"text": "face_detection=\ncv2.CascadeClassifier('D:/ProgramData/cascadeclassifier/\nhaarcascade_frontalface_default.xml')"
},
{
"code": null,
"e": 10146,
"s": 10081,
"text": "Now, for reading a particular image, use the imread() function β"
},
{
"code": null,
"e": 10173,
"s": 10146,
"text": "img = cv2.imread('AB.jpg')"
},
{
"code": null,
"e": 10242,
"s": 10173,
"text": "Now, convert it into grayscale because it would accept gray images β"
},
{
"code": null,
"e": 10287,
"s": 10242,
"text": "gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)"
},
{
"code": null,
"e": 10361,
"s": 10287,
"text": "Now, using face_detection.detectMultiScale, perform actual face detection"
},
{
"code": null,
"e": 10415,
"s": 10361,
"text": "faces = face_detection.detectMultiScale(gray, 1.3, 5)"
},
{
"code": null,
"e": 10461,
"s": 10415,
"text": "Now, draw a rectangle around the whole face β"
},
{
"code": null,
"e": 10573,
"s": 10461,
"text": "for (x,y,w,h) in faces:\n img = cv2.rectangle(img,(x,y),(x+w, y+h),(255,0,0),3)\ncv2.imwrite('Face_AB.jpg',img)"
},
{
"code": null,
"e": 10661,
"s": 10573,
"text": "This Python program will create an image named Face_AB.jpg with face detection as shown"
},
{
"code": null,
"e": 10906,
"s": 10661,
"text": "Eye detection is another fascinating application of computer vision which makes it more realistic as well as futuristic. OpenCV has a built-in facility to perform eye detection. We are going to use the Haar cascade classifier for eye detection."
},
{
"code": null,
"e": 11037,
"s": 10906,
"text": "The following example gives the Python code using Haar Cascade to detect the face of Amitabh Bachan given in the following image β"
},
{
"code": null,
"e": 11070,
"s": 11037,
"text": "Import OpenCV package as shown β"
},
{
"code": null,
"e": 11100,
"s": 11070,
"text": "import cv2\nimport numpy as np"
},
{
"code": null,
"e": 11156,
"s": 11100,
"text": "Now, use the HaarCascadeClassifier for detecting face β"
},
{
"code": null,
"e": 11248,
"s": 11156,
"text": "eye_cascade = cv2.CascadeClassifier('D:/ProgramData/cascadeclassifier/haarcascade_eye.xml')"
},
{
"code": null,
"e": 11312,
"s": 11248,
"text": "Now, for reading a particular image, use the imread() function "
},
{
"code": null,
"e": 11343,
"s": 11312,
"text": "img = cv2.imread('AB_Eye.jpg')"
},
{
"code": null,
"e": 11412,
"s": 11343,
"text": "Now, convert it into grayscale because it would accept grey images β"
},
{
"code": null,
"e": 11457,
"s": 11412,
"text": "gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)"
},
{
"code": null,
"e": 11539,
"s": 11457,
"text": "Now with the help of eye_cascade.detectMultiScale, perform actual face detection "
},
{
"code": null,
"e": 11590,
"s": 11539,
"text": "eyes = eye_cascade.detectMultiScale(gray, 1.03, 5)"
},
{
"code": null,
"e": 11636,
"s": 11590,
"text": "Now, draw a rectangle around the whole face β"
},
{
"code": null,
"e": 11756,
"s": 11636,
"text": "for (ex,ey,ew,eh) in eyes:\n img = cv2.rectangle(img,(ex,ey),(ex+ew, ey+eh),(0,255,0),2)\ncv2.imwrite('Eye_AB.jpg',img)"
},
{
"code": null,
"e": 11844,
"s": 11756,
"text": "This Python program will create an image named Eye_AB.jpg with eye detection as shown β"
},
{
"code": null,
"e": 11877,
"s": 11844,
"text": "\n 78 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 11896,
"s": 11877,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 11931,
"s": 11896,
"text": "\n 87 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 11962,
"s": 11931,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 11995,
"s": 11962,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 12014,
"s": 11995,
"text": " Nikoloz Sanakoevi"
},
{
"code": null,
"e": 12046,
"s": 12014,
"text": "\n 15 Lectures \n 54 mins\n"
},
{
"code": null,
"e": 12067,
"s": 12046,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 12100,
"s": 12067,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 12118,
"s": 12100,
"text": " Gilad James, PhD"
},
{
"code": null,
"e": 12151,
"s": 12118,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 12169,
"s": 12151,
"text": " Gilad James, PhD"
},
{
"code": null,
"e": 12176,
"s": 12169,
"text": " Print"
},
{
"code": null,
"e": 12187,
"s": 12176,
"text": " Add Notes"
}
] |
Python Virtual Environments made easy | by Karan Bhanot | Towards Data Science
|
I was starting a project where I had to quickly check if a package, Flask, worked with the Python installed on my machine. As I ran the command to install Flask, it alerted me that the package was already installed as I had Anaconda on my machine.
But when I tried to run the Hello World Flask app on Sublime Text 3, the console gave an error that it could not find the Flask module. I was confused and started reading online about the problem. I discovered that Anaconda had the Flask module but the Python I was using inside Sublime Text did not have it. I jot down to find a solution to understand how to setup Python properly, install the correct packages at the right place, and setup Sublime Text build system. My online research revealed about Virtual Environments, something that I had not read about before.
After reading many articles on Virtual Environments, I learnt a lot about Python and how I should create environments to work with Python. In this article, Iβll share my knowledge on how you can setup these environments using the Terminal.
There are two versions currently being supported in the community, 2.x and 3.x versions. Some packages work well with Python 3.x but there are some which have no support for 3.x and only work with 2.x. In such a case, sometimes one would want to work with Python 2.x and sometimes with Python 3.x. We begin by installing both versions of Python, so that we can setup environments using either or both. If you have a package installer, such as Homebrew, you can use it to install Python.
Python 3.X
brew install python@3
Python 2.X
brew install python@2
It also installs pip, which helps us install Python packages.
Whenever you start working on a project, youβll first decide which Python version to use and then select a number of libraries/packages that you would want. However, itβs always a good practice to not install these packages systemwide. You might be working on multiple versions of Python on the same machine or some packages that only work with certain versions of Python and break with others. In such scenarios, we can setup different environments, called Virtual Environments.
Each environment will be its own virtual space. All packages installed within that space would not interfere with packages outside the environment and will be contained only inside this space.
Based on which method you used to install, Python would be installed in different locations.
Python installed from official website
/Library/Frameworks/Python.framework/Versions/
Here, youβll find the installed version. I have version 3.6, so the path for Python would be:
/Library/Frameworks/Python.framework/Versions/3.6/bin
Python installed using Homebrew
/usr/local/Cellar/
This will be followed by the versions under the directory python or python@2. If we take the example of python and version 3.7.2_1, the location would be:
/usr/local/Cellar/python/3.7.2_1/bin
Weβll work with Python 3 installed using Homebrew. We install virtualenv using pip3.
pip3 install virtualenv
All packages are installed and now we can begin setting up our Virtual Environment. We need to define the location where we would like to establish our environment and also provide a name. Iβll place it in the home directory and set the name as virtEnv1.
virtualenv -p python3 ~/virtEnv1
The last argument in the above command defines the exact path of our environment along with the environment name. Our environment is now set and we can start working in it.
To begin working inside an environment, we need to activate the environment. When the environment is set up, a file called activate is created inside the bin folder in the environment. We set this file as the source and we are now inside the environment.
cd ~/virtEnv1source bin/activate
The name of the environment starts showing up inside parentheses to indicate that we are now working inside the environment.
Iβll install Flask.
pip install flask
Iβve also made a file app.py inside the home directory which has the most basic Hello World code in Flask.
If I try to run the code inside the environment, it works as seen in the images below.
python ~/app.py
Client
Server
If your environment is enabled, itβs easy to move out of it. Just type deactivate in the terminal.
As the environment is now deactivated, we use the systemwide installed Python. There is no Flask installed across the system. Thus, if I try to run the same code again, it gives an error that flask is not found.
In a similar fashion, we can create many more environments and replicate the similar process even for Python 2.
I prefer to work with Sublime Text whenever I am not working on Jupyter notebooks. To set up Sublime Text for Python, we need to create a new build system. Go to:
Tools > Build System > New Build System...
And set the text as below:
Replace <username> with your username.
Letβs save it as virtEnv1Python. Open the file, app.py, in Sublime Text. Set Build System as virtEnv1Python. To test if the app is working, press Command + B. Youβll see that the app starts running which you can confirm by going to the link http://127.0.0.1:5000/.
In this article, I discussed the use of virtualenv to create Python Virtual Environments and install packages inside these environments.
Please feel free to share your thoughts, ideas and suggestions.
|
[
{
"code": null,
"e": 420,
"s": 172,
"text": "I was starting a project where I had to quickly check if a package, Flask, worked with the Python installed on my machine. As I ran the command to install Flask, it alerted me that the package was already installed as I had Anaconda on my machine."
},
{
"code": null,
"e": 989,
"s": 420,
"text": "But when I tried to run the Hello World Flask app on Sublime Text 3, the console gave an error that it could not find the Flask module. I was confused and started reading online about the problem. I discovered that Anaconda had the Flask module but the Python I was using inside Sublime Text did not have it. I jot down to find a solution to understand how to setup Python properly, install the correct packages at the right place, and setup Sublime Text build system. My online research revealed about Virtual Environments, something that I had not read about before."
},
{
"code": null,
"e": 1229,
"s": 989,
"text": "After reading many articles on Virtual Environments, I learnt a lot about Python and how I should create environments to work with Python. In this article, Iβll share my knowledge on how you can setup these environments using the Terminal."
},
{
"code": null,
"e": 1716,
"s": 1229,
"text": "There are two versions currently being supported in the community, 2.x and 3.x versions. Some packages work well with Python 3.x but there are some which have no support for 3.x and only work with 2.x. In such a case, sometimes one would want to work with Python 2.x and sometimes with Python 3.x. We begin by installing both versions of Python, so that we can setup environments using either or both. If you have a package installer, such as Homebrew, you can use it to install Python."
},
{
"code": null,
"e": 1727,
"s": 1716,
"text": "Python 3.X"
},
{
"code": null,
"e": 1749,
"s": 1727,
"text": "brew install python@3"
},
{
"code": null,
"e": 1760,
"s": 1749,
"text": "Python 2.X"
},
{
"code": null,
"e": 1782,
"s": 1760,
"text": "brew install python@2"
},
{
"code": null,
"e": 1844,
"s": 1782,
"text": "It also installs pip, which helps us install Python packages."
},
{
"code": null,
"e": 2324,
"s": 1844,
"text": "Whenever you start working on a project, youβll first decide which Python version to use and then select a number of libraries/packages that you would want. However, itβs always a good practice to not install these packages systemwide. You might be working on multiple versions of Python on the same machine or some packages that only work with certain versions of Python and break with others. In such scenarios, we can setup different environments, called Virtual Environments."
},
{
"code": null,
"e": 2517,
"s": 2324,
"text": "Each environment will be its own virtual space. All packages installed within that space would not interfere with packages outside the environment and will be contained only inside this space."
},
{
"code": null,
"e": 2610,
"s": 2517,
"text": "Based on which method you used to install, Python would be installed in different locations."
},
{
"code": null,
"e": 2649,
"s": 2610,
"text": "Python installed from official website"
},
{
"code": null,
"e": 2696,
"s": 2649,
"text": "/Library/Frameworks/Python.framework/Versions/"
},
{
"code": null,
"e": 2790,
"s": 2696,
"text": "Here, youβll find the installed version. I have version 3.6, so the path for Python would be:"
},
{
"code": null,
"e": 2844,
"s": 2790,
"text": "/Library/Frameworks/Python.framework/Versions/3.6/bin"
},
{
"code": null,
"e": 2876,
"s": 2844,
"text": "Python installed using Homebrew"
},
{
"code": null,
"e": 2895,
"s": 2876,
"text": "/usr/local/Cellar/"
},
{
"code": null,
"e": 3050,
"s": 2895,
"text": "This will be followed by the versions under the directory python or python@2. If we take the example of python and version 3.7.2_1, the location would be:"
},
{
"code": null,
"e": 3087,
"s": 3050,
"text": "/usr/local/Cellar/python/3.7.2_1/bin"
},
{
"code": null,
"e": 3172,
"s": 3087,
"text": "Weβll work with Python 3 installed using Homebrew. We install virtualenv using pip3."
},
{
"code": null,
"e": 3196,
"s": 3172,
"text": "pip3 install virtualenv"
},
{
"code": null,
"e": 3451,
"s": 3196,
"text": "All packages are installed and now we can begin setting up our Virtual Environment. We need to define the location where we would like to establish our environment and also provide a name. Iβll place it in the home directory and set the name as virtEnv1."
},
{
"code": null,
"e": 3484,
"s": 3451,
"text": "virtualenv -p python3 ~/virtEnv1"
},
{
"code": null,
"e": 3657,
"s": 3484,
"text": "The last argument in the above command defines the exact path of our environment along with the environment name. Our environment is now set and we can start working in it."
},
{
"code": null,
"e": 3912,
"s": 3657,
"text": "To begin working inside an environment, we need to activate the environment. When the environment is set up, a file called activate is created inside the bin folder in the environment. We set this file as the source and we are now inside the environment."
},
{
"code": null,
"e": 3945,
"s": 3912,
"text": "cd ~/virtEnv1source bin/activate"
},
{
"code": null,
"e": 4070,
"s": 3945,
"text": "The name of the environment starts showing up inside parentheses to indicate that we are now working inside the environment."
},
{
"code": null,
"e": 4090,
"s": 4070,
"text": "Iβll install Flask."
},
{
"code": null,
"e": 4108,
"s": 4090,
"text": "pip install flask"
},
{
"code": null,
"e": 4215,
"s": 4108,
"text": "Iβve also made a file app.py inside the home directory which has the most basic Hello World code in Flask."
},
{
"code": null,
"e": 4302,
"s": 4215,
"text": "If I try to run the code inside the environment, it works as seen in the images below."
},
{
"code": null,
"e": 4318,
"s": 4302,
"text": "python ~/app.py"
},
{
"code": null,
"e": 4325,
"s": 4318,
"text": "Client"
},
{
"code": null,
"e": 4332,
"s": 4325,
"text": "Server"
},
{
"code": null,
"e": 4431,
"s": 4332,
"text": "If your environment is enabled, itβs easy to move out of it. Just type deactivate in the terminal."
},
{
"code": null,
"e": 4643,
"s": 4431,
"text": "As the environment is now deactivated, we use the systemwide installed Python. There is no Flask installed across the system. Thus, if I try to run the same code again, it gives an error that flask is not found."
},
{
"code": null,
"e": 4755,
"s": 4643,
"text": "In a similar fashion, we can create many more environments and replicate the similar process even for Python 2."
},
{
"code": null,
"e": 4918,
"s": 4755,
"text": "I prefer to work with Sublime Text whenever I am not working on Jupyter notebooks. To set up Sublime Text for Python, we need to create a new build system. Go to:"
},
{
"code": null,
"e": 4961,
"s": 4918,
"text": "Tools > Build System > New Build System..."
},
{
"code": null,
"e": 4988,
"s": 4961,
"text": "And set the text as below:"
},
{
"code": null,
"e": 5027,
"s": 4988,
"text": "Replace <username> with your username."
},
{
"code": null,
"e": 5292,
"s": 5027,
"text": "Letβs save it as virtEnv1Python. Open the file, app.py, in Sublime Text. Set Build System as virtEnv1Python. To test if the app is working, press Command + B. Youβll see that the app starts running which you can confirm by going to the link http://127.0.0.1:5000/."
},
{
"code": null,
"e": 5429,
"s": 5292,
"text": "In this article, I discussed the use of virtualenv to create Python Virtual Environments and install packages inside these environments."
}
] |
Angular Material 7 - Progress Spinner
|
The <mat-progress-spinner>, an Angular Directive, is used to show a progress spinner with material styling.
In this chapter, we will showcase the configuration required to draw a deterministic as well as indeterministic progress spinner using Angular Material.
Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter β
Following is the content of the modified module descriptor app.module.ts.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatProgressSpinnerModule, MatRadioModule, MatSliderModule} from '@angular/material'
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
MatProgressSpinnerModule, MatRadioModule, MatSliderModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Following is the content of the modified ts file app.component.css.
.tp-section {
display: flex;
align-content: center;
align-items: center;
height: 60px;
}
.tp-margin {
margin: 0 10px;
}
Following is the content of the modified HTML host file app.component.html.
<section class = "tp-section">
<label class = "tp-margin">Color:</label>
<mat-radio-group [(ngModel)] = "color">
<mat-radio-button class = "tp-margin" value = "primary">
Primary
</mat-radio-button>
<mat-radio-button class = "tp-margin" value = "accent">
Accent
</mat-radio-button>
<mat-radio-button class = "tp-margin" value = "warn">
Warn
</mat-radio-button>
</mat-radio-group>
</section>
<section class = "tp-section">
<label class = "tp-margin">Mode:</label>
<mat-radio-group [(ngModel)] = "mode">
<mat-radio-button class = "tp-margin" value = "determinate">
Determinate
</mat-radio-button>
<mat-radio-button class = "tp-margin" value = "indeterminate">
Indeterminate
</mat-radio-button>
</mat-radio-group>
</section>
<section class = "tp-section" *ngIf = "mode === 'determinate'">
<label class = "tp-margin">Progress:</label>
<mat-slider class = "tp-margin" [(ngModel)] = "value"></mat-slider>
</section>
<section class = "tp-section">
<label class = "tp-margin">Mode: {{mode}}</label>
<mat-progress-spinner
class = "tp-margin"
[color] = "color"
[mode] = "mode"
[value] = "value">
</mat-progress-spinner>
</section>
Following is the content of the modified ts file app.component.ts.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'materialApp';
color = 'primary';
mode = 'determinate';
value = 50;
}
Verify the result.
Here, we've created progress spinner using mat-progress-spinner.
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": 2863,
"s": 2755,
"text": "The <mat-progress-spinner>, an Angular Directive, is used to show a progress spinner with material styling."
},
{
"code": null,
"e": 3016,
"s": 2863,
"text": "In this chapter, we will showcase the configuration required to draw a deterministic as well as indeterministic progress spinner using Angular Material."
},
{
"code": null,
"e": 3127,
"s": 3016,
"text": "Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter β"
},
{
"code": null,
"e": 3201,
"s": 3127,
"text": "Following is the content of the modified module descriptor app.module.ts."
},
{
"code": null,
"e": 3900,
"s": 3201,
"text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\nimport {BrowserAnimationsModule} from '@angular/platform-browser/animations';\nimport {MatProgressSpinnerModule, MatRadioModule, MatSliderModule} from '@angular/material'\nimport {FormsModule, ReactiveFormsModule} from '@angular/forms';\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule,\n BrowserAnimationsModule,\n MatProgressSpinnerModule, MatRadioModule, MatSliderModule,\n FormsModule,\n ReactiveFormsModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }"
},
{
"code": null,
"e": 3968,
"s": 3900,
"text": "Following is the content of the modified ts file app.component.css."
},
{
"code": null,
"e": 4103,
"s": 3968,
"text": ".tp-section {\n display: flex;\n align-content: center;\n align-items: center;\n height: 60px;\n}\n.tp-margin {\n margin: 0 10px;\n}"
},
{
"code": null,
"e": 4179,
"s": 4103,
"text": "Following is the content of the modified HTML host file app.component.html."
},
{
"code": null,
"e": 5461,
"s": 4179,
"text": "<section class = \"tp-section\">\n <label class = \"tp-margin\">Color:</label>\n <mat-radio-group [(ngModel)] = \"color\">\n <mat-radio-button class = \"tp-margin\" value = \"primary\">\n Primary\n </mat-radio-button>\n <mat-radio-button class = \"tp-margin\" value = \"accent\">\n Accent\n </mat-radio-button>\n <mat-radio-button class = \"tp-margin\" value = \"warn\">\n Warn\n </mat-radio-button>\n </mat-radio-group>\n</section>\n<section class = \"tp-section\">\n <label class = \"tp-margin\">Mode:</label>\n <mat-radio-group [(ngModel)] = \"mode\">\n <mat-radio-button class = \"tp-margin\" value = \"determinate\">\n Determinate\n </mat-radio-button>\n <mat-radio-button class = \"tp-margin\" value = \"indeterminate\">\n Indeterminate\n </mat-radio-button>\n </mat-radio-group>\n</section>\n<section class = \"tp-section\" *ngIf = \"mode === 'determinate'\">\n <label class = \"tp-margin\">Progress:</label>\n <mat-slider class = \"tp-margin\" [(ngModel)] = \"value\"></mat-slider>\n</section>\n<section class = \"tp-section\">\n <label class = \"tp-margin\">Mode: {{mode}}</label>\n <mat-progress-spinner\n class = \"tp-margin\"\n [color] = \"color\"\n [mode] = \"mode\"\n [value] = \"value\">\n </mat-progress-spinner>\n</section>"
},
{
"code": null,
"e": 5528,
"s": 5461,
"text": "Following is the content of the modified ts file app.component.ts."
},
{
"code": null,
"e": 5813,
"s": 5528,
"text": "import { Component } from '@angular/core';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'materialApp'; \n color = 'primary';\n mode = 'determinate';\n value = 50;\n \n}"
},
{
"code": null,
"e": 5832,
"s": 5813,
"text": "Verify the result."
},
{
"code": null,
"e": 5897,
"s": 5832,
"text": "Here, we've created progress spinner using mat-progress-spinner."
},
{
"code": null,
"e": 5932,
"s": 5897,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5946,
"s": 5932,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5981,
"s": 5946,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5995,
"s": 5981,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6030,
"s": 5995,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 6050,
"s": 6030,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 6085,
"s": 6050,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6102,
"s": 6085,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6135,
"s": 6102,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6147,
"s": 6135,
"text": " Senol Atac"
},
{
"code": null,
"e": 6182,
"s": 6147,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6194,
"s": 6182,
"text": " Senol Atac"
},
{
"code": null,
"e": 6201,
"s": 6194,
"text": " Print"
},
{
"code": null,
"e": 6212,
"s": 6201,
"text": " Add Notes"
}
] |
Diverging Bar Chart using Python - GeeksforGeeks
|
15 Mar, 2021
Diverging Bar Charts are used to ease the comparison of multiple groups. Its design allows us to compare numerical values in various groups. It also helps us to quickly visualize the favorable and unfavorable or positive and negative responses. The bar chart consisted of a combination of two horizontal bars starting from the middle- one bar extends out from right to left and the other extends out from left to right. The length of the bar is corresponding to the numerical value it represents.
Commonly the two diverging bars are represented with different colors. Values to the left are usually but not necessarily negative or unsatisfactory responses.
Python doesnβt have a particular function to plot diverging bar charts. The alternate way is to use hlines function to draw horizontal lines with a certain value of linewidth to represent them as horizontal bars.
Datasets in use:
Mercedes Benz Car Sales Data
Twitter Airline Sentiment
Approach :
Import module
Import or create data
Preprocess the dataset and clean out the unnecessary noise
Specify the colors for representing the horizontal bars
Sort the values in ascending order
Set the labels for the x-axis and y-axis as well as the title of the chart
Display the Diverging Bar Chart
Example 1:
Python
import pandas as pdimport matplotlib.pyplot as pltimport string as str # Creating a DataFrame from the CSV Datasetdf = pd.read_csv("car_sales.csv", sep=';') # Separating the Date and Mercedes-Benz Cars unit sales (USA)df['car_sales_z'] = df.loc[:, ['Mercedes-Benz Cars unit sales (USA)']]df['car_sales_z'] = df['car_sales_z'] .str.replace( ',', '').astype(float) # Removing null valuedf.drop(df.tail(1).index, inplace=True) for i in range(35): # Colour of bar chart is set to red if the sales # is < 60000 and green otherwise df['colors'] = ['red' if float( x) < 60000 else 'green' for x in df['car_sales_z']] # Sort values from lowest to highestdf.sort_values('car_sales_z', inplace=True) # Resets initial index in Dataframe to Nonedf.reset_index(inplace=True) # Draw plotplt.figure(figsize=(14, 10), dpi=80) # Plotting the horizontal linesplt.hlines(y=df.index, xmin=60000, xmax=df.car_sales_z, color=df.colors, alpha=0.4, linewidth=5) # Decorations# Setting the labels of x-axis and y-axisplt.gca().set(ylabel='Quarter', xlabel='Sales') # Setting Date to y-axisplt.yticks(df.index, df.Date, fontsize=12) # Title of Bar Chartplt.title('Diverging Bars Chart Example', fontdict={ 'size': 20}) # Optional grid layoutplt.grid(linestyle='--', alpha=0.5) # Displaying the Diverging Bar Chartplt.show()
Output:
Approach:
Import required libraries
Create or import data
Preprocess the Dataset and clean out the unnecessary noise
Plot the graph using plotly.graph_objects
Set the labels for the x-axis and y-axis as well as the legend
Display the Diverging Bar Chart
Example:
Python
import pandas as pdimport plotly.graph_objects as go df = pd.read_csv("Tweets.csv")df.head() # Preprocessing the dataset to extract only# the necessary columnscategories = [ 'negative', 'neutral', 'positive'] # Construct a pivot table with the column# 'airline' as the index and the sentiments# as the columnsgfg = pd.pivot_table( df, index='airline', columns='airline_sentiment', values='tweet_id', aggfunc='count') # Include the sentiments - negative, neutral# and positivegfg = gfg[categories] # Representing negative sentiment with negative# numbersgfg.negative = gfg.negative * -1 df = gfg # Creating a FigureDiverging = go.Figure() # Iterating over the columnsfor col in df.columns[4:]: # Adding a trace and specifying the parameters # for negative sentiment Diverging.add_trace(go.Bar(x=-df[col].values, y=df.index, orientation='h', name=col, customdata=df[col], hovertemplate="%{y}: %{customdata}"))for col in df.columns: # Adding a trace and specifying the parameters # for positive and neutral sentiment Diverging.add_trace(go.Bar(x=df[col], y=df.index, orientation='h', name=col, hovertemplate="%{y}: %{x}")) # Specifying the layout of the plotDiverging.update_layout(barmode='relative', height=400, width=700, yaxis_autorange='reversed', bargap=0.5, legend_orientation='v', legend_x=1, legend_y=0 )Diverging
Output:
Data Visualization
Picked
Python-matplotlib
Python-Plotly
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": 24238,
"s": 24210,
"text": "\n15 Mar, 2021"
},
{
"code": null,
"e": 24735,
"s": 24238,
"text": "Diverging Bar Charts are used to ease the comparison of multiple groups. Its design allows us to compare numerical values in various groups. It also helps us to quickly visualize the favorable and unfavorable or positive and negative responses. The bar chart consisted of a combination of two horizontal bars starting from the middle- one bar extends out from right to left and the other extends out from left to right. The length of the bar is corresponding to the numerical value it represents."
},
{
"code": null,
"e": 24895,
"s": 24735,
"text": "Commonly the two diverging bars are represented with different colors. Values to the left are usually but not necessarily negative or unsatisfactory responses."
},
{
"code": null,
"e": 25108,
"s": 24895,
"text": "Python doesnβt have a particular function to plot diverging bar charts. The alternate way is to use hlines function to draw horizontal lines with a certain value of linewidth to represent them as horizontal bars."
},
{
"code": null,
"e": 25125,
"s": 25108,
"text": "Datasets in use:"
},
{
"code": null,
"e": 25154,
"s": 25125,
"text": "Mercedes Benz Car Sales Data"
},
{
"code": null,
"e": 25180,
"s": 25154,
"text": "Twitter Airline Sentiment"
},
{
"code": null,
"e": 25191,
"s": 25180,
"text": "Approach :"
},
{
"code": null,
"e": 25205,
"s": 25191,
"text": "Import module"
},
{
"code": null,
"e": 25227,
"s": 25205,
"text": "Import or create data"
},
{
"code": null,
"e": 25286,
"s": 25227,
"text": "Preprocess the dataset and clean out the unnecessary noise"
},
{
"code": null,
"e": 25342,
"s": 25286,
"text": "Specify the colors for representing the horizontal bars"
},
{
"code": null,
"e": 25377,
"s": 25342,
"text": "Sort the values in ascending order"
},
{
"code": null,
"e": 25452,
"s": 25377,
"text": "Set the labels for the x-axis and y-axis as well as the title of the chart"
},
{
"code": null,
"e": 25484,
"s": 25452,
"text": "Display the Diverging Bar Chart"
},
{
"code": null,
"e": 25496,
"s": 25484,
"text": "Example 1: "
},
{
"code": null,
"e": 25503,
"s": 25496,
"text": "Python"
},
{
"code": "import pandas as pdimport matplotlib.pyplot as pltimport string as str # Creating a DataFrame from the CSV Datasetdf = pd.read_csv(\"car_sales.csv\", sep=';') # Separating the Date and Mercedes-Benz Cars unit sales (USA)df['car_sales_z'] = df.loc[:, ['Mercedes-Benz Cars unit sales (USA)']]df['car_sales_z'] = df['car_sales_z'] .str.replace( ',', '').astype(float) # Removing null valuedf.drop(df.tail(1).index, inplace=True) for i in range(35): # Colour of bar chart is set to red if the sales # is < 60000 and green otherwise df['colors'] = ['red' if float( x) < 60000 else 'green' for x in df['car_sales_z']] # Sort values from lowest to highestdf.sort_values('car_sales_z', inplace=True) # Resets initial index in Dataframe to Nonedf.reset_index(inplace=True) # Draw plotplt.figure(figsize=(14, 10), dpi=80) # Plotting the horizontal linesplt.hlines(y=df.index, xmin=60000, xmax=df.car_sales_z, color=df.colors, alpha=0.4, linewidth=5) # Decorations# Setting the labels of x-axis and y-axisplt.gca().set(ylabel='Quarter', xlabel='Sales') # Setting Date to y-axisplt.yticks(df.index, df.Date, fontsize=12) # Title of Bar Chartplt.title('Diverging Bars Chart Example', fontdict={ 'size': 20}) # Optional grid layoutplt.grid(linestyle='--', alpha=0.5) # Displaying the Diverging Bar Chartplt.show()",
"e": 26855,
"s": 25503,
"text": null
},
{
"code": null,
"e": 26863,
"s": 26855,
"text": "Output:"
},
{
"code": null,
"e": 26873,
"s": 26863,
"text": "Approach:"
},
{
"code": null,
"e": 26899,
"s": 26873,
"text": "Import required libraries"
},
{
"code": null,
"e": 26921,
"s": 26899,
"text": "Create or import data"
},
{
"code": null,
"e": 26980,
"s": 26921,
"text": "Preprocess the Dataset and clean out the unnecessary noise"
},
{
"code": null,
"e": 27022,
"s": 26980,
"text": "Plot the graph using plotly.graph_objects"
},
{
"code": null,
"e": 27085,
"s": 27022,
"text": "Set the labels for the x-axis and y-axis as well as the legend"
},
{
"code": null,
"e": 27117,
"s": 27085,
"text": "Display the Diverging Bar Chart"
},
{
"code": null,
"e": 27126,
"s": 27117,
"text": "Example:"
},
{
"code": null,
"e": 27133,
"s": 27126,
"text": "Python"
},
{
"code": "import pandas as pdimport plotly.graph_objects as go df = pd.read_csv(\"Tweets.csv\")df.head() # Preprocessing the dataset to extract only# the necessary columnscategories = [ 'negative', 'neutral', 'positive'] # Construct a pivot table with the column# 'airline' as the index and the sentiments# as the columnsgfg = pd.pivot_table( df, index='airline', columns='airline_sentiment', values='tweet_id', aggfunc='count') # Include the sentiments - negative, neutral# and positivegfg = gfg[categories] # Representing negative sentiment with negative# numbersgfg.negative = gfg.negative * -1 df = gfg # Creating a FigureDiverging = go.Figure() # Iterating over the columnsfor col in df.columns[4:]: # Adding a trace and specifying the parameters # for negative sentiment Diverging.add_trace(go.Bar(x=-df[col].values, y=df.index, orientation='h', name=col, customdata=df[col], hovertemplate=\"%{y}: %{customdata}\"))for col in df.columns: # Adding a trace and specifying the parameters # for positive and neutral sentiment Diverging.add_trace(go.Bar(x=df[col], y=df.index, orientation='h', name=col, hovertemplate=\"%{y}: %{x}\")) # Specifying the layout of the plotDiverging.update_layout(barmode='relative', height=400, width=700, yaxis_autorange='reversed', bargap=0.5, legend_orientation='v', legend_x=1, legend_y=0 )Diverging",
"e": 28941,
"s": 27133,
"text": null
},
{
"code": null,
"e": 28949,
"s": 28941,
"text": "Output:"
},
{
"code": null,
"e": 28968,
"s": 28949,
"text": "Data Visualization"
},
{
"code": null,
"e": 28975,
"s": 28968,
"text": "Picked"
},
{
"code": null,
"e": 28993,
"s": 28975,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 29007,
"s": 28993,
"text": "Python-Plotly"
},
{
"code": null,
"e": 29014,
"s": 29007,
"text": "Python"
},
{
"code": null,
"e": 29112,
"s": 29014,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29121,
"s": 29112,
"text": "Comments"
},
{
"code": null,
"e": 29134,
"s": 29121,
"text": "Old Comments"
},
{
"code": null,
"e": 29155,
"s": 29134,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 29187,
"s": 29155,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29210,
"s": 29187,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 29232,
"s": 29210,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29259,
"s": 29232,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29275,
"s": 29259,
"text": "Deque in Python"
},
{
"code": null,
"e": 29317,
"s": 29275,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29373,
"s": 29317,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29418,
"s": 29373,
"text": "Python - Ways to remove duplicates from list"
}
] |
How to use count with CASE condition in a MySQL query?
|
Use CASE WHEN for this in MySQL and set CASE condition inside the COUNT() method to count. Let us first create a table β
mysql> create table DemoTable1374
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> Name varchar(20),
-> Score int
-> );
Query OK, 0 rows affected (0.61 sec)
Insert some records in the table using insert command β
mysql> insert into DemoTable1374(Name,Score) values('Chris',45);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1374(Name,Score) values('David',78);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1374(Name,Score) values('Bob',45);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1374(Name,Score) values('Mike',75);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1374(Name,Score) values('Carol',45);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1374(Name,Score) values('Adam',89);
Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement β
mysql> select * from DemoTable1374;
This will produce the following output β
+----+-------+-------+
| Id | Name | Score |
+----+-------+-------+
| 1 | Chris | 45 |
| 2 | David | 78 |
| 3 | Bob | 45 |
| 4 | Mike | 75 |
| 5 | Carol | 45 |
| 6 | Adam | 89 |
+----+-------+-------+
6 rows in set (0.00 sec)
Following is the query for CASE WHEN to set condition and count β
mysql> select count( case when Score=45 then 1 else NULL end) as SpecificCondition from DemoTable1374;
This will produce the following output β
+-------------------+
| SpecificCondition |
+-------------------+
| 3 |
+-------------------+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1183,
"s": 1062,
"text": "Use CASE WHEN for this in MySQL and set CASE condition inside the COUNT() method to count. Let us first create a table β"
},
{
"code": null,
"e": 1361,
"s": 1183,
"text": "mysql> create table DemoTable1374\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> Name varchar(20),\n -> Score int\n -> );\nQuery OK, 0 rows affected (0.61 sec)"
},
{
"code": null,
"e": 1417,
"s": 1361,
"text": "Insert some records in the table using insert command β"
},
{
"code": null,
"e": 2019,
"s": 1417,
"text": "mysql> insert into DemoTable1374(Name,Score) values('Chris',45);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable1374(Name,Score) values('David',78);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable1374(Name,Score) values('Bob',45);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable1374(Name,Score) values('Mike',75);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable1374(Name,Score) values('Carol',45);\nQuery OK, 1 row affected (0.09 sec)\nmysql> insert into DemoTable1374(Name,Score) values('Adam',89);\nQuery OK, 1 row affected (0.18 sec)"
},
{
"code": null,
"e": 2079,
"s": 2019,
"text": "Display all records from the table using select statement β"
},
{
"code": null,
"e": 2115,
"s": 2079,
"text": "mysql> select * from DemoTable1374;"
},
{
"code": null,
"e": 2156,
"s": 2115,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2411,
"s": 2156,
"text": "+----+-------+-------+\n| Id | Name | Score |\n+----+-------+-------+\n| 1 | Chris | 45 |\n| 2 | David | 78 |\n| 3 | Bob | 45 |\n| 4 | Mike | 75 |\n| 5 | Carol | 45 |\n| 6 | Adam | 89 |\n+----+-------+-------+\n6 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2477,
"s": 2411,
"text": "Following is the query for CASE WHEN to set condition and count β"
},
{
"code": null,
"e": 2581,
"s": 2477,
"text": "mysql> select count( case when Score=45 then 1 else NULL end) as SpecificCondition from DemoTable1374;"
},
{
"code": null,
"e": 2622,
"s": 2581,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2756,
"s": 2622,
"text": "+-------------------+\n| SpecificCondition |\n+-------------------+\n| 3 |\n+-------------------+\n1 row in set (0.00 sec)"
}
] |
Bootstrap 4 - Input Group
|
Using input groups you can easily prepend and append text or buttons to the text-based inputs.
You can create an input group by adding .input-group class within <div> element. Add the text in front of the input by using .input-group-prepend and use .input-group-append class to add the text behind the input. Style the specified text by adding .input-group-text class.
The following example demonstrates basic input group β
<html lang = "en">
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin = "anonymous">
<title>Bootstrap 4 Example</title>
</head>
<body>
<div class = "container">
<h2>Input Group</h2>
<div class = "input-group mb-3">
<div class = "input-group-prepend">
<span class = "input-group-text" id = "basic-addon1">Username@</span>
</div>
<input type = "text" class = "form-control" placeholder = "Username"
aria-label = "Username" aria-describedby = "basic-addon1">
</div>
<div class = "input-group mb-3">
<input type = "text" class = "form-control"
placeholder = "Recipient's username" aria-label = "Recipient's username"
aria-describedby = "basic-addon2">
<div class = "input-group-append">
<span class = "input-group-text" id = "basic-addon2">@tutorialspoint.com</span>
</div>
</div>
<div class = "input-group mb-3">
<div class = "input-group-prepend">
<span class = "input-group-text">Price in $</span>
</div>
<input type = "text" class = "form-control"
aria-label = "Amount (to the nearest dollar)">
<div class = "input-group-append">
<span class = "input-group-text">.00</span>
</div>
</div>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin = "anonymous">
</script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin = "anonymous">
</script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result β
You can create small input groups by using .input-group-sm class and large inputs groups by using .input-group-lg class as shown in the example below β
<html lang = "en">
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin = "anonymous">
<title>Bootstrap 4 Example</title>
</head>
<body>
<div class = "container">
<h2>Input Group Sizing</h2>
<div class = "input-group input-group-lg">
<div class = "input-group-prepend">
<span class = "input-group-text" id = "inputGroup-sizing-lg">@</span>
</div>
<input type = "text" class = "form-control" aria-label = "Sizing example input"
aria-describedby = "inputGroup-sizing-lg" placeholder = "Large Input Group">
</div>
<br>
<div class = "input-group mb-3">
<div class = "input-group-prepend">
<span class = "input-group-text" id = "inputGroup-sizing-default">@</span>
</div>
<input type = "text" class = "form-control" aria-label = "Sizing example input"
aria-describedby = "inputGroup-sizing-default" placeholder = "Default Input Group">
</div>
<div class = "input-group input-group-sm mb-3">
<div class = "input-group-prepend">
<span class = "input-group-text" id = "inputGroup-sizing-sm">@</span>
</div>
<input type = "text" class = "form-control" aria-label = "Sizing example input"
aria-describedby = "inputGroup-sizing-sm" placeholder = "Small Input Group">
</div>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin = "anonymous">
</script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin = "anonymous">
</script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result β
You can use checkboxes and radio buttons instead of text within an input group as shown in the below example β
<html lang = "en">
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin = "anonymous">
<title>Bootstrap 4 Example</title>
</head>
<body>
<div class = "container">
<h2>Input Group with Checkbox and Radio Button</h2>
<div class = "input-group mb-3">
<div class = "input-group-prepend">
<div class = "input-group-text">
<input type = "checkbox" aria-label = "Checkbox for following text input">
</div>
</div>
<input type = "text" class = "form-control"
aria-label = "Text input with checkbox" placeholder = "Checkbox">
</div>
<div class = "input-group">
<div class = "input-group-prepend">
<div class = "input-group-text">
<input type = "radio" aria-label = "Radio button for following text input">
</div>
</div>
<input type = "text" class = "form-control"
aria-label = "Text input with radio button" placeholder = "Radio button">
</div>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin = "anonymous">
</script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin = "anonymous">
</script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result β
You can add multiple inputs to an input group as shown in the example below β
<html lang = "en">
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin = "anonymous">
<title>Bootstrap 4 Example</title>
</head>
<body>
<div class = "container">
<h2>Multiple Inputs</h2>
<div class = "input-group">
<div class = "input-group-prepend">
<span class = "input-group-text">User Name and Password</span>
</div>
<input type = "email" aria-label = "User Name" class = "form-control">
<input type = "password" aria-label = "Password" class = "form-control">
</div>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin = "anonymous">
</script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin = "anonymous">
</script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result β
You can add button in an input group by adding .btn class within the .input-group class and also you can add dropdowns within the .input-group class.
The following example demonstrates adding of input Group buttons and along with dropdown button β
<html lang = "en">
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin = "anonymous">
<title>Bootstrap 4 Example</title>
</head>
<body>
<div class = "container">
<h2>Input Group Button</h2>
<div class = "input-group mb-3">
<div class = "input-group-prepend">
<button class = "btn btn-outline-info" type = "button"
id = "button-addon1">Button</button>
</div>
<input type = "text" class = "form-control"
placeholder = "Button in Input Group"
aria-label = "Example text with button addon" aria-describedby = "button-addon1">
</div>
<h2>Input Group with Dropdown Button</h2>
<div class = "input-group mb-3">
<div class = "input-group-prepend">
<button class = "btn btn-outline-info dropdown-toggle"
type = "button" data-toggle = "dropdown"
aria-haspopup = "true" aria-expanded = "false">Dropdown</button>
<div class = "dropdown-menu">
<a class = "dropdown-item" href = "#">Option #1</a>
<a class = "dropdown-item" href = "#">Option #2</a>
<a class = "dropdown-item" href = "#">Option #3</a>
<div role = "separator" class = "dropdown-divider"></div>
<a class = "dropdown-item" href = "#">Option #4</a>
</div>
</div>
<input type = "text" class = "form-control"
aria-label = "Text input with dropdown button"
placeholder = "Dropdown in Input Group">
</div>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin = "anonymous">
</script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin = "anonymous">
</script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result β
You can create custom select and custom file inputs in an input group. The following example demonstrates this β
<html lang = "en">
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin = "anonymous">
<title>Bootstrap 4 Example</title>
</head>
<body>
<div class = "container">
<h2>Custom Select</h2>
<div class = "input-group mb-3">
<div class = "input-group-prepend">
<label class = "input-group-text" for = "inputGroupSelect01">Select Options</label>
</div>
<select class = "custom-select" id = "inputGroupSelect01">
<option selected>Select</option>
<option value = "1">Option #1</option>
<option value = "2">Option #2</option>
<option value = "3">Option #3</option>
</select>
</div>
<h2>Custom File Input</h2>
<div class = "input-group mb-3">
<div class = "input-group-prepend">
<span class = "input-group-text" id = "inputGroupFileAddon01">Attach Files</span>
</div>
<div class = "custom-file">
<input type = "file" class = "custom-file-input"
id = "inputGroupFile01" aria-describedby = "inputGroupFileAddon01">
<label class = "custom-file-label" for = "inputGroupFile01">Choose Files</label>
</div>
</div>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin = "anonymous">
</script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin = "anonymous">
</script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result β
26 Lectures
2 hours
Anadi Sharma
54 Lectures
4.5 hours
Frahaan Hussain
161 Lectures
14.5 hours
Eduonix Learning Solutions
20 Lectures
4 hours
Azaz Patel
15 Lectures
1.5 hours
Muhammad Ismail
62 Lectures
8 hours
Yossef Ayman Zedan
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1911,
"s": 1816,
"text": "Using input groups you can easily prepend and append text or buttons to the text-based inputs."
},
{
"code": null,
"e": 2185,
"s": 1911,
"text": "You can create an input group by adding .input-group class within <div> element. Add the text in front of the input by using .input-group-prepend and use .input-group-append class to add the text behind the input. Style the specified text by adding .input-group-text class."
},
{
"code": null,
"e": 2240,
"s": 2185,
"text": "The following example demonstrates basic input group β"
},
{
"code": null,
"e": 4934,
"s": 2240,
"text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n \n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Input Group</h2>\n <div class = \"input-group mb-3\">\n <div class = \"input-group-prepend\">\n <span class = \"input-group-text\" id = \"basic-addon1\">Username@</span>\n </div>\n <input type = \"text\" class = \"form-control\" placeholder = \"Username\" \n aria-label = \"Username\" aria-describedby = \"basic-addon1\">\n </div>\n \n <div class = \"input-group mb-3\">\n <input type = \"text\" class = \"form-control\" \n placeholder = \"Recipient's username\" aria-label = \"Recipient's username\" \n aria-describedby = \"basic-addon2\">\n <div class = \"input-group-append\">\n <span class = \"input-group-text\" id = \"basic-addon2\">@tutorialspoint.com</span>\n </div>\n </div>\n \n <div class = \"input-group mb-3\">\n <div class = \"input-group-prepend\">\n <span class = \"input-group-text\">Price in $</span>\n </div>\n <input type = \"text\" class = \"form-control\" \n aria-label = \"Amount (to the nearest dollar)\">\n \n <div class = \"input-group-append\">\n <span class = \"input-group-text\">.00</span>\n </div>\n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 4973,
"s": 4934,
"text": "It will produce the following result β"
},
{
"code": null,
"e": 5125,
"s": 4973,
"text": "You can create small input groups by using .input-group-sm class and large inputs groups by using .input-group-lg class as shown in the example below β"
},
{
"code": null,
"e": 7833,
"s": 5125,
"text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n \n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Input Group Sizing</h2>\n <div class = \"input-group input-group-lg\">\n <div class = \"input-group-prepend\">\n <span class = \"input-group-text\" id = \"inputGroup-sizing-lg\">@</span>\n </div>\n <input type = \"text\" class = \"form-control\" aria-label = \"Sizing example input\" \n aria-describedby = \"inputGroup-sizing-lg\" placeholder = \"Large Input Group\">\n </div>\n <br>\n \n <div class = \"input-group mb-3\">\n <div class = \"input-group-prepend\">\n <span class = \"input-group-text\" id = \"inputGroup-sizing-default\">@</span>\n </div>\n <input type = \"text\" class = \"form-control\" aria-label = \"Sizing example input\" \n aria-describedby = \"inputGroup-sizing-default\" placeholder = \"Default Input Group\">\n </div>\n \n <div class = \"input-group input-group-sm mb-3\">\n <div class = \"input-group-prepend\">\n <span class = \"input-group-text\" id = \"inputGroup-sizing-sm\">@</span>\n </div>\n <input type = \"text\" class = \"form-control\" aria-label = \"Sizing example input\" \n aria-describedby = \"inputGroup-sizing-sm\" placeholder = \"Small Input Group\">\n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 7872,
"s": 7833,
"text": "It will produce the following result β"
},
{
"code": null,
"e": 7983,
"s": 7872,
"text": "You can use checkboxes and radio buttons instead of text within an input group as shown in the below example β"
},
{
"code": null,
"e": 10325,
"s": 7983,
"text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n \n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Input Group with Checkbox and Radio Button</h2>\n <div class = \"input-group mb-3\">\n <div class = \"input-group-prepend\">\n <div class = \"input-group-text\">\n <input type = \"checkbox\" aria-label = \"Checkbox for following text input\">\n </div>\n </div>\n <input type = \"text\" class = \"form-control\" \n aria-label = \"Text input with checkbox\" placeholder = \"Checkbox\">\n </div>\n \n <div class = \"input-group\">\n <div class = \"input-group-prepend\">\n <div class = \"input-group-text\">\n <input type = \"radio\" aria-label = \"Radio button for following text input\">\n </div>\n </div>\n <input type = \"text\" class = \"form-control\" \n aria-label = \"Text input with radio button\" placeholder = \"Radio button\">\n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 10364,
"s": 10325,
"text": "It will produce the following result β"
},
{
"code": null,
"e": 10442,
"s": 10364,
"text": "You can add multiple inputs to an input group as shown in the example below β"
},
{
"code": null,
"e": 12257,
"s": 10442,
"text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n \n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Multiple Inputs</h2>\n <div class = \"input-group\">\n <div class = \"input-group-prepend\">\n <span class = \"input-group-text\">User Name and Password</span>\n </div>\n <input type = \"email\" aria-label = \"User Name\" class = \"form-control\">\n <input type = \"password\" aria-label = \"Password\" class = \"form-control\">\n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 12296,
"s": 12257,
"text": "It will produce the following result β"
},
{
"code": null,
"e": 12446,
"s": 12296,
"text": "You can add button in an input group by adding .btn class within the .input-group class and also you can add dropdowns within the .input-group class."
},
{
"code": null,
"e": 12544,
"s": 12446,
"text": "The following example demonstrates adding of input Group buttons and along with dropdown button β"
},
{
"code": null,
"e": 15454,
"s": 12544,
"text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n \n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Input Group Button</h2>\n <div class = \"input-group mb-3\">\n <div class = \"input-group-prepend\">\n <button class = \"btn btn-outline-info\" type = \"button\" \n id = \"button-addon1\">Button</button>\n </div>\n <input type = \"text\" class = \"form-control\" \n placeholder = \"Button in Input Group\" \n aria-label = \"Example text with button addon\" aria-describedby = \"button-addon1\">\n </div>\n \n <h2>Input Group with Dropdown Button</h2>\n <div class = \"input-group mb-3\">\n <div class = \"input-group-prepend\">\n <button class = \"btn btn-outline-info dropdown-toggle\" \n type = \"button\" data-toggle = \"dropdown\" \n aria-haspopup = \"true\" aria-expanded = \"false\">Dropdown</button>\n <div class = \"dropdown-menu\">\n <a class = \"dropdown-item\" href = \"#\">Option #1</a>\n <a class = \"dropdown-item\" href = \"#\">Option #2</a>\n <a class = \"dropdown-item\" href = \"#\">Option #3</a>\n <div role = \"separator\" class = \"dropdown-divider\"></div>\n <a class = \"dropdown-item\" href = \"#\">Option #4</a>\n </div>\n </div>\n <input type = \"text\" class = \"form-control\" \n aria-label = \"Text input with dropdown button\" \n placeholder = \"Dropdown in Input Group\">\n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 15493,
"s": 15454,
"text": "It will produce the following result β"
},
{
"code": null,
"e": 15606,
"s": 15493,
"text": "You can create custom select and custom file inputs in an input group. The following example demonstrates this β"
},
{
"code": null,
"e": 18180,
"s": 15606,
"text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n \n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Custom Select</h2>\n <div class = \"input-group mb-3\">\n <div class = \"input-group-prepend\">\n <label class = \"input-group-text\" for = \"inputGroupSelect01\">Select Options</label>\n </div>\n <select class = \"custom-select\" id = \"inputGroupSelect01\">\n <option selected>Select</option>\n <option value = \"1\">Option #1</option>\n <option value = \"2\">Option #2</option>\n <option value = \"3\">Option #3</option>\n </select>\n </div>\n \n <h2>Custom File Input</h2>\n <div class = \"input-group mb-3\">\n <div class = \"input-group-prepend\">\n <span class = \"input-group-text\" id = \"inputGroupFileAddon01\">Attach Files</span>\n </div>\n \n <div class = \"custom-file\">\n <input type = \"file\" class = \"custom-file-input\" \n id = \"inputGroupFile01\" aria-describedby = \"inputGroupFileAddon01\">\n <label class = \"custom-file-label\" for = \"inputGroupFile01\">Choose Files</label>\n </div>\n \n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 18219,
"s": 18180,
"text": "It will produce the following result β"
},
{
"code": null,
"e": 18252,
"s": 18219,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 18266,
"s": 18252,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 18301,
"s": 18266,
"text": "\n 54 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 18318,
"s": 18301,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 18355,
"s": 18318,
"text": "\n 161 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 18383,
"s": 18355,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 18416,
"s": 18383,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 18428,
"s": 18416,
"text": " Azaz Patel"
},
{
"code": null,
"e": 18463,
"s": 18428,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 18480,
"s": 18463,
"text": " Muhammad Ismail"
},
{
"code": null,
"e": 18513,
"s": 18480,
"text": "\n 62 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 18533,
"s": 18513,
"text": " Yossef Ayman Zedan"
},
{
"code": null,
"e": 18540,
"s": 18533,
"text": " Print"
},
{
"code": null,
"e": 18551,
"s": 18540,
"text": " Add Notes"
}
] |
Python VLC MediaPlayer β Taking Screenshot - GeeksforGeeks
|
18 Aug, 2020
In this article we will see how we can take screen shot of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediPlyer object is the basic object in vlc module for playing the video. A screenshot, also known as ss, sc, screen capture, or screen grab, is a digital image that shows the contents of a computer display. A common screenshot is created by the operating system or software running on the device. A screenshot or screen capture may also be created by taking a photo of the screen.
In order to do this we will use video_take_snapshot method with the MediaPlayer object
Syntax : media_player.video_take_snapshot(n, location, width, height)
Argument : It takes video output number, folder location and width and height of screenshot as argument
Return : It returns 0 on success, -1 if the video was not found
Below is the implementation
# importing vlc moduleimport vlc # importing time moduleimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer() # media objectmedia = vlc.Media("death_note.mkv") # setting media to the media playermedia_player.set_media(media) # setting video scalemedia_player.video_set_scale(0.6) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) # taking screen shotmedia_player.video_take_snapshot(0, "F://test", 400, 300)
Output :
Below is the folder location
Another exampleBelow is the implementation
# importing vlc moduleimport vlc # importing time moduleimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer() # media objectmedia = vlc.Media("1mp4.mkv") # setting media to the media playermedia_player.set_media(media) # setting video scalemedia_player.video_set_scale(0.6) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) # taking screen shotmedia_player.video_take_snapshot(0, "F://test", 400, 300)
Output :
Below is the folder location
Python vlc-library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25995,
"s": 25967,
"text": "\n18 Aug, 2020"
},
{
"code": null,
"e": 26636,
"s": 25995,
"text": "In this article we will see how we can take screen shot of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediPlyer object is the basic object in vlc module for playing the video. A screenshot, also known as ss, sc, screen capture, or screen grab, is a digital image that shows the contents of a computer display. A common screenshot is created by the operating system or software running on the device. A screenshot or screen capture may also be created by taking a photo of the screen."
},
{
"code": null,
"e": 26723,
"s": 26636,
"text": "In order to do this we will use video_take_snapshot method with the MediaPlayer object"
},
{
"code": null,
"e": 26793,
"s": 26723,
"text": "Syntax : media_player.video_take_snapshot(n, location, width, height)"
},
{
"code": null,
"e": 26897,
"s": 26793,
"text": "Argument : It takes video output number, folder location and width and height of screenshot as argument"
},
{
"code": null,
"e": 26961,
"s": 26897,
"text": "Return : It returns 0 on success, -1 if the video was not found"
},
{
"code": null,
"e": 26989,
"s": 26961,
"text": "Below is the implementation"
},
{
"code": "# importing vlc moduleimport vlc # importing time moduleimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer() # media objectmedia = vlc.Media(\"death_note.mkv\") # setting media to the media playermedia_player.set_media(media) # setting video scalemedia_player.video_set_scale(0.6) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) # taking screen shotmedia_player.video_take_snapshot(0, \"F://test\", 400, 300)",
"e": 27518,
"s": 26989,
"text": null
},
{
"code": null,
"e": 27527,
"s": 27518,
"text": "Output :"
},
{
"code": null,
"e": 27556,
"s": 27527,
"text": "Below is the folder location"
},
{
"code": null,
"e": 27599,
"s": 27556,
"text": "Another exampleBelow is the implementation"
},
{
"code": "# importing vlc moduleimport vlc # importing time moduleimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer() # media objectmedia = vlc.Media(\"1mp4.mkv\") # setting media to the media playermedia_player.set_media(media) # setting video scalemedia_player.video_set_scale(0.6) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) # taking screen shotmedia_player.video_take_snapshot(0, \"F://test\", 400, 300)",
"e": 28124,
"s": 27599,
"text": null
},
{
"code": null,
"e": 28133,
"s": 28124,
"text": "Output :"
},
{
"code": null,
"e": 28162,
"s": 28133,
"text": "Below is the folder location"
},
{
"code": null,
"e": 28181,
"s": 28162,
"text": "Python vlc-library"
},
{
"code": null,
"e": 28188,
"s": 28181,
"text": "Python"
},
{
"code": null,
"e": 28286,
"s": 28188,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28304,
"s": 28286,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28339,
"s": 28304,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28371,
"s": 28339,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28393,
"s": 28371,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28435,
"s": 28393,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28465,
"s": 28435,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28491,
"s": 28465,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28520,
"s": 28491,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28564,
"s": 28520,
"text": "Reading and Writing to text files in Python"
}
] |
OpenCV - Rotation
|
You can perform rotation operation on an image using the warpAffine() method of the imgproc class. Following is the syntax of this method β
Imgproc.warpAffine(src, dst, rotationMatrix, size);
This method accepts the following parameters β
src β A Mat object representing the source (input image) for this operation.
src β A Mat object representing the source (input image) for this operation.
dst β A Mat object representing the destination (output image) for this operation.
dst β A Mat object representing the destination (output image) for this operation.
rotationMatrix β A Mat object representing the rotation matrix.
rotationMatrix β A Mat object representing the rotation matrix.
size β A variable of the type integer representing the size of the output image.
size β A variable of the type integer representing the size of the output image.
The following program demonstrates how to rotate an image.
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class Rotation {
public static void main(String args[]) {
// Loading the OpenCV core library
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
// Reading the Image from the file and storing it in to a Matrix object
String file ="E:/OpenCV/chap24/transform_input.jpg";
Mat src = Imgcodecs.imread(file);
// Creating an empty matrix to store the result
Mat dst = new Mat();
// Creating a Point object
Point point = new Point(300, 200)
// Creating the transformation matrix M
Mat rotationMatrix = Imgproc.getRotationMatrix2D(point, 30, 1);
// Creating the object of the class Size
Size size = new Size(src.cols(), src.cols());
// Rotating the given image
Imgproc.warpAffine(src, dst, rotationMatrix, size);
// Writing the image
Imgcodecs.imwrite("E:/OpenCV/chap24/rotate_output.jpg", dst);
System.out.println("Image Processed");
}
}
Assume that following is the input image transform_input.jpg specified in the above program.
On executing the program, you will get the following output β
Image Processed
If you open the specified path, you can observe the output image as follows β
70 Lectures
9 hours
Abhilash Nelson
41 Lectures
4 hours
Abhilash Nelson
20 Lectures
2 hours
Spotle Learn
12 Lectures
46 mins
Srikanth Guskra
19 Lectures
2 hours
Haithem Gasmi
67 Lectures
6.5 hours
Gianluca Mottola
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3144,
"s": 3004,
"text": "You can perform rotation operation on an image using the warpAffine() method of the imgproc class. Following is the syntax of this method β"
},
{
"code": null,
"e": 3197,
"s": 3144,
"text": "Imgproc.warpAffine(src, dst, rotationMatrix, size);\n"
},
{
"code": null,
"e": 3244,
"s": 3197,
"text": "This method accepts the following parameters β"
},
{
"code": null,
"e": 3321,
"s": 3244,
"text": "src β A Mat object representing the source (input image) for this operation."
},
{
"code": null,
"e": 3398,
"s": 3321,
"text": "src β A Mat object representing the source (input image) for this operation."
},
{
"code": null,
"e": 3481,
"s": 3398,
"text": "dst β A Mat object representing the destination (output image) for this operation."
},
{
"code": null,
"e": 3564,
"s": 3481,
"text": "dst β A Mat object representing the destination (output image) for this operation."
},
{
"code": null,
"e": 3629,
"s": 3564,
"text": "rotationMatrix β A Mat object representing the rotation matrix."
},
{
"code": null,
"e": 3694,
"s": 3629,
"text": "rotationMatrix β A Mat object representing the rotation matrix."
},
{
"code": null,
"e": 3776,
"s": 3694,
"text": "size β A variable of the type integer representing the size of the output image."
},
{
"code": null,
"e": 3858,
"s": 3776,
"text": "size β A variable of the type integer representing the size of the output image."
},
{
"code": null,
"e": 3917,
"s": 3858,
"text": "The following program demonstrates how to rotate an image."
},
{
"code": null,
"e": 5065,
"s": 3917,
"text": "import org.opencv.core.Core;\nimport org.opencv.core.Mat;\nimport org.opencv.core.Point;\nimport org.opencv.core.Size;\n\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\n\npublic class Rotation {\n public static void main(String args[]) {\n // Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n\n // Reading the Image from the file and storing it in to a Matrix object\n String file =\"E:/OpenCV/chap24/transform_input.jpg\";\n Mat src = Imgcodecs.imread(file);\n\n // Creating an empty matrix to store the result\n Mat dst = new Mat();\n\n // Creating a Point object\n Point point = new Point(300, 200)\n\n // Creating the transformation matrix M\n Mat rotationMatrix = Imgproc.getRotationMatrix2D(point, 30, 1);\n\n // Creating the object of the class Size\n Size size = new Size(src.cols(), src.cols());\n\n // Rotating the given image\n Imgproc.warpAffine(src, dst, rotationMatrix, size);\n\n // Writing the image\n Imgcodecs.imwrite(\"E:/OpenCV/chap24/rotate_output.jpg\", dst);\n\n System.out.println(\"Image Processed\");\n }\n}"
},
{
"code": null,
"e": 5158,
"s": 5065,
"text": "Assume that following is the input image transform_input.jpg specified in the above program."
},
{
"code": null,
"e": 5220,
"s": 5158,
"text": "On executing the program, you will get the following output β"
},
{
"code": null,
"e": 5237,
"s": 5220,
"text": "Image Processed\n"
},
{
"code": null,
"e": 5315,
"s": 5237,
"text": "If you open the specified path, you can observe the output image as follows β"
},
{
"code": null,
"e": 5348,
"s": 5315,
"text": "\n 70 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 5365,
"s": 5348,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5398,
"s": 5365,
"text": "\n 41 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5415,
"s": 5398,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5448,
"s": 5415,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5462,
"s": 5448,
"text": " Spotle Learn"
},
{
"code": null,
"e": 5494,
"s": 5462,
"text": "\n 12 Lectures \n 46 mins\n"
},
{
"code": null,
"e": 5511,
"s": 5494,
"text": " Srikanth Guskra"
},
{
"code": null,
"e": 5544,
"s": 5511,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5559,
"s": 5544,
"text": " Haithem Gasmi"
},
{
"code": null,
"e": 5594,
"s": 5559,
"text": "\n 67 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 5612,
"s": 5594,
"text": " Gianluca Mottola"
},
{
"code": null,
"e": 5619,
"s": 5612,
"text": " Print"
},
{
"code": null,
"e": 5630,
"s": 5619,
"text": " Add Notes"
}
] |
Flipping an Image in Python
|
Suppose we have a binary matrix A, this is the representation of an image, we want to flip the image horizontally, after that invert it, and finally return the resulting image. To flip the image horizontally each row of the image will be reversed. And to invert the image each 0 will be replaced by 1, and each 1 will be replaced by 0.
So, if the input is like
then the output will be
To solve this, we will follow these steps β
result:= a new list
for each row i in A, doReverse:= reverse row ifor j in range 0 to size of Reverse, doif Reverse[j] is same as 1, thenReverse[j]:= 0otherwise,Reverse[j]:= 1insert Reverse at the end of result
Reverse:= reverse row i
for j in range 0 to size of Reverse, doif Reverse[j] is same as 1, thenReverse[j]:= 0otherwise,Reverse[j]:= 1
if Reverse[j] is same as 1, thenReverse[j]:= 0
Reverse[j]:= 0
otherwise,Reverse[j]:= 1
Reverse[j]:= 1
insert Reverse at the end of result
return result
Let us see the following implementation to get better understanding β
Live Demo
class Solution:
def flipAndInvertImage(self, A):
result=[]
for i in A:
Reverse=i[::-1]
for j in range(len(Reverse)):
if Reverse[j]==1:
Reverse[j]=0
else:
Reverse[j]=1
result.append(Reverse)
return result
ob = Solution()
print(ob.flipAndInvertImage([[1,1,0],[1,0,1],[0,0,0]]))
[[1,1,0],[1,0,1],[0,0,0]]
[[1, 0, 0], [0, 1, 0], [1, 1, 1]]
|
[
{
"code": null,
"e": 1398,
"s": 1062,
"text": "Suppose we have a binary matrix A, this is the representation of an image, we want to flip the image horizontally, after that invert it, and finally return the resulting image. To flip the image horizontally each row of the image will be reversed. And to invert the image each 0 will be replaced by 1, and each 1 will be replaced by 0."
},
{
"code": null,
"e": 1423,
"s": 1398,
"text": "So, if the input is like"
},
{
"code": null,
"e": 1447,
"s": 1423,
"text": "then the output will be"
},
{
"code": null,
"e": 1491,
"s": 1447,
"text": "To solve this, we will follow these steps β"
},
{
"code": null,
"e": 1511,
"s": 1491,
"text": "result:= a new list"
},
{
"code": null,
"e": 1702,
"s": 1511,
"text": "for each row i in A, doReverse:= reverse row ifor j in range 0 to size of Reverse, doif Reverse[j] is same as 1, thenReverse[j]:= 0otherwise,Reverse[j]:= 1insert Reverse at the end of result"
},
{
"code": null,
"e": 1726,
"s": 1702,
"text": "Reverse:= reverse row i"
},
{
"code": null,
"e": 1836,
"s": 1726,
"text": "for j in range 0 to size of Reverse, doif Reverse[j] is same as 1, thenReverse[j]:= 0otherwise,Reverse[j]:= 1"
},
{
"code": null,
"e": 1883,
"s": 1836,
"text": "if Reverse[j] is same as 1, thenReverse[j]:= 0"
},
{
"code": null,
"e": 1898,
"s": 1883,
"text": "Reverse[j]:= 0"
},
{
"code": null,
"e": 1923,
"s": 1898,
"text": "otherwise,Reverse[j]:= 1"
},
{
"code": null,
"e": 1938,
"s": 1923,
"text": "Reverse[j]:= 1"
},
{
"code": null,
"e": 1974,
"s": 1938,
"text": "insert Reverse at the end of result"
},
{
"code": null,
"e": 1988,
"s": 1974,
"text": "return result"
},
{
"code": null,
"e": 2058,
"s": 1988,
"text": "Let us see the following implementation to get better understanding β"
},
{
"code": null,
"e": 2069,
"s": 2058,
"text": " Live Demo"
},
{
"code": null,
"e": 2453,
"s": 2069,
"text": "class Solution:\n def flipAndInvertImage(self, A):\n result=[]\n for i in A:\n Reverse=i[::-1]\n for j in range(len(Reverse)):\n if Reverse[j]==1:\n Reverse[j]=0\n else:\n Reverse[j]=1\n result.append(Reverse)\n return result\nob = Solution()\nprint(ob.flipAndInvertImage([[1,1,0],[1,0,1],[0,0,0]]))"
},
{
"code": null,
"e": 2479,
"s": 2453,
"text": "[[1,1,0],[1,0,1],[0,0,0]]"
},
{
"code": null,
"e": 2513,
"s": 2479,
"text": "[[1, 0, 0], [0, 1, 0], [1, 1, 1]]"
}
] |
new vs operator new in C++ - GeeksforGeeks
|
23 Jun, 2017
When you create a new object, memory is allocated using operator new function and then the constructor is invoked to initialize the memory. Here, The new operator does both the allocation and the initialization, where as the operator new only does the allocation.Let us see how these both work individually.
new keyword
The new operator is an operator which denotes a request for memory allocation on the Heap. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable. When you create an object of class using new keyword(normal new).
The memory for the object is allocated using operator new from heap.
The constructor of the class is invoked to properly initialize this memory.
// CPP program to illustrate // use of new keyword#include<iostream>using namespace std;class car{ string name; int num; public: car(string a, int n) { cout << "Constructor called" << endl; this ->name = a; this ->num = n; } void enter() { cin>>name; cin>>num; } void display() { cout << "Name: " << name << endl; cout << "Num: " << num << endl; }}; int main(){ // Using new keyword car *p = new car("Honda", 2017); p->display();}
Output:
Constructor called
Name: Honda
Num: 2017
Operator new
Operator new is a function that allocates raw memory and conceptually a bit similar to malloc().
It is the mechanism of overriding the default heap allocation logic.
It doesnβt initializes the memory i.e constructor is not called. However, after our overloaded new returns, the compiler then automatically calls the constructor also as applicable.
Itβs also possible to overload operator new either globally, or for a specific class
// CPP program to illustrate // use of operator new#include<iostream>#include<stdlib.h> using namespace std; class car{ string name; int num; public: car(string a, int n) { cout << "Constructor called" << endl; this->name = a; this->num = n; } void display() { cout << "Name: " << name << endl; cout << "Num: " << num << endl; } void *operator new(size_t size) { cout << "new operator overloaded" << endl; void *p = malloc(size); return p; } void operator delete(void *ptr) { cout << "delete operator overloaded" << endl; free(ptr); }}; int main(){ car *p = new car("HYUNDAI", 2012); p->display(); delete p;}
Output:
new operator overloaded
Constructor called
Name:HYUNDAI
Num:2012
delete operator overloaded
New operator vs operator new
Operator vs function: new is an operator as well as a keyword whereas operator new is only a function.New calls βOperator newβ: βnew operatorβ calls βoperator new()β , like the way + operator calls operator +()βOperator newβ can be Overloaded: Operator new can be overloaded just like functions allowing us to do customized tasks.Memory allocation: βnew expressionβ call βoperator newβ to allocate raw memory, then call constructor.
Operator vs function: new is an operator as well as a keyword whereas operator new is only a function.
New calls βOperator newβ: βnew operatorβ calls βoperator new()β , like the way + operator calls operator +()
βOperator newβ can be Overloaded: Operator new can be overloaded just like functions allowing us to do customized tasks.
Memory allocation: βnew expressionβ call βoperator newβ to allocate raw memory, then call constructor.
This article is contributed by Yash Singla. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Dynamic Memory Allocation
C++
Difference Between
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Differences between IPv4 and IPv6
|
[
{
"code": null,
"e": 25918,
"s": 25890,
"text": "\n23 Jun, 2017"
},
{
"code": null,
"e": 26226,
"s": 25918,
"text": "When you create a new object, memory is allocated using operator new function and then the constructor is invoked to initialize the memory. Here, The new operator does both the allocation and the initialization, where as the operator new only does the allocation.Let us see how these both work individually."
},
{
"code": null,
"e": 26238,
"s": 26226,
"text": "new keyword"
},
{
"code": null,
"e": 26561,
"s": 26238,
"text": "The new operator is an operator which denotes a request for memory allocation on the Heap. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable. When you create an object of class using new keyword(normal new)."
},
{
"code": null,
"e": 26630,
"s": 26561,
"text": "The memory for the object is allocated using operator new from heap."
},
{
"code": null,
"e": 26706,
"s": 26630,
"text": "The constructor of the class is invoked to properly initialize this memory."
},
{
"code": "// CPP program to illustrate // use of new keyword#include<iostream>using namespace std;class car{ string name; int num; public: car(string a, int n) { cout << \"Constructor called\" << endl; this ->name = a; this ->num = n; } void enter() { cin>>name; cin>>num; } void display() { cout << \"Name: \" << name << endl; cout << \"Num: \" << num << endl; }}; int main(){ // Using new keyword car *p = new car(\"Honda\", 2017); p->display();}",
"e": 27302,
"s": 26706,
"text": null
},
{
"code": null,
"e": 27310,
"s": 27302,
"text": "Output:"
},
{
"code": null,
"e": 27352,
"s": 27310,
"text": "Constructor called\nName: Honda\nNum: 2017\n"
},
{
"code": null,
"e": 27365,
"s": 27352,
"text": "Operator new"
},
{
"code": null,
"e": 27462,
"s": 27365,
"text": "Operator new is a function that allocates raw memory and conceptually a bit similar to malloc()."
},
{
"code": null,
"e": 27531,
"s": 27462,
"text": "It is the mechanism of overriding the default heap allocation logic."
},
{
"code": null,
"e": 27713,
"s": 27531,
"text": "It doesnβt initializes the memory i.e constructor is not called. However, after our overloaded new returns, the compiler then automatically calls the constructor also as applicable."
},
{
"code": null,
"e": 27798,
"s": 27713,
"text": "Itβs also possible to overload operator new either globally, or for a specific class"
},
{
"code": "// CPP program to illustrate // use of operator new#include<iostream>#include<stdlib.h> using namespace std; class car{ string name; int num; public: car(string a, int n) { cout << \"Constructor called\" << endl; this->name = a; this->num = n; } void display() { cout << \"Name: \" << name << endl; cout << \"Num: \" << num << endl; } void *operator new(size_t size) { cout << \"new operator overloaded\" << endl; void *p = malloc(size); return p; } void operator delete(void *ptr) { cout << \"delete operator overloaded\" << endl; free(ptr); }}; int main(){ car *p = new car(\"HYUNDAI\", 2012); p->display(); delete p;}",
"e": 28633,
"s": 27798,
"text": null
},
{
"code": null,
"e": 28641,
"s": 28633,
"text": "Output:"
},
{
"code": null,
"e": 28734,
"s": 28641,
"text": "new operator overloaded\nConstructor called\nName:HYUNDAI\nNum:2012\ndelete operator overloaded\n"
},
{
"code": null,
"e": 28763,
"s": 28734,
"text": "New operator vs operator new"
},
{
"code": null,
"e": 29196,
"s": 28763,
"text": "Operator vs function: new is an operator as well as a keyword whereas operator new is only a function.New calls βOperator newβ: βnew operatorβ calls βoperator new()β , like the way + operator calls operator +()βOperator newβ can be Overloaded: Operator new can be overloaded just like functions allowing us to do customized tasks.Memory allocation: βnew expressionβ call βoperator newβ to allocate raw memory, then call constructor."
},
{
"code": null,
"e": 29299,
"s": 29196,
"text": "Operator vs function: new is an operator as well as a keyword whereas operator new is only a function."
},
{
"code": null,
"e": 29408,
"s": 29299,
"text": "New calls βOperator newβ: βnew operatorβ calls βoperator new()β , like the way + operator calls operator +()"
},
{
"code": null,
"e": 29529,
"s": 29408,
"text": "βOperator newβ can be Overloaded: Operator new can be overloaded just like functions allowing us to do customized tasks."
},
{
"code": null,
"e": 29632,
"s": 29529,
"text": "Memory allocation: βnew expressionβ call βoperator newβ to allocate raw memory, then call constructor."
},
{
"code": null,
"e": 29931,
"s": 29632,
"text": "This article is contributed by Yash Singla. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 30056,
"s": 29931,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 30082,
"s": 30056,
"text": "Dynamic Memory Allocation"
},
{
"code": null,
"e": 30086,
"s": 30082,
"text": "C++"
},
{
"code": null,
"e": 30105,
"s": 30086,
"text": "Difference Between"
},
{
"code": null,
"e": 30109,
"s": 30105,
"text": "CPP"
},
{
"code": null,
"e": 30207,
"s": 30109,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30235,
"s": 30207,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 30255,
"s": 30235,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 30288,
"s": 30255,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 30312,
"s": 30288,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 30337,
"s": 30312,
"text": "std::string class in C++"
},
{
"code": null,
"e": 30368,
"s": 30337,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 30408,
"s": 30368,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 30440,
"s": 30408,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 30501,
"s": 30440,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
Validate Date in MySQL using a custom function
|
Let us create a custom function to validate date in MySQL β
mysql> set global log_bin_trust_function_creators=1;
Query OK, 0 rows affected (0.03 sec)
mysql> delimiter //
mysql> create function isValidDate(actualDate varchar(255)) returns int
-> begin
-> declare flag int;
-> if (select length(date(actualDate)) IS NOT NULL ) then
-> set flag = 1;
-> else
-> set flag = 0;
-> end if;
-> return flag;
-> end
-> //
Query OK, 0 rows affected (0.11 sec)
mysql> delimiter ;
Case 1 β
When parameter is null value i.e. the date to be checked isnβt an actual date. Call the function using SELECT statement β
mysql> select isValidDate(NULL);
This will produce the following output i.e. not a date β
+-------------------+
| isValidDate(NULL) |
+-------------------+
| 0 |
+-------------------+
1 row in set (0.05 sec)
Case 2 β
When parameter is an actual date value. Call the function using SELECT statement β
mysql> select isValidDate('2019-10-21');
This will produce the following output i.e. 1, an actual date β
+---------------------------+
| isValidDate('2019-10-21') |
+---------------------------+
| 1 |
+---------------------------+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1122,
"s": 1062,
"text": "Let us create a custom function to validate date in MySQL β"
},
{
"code": null,
"e": 1560,
"s": 1122,
"text": "mysql> set global log_bin_trust_function_creators=1;\nQuery OK, 0 rows affected (0.03 sec)\nmysql> delimiter //\nmysql> create function isValidDate(actualDate varchar(255)) returns int\n -> begin\n -> declare flag int;\n -> if (select length(date(actualDate)) IS NOT NULL ) then\n -> set flag = 1;\n -> else\n -> set flag = 0;\n -> end if;\n -> return flag;\n -> end\n -> //\nQuery OK, 0 rows affected (0.11 sec)\nmysql> delimiter ;"
},
{
"code": null,
"e": 1569,
"s": 1560,
"text": "Case 1 β"
},
{
"code": null,
"e": 1691,
"s": 1569,
"text": "When parameter is null value i.e. the date to be checked isnβt an actual date. Call the function using SELECT statement β"
},
{
"code": null,
"e": 1724,
"s": 1691,
"text": "mysql> select isValidDate(NULL);"
},
{
"code": null,
"e": 1781,
"s": 1724,
"text": "This will produce the following output i.e. not a date β"
},
{
"code": null,
"e": 1915,
"s": 1781,
"text": "+-------------------+\n| isValidDate(NULL) |\n+-------------------+\n| 0 |\n+-------------------+\n1 row in set (0.05 sec)"
},
{
"code": null,
"e": 1924,
"s": 1915,
"text": "Case 2 β"
},
{
"code": null,
"e": 2007,
"s": 1924,
"text": "When parameter is an actual date value. Call the function using SELECT statement β"
},
{
"code": null,
"e": 2048,
"s": 2007,
"text": "mysql> select isValidDate('2019-10-21');"
},
{
"code": null,
"e": 2112,
"s": 2048,
"text": "This will produce the following output i.e. 1, an actual date β"
},
{
"code": null,
"e": 2286,
"s": 2112,
"text": "+---------------------------+\n| isValidDate('2019-10-21') |\n+---------------------------+\n| 1 |\n+---------------------------+\n1 row in set (0.00 sec)"
}
] |
Field setBoolean() method in Java with Examples - GeeksforGeeks
|
26 Aug, 2019
The setBoolean() method of java.lang.reflect.Field used to set the value of a field as a boolean on the specified object. When you need to set the value of a field of an object as boolean then you can use this method to set value over an Object.
Syntax:
public void setBoolean(Object obj, boolean z)
throws IllegalArgumentException,
IllegalAccessException
Parameters: This method accepts two parameters:
obj: which is the object whose field should be modified and
z: which is the new value for the field of obj being modified.
Return value: This method returns nothing.
Exception: This method throws following Exception:
IllegalAccessException: if this Field object is enforcing Java language access control and the underlying field is either inaccessible or final.
IllegalArgumentException: if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof), or if an unwrapping conversion fails.
NullPointerException: if the specified object is null and the field is an instance field.
ExceptionInInitializerError: if the initialization provoked by this method fails.
Below programs illustrate setBoolean() method:Program 1:
// Java program to illustrate setBoolean() method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws Exception { // create user object User user = new User(); // print value of isActive System.out.println("Value before " + "applying setBoolean is " + user.isActive); // Get the marks field object Field field = User.class .getField("isActive"); // Apply setBoolean Method field.setBoolean(field, false); // print result System.out.println("Value after " + "applying setBoolean is " + user.isActive); }} // sample User classclass User { // static boolean values public static boolean isActive = true;}
Value before applying setBoolean is true
Value after applying setBoolean is false
Program 2:
// Java program to illustrate setBoolean() method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws Exception { // create user object Employee emp = new Employee(); // print value of isManager System.out.println("Value of isManager before " + "applying setBoolean is " + emp.isManager); // Get the marks field object Field field = Employee.class .getField("isManager"); // Apply setBoolean Method field.setBoolean(emp, false); // print value of isActive System.out.println("Value of isPresent before " + "applying setBoolean is " + emp.isManager); // print value of isManager System.out.println("Value of isManager before " + "applying setBoolean is " + emp.isPresent); // Get the marks field object field = Employee.class .getField("isPresent"); // Apply setBoolean Method field.setBoolean(emp, true); // print value of isActive System.out.println("Value of isPresent before " + "applying setBoolean is " + emp.isPresent); }} // sample User classclass Employee { // static boolean values public static boolean isPresent = false; public static boolean isManager = true;}
Value of isManager before applying setBoolean is true
Value of isPresent before applying setBoolean is false
Value of isManager before applying setBoolean is false
Value of isPresent before applying setBoolean is true
References: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#setBoolean-java.lang.Object-boolean-
Java-Field
Java-Functions
java-lang-reflect-package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Multithreading in Java
Collections in Java
|
[
{
"code": null,
"e": 25817,
"s": 25789,
"text": "\n26 Aug, 2019"
},
{
"code": null,
"e": 26063,
"s": 25817,
"text": "The setBoolean() method of java.lang.reflect.Field used to set the value of a field as a boolean on the specified object. When you need to set the value of a field of an object as boolean then you can use this method to set value over an Object."
},
{
"code": null,
"e": 26071,
"s": 26063,
"text": "Syntax:"
},
{
"code": null,
"e": 26205,
"s": 26071,
"text": "public void setBoolean(Object obj, boolean z)\n throws IllegalArgumentException,\n IllegalAccessException\n"
},
{
"code": null,
"e": 26253,
"s": 26205,
"text": "Parameters: This method accepts two parameters:"
},
{
"code": null,
"e": 26313,
"s": 26253,
"text": "obj: which is the object whose field should be modified and"
},
{
"code": null,
"e": 26376,
"s": 26313,
"text": "z: which is the new value for the field of obj being modified."
},
{
"code": null,
"e": 26419,
"s": 26376,
"text": "Return value: This method returns nothing."
},
{
"code": null,
"e": 26470,
"s": 26419,
"text": "Exception: This method throws following Exception:"
},
{
"code": null,
"e": 26615,
"s": 26470,
"text": "IllegalAccessException: if this Field object is enforcing Java language access control and the underlying field is either inaccessible or final."
},
{
"code": null,
"e": 26819,
"s": 26615,
"text": "IllegalArgumentException: if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof), or if an unwrapping conversion fails."
},
{
"code": null,
"e": 26909,
"s": 26819,
"text": "NullPointerException: if the specified object is null and the field is an instance field."
},
{
"code": null,
"e": 26991,
"s": 26909,
"text": "ExceptionInInitializerError: if the initialization provoked by this method fails."
},
{
"code": null,
"e": 27048,
"s": 26991,
"text": "Below programs illustrate setBoolean() method:Program 1:"
},
{
"code": "// Java program to illustrate setBoolean() method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws Exception { // create user object User user = new User(); // print value of isActive System.out.println(\"Value before \" + \"applying setBoolean is \" + user.isActive); // Get the marks field object Field field = User.class .getField(\"isActive\"); // Apply setBoolean Method field.setBoolean(field, false); // print result System.out.println(\"Value after \" + \"applying setBoolean is \" + user.isActive); }} // sample User classclass User { // static boolean values public static boolean isActive = true;}",
"e": 27936,
"s": 27048,
"text": null
},
{
"code": null,
"e": 28019,
"s": 27936,
"text": "Value before applying setBoolean is true\nValue after applying setBoolean is false\n"
},
{
"code": null,
"e": 28030,
"s": 28019,
"text": "Program 2:"
},
{
"code": "// Java program to illustrate setBoolean() method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws Exception { // create user object Employee emp = new Employee(); // print value of isManager System.out.println(\"Value of isManager before \" + \"applying setBoolean is \" + emp.isManager); // Get the marks field object Field field = Employee.class .getField(\"isManager\"); // Apply setBoolean Method field.setBoolean(emp, false); // print value of isActive System.out.println(\"Value of isPresent before \" + \"applying setBoolean is \" + emp.isManager); // print value of isManager System.out.println(\"Value of isManager before \" + \"applying setBoolean is \" + emp.isPresent); // Get the marks field object field = Employee.class .getField(\"isPresent\"); // Apply setBoolean Method field.setBoolean(emp, true); // print value of isActive System.out.println(\"Value of isPresent before \" + \"applying setBoolean is \" + emp.isPresent); }} // sample User classclass Employee { // static boolean values public static boolean isPresent = false; public static boolean isManager = true;}",
"e": 29579,
"s": 28030,
"text": null
},
{
"code": null,
"e": 29798,
"s": 29579,
"text": "Value of isManager before applying setBoolean is true\nValue of isPresent before applying setBoolean is false\nValue of isManager before applying setBoolean is false\nValue of isPresent before applying setBoolean is true\n"
},
{
"code": null,
"e": 29918,
"s": 29798,
"text": "References: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#setBoolean-java.lang.Object-boolean-"
},
{
"code": null,
"e": 29929,
"s": 29918,
"text": "Java-Field"
},
{
"code": null,
"e": 29944,
"s": 29929,
"text": "Java-Functions"
},
{
"code": null,
"e": 29970,
"s": 29944,
"text": "java-lang-reflect-package"
},
{
"code": null,
"e": 29975,
"s": 29970,
"text": "Java"
},
{
"code": null,
"e": 29980,
"s": 29975,
"text": "Java"
},
{
"code": null,
"e": 30078,
"s": 29980,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30093,
"s": 30078,
"text": "Stream In Java"
},
{
"code": null,
"e": 30112,
"s": 30093,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 30144,
"s": 30112,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 30162,
"s": 30144,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 30182,
"s": 30162,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 30206,
"s": 30182,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 30238,
"s": 30206,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 30250,
"s": 30238,
"text": "Set in Java"
},
{
"code": null,
"e": 30273,
"s": 30250,
"text": "Multithreading in Java"
}
] |
Subsequence with maximum odd sum - GeeksforGeeks
|
07 Oct, 2021
Given a set of integers, check whether there is a subsequence with odd sum and if yes, then finding the maximum odd sum. If no subsequence contains odd sum, return -1.
Examples :
Input : arr[] = {2, 5, -4, 3, -1};
Output : 9
The subsequence with maximum odd
sum is 2, 5, 3 and -1.
Input : arr[] = {4, -3, 3, -5}
Output : 7
The subsequence with maximum odd
sum is 4 and 3
Input : arr[] = {2, 4, 6}
Output : -1
There is no subsequence with odd sum.
A simple solution to generate all subsequences and find the maximum sum of all subsequences with odd sums. Time complexity of this solution would be exponential.
An efficient solution can work in O(n) time. The idea is based on the following facts. 1) Odd sum is not possible if all numbers are even. Otherwise, we always find an answer. 2) If odd sum is possible, we find sum of all positive integers. If sum is odd, we return it as this is the maximum overall positive sum. If sum is even, we subtract the odd number with the smallest absolute value from sum. This step can be justified by the fact that the smallest absolute odd value number becomes part of result if it is negative, and removed from the result when it is positive.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find maximum sum of odd// subsequence if it exists.#include<bits/stdc++.h>using namespace std; // Returns maximum sum odd subsequence if exists// Else returns -1int findMaxOddSubarraySum(int arr[], int n){ // Here min_odd is the minimum odd number (in // absolute terms). Initializing with max value // of int . int min_odd = INT_MAX; // To check if there is al-least one odd number. bool isOdd = false; int sum = 0; // To store sum of all positive elements for (int i=0 ; i<n ; i++) { // Adding positive number would increase // the sum. if (arr[i] > 0) sum = sum + arr[i]; // To find the minimum odd number(absolute) // in the array. if (arr[i]%2 != 0) { isOdd = true; if (min_odd> abs(arr[i])) min_odd = abs(arr[i]); } } // If there was no odd number if (isOdd == false) return -1; // Now, sum will be either odd or even. // If even, changing it to odd. As, even - odd = odd. // since m is the minimum odd number(absolute). if (sum%2 == 0) sum = sum - min_odd; return sum;} // Driver codeint main(){ int arr[] = {2, -3, 5, -1, 4}; int n = sizeof(arr)/sizeof(arr[0]); cout << findMaxOddSubarraySum(arr, n); return 0;}
// Java program to find maximum sum// of odd subsequence if it exists.import java.io.*; class GFG { // Returns maximum sum odd subsequence,// if exists Else returns -1static int findMaxOddSubarraySum(int arr[], int n){ // Here min_odd is the minimum odd number // (in absolute terms). Initializing with // max value of int . int min_odd = Integer.MAX_VALUE; // To check if there is al-least // one odd number. boolean isOdd = false; // To store sum of all positive elements int sum = 0; for (int i = 0 ; i < n ; i++) { // Adding positive number would // increase the sum. if (arr[i] > 0) sum = sum + arr[i]; // To find the minimum odd number // (absolute) in the array. if (arr[i] % 2 != 0) { isOdd = true; if (min_odd > Math.abs(arr[i])) min_odd = Math.abs(arr[i]); } } // If there was no odd number if (isOdd == false) return -1; // Now, sum will be either odd or even. // If even, changing it to odd. // As, even - odd = odd. // since m is the minimum odd // number(absolute). if (sum % 2 == 0) sum = sum - min_odd; return sum;} // Driver codepublic static void main (String[] args){ int arr[] = {2, -3, 5, -1, 4}; int n = arr.length; System.out.println(findMaxOddSubarraySum(arr, n)); }} // This code is contributed by vt_m
# Python program to find# maximum sum of odd# subsequence if it exists. # Returns maximum sum odd# subsequence if exists# Else returns -1def findMaxOddSubarraySum(arr, n): # Here min_odd is the # minimum odd number (in # absolute terms). # Initializing with max value # of int . min_odd = +2147483647 # To check if there is # at-least one odd number. isOdd = False # To store sum of # all positive elements sum = 0 for i in range(n): # Adding positive number # would increase # the sum. if (arr[i] > 0): sum = sum + arr[i] # To find the minimum # odd number(absolute) # in the array. if (arr[i]%2 != 0): isOdd = True if (min_odd > abs(arr[i])): min_odd = abs(arr[i]) # If there was no odd number if (isOdd == False): return -1 # Now, sum will be # either odd or even. # If even, changing it to # odd. As, even - odd = odd. # since m is the minimum # odd number(absolute). if (sum%2 == 0): sum = sum - m return sum # Driver code arr = [2, -3, 5, -1, 4]n =len(arr) print(findMaxOddSubarraySum(arr, n)) # This code is contributed# by Anant Agarwal.
// C# program to find maximum sum// of odd subsequence if it exists.using System; class GFG { // Returns maximum sum odd subsequence, // if exists Else returns -1 static int findMaxOddSubarraySum(int []arr, int n) { // Here min_odd is the minimum odd number // (in absolute terms). Initializing with // max value of int . int min_odd = int.MaxValue; // To check if there is al-least // one odd number. bool isOdd = false; // To store sum of all positive elements int sum = 0; for (int i = 0 ; i < n ; i++) { // Adding positive number would // increase the sum. if (arr[i] > 0) sum = sum + arr[i]; // To find the minimum odd number // (absolute) in the array. if (arr[i] % 2 != 0) { isOdd = true; if (min_odd > Math.Abs(arr[i])) min_odd = Math.Abs(arr[i]); } } // If there was no odd number if (isOdd == false) return -1; // Now, sum will be either odd or even. // If even, changing it to odd. // As, even - odd = odd. // since m is the minimum odd // number(absolute). if (sum % 2 == 0) sum = sum - min_odd; return sum; } // Driver code public static void Main () { int []arr = {2, -3, 5, -1, 4}; int n = arr.Length; Console.Write(findMaxOddSubarraySum(arr, n)); }} // This code is contributed by nitin mittal.
<?php// PHP program to find maximum// sum of odd subsequence if// it exists. // Returns maximum sum odd// subsequence if exists Else// returns -1function findMaxOddSubarraySum( $arr, $n){ // Here min_odd is the minimum // odd number (in absolute terms). // Initializing with max value // of int . $min_odd = PHP_INT_MAX; // To check if there is // at-least one odd number. $isOdd = false; // To store sum of all // positive elements $sum = 0; for ( $i = 0; $i < $n; $i++) { // Adding positive number // would increase the sum. if ($arr[$i] > 0) $sum = $sum + $arr[$i]; // To find the minimum odd // number(absolute) in the array. if ($arr[$i] % 2 != 0) { $isOdd = true; if ($min_odd > abs($arr[$i])) $min_odd = abs($arr[$i]); } } // If there was no odd number if ($isOdd == false) return -1; // Now, sum will be either // odd or even. If even, // changing it to odd. As, // even - odd = odd. since // m is the minimum odd // number(absolute). if ($sum % 2 == 0) $sum = $sum - $min_odd; return $sum;} // Driver code$arr = array(2, -3, 5, -1, 4);$n = count($arr);echo findMaxOddSubarraySum($arr, $n); // This code is contributed by anuj_67.?>
<script> // Javascript program to find maximum sum // of odd subsequence if it exists. // Returns maximum sum odd subsequence, // if exists Else returns -1 function findMaxOddSubarraySum(arr, n) { // Here min_odd is the minimum odd number // (in absolute terms). Initializing with // max value of int . let min_odd = Number.MAX_VALUE; // To check if there is al-least // one odd number. let isOdd = false; // To store sum of all positive elements let sum = 0; for (let i = 0 ; i < n ; i++) { // Adding positive number would // increase the sum. if (arr[i] > 0) sum = sum + arr[i]; // To find the minimum odd number // (absolute) in the array. if (arr[i] % 2 != 0) { isOdd = true; if (min_odd > Math.abs(arr[i])) min_odd = Math.abs(arr[i]); } } // If there was no odd number if (isOdd == false) return -1; // Now, sum will be either odd or even. // If even, changing it to odd. // As, even - odd = odd. // since m is the minimum odd // number(absolute). if (sum % 2 == 0) sum = sum - min_odd; return sum; } let arr = [2, -3, 5, -1, 4]; let n = arr.length; document.write(findMaxOddSubarraySum(arr, n)); // This code is contributed by rameshtravel07.</script>
Output :
11
Time Complexity : O(n) Auxiliary Space : O(1)
This article is contributed by Jatin Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
nitin mittal
rameshtravel07
surinderdawra388
subsequence
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Reversal algorithm for array rotation
Window Sliding Technique
Next Greater Element
Find duplicates in O(n) time and O(1) extra space | Set 1
Building Heap from Array
Count pairs with given sum
Remove duplicates from sorted array
Find subarray with given sum | Set 1 (Nonnegative Numbers)
Trapping Rain Water
|
[
{
"code": null,
"e": 26177,
"s": 26149,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 26345,
"s": 26177,
"text": "Given a set of integers, check whether there is a subsequence with odd sum and if yes, then finding the maximum odd sum. If no subsequence contains odd sum, return -1."
},
{
"code": null,
"e": 26357,
"s": 26345,
"text": "Examples : "
},
{
"code": null,
"e": 26629,
"s": 26357,
"text": "Input : arr[] = {2, 5, -4, 3, -1};\nOutput : 9\nThe subsequence with maximum odd \nsum is 2, 5, 3 and -1.\n\nInput : arr[] = {4, -3, 3, -5}\nOutput : 7\nThe subsequence with maximum odd\nsum is 4 and 3\n\nInput : arr[] = {2, 4, 6}\nOutput : -1\nThere is no subsequence with odd sum."
},
{
"code": null,
"e": 26791,
"s": 26629,
"text": "A simple solution to generate all subsequences and find the maximum sum of all subsequences with odd sums. Time complexity of this solution would be exponential."
},
{
"code": null,
"e": 27365,
"s": 26791,
"text": "An efficient solution can work in O(n) time. The idea is based on the following facts. 1) Odd sum is not possible if all numbers are even. Otherwise, we always find an answer. 2) If odd sum is possible, we find sum of all positive integers. If sum is odd, we return it as this is the maximum overall positive sum. If sum is even, we subtract the odd number with the smallest absolute value from sum. This step can be justified by the fact that the smallest absolute odd value number becomes part of result if it is negative, and removed from the result when it is positive."
},
{
"code": null,
"e": 27369,
"s": 27365,
"text": "C++"
},
{
"code": null,
"e": 27374,
"s": 27369,
"text": "Java"
},
{
"code": null,
"e": 27382,
"s": 27374,
"text": "Python3"
},
{
"code": null,
"e": 27385,
"s": 27382,
"text": "C#"
},
{
"code": null,
"e": 27389,
"s": 27385,
"text": "PHP"
},
{
"code": null,
"e": 27400,
"s": 27389,
"text": "Javascript"
},
{
"code": "// C++ program to find maximum sum of odd// subsequence if it exists.#include<bits/stdc++.h>using namespace std; // Returns maximum sum odd subsequence if exists// Else returns -1int findMaxOddSubarraySum(int arr[], int n){ // Here min_odd is the minimum odd number (in // absolute terms). Initializing with max value // of int . int min_odd = INT_MAX; // To check if there is al-least one odd number. bool isOdd = false; int sum = 0; // To store sum of all positive elements for (int i=0 ; i<n ; i++) { // Adding positive number would increase // the sum. if (arr[i] > 0) sum = sum + arr[i]; // To find the minimum odd number(absolute) // in the array. if (arr[i]%2 != 0) { isOdd = true; if (min_odd> abs(arr[i])) min_odd = abs(arr[i]); } } // If there was no odd number if (isOdd == false) return -1; // Now, sum will be either odd or even. // If even, changing it to odd. As, even - odd = odd. // since m is the minimum odd number(absolute). if (sum%2 == 0) sum = sum - min_odd; return sum;} // Driver codeint main(){ int arr[] = {2, -3, 5, -1, 4}; int n = sizeof(arr)/sizeof(arr[0]); cout << findMaxOddSubarraySum(arr, n); return 0;}",
"e": 28725,
"s": 27400,
"text": null
},
{
"code": "// Java program to find maximum sum// of odd subsequence if it exists.import java.io.*; class GFG { // Returns maximum sum odd subsequence,// if exists Else returns -1static int findMaxOddSubarraySum(int arr[], int n){ // Here min_odd is the minimum odd number // (in absolute terms). Initializing with // max value of int . int min_odd = Integer.MAX_VALUE; // To check if there is al-least // one odd number. boolean isOdd = false; // To store sum of all positive elements int sum = 0; for (int i = 0 ; i < n ; i++) { // Adding positive number would // increase the sum. if (arr[i] > 0) sum = sum + arr[i]; // To find the minimum odd number // (absolute) in the array. if (arr[i] % 2 != 0) { isOdd = true; if (min_odd > Math.abs(arr[i])) min_odd = Math.abs(arr[i]); } } // If there was no odd number if (isOdd == false) return -1; // Now, sum will be either odd or even. // If even, changing it to odd. // As, even - odd = odd. // since m is the minimum odd // number(absolute). if (sum % 2 == 0) sum = sum - min_odd; return sum;} // Driver codepublic static void main (String[] args){ int arr[] = {2, -3, 5, -1, 4}; int n = arr.length; System.out.println(findMaxOddSubarraySum(arr, n)); }} // This code is contributed by vt_m",
"e": 30161,
"s": 28725,
"text": null
},
{
"code": "# Python program to find# maximum sum of odd# subsequence if it exists. # Returns maximum sum odd# subsequence if exists# Else returns -1def findMaxOddSubarraySum(arr, n): # Here min_odd is the # minimum odd number (in # absolute terms). # Initializing with max value # of int . min_odd = +2147483647 # To check if there is # at-least one odd number. isOdd = False # To store sum of # all positive elements sum = 0 for i in range(n): # Adding positive number # would increase # the sum. if (arr[i] > 0): sum = sum + arr[i] # To find the minimum # odd number(absolute) # in the array. if (arr[i]%2 != 0): isOdd = True if (min_odd > abs(arr[i])): min_odd = abs(arr[i]) # If there was no odd number if (isOdd == False): return -1 # Now, sum will be # either odd or even. # If even, changing it to # odd. As, even - odd = odd. # since m is the minimum # odd number(absolute). if (sum%2 == 0): sum = sum - m return sum # Driver code arr = [2, -3, 5, -1, 4]n =len(arr) print(findMaxOddSubarraySum(arr, n)) # This code is contributed# by Anant Agarwal.",
"e": 31428,
"s": 30161,
"text": null
},
{
"code": "// C# program to find maximum sum// of odd subsequence if it exists.using System; class GFG { // Returns maximum sum odd subsequence, // if exists Else returns -1 static int findMaxOddSubarraySum(int []arr, int n) { // Here min_odd is the minimum odd number // (in absolute terms). Initializing with // max value of int . int min_odd = int.MaxValue; // To check if there is al-least // one odd number. bool isOdd = false; // To store sum of all positive elements int sum = 0; for (int i = 0 ; i < n ; i++) { // Adding positive number would // increase the sum. if (arr[i] > 0) sum = sum + arr[i]; // To find the minimum odd number // (absolute) in the array. if (arr[i] % 2 != 0) { isOdd = true; if (min_odd > Math.Abs(arr[i])) min_odd = Math.Abs(arr[i]); } } // If there was no odd number if (isOdd == false) return -1; // Now, sum will be either odd or even. // If even, changing it to odd. // As, even - odd = odd. // since m is the minimum odd // number(absolute). if (sum % 2 == 0) sum = sum - min_odd; return sum; } // Driver code public static void Main () { int []arr = {2, -3, 5, -1, 4}; int n = arr.Length; Console.Write(findMaxOddSubarraySum(arr, n)); }} // This code is contributed by nitin mittal.",
"e": 33087,
"s": 31428,
"text": null
},
{
"code": "<?php// PHP program to find maximum// sum of odd subsequence if// it exists. // Returns maximum sum odd// subsequence if exists Else// returns -1function findMaxOddSubarraySum( $arr, $n){ // Here min_odd is the minimum // odd number (in absolute terms). // Initializing with max value // of int . $min_odd = PHP_INT_MAX; // To check if there is // at-least one odd number. $isOdd = false; // To store sum of all // positive elements $sum = 0; for ( $i = 0; $i < $n; $i++) { // Adding positive number // would increase the sum. if ($arr[$i] > 0) $sum = $sum + $arr[$i]; // To find the minimum odd // number(absolute) in the array. if ($arr[$i] % 2 != 0) { $isOdd = true; if ($min_odd > abs($arr[$i])) $min_odd = abs($arr[$i]); } } // If there was no odd number if ($isOdd == false) return -1; // Now, sum will be either // odd or even. If even, // changing it to odd. As, // even - odd = odd. since // m is the minimum odd // number(absolute). if ($sum % 2 == 0) $sum = $sum - $min_odd; return $sum;} // Driver code$arr = array(2, -3, 5, -1, 4);$n = count($arr);echo findMaxOddSubarraySum($arr, $n); // This code is contributed by anuj_67.?>",
"e": 34420,
"s": 33087,
"text": null
},
{
"code": "<script> // Javascript program to find maximum sum // of odd subsequence if it exists. // Returns maximum sum odd subsequence, // if exists Else returns -1 function findMaxOddSubarraySum(arr, n) { // Here min_odd is the minimum odd number // (in absolute terms). Initializing with // max value of int . let min_odd = Number.MAX_VALUE; // To check if there is al-least // one odd number. let isOdd = false; // To store sum of all positive elements let sum = 0; for (let i = 0 ; i < n ; i++) { // Adding positive number would // increase the sum. if (arr[i] > 0) sum = sum + arr[i]; // To find the minimum odd number // (absolute) in the array. if (arr[i] % 2 != 0) { isOdd = true; if (min_odd > Math.abs(arr[i])) min_odd = Math.abs(arr[i]); } } // If there was no odd number if (isOdd == false) return -1; // Now, sum will be either odd or even. // If even, changing it to odd. // As, even - odd = odd. // since m is the minimum odd // number(absolute). if (sum % 2 == 0) sum = sum - min_odd; return sum; } let arr = [2, -3, 5, -1, 4]; let n = arr.length; document.write(findMaxOddSubarraySum(arr, n)); // This code is contributed by rameshtravel07.</script>",
"e": 36013,
"s": 34420,
"text": null
},
{
"code": null,
"e": 36023,
"s": 36013,
"text": "Output : "
},
{
"code": null,
"e": 36026,
"s": 36023,
"text": "11"
},
{
"code": null,
"e": 36072,
"s": 36026,
"text": "Time Complexity : O(n) Auxiliary Space : O(1)"
},
{
"code": null,
"e": 36492,
"s": 36072,
"text": "This article is contributed by Jatin Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 36497,
"s": 36492,
"text": "vt_m"
},
{
"code": null,
"e": 36510,
"s": 36497,
"text": "nitin mittal"
},
{
"code": null,
"e": 36525,
"s": 36510,
"text": "rameshtravel07"
},
{
"code": null,
"e": 36542,
"s": 36525,
"text": "surinderdawra388"
},
{
"code": null,
"e": 36554,
"s": 36542,
"text": "subsequence"
},
{
"code": null,
"e": 36561,
"s": 36554,
"text": "Arrays"
},
{
"code": null,
"e": 36568,
"s": 36561,
"text": "Arrays"
},
{
"code": null,
"e": 36666,
"s": 36568,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36697,
"s": 36666,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 36735,
"s": 36697,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 36760,
"s": 36735,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 36781,
"s": 36760,
"text": "Next Greater Element"
},
{
"code": null,
"e": 36839,
"s": 36781,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 36864,
"s": 36839,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 36891,
"s": 36864,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 36927,
"s": 36891,
"text": "Remove duplicates from sorted array"
},
{
"code": null,
"e": 36986,
"s": 36927,
"text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)"
}
] |
Elixir - File IO
|
File IO is an integral part of any programming language as it allows the language to interact with the files on the file system. In this chapter, we will discuss two modules β Path and File.
The path module is a very small module that can be considered as a helper module for filesystem operations. The majority of the functions in the File module expect paths as arguments. Most commonly, those paths will be regular binaries. The Path module provides facilities for working with such paths. Using functions from the Path module as opposed to just manipulating binaries is preferred since the Path module takes care of different operating systems transparently. It is to be observed that Elixir will automatically convert slashes (/) into backslashes (\) on Windows when performing file operations.
Let us consider the following example to further understand the Path module β
IO.puts(Path.join("foo", "bar"))
When the above program is run, it produces the following result β
foo/bar
There are a lot of methods that the path module provides. You can have a look at the different methods here. These methods are frequently used if you are performing many file manipulation operations.
The file module contains functions that allow us to open files as IO devices. By default, files are opened in binary mode, which requires developers to use the specific IO.binread and IO.binwrite functions from the IO module. Let us create a file called newfile and write some data to it.
{:ok, file} = File.read("newfile", [:write])
# Pattern matching to store returned stream
IO.binwrite(file, "This will be written to the file")
If you go to open the file we just wrote into, content will be displayed in the following way β
This will be written to the file
Let us now understand how to use the file module.
To open a file, we can use any one of the following 2 functions β
{:ok, file} = File.open("newfile")
file = File.open!("newfile")
Let us now understand the difference between the File.open function and the File.open!() function.
The File.open function always returns a tuple. If file is successfully opened, it returns the first value in the tuple as :ok and the second value is literal of type io_device. If an error is caused, it will return a tuple with first value as :error and second value as the reason.
The File.open function always returns a tuple. If file is successfully opened, it returns the first value in the tuple as :ok and the second value is literal of type io_device. If an error is caused, it will return a tuple with first value as :error and second value as the reason.
The File.open!() function on the other hand will return a io_device if file is successfully opened else it will raise an error. NOTE: This is the pattern followed in all of the file module functions we are going to discuss.
The File.open!() function on the other hand will return a io_device if file is successfully opened else it will raise an error. NOTE: This is the pattern followed in all of the file module functions we are going to discuss.
We can also specify the modes in which we want to open this file. To open a file as read only and in utf-8 encoding mode, we use the following code β
file = File.open!("newfile", [:read, :utf8])
We have two ways to write to files. Let us see the first one using the write function from the File module.
File.write("newfile", "Hello")
But this should not be used if you are making multiple writes to the same file. Every time this function is invoked, a file descriptor is opened and a new process is spawned to write to the file. If you are doing multiple writes in a loop, open the file via File.open and write to it using the methods in IO module. Let us consider an example to understand the same β
#Open the file in read, write and utf8 modes.
file = File.open!("newfile_2", [:read, :utf8, :write])
#Write to this "io_device" using standard IO functions
IO.puts(file, "Random text")
You can use other IO module methods like IO.write and IO.binwrite to write to files opened as io_device.
We have two ways to read from files. Let us see the first one using the read function from the File module.
IO.puts(File.read("newfile"))
When running this code, you should get a tuple with the first element as :ok and the second one as the contents of newfile
We can also use the File.read! function to just get the contents of the files returned to us.
Whenever you open a file using the File.open function, after you are done using it, you should close it using the File.close function β
File.close(file)
35 Lectures
3 hours
Pranjal Srivastava
54 Lectures
6 hours
Pranjal Srivastava, Harshit Srivastava
80 Lectures
9.5 hours
Pranjal Srivastava
43 Lectures
4 hours
Mohammad Nauman
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2373,
"s": 2182,
"text": "File IO is an integral part of any programming language as it allows the language to interact with the files on the file system. In this chapter, we will discuss two modules β Path and File."
},
{
"code": null,
"e": 2982,
"s": 2373,
"text": "The path module is a very small module that can be considered as a helper module for filesystem operations. The majority of the functions in the File module expect paths as arguments. Most commonly, those paths will be regular binaries. The Path module provides facilities for working with such paths. Using functions from the Path module as opposed to just manipulating binaries is preferred since the Path module takes care of different operating systems transparently. It is to be observed that Elixir will automatically convert slashes (/) into backslashes (\\) on Windows when performing file operations."
},
{
"code": null,
"e": 3060,
"s": 2982,
"text": "Let us consider the following example to further understand the Path module β"
},
{
"code": null,
"e": 3093,
"s": 3060,
"text": "IO.puts(Path.join(\"foo\", \"bar\"))"
},
{
"code": null,
"e": 3159,
"s": 3093,
"text": "When the above program is run, it produces the following result β"
},
{
"code": null,
"e": 3168,
"s": 3159,
"text": "foo/bar\n"
},
{
"code": null,
"e": 3368,
"s": 3168,
"text": "There are a lot of methods that the path module provides. You can have a look at the different methods here. These methods are frequently used if you are performing many file manipulation operations."
},
{
"code": null,
"e": 3657,
"s": 3368,
"text": "The file module contains functions that allow us to open files as IO devices. By default, files are opened in binary mode, which requires developers to use the specific IO.binread and IO.binwrite functions from the IO module. Let us create a file called newfile and write some data to it."
},
{
"code": null,
"e": 3801,
"s": 3657,
"text": "{:ok, file} = File.read(\"newfile\", [:write]) \n# Pattern matching to store returned stream\nIO.binwrite(file, \"This will be written to the file\")"
},
{
"code": null,
"e": 3897,
"s": 3801,
"text": "If you go to open the file we just wrote into, content will be displayed in the following way β"
},
{
"code": null,
"e": 3932,
"s": 3897,
"text": "This will be written to the file \n"
},
{
"code": null,
"e": 3982,
"s": 3932,
"text": "Let us now understand how to use the file module."
},
{
"code": null,
"e": 4048,
"s": 3982,
"text": "To open a file, we can use any one of the following 2 functions β"
},
{
"code": null,
"e": 4112,
"s": 4048,
"text": "{:ok, file} = File.open(\"newfile\")\nfile = File.open!(\"newfile\")"
},
{
"code": null,
"e": 4211,
"s": 4112,
"text": "Let us now understand the difference between the File.open function and the File.open!() function."
},
{
"code": null,
"e": 4493,
"s": 4211,
"text": "The File.open function always returns a tuple. If file is successfully opened, it returns the first value in the tuple as :ok and the second value is literal of type io_device. If an error is caused, it will return a tuple with first value as :error and second value as the reason."
},
{
"code": null,
"e": 4775,
"s": 4493,
"text": "The File.open function always returns a tuple. If file is successfully opened, it returns the first value in the tuple as :ok and the second value is literal of type io_device. If an error is caused, it will return a tuple with first value as :error and second value as the reason."
},
{
"code": null,
"e": 4999,
"s": 4775,
"text": "The File.open!() function on the other hand will return a io_device if file is successfully opened else it will raise an error. NOTE: This is the pattern followed in all of the file module functions we are going to discuss."
},
{
"code": null,
"e": 5223,
"s": 4999,
"text": "The File.open!() function on the other hand will return a io_device if file is successfully opened else it will raise an error. NOTE: This is the pattern followed in all of the file module functions we are going to discuss."
},
{
"code": null,
"e": 5373,
"s": 5223,
"text": "We can also specify the modes in which we want to open this file. To open a file as read only and in utf-8 encoding mode, we use the following code β"
},
{
"code": null,
"e": 5418,
"s": 5373,
"text": "file = File.open!(\"newfile\", [:read, :utf8])"
},
{
"code": null,
"e": 5526,
"s": 5418,
"text": "We have two ways to write to files. Let us see the first one using the write function from the File module."
},
{
"code": null,
"e": 5557,
"s": 5526,
"text": "File.write(\"newfile\", \"Hello\")"
},
{
"code": null,
"e": 5925,
"s": 5557,
"text": "But this should not be used if you are making multiple writes to the same file. Every time this function is invoked, a file descriptor is opened and a new process is spawned to write to the file. If you are doing multiple writes in a loop, open the file via File.open and write to it using the methods in IO module. Let us consider an example to understand the same β"
},
{
"code": null,
"e": 6112,
"s": 5925,
"text": "#Open the file in read, write and utf8 modes. \nfile = File.open!(\"newfile_2\", [:read, :utf8, :write])\n\n#Write to this \"io_device\" using standard IO functions\nIO.puts(file, \"Random text\")"
},
{
"code": null,
"e": 6217,
"s": 6112,
"text": "You can use other IO module methods like IO.write and IO.binwrite to write to files opened as io_device."
},
{
"code": null,
"e": 6325,
"s": 6217,
"text": "We have two ways to read from files. Let us see the first one using the read function from the File module."
},
{
"code": null,
"e": 6355,
"s": 6325,
"text": "IO.puts(File.read(\"newfile\"))"
},
{
"code": null,
"e": 6478,
"s": 6355,
"text": "When running this code, you should get a tuple with the first element as :ok and the second one as the contents of newfile"
},
{
"code": null,
"e": 6572,
"s": 6478,
"text": "We can also use the File.read! function to just get the contents of the files returned to us."
},
{
"code": null,
"e": 6708,
"s": 6572,
"text": "Whenever you open a file using the File.open function, after you are done using it, you should close it using the File.close function β"
},
{
"code": null,
"e": 6725,
"s": 6708,
"text": "File.close(file)"
},
{
"code": null,
"e": 6758,
"s": 6725,
"text": "\n 35 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6778,
"s": 6758,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 6811,
"s": 6778,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6851,
"s": 6811,
"text": " Pranjal Srivastava, Harshit Srivastava"
},
{
"code": null,
"e": 6886,
"s": 6851,
"text": "\n 80 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 6906,
"s": 6886,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 6939,
"s": 6906,
"text": "\n 43 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6956,
"s": 6939,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 6963,
"s": 6956,
"text": " Print"
},
{
"code": null,
"e": 6974,
"s": 6963,
"text": " Add Notes"
}
] |
Distinct permutations of the string | Set 2 - GeeksforGeeks
|
17 Apr, 2022
Print all distinct permutations of a string having duplicates.
Examples:
Input : ABCA
Output : AABC AACB ABAC ABCA ACBA
ACAB BAAC BACA BCAA CABA
CAAB CBAA
An algorithm to print all distinct permutations has already been discussed here. Here weβll discuss one more approach to do the same. Recall first how we print permutations without any duplicates in the input string. It is given here. Letβs now take the case of the string βABACβ. While generating permutations, letβs say we are at index = 0, swap it with all elements after it. When we reach i=2, we see that in the string s[index...i-1], there was an index that is equal to s[i]. Thus, swapping it will produce repeated permutations. Thus, we donβt swap it. The below explains it better.
Illustration: Let us understand with the below example.
i = 0 1 2 3
A B A C
index = 0, s[0] = A
Start swapping s[index] with s[i] following it:
i = index + 1 = 1
Since s[index] != s[i], swap and recur.
i = 2, s[index] == s[i], don't swap
i = 3, s[index] != s[i], swap and recur.
Below code does the same.
C++
C
Java
Python3
C#
Javascript
// C++ program to distinct permutations of the string#include <bits/stdc++.h>using namespace std; // Returns true if str[curr] does not matches with any of the// characters after str[start]bool shouldSwap(char str[], int start, int curr){ for (int i = start; i < curr; i++) if (str[i] == str[curr]) return 0; return 1;} // Prints all distinct permutations in str[0..n-1]void findPermutations(char str[], int index, int n){ if (index >= n) { cout << str << endl; return; } for (int i = index; i < n; i++) { // Proceed further for str[i] only if it // doesn't match with any of the characters // after str[index] bool check = shouldSwap(str, index, i); if (check) { swap(str[index], str[i]); findPermutations(str, index + 1, n); swap(str[index], str[i]); } }} // Driver codeint main(){ char str[] = "ABCA"; int n = strlen(str); findPermutations(str, 0, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// C program to distinct permutations of the string#include <stdbool.h>#include <stdio.h>#include <string.h> // Returns true if str[curr] does not matches with any of// the characters after str[start]bool shouldSwap(char str[], int start, int curr){ for (int i = start; i < curr; i++) if (str[i] == str[curr]) return 0; return 1;} // Prints all distinct permutations in str[0..n-1]void findPermutations(char str[], int index, int n){ if (index >= n) { printf("%s\n", str); return; } for (int i = index; i < n; i++) { // Proceed further for str[i] only if it // doesn't match with any of the characters // after str[index] bool check = shouldSwap(str, index, i); if (check) { // Swapping the str[index] with str[i] char temp = str[index]; str[index] = str[i]; str[i] = temp; findPermutations(str, index + 1, n); // Swapping the str[index] with str[i] temp = str[index]; str[index] = str[i]; str[i] = temp; } }} // Driver codeint main(){ char str[] = "ABCA"; int n = strlen(str); findPermutations(str, 0, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java program to distinct permutations of the stringpublic class GFG { // Returns true if str[curr] does not matches with any of the// characters after str[start] static boolean shouldSwap(char str[], int start, int curr) { for (int i = start; i < curr; i++) { if (str[i] == str[curr]) { return false; } } return true; } // Prints all distinct permutations in str[0..n-1] static void findPermutations(char str[], int index, int n) { if (index >= n) { System.out.println(str); return; } for (int i = index; i < n; i++) { // Proceed further for str[i] only if it // doesn't match with any of the characters // after str[index] boolean check = shouldSwap(str, index, i); if (check) { swap(str, index, i); findPermutations(str, index + 1, n); swap(str, index, i); } } } static void swap(char[] str, int i, int j) { char c = str[i]; str[i] = str[j]; str[j] = c; } // Driver code public static void main(String[] args) { char str[] = {'A', 'B', 'C', 'A'}; int n = str.length; findPermutations(str, 0, n); } }
# Python3 program to distinct# permutations of the string # Returns true if str[curr] does not# matches with any of the characters# after str[start]def shouldSwap(string, start, curr): for i in range(start, curr): if string[i] == string[curr]: return 0 return 1 # Prints all distinct permutations# in str[0..n-1]def findPermutations(string, index, n): if index >= n: print(''.join(string)) return for i in range(index, n): # Proceed further for str[i] only # if it doesn't match with any of # the characters after str[index] check = shouldSwap(string, index, i) if check: string[index], string[i] = string[i], string[index] findPermutations(string, index + 1, n) string[index], string[i] = string[i], string[index] # Driver codeif __name__ == "__main__": string = list("ABCA") n = len(string) findPermutations(string, 0, n) # This code is contributed by Rituraj Jain
// C# program to distinct permutations// of the stringusing System; class GFG{ // Returns true if str[curr] does// not matches with any of the// characters after str[start]static bool shouldSwap(char []str, int start, int curr){ for (int i = start; i < curr; i++) { if (str[i] == str[curr]) { return false; } } return true;} // Prints all distinct permutations// in str[0..n-1]static void findPermutations(char []str, int index, int n){ if (index >= n) { Console.WriteLine(str); return; } for (int i = index; i < n; i++) { // Proceed further for str[i] only // if it doesn't match with any of // the characters after str[index] bool check = shouldSwap(str, index, i); if (check) { swap(str, index, i); findPermutations(str, index + 1, n); swap(str, index, i); } }} static void swap(char[] str, int i, int j){ char c = str[i]; str[i] = str[j]; str[j] = c;} // Driver codepublic static void Main(){ char []str = {'A', 'B', 'C', 'A'}; int n = str.Length; findPermutations(str, 0, n);}} // This code is contributed// by 29AjayKumar
<script> // Javascript program to distinct permutations of the string // Returns true if str[curr] does not matches with any of the// characters after str[start] function shouldSwap(str, start, curr) { for (let i = start; i < curr; i++) { if (str[i] == str[curr]) { return false; } } return true; } // Prints all distinct permutations in str[0..n-1] function findPermutations(str, index, n) { if (index >= n) { document.write(str); document.write("<br/>") return; } for (let i = index; i < n; i++) { // Proceed further for str[i] only if it // doesn't match with any of the characters // after str[index] let check = shouldSwap(str, index, i); if (check) { swap(str, index, i); findPermutations(str, index + 1, n); swap(str, index, i); } } } function swap(str, i, j) { let c = str[i]; str[i] = str[j]; str[j] = c; } // Driver code let str = ['A', 'B', 'C', 'A']; let n = str.length; findPermutations(str, 0, n); </script>
ABCA
ABAC
ACBA
ACAB
AACB
AABC
BACA
BAAC
BCAA
CBAA
CABA
CAAB
Better Approach:
Generate all distinct strings is to simply use some if conditions. The technique above uses an extra loop inside the recursion which causes a major time complexity cost. Instead, we can improve it by little pre-processing. We first sort the given string and then apply the below code.
Below is the implementation of the above idea:
C++
Java
Python3
Javascript
// C++ program to print all the permutation// of the given string.#include <algorithm>#include <iostream>#include <string>using namespace std; // count of total permutationsint total = 0; void permute(int i, string s){ // base case if (i == (s.length() - 1)) { cout << s << endl; total++; return; } char prev = '*'; // loop from j = 1 to length of string for (int j = i; j < s.length(); j++) { string temp = s; if (j > i && temp[i] == temp[j]) continue; if (prev != '*' && prev == s[j]) { continue; } // swap the elements swap(temp[i], temp[j]); prev = s[j]; // recursion call permute(i + 1, temp); }} // Driver codeint main(){ string s = "abca"; // sort sort(s.begin(), s.end()); // Function call permute(0, s); cout << "Total distinct permutations = " << total << endl; return 0;} // This code is contributed by risingStark.
// Java program to print all the permutation// of the given String.//include <algorithm> //include <String>import java.util.*; class GFG{ // Count of total permutationsstatic int total = 0; static void permute(int i, String s){ // Base case if (i == (s.length() - 1)) { System.out.print(s + "\n"); total++; return; } char prev = '*'; // Loop from j = 1 to length of String for(int j = i; j < s.length(); j++) { char []temp = s.toCharArray(); if (j > i && temp[i] == temp[j]) continue; if (prev != '*' && prev == s.charAt(j)) { continue; } // Swap the elements temp = swap(temp,i,j); prev = s.charAt(j); // Recursion call permute(i + 1, String.valueOf(temp)); }} static char[] swap(char []arr, int i, int j){ char temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr;} static String sortString(String inputString){ // Convert input string to char array char tempArray[] = inputString.toCharArray(); // Sort tempArray Arrays.sort(tempArray); // Return new sorted string return new String(tempArray);} // Driver codepublic static void main(String[] args){ String s = "abca"; // Sort s = sortString(s); // Function call permute(0, s); System.out.print("Total distinct permutations = " + total +"\n");}} // This code is contributed by Amit Katiyar
# Python program to print all the permutation# of the given String. # Count of total permutationstotal = 0 def swap(arr, i, j): temp = arr[i] arr[i] = arr[j] arr[j] = temp return arr def permute(i, s): global total # Base case if(i == (len(s) - 1)): print(s) total += 1 return prev = '*' # Loop from j = 1 to length of String for j in range(i,len(s)): temp = list(s) if (j > i and temp[i] == temp[j]): continue if (prev != '*' and prev == s[j]): continue # Swap the elements temp = swap(temp,i,j) prev = s[j] # Recursion call permute(i + 1, "".join(temp)) def sortString(inputString): # Convert input string to char array tempArray = list(inputString) # Sort tempArray tempArray.sort() # Return new sorted string return "".join(tempArray) # Driver codes = "abca" # Sorts = sortString(s) # Function callpermute(0, s)print(f"Total distinct permutations = {total}") # This code is contributed by shinjanpatra
<script> // JavaScript program to print all the permutation// of the given String. // Count of total permutationslet total = 0;function permute(i,s){ // Base case if (i == (s.length - 1)) { document.write(s + "<br>"); total++; return; } let prev = '*'; // Loop from j = 1 to length of String for(let j = i; j < s.length; j++) { let temp = s.split(""); if (j > i && temp[i] == temp[j]) continue; if (prev != '*' && prev == s[j]) { continue; } // Swap the elements temp = swap(temp,i,j); prev = s[j]; // Recursion call permute(i + 1, (temp).join("")); }} function swap(arr,i,j){ let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr;} function sortString(inputString){ // Convert input string to char array let tempArray = inputString.split(""); // Sort tempArray (tempArray).sort(); // Return new sorted string return (tempArray).join("");} // Driver codelet s = "abca"; // Sorts = sortString(s); // Function callpermute(0, s);document.write("Total distinct permutations = " + total +"<br>"); // This code is contributed by rag2127 </script>
aabc
aacb
abac
abca
acba
acab
baac
baca
bcaa
caba
caab
cbaa
Total distinct permutations = 12
Time complexity: If we take the length of the string to be N, then the complexity of my code will be O(N log N) for sorting and O(N*N!) for the permutation. Total time complexity would be O(N log N + N*N!) which is effectively only O(N*N!).
sadiqRaza
Rajput-Ji
29AjayKumar
rituraj_jain
shreyashagrawal
risingStark
susmitakundugoaldanga
amit143katiyar
rag2127
shinjanpatra
adityakumar129
Combinatorial
Strings
Strings
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find the Number of Permutations that satisfy the given condition in an array
Python program to get all subsets of given size of a set
Print all subsets of given size of a set
Find all distinct subsets of a given set using BitMasking Approach
Make all combinations of size k
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
C++ Data Types
Python program to check if a string is palindrome or not
|
[
{
"code": null,
"e": 24661,
"s": 24633,
"text": "\n17 Apr, 2022"
},
{
"code": null,
"e": 24724,
"s": 24661,
"text": "Print all distinct permutations of a string having duplicates."
},
{
"code": null,
"e": 24736,
"s": 24724,
"text": "Examples: "
},
{
"code": null,
"e": 24838,
"s": 24736,
"text": "Input : ABCA\nOutput : AABC AACB ABAC ABCA ACBA \n ACAB BAAC BACA BCAA CABA \n CAAB CBAA"
},
{
"code": null,
"e": 25428,
"s": 24838,
"text": "An algorithm to print all distinct permutations has already been discussed here. Here weβll discuss one more approach to do the same. Recall first how we print permutations without any duplicates in the input string. It is given here. Letβs now take the case of the string βABACβ. While generating permutations, letβs say we are at index = 0, swap it with all elements after it. When we reach i=2, we see that in the string s[index...i-1], there was an index that is equal to s[i]. Thus, swapping it will produce repeated permutations. Thus, we donβt swap it. The below explains it better."
},
{
"code": null,
"e": 25485,
"s": 25428,
"text": "Illustration: Let us understand with the below example. "
},
{
"code": null,
"e": 25718,
"s": 25485,
"text": "i = 0 1 2 3\n A B A C\nindex = 0, s[0] = A\nStart swapping s[index] with s[i] following it:\ni = index + 1 = 1 \n\nSince s[index] != s[i], swap and recur.\n\ni = 2, s[index] == s[i], don't swap\n\ni = 3, s[index] != s[i], swap and recur. "
},
{
"code": null,
"e": 25745,
"s": 25718,
"text": "Below code does the same. "
},
{
"code": null,
"e": 25749,
"s": 25745,
"text": "C++"
},
{
"code": null,
"e": 25751,
"s": 25749,
"text": "C"
},
{
"code": null,
"e": 25756,
"s": 25751,
"text": "Java"
},
{
"code": null,
"e": 25764,
"s": 25756,
"text": "Python3"
},
{
"code": null,
"e": 25767,
"s": 25764,
"text": "C#"
},
{
"code": null,
"e": 25778,
"s": 25767,
"text": "Javascript"
},
{
"code": "// C++ program to distinct permutations of the string#include <bits/stdc++.h>using namespace std; // Returns true if str[curr] does not matches with any of the// characters after str[start]bool shouldSwap(char str[], int start, int curr){ for (int i = start; i < curr; i++) if (str[i] == str[curr]) return 0; return 1;} // Prints all distinct permutations in str[0..n-1]void findPermutations(char str[], int index, int n){ if (index >= n) { cout << str << endl; return; } for (int i = index; i < n; i++) { // Proceed further for str[i] only if it // doesn't match with any of the characters // after str[index] bool check = shouldSwap(str, index, i); if (check) { swap(str[index], str[i]); findPermutations(str, index + 1, n); swap(str[index], str[i]); } }} // Driver codeint main(){ char str[] = \"ABCA\"; int n = strlen(str); findPermutations(str, 0, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 26844,
"s": 25778,
"text": null
},
{
"code": "// C program to distinct permutations of the string#include <stdbool.h>#include <stdio.h>#include <string.h> // Returns true if str[curr] does not matches with any of// the characters after str[start]bool shouldSwap(char str[], int start, int curr){ for (int i = start; i < curr; i++) if (str[i] == str[curr]) return 0; return 1;} // Prints all distinct permutations in str[0..n-1]void findPermutations(char str[], int index, int n){ if (index >= n) { printf(\"%s\\n\", str); return; } for (int i = index; i < n; i++) { // Proceed further for str[i] only if it // doesn't match with any of the characters // after str[index] bool check = shouldSwap(str, index, i); if (check) { // Swapping the str[index] with str[i] char temp = str[index]; str[index] = str[i]; str[i] = temp; findPermutations(str, index + 1, n); // Swapping the str[index] with str[i] temp = str[index]; str[index] = str[i]; str[i] = temp; } }} // Driver codeint main(){ char str[] = \"ABCA\"; int n = strlen(str); findPermutations(str, 0, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 28128,
"s": 26844,
"text": null
},
{
"code": "// Java program to distinct permutations of the stringpublic class GFG { // Returns true if str[curr] does not matches with any of the// characters after str[start] static boolean shouldSwap(char str[], int start, int curr) { for (int i = start; i < curr; i++) { if (str[i] == str[curr]) { return false; } } return true; } // Prints all distinct permutations in str[0..n-1] static void findPermutations(char str[], int index, int n) { if (index >= n) { System.out.println(str); return; } for (int i = index; i < n; i++) { // Proceed further for str[i] only if it // doesn't match with any of the characters // after str[index] boolean check = shouldSwap(str, index, i); if (check) { swap(str, index, i); findPermutations(str, index + 1, n); swap(str, index, i); } } } static void swap(char[] str, int i, int j) { char c = str[i]; str[i] = str[j]; str[j] = c; } // Driver code public static void main(String[] args) { char str[] = {'A', 'B', 'C', 'A'}; int n = str.length; findPermutations(str, 0, n); } }",
"e": 29426,
"s": 28128,
"text": null
},
{
"code": "# Python3 program to distinct# permutations of the string # Returns true if str[curr] does not# matches with any of the characters# after str[start]def shouldSwap(string, start, curr): for i in range(start, curr): if string[i] == string[curr]: return 0 return 1 # Prints all distinct permutations# in str[0..n-1]def findPermutations(string, index, n): if index >= n: print(''.join(string)) return for i in range(index, n): # Proceed further for str[i] only # if it doesn't match with any of # the characters after str[index] check = shouldSwap(string, index, i) if check: string[index], string[i] = string[i], string[index] findPermutations(string, index + 1, n) string[index], string[i] = string[i], string[index] # Driver codeif __name__ == \"__main__\": string = list(\"ABCA\") n = len(string) findPermutations(string, 0, n) # This code is contributed by Rituraj Jain",
"e": 30423,
"s": 29426,
"text": null
},
{
"code": "// C# program to distinct permutations// of the stringusing System; class GFG{ // Returns true if str[curr] does// not matches with any of the// characters after str[start]static bool shouldSwap(char []str, int start, int curr){ for (int i = start; i < curr; i++) { if (str[i] == str[curr]) { return false; } } return true;} // Prints all distinct permutations// in str[0..n-1]static void findPermutations(char []str, int index, int n){ if (index >= n) { Console.WriteLine(str); return; } for (int i = index; i < n; i++) { // Proceed further for str[i] only // if it doesn't match with any of // the characters after str[index] bool check = shouldSwap(str, index, i); if (check) { swap(str, index, i); findPermutations(str, index + 1, n); swap(str, index, i); } }} static void swap(char[] str, int i, int j){ char c = str[i]; str[i] = str[j]; str[j] = c;} // Driver codepublic static void Main(){ char []str = {'A', 'B', 'C', 'A'}; int n = str.Length; findPermutations(str, 0, n);}} // This code is contributed// by 29AjayKumar",
"e": 31679,
"s": 30423,
"text": null
},
{
"code": "<script> // Javascript program to distinct permutations of the string // Returns true if str[curr] does not matches with any of the// characters after str[start] function shouldSwap(str, start, curr) { for (let i = start; i < curr; i++) { if (str[i] == str[curr]) { return false; } } return true; } // Prints all distinct permutations in str[0..n-1] function findPermutations(str, index, n) { if (index >= n) { document.write(str); document.write(\"<br/>\") return; } for (let i = index; i < n; i++) { // Proceed further for str[i] only if it // doesn't match with any of the characters // after str[index] let check = shouldSwap(str, index, i); if (check) { swap(str, index, i); findPermutations(str, index + 1, n); swap(str, index, i); } } } function swap(str, i, j) { let c = str[i]; str[i] = str[j]; str[j] = c; } // Driver code let str = ['A', 'B', 'C', 'A']; let n = str.length; findPermutations(str, 0, n); </script>",
"e": 32934,
"s": 31679,
"text": null
},
{
"code": null,
"e": 32994,
"s": 32934,
"text": "ABCA\nABAC\nACBA\nACAB\nAACB\nAABC\nBACA\nBAAC\nBCAA\nCBAA\nCABA\nCAAB"
},
{
"code": null,
"e": 33011,
"s": 32994,
"text": "Better Approach:"
},
{
"code": null,
"e": 33296,
"s": 33011,
"text": "Generate all distinct strings is to simply use some if conditions. The technique above uses an extra loop inside the recursion which causes a major time complexity cost. Instead, we can improve it by little pre-processing. We first sort the given string and then apply the below code."
},
{
"code": null,
"e": 33343,
"s": 33296,
"text": "Below is the implementation of the above idea:"
},
{
"code": null,
"e": 33347,
"s": 33343,
"text": "C++"
},
{
"code": null,
"e": 33352,
"s": 33347,
"text": "Java"
},
{
"code": null,
"e": 33360,
"s": 33352,
"text": "Python3"
},
{
"code": null,
"e": 33371,
"s": 33360,
"text": "Javascript"
},
{
"code": "// C++ program to print all the permutation// of the given string.#include <algorithm>#include <iostream>#include <string>using namespace std; // count of total permutationsint total = 0; void permute(int i, string s){ // base case if (i == (s.length() - 1)) { cout << s << endl; total++; return; } char prev = '*'; // loop from j = 1 to length of string for (int j = i; j < s.length(); j++) { string temp = s; if (j > i && temp[i] == temp[j]) continue; if (prev != '*' && prev == s[j]) { continue; } // swap the elements swap(temp[i], temp[j]); prev = s[j]; // recursion call permute(i + 1, temp); }} // Driver codeint main(){ string s = \"abca\"; // sort sort(s.begin(), s.end()); // Function call permute(0, s); cout << \"Total distinct permutations = \" << total << endl; return 0;} // This code is contributed by risingStark.",
"e": 34382,
"s": 33371,
"text": null
},
{
"code": "// Java program to print all the permutation// of the given String.//include <algorithm> //include <String>import java.util.*; class GFG{ // Count of total permutationsstatic int total = 0; static void permute(int i, String s){ // Base case if (i == (s.length() - 1)) { System.out.print(s + \"\\n\"); total++; return; } char prev = '*'; // Loop from j = 1 to length of String for(int j = i; j < s.length(); j++) { char []temp = s.toCharArray(); if (j > i && temp[i] == temp[j]) continue; if (prev != '*' && prev == s.charAt(j)) { continue; } // Swap the elements temp = swap(temp,i,j); prev = s.charAt(j); // Recursion call permute(i + 1, String.valueOf(temp)); }} static char[] swap(char []arr, int i, int j){ char temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr;} static String sortString(String inputString){ // Convert input string to char array char tempArray[] = inputString.toCharArray(); // Sort tempArray Arrays.sort(tempArray); // Return new sorted string return new String(tempArray);} // Driver codepublic static void main(String[] args){ String s = \"abca\"; // Sort s = sortString(s); // Function call permute(0, s); System.out.print(\"Total distinct permutations = \" + total +\"\\n\");}} // This code is contributed by Amit Katiyar",
"e": 35890,
"s": 34382,
"text": null
},
{
"code": "# Python program to print all the permutation# of the given String. # Count of total permutationstotal = 0 def swap(arr, i, j): temp = arr[i] arr[i] = arr[j] arr[j] = temp return arr def permute(i, s): global total # Base case if(i == (len(s) - 1)): print(s) total += 1 return prev = '*' # Loop from j = 1 to length of String for j in range(i,len(s)): temp = list(s) if (j > i and temp[i] == temp[j]): continue if (prev != '*' and prev == s[j]): continue # Swap the elements temp = swap(temp,i,j) prev = s[j] # Recursion call permute(i + 1, \"\".join(temp)) def sortString(inputString): # Convert input string to char array tempArray = list(inputString) # Sort tempArray tempArray.sort() # Return new sorted string return \"\".join(tempArray) # Driver codes = \"abca\" # Sorts = sortString(s) # Function callpermute(0, s)print(f\"Total distinct permutations = {total}\") # This code is contributed by shinjanpatra",
"e": 36991,
"s": 35890,
"text": null
},
{
"code": "<script> // JavaScript program to print all the permutation// of the given String. // Count of total permutationslet total = 0;function permute(i,s){ // Base case if (i == (s.length - 1)) { document.write(s + \"<br>\"); total++; return; } let prev = '*'; // Loop from j = 1 to length of String for(let j = i; j < s.length; j++) { let temp = s.split(\"\"); if (j > i && temp[i] == temp[j]) continue; if (prev != '*' && prev == s[j]) { continue; } // Swap the elements temp = swap(temp,i,j); prev = s[j]; // Recursion call permute(i + 1, (temp).join(\"\")); }} function swap(arr,i,j){ let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr;} function sortString(inputString){ // Convert input string to char array let tempArray = inputString.split(\"\"); // Sort tempArray (tempArray).sort(); // Return new sorted string return (tempArray).join(\"\");} // Driver codelet s = \"abca\"; // Sorts = sortString(s); // Function callpermute(0, s);document.write(\"Total distinct permutations = \" + total +\"<br>\"); // This code is contributed by rag2127 </script>",
"e": 38268,
"s": 36991,
"text": null
},
{
"code": null,
"e": 38361,
"s": 38268,
"text": "aabc\naacb\nabac\nabca\nacba\nacab\nbaac\nbaca\nbcaa\ncaba\ncaab\ncbaa\nTotal distinct permutations = 12"
},
{
"code": null,
"e": 38602,
"s": 38361,
"text": "Time complexity: If we take the length of the string to be N, then the complexity of my code will be O(N log N) for sorting and O(N*N!) for the permutation. Total time complexity would be O(N log N + N*N!) which is effectively only O(N*N!)."
},
{
"code": null,
"e": 38612,
"s": 38602,
"text": "sadiqRaza"
},
{
"code": null,
"e": 38622,
"s": 38612,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 38634,
"s": 38622,
"text": "29AjayKumar"
},
{
"code": null,
"e": 38647,
"s": 38634,
"text": "rituraj_jain"
},
{
"code": null,
"e": 38663,
"s": 38647,
"text": "shreyashagrawal"
},
{
"code": null,
"e": 38675,
"s": 38663,
"text": "risingStark"
},
{
"code": null,
"e": 38697,
"s": 38675,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 38712,
"s": 38697,
"text": "amit143katiyar"
},
{
"code": null,
"e": 38720,
"s": 38712,
"text": "rag2127"
},
{
"code": null,
"e": 38733,
"s": 38720,
"text": "shinjanpatra"
},
{
"code": null,
"e": 38748,
"s": 38733,
"text": "adityakumar129"
},
{
"code": null,
"e": 38762,
"s": 38748,
"text": "Combinatorial"
},
{
"code": null,
"e": 38770,
"s": 38762,
"text": "Strings"
},
{
"code": null,
"e": 38778,
"s": 38770,
"text": "Strings"
},
{
"code": null,
"e": 38792,
"s": 38778,
"text": "Combinatorial"
},
{
"code": null,
"e": 38890,
"s": 38792,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38899,
"s": 38890,
"text": "Comments"
},
{
"code": null,
"e": 38912,
"s": 38899,
"text": "Old Comments"
},
{
"code": null,
"e": 38989,
"s": 38912,
"text": "Find the Number of Permutations that satisfy the given condition in an array"
},
{
"code": null,
"e": 39046,
"s": 38989,
"text": "Python program to get all subsets of given size of a set"
},
{
"code": null,
"e": 39087,
"s": 39046,
"text": "Print all subsets of given size of a set"
},
{
"code": null,
"e": 39154,
"s": 39087,
"text": "Find all distinct subsets of a given set using BitMasking Approach"
},
{
"code": null,
"e": 39186,
"s": 39154,
"text": "Make all combinations of size k"
},
{
"code": null,
"e": 39211,
"s": 39186,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 39257,
"s": 39211,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 39291,
"s": 39257,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 39306,
"s": 39291,
"text": "C++ Data Types"
}
] |
Generating random Idβs in Python
|
We use to generate a random number in our project for a sample data, which later can be used for testing, filled empty columns or for many other purposes, the key thing is we need to generate random data. In python, there are numerous ways to generate random data and we're going to explore some of them here in this article β
One of the important library, what comes with python is random and we are going to use it throughout in our code.
To use this module in your code, you just need to import it, thatβs it and we are ready to use it.
import random
Letβs see how to use it β
Live Demo
import random
print("What i will get, no idea as i'm using random.random()")
print(random.random())
What i will get, no idea as i'm using random.random()
0.5306626723173611
The second time, if I try to run the same program- youβll get different output β
What i will get, no idea as i'm using random.random()
0.5504289430397661
random() is the basic function of the random module
Almost all functions of the random module use random() function.
Random() function will generate any number between [0.0 to 1.0).
Below two functions weβre using to generate random integers β
randint()
randrange()
Live Demo
from random import randint, randrange
print("Printing random integer ", randint(0, 20))
print("Printing random integer ", randrange(0, 20, 2))
Printing random integer 15
Printing random integer 4
Consider we have a list of companies name and we want to retrieve an item(company name) from that list. We can achieve this by,
Live Demo
import random
companies = ['RELIANCE', 'TCS', 'INFY', 'SBI', 'PNB','HDFC']
print('Randomly selecting company from a list: ', random.choice(companies))
Randomly selecting company from a list: INFY
Consider the above example but instead of one item(company) we want to select multiple items(companies) randomly from a list, we can achieve this through, random.sample() function β
Live Demo
import random
companies = ['RELIANCE', 'TCS', 'INFY', 'SBI', 'PNB','HDFC']
print('Randomly selecting 3 companies from a list: ', random.sample(companies,3))
Randomly selecting 3 companies from a list: ['TCS', 'RELIANCE', 'INFY']
However, if we try to select items more than the number of items in the list, we encounter ValueError β
Input β
random.sample(companies,20)
output β
ValueError: Sample larger than population or is negative
Another method to select multiple random items from a list is β random.choices().
Live Demo
import random
companies = ['RELIANCE', 'TCS', 'INFY', 'SBI', 'PNB','HDFC']
print('Randomly selecting 3 companies from a list: ', random.choices(companies,k=6))
Randomly selecting 3 companies from a list: ['TCS', 'TCS', 'INFY', 'HDFC', 'INFY', 'TCS']
As we can see from the above output, we may get a duplicate item from the list on using random.choices() method.
Pseudo-random number generator work by performing some operation on a value. Generally, this value is the previous number generated by the generator. However, the first time you use the generator, there is no previous value.
Live Demo
import random
print("Seed value 10: ") # Initialize seed value
random.seed(10)
for i in range(5):
print(random.randint(1,100))
print()
print("Seed Value 5: ") # this time we'll get different values
random.seed(5)
for i in range(5):
print(random.randint(1,100))
print()
print("Seed value: 10") # will get the same result, what we got initially
random.seed(10)
for i in range(5):
print(random.randint(1,100))
Seed value 10:
74
5
55
62
74
Seed Value 5:
80
33
95
46
89
Seed value: 10
74
5
55
62
74
As we see from the above example, if the seed is the same, it generates the first previous value. Each seed value corresponds to a fixed sequence of generated value for a given random number generator.
We can generate a cryptographically secure random number in python 3.x. If we have python 3.6 or above we can use the new secrets module and the function rand below for it. It will generate a random number below the specified value.
Live Demo
import secrets
#generate 10 secure random numbers between 10 and 500
for x in range(0,10):
secV =10+ secrets.randbelow(500)
print(secV)
464
406
184
293
399
332
495
292
118
134
Another way for python 3.5 or below, we can use the random module and SystemRandom class to generate cryptographically secure random numbers is,
Live Demo
import random
randGen = random.SystemRandom()
for x in range(0,10):
secV = 10+ randGen.randint(0,499)
print(secV)
374
211
425
264
217
97
210
39
319
52
Another way is to use the random and secrets(to secure data) module.
Live Demo
import secrets
import random
secNum = random.SystemRandom().random()
print("secure number is ", secNum)
print("Secure byte token", secrets.token_bytes(16))
secure number is 0.5205307353786663
Secure byte token b'\x05T>\xacsqn0\x08\xc4\xf4\x8aU\x13\x9f\xcf'
|
[
{
"code": null,
"e": 1389,
"s": 1062,
"text": "We use to generate a random number in our project for a sample data, which later can be used for testing, filled empty columns or for many other purposes, the key thing is we need to generate random data. In python, there are numerous ways to generate random data and we're going to explore some of them here in this article β"
},
{
"code": null,
"e": 1503,
"s": 1389,
"text": "One of the important library, what comes with python is random and we are going to use it throughout in our code."
},
{
"code": null,
"e": 1602,
"s": 1503,
"text": "To use this module in your code, you just need to import it, thatβs it and we are ready to use it."
},
{
"code": null,
"e": 1616,
"s": 1602,
"text": "import random"
},
{
"code": null,
"e": 1642,
"s": 1616,
"text": "Letβs see how to use it β"
},
{
"code": null,
"e": 1653,
"s": 1642,
"text": " Live Demo"
},
{
"code": null,
"e": 1753,
"s": 1653,
"text": "import random\nprint(\"What i will get, no idea as i'm using random.random()\")\nprint(random.random())"
},
{
"code": null,
"e": 1826,
"s": 1753,
"text": "What i will get, no idea as i'm using random.random()\n0.5306626723173611"
},
{
"code": null,
"e": 1907,
"s": 1826,
"text": "The second time, if I try to run the same program- youβll get different output β"
},
{
"code": null,
"e": 1980,
"s": 1907,
"text": "What i will get, no idea as i'm using random.random()\n0.5504289430397661"
},
{
"code": null,
"e": 2032,
"s": 1980,
"text": "random() is the basic function of the random module"
},
{
"code": null,
"e": 2097,
"s": 2032,
"text": "Almost all functions of the random module use random() function."
},
{
"code": null,
"e": 2162,
"s": 2097,
"text": "Random() function will generate any number between [0.0 to 1.0)."
},
{
"code": null,
"e": 2224,
"s": 2162,
"text": "Below two functions weβre using to generate random integers β"
},
{
"code": null,
"e": 2234,
"s": 2224,
"text": "randint()"
},
{
"code": null,
"e": 2246,
"s": 2234,
"text": "randrange()"
},
{
"code": null,
"e": 2257,
"s": 2246,
"text": " Live Demo"
},
{
"code": null,
"e": 2400,
"s": 2257,
"text": "from random import randint, randrange\nprint(\"Printing random integer \", randint(0, 20))\nprint(\"Printing random integer \", randrange(0, 20, 2))"
},
{
"code": null,
"e": 2453,
"s": 2400,
"text": "Printing random integer 15\nPrinting random integer 4"
},
{
"code": null,
"e": 2581,
"s": 2453,
"text": "Consider we have a list of companies name and we want to retrieve an item(company name) from that list. We can achieve this by,"
},
{
"code": null,
"e": 2592,
"s": 2581,
"text": " Live Demo"
},
{
"code": null,
"e": 2743,
"s": 2592,
"text": "import random\ncompanies = ['RELIANCE', 'TCS', 'INFY', 'SBI', 'PNB','HDFC']\nprint('Randomly selecting company from a list: ', random.choice(companies))"
},
{
"code": null,
"e": 2788,
"s": 2743,
"text": "Randomly selecting company from a list: INFY"
},
{
"code": null,
"e": 2970,
"s": 2788,
"text": "Consider the above example but instead of one item(company) we want to select multiple items(companies) randomly from a list, we can achieve this through, random.sample() function β"
},
{
"code": null,
"e": 2981,
"s": 2970,
"text": " Live Demo"
},
{
"code": null,
"e": 3138,
"s": 2981,
"text": "import random\ncompanies = ['RELIANCE', 'TCS', 'INFY', 'SBI', 'PNB','HDFC']\nprint('Randomly selecting 3 companies from a list: ', random.sample(companies,3))"
},
{
"code": null,
"e": 3210,
"s": 3138,
"text": "Randomly selecting 3 companies from a list: ['TCS', 'RELIANCE', 'INFY']"
},
{
"code": null,
"e": 3314,
"s": 3210,
"text": "However, if we try to select items more than the number of items in the list, we encounter ValueError β"
},
{
"code": null,
"e": 3322,
"s": 3314,
"text": "Input β"
},
{
"code": null,
"e": 3350,
"s": 3322,
"text": "random.sample(companies,20)"
},
{
"code": null,
"e": 3359,
"s": 3350,
"text": "output β"
},
{
"code": null,
"e": 3416,
"s": 3359,
"text": "ValueError: Sample larger than population or is negative"
},
{
"code": null,
"e": 3498,
"s": 3416,
"text": "Another method to select multiple random items from a list is β random.choices()."
},
{
"code": null,
"e": 3509,
"s": 3498,
"text": " Live Demo"
},
{
"code": null,
"e": 3669,
"s": 3509,
"text": "import random\ncompanies = ['RELIANCE', 'TCS', 'INFY', 'SBI', 'PNB','HDFC']\nprint('Randomly selecting 3 companies from a list: ', random.choices(companies,k=6))"
},
{
"code": null,
"e": 3759,
"s": 3669,
"text": "Randomly selecting 3 companies from a list: ['TCS', 'TCS', 'INFY', 'HDFC', 'INFY', 'TCS']"
},
{
"code": null,
"e": 3872,
"s": 3759,
"text": "As we can see from the above output, we may get a duplicate item from the list on using random.choices() method."
},
{
"code": null,
"e": 4097,
"s": 3872,
"text": "Pseudo-random number generator work by performing some operation on a value. Generally, this value is the previous number generated by the generator. However, the first time you use the generator, there is no previous value."
},
{
"code": null,
"e": 4108,
"s": 4097,
"text": " Live Demo"
},
{
"code": null,
"e": 4515,
"s": 4108,
"text": "import random\nprint(\"Seed value 10: \") # Initialize seed value\nrandom.seed(10)\nfor i in range(5):\nprint(random.randint(1,100))\nprint()\nprint(\"Seed Value 5: \") # this time we'll get different values\nrandom.seed(5)\nfor i in range(5):\nprint(random.randint(1,100))\nprint()\nprint(\"Seed value: 10\") # will get the same result, what we got initially\nrandom.seed(10)\nfor i in range(5):\nprint(random.randint(1,100))"
},
{
"code": null,
"e": 4602,
"s": 4515,
"text": "Seed value 10:\n74\n5\n55\n62\n74\nSeed Value 5:\n80\n33\n95\n46\n89\nSeed value: 10\n74\n5\n55\n62\n74"
},
{
"code": null,
"e": 4804,
"s": 4602,
"text": "As we see from the above example, if the seed is the same, it generates the first previous value. Each seed value corresponds to a fixed sequence of generated value for a given random number generator."
},
{
"code": null,
"e": 5037,
"s": 4804,
"text": "We can generate a cryptographically secure random number in python 3.x. If we have python 3.6 or above we can use the new secrets module and the function rand below for it. It will generate a random number below the specified value."
},
{
"code": null,
"e": 5048,
"s": 5037,
"text": " Live Demo"
},
{
"code": null,
"e": 5184,
"s": 5048,
"text": "import secrets\n#generate 10 secure random numbers between 10 and 500\nfor x in range(0,10):\nsecV =10+ secrets.randbelow(500)\nprint(secV)"
},
{
"code": null,
"e": 5224,
"s": 5184,
"text": "464\n406\n184\n293\n399\n332\n495\n292\n118\n134"
},
{
"code": null,
"e": 5369,
"s": 5224,
"text": "Another way for python 3.5 or below, we can use the random module and SystemRandom class to generate cryptographically secure random numbers is,"
},
{
"code": null,
"e": 5380,
"s": 5369,
"text": " Live Demo"
},
{
"code": null,
"e": 5494,
"s": 5380,
"text": "import random\nrandGen = random.SystemRandom()\nfor x in range(0,10):\nsecV = 10+ randGen.randint(0,499)\nprint(secV)"
},
{
"code": null,
"e": 5531,
"s": 5494,
"text": "374\n211\n425\n264\n217\n97\n210\n39\n319\n52"
},
{
"code": null,
"e": 5600,
"s": 5531,
"text": "Another way is to use the random and secrets(to secure data) module."
},
{
"code": null,
"e": 5611,
"s": 5600,
"text": " Live Demo"
},
{
"code": null,
"e": 5767,
"s": 5611,
"text": "import secrets\nimport random\nsecNum = random.SystemRandom().random()\nprint(\"secure number is \", secNum)\nprint(\"Secure byte token\", secrets.token_bytes(16))"
},
{
"code": null,
"e": 5868,
"s": 5767,
"text": "secure number is 0.5205307353786663\nSecure byte token b'\\x05T>\\xacsqn0\\x08\\xc4\\xf4\\x8aU\\x13\\x9f\\xcf'"
}
] |
Do you think Python Dictionary is really Mutable?
|
Yes, Python Dictionary is mutable. Changing references to keys doesn't lead to the creation of new dictionaries. Rather it updates the current dictionary in place.
a = {'foo': 1, 'bar': 12}
b = a
b['foo'] = 20
print(a)
print(b)
This will give the output β
{'foo': 20, 'bar': 12}
{'foo': 20, 'bar': 12}
|
[
{
"code": null,
"e": 1227,
"s": 1062,
"text": "Yes, Python Dictionary is mutable. Changing references to keys doesn't lead to the creation of new dictionaries. Rather it updates the current dictionary in place. "
},
{
"code": null,
"e": 1292,
"s": 1227,
"text": "a = {'foo': 1, 'bar': 12}\nb = a\nb['foo'] = 20\n\nprint(a)\nprint(b)"
},
{
"code": null,
"e": 1320,
"s": 1292,
"text": "This will give the output β"
},
{
"code": null,
"e": 1366,
"s": 1320,
"text": "{'foo': 20, 'bar': 12}\n{'foo': 20, 'bar': 12}"
}
] |
Difference between Inline and Macro in C++ - GeeksforGeeks
|
28 Jun, 2020
1. Inline :An inline function is a normal function that is defined by the inline keyword. An inline function is a short function that is expanded by the compiler. And its arguments are evaluated only once. An inline functions are the short length functions that are automatically made the inline functions without using the inline keyword inside the class.
Syntax of an Inline function:
inline return_type function_name ( parameters )
{
// inline function code
}
Example of an Inline function:
#include <iostream>using namespace std; // Inline functioninline int Maximum(int a, int b){ return (a > b) ? a : b;} // Main function for the programint main(){ cout << "Max (100, 1000):" << Maximum(100, 1000) << endl; cout << "Max (20, 0): " << Maximum(20, 0) << endl; return 0;}
Output:
Max (100, 1000): 1000
Max (20, 0): 20
2. Macro :It is also called preprocessors directive. The macros are defined by the #define keyword. Before the program compilation, the preprocessor examines the program whenever the preprocessor detects the macros then preprocessor replaces the macro by the macro definition.
Syntax of Macro:
#define MACRO_NAME Macro_definition
Example of Macro:
#include <iostream>using namespace std; // macro with parameter#define MAXIMUM(a, b) (a > b) ? a : b // Main function for the programint main(){ cout << "Max (100, 1000):"; int k = MAXIMUM(100, 1000); cout << k << endl; cout << "Max (20, 0):"; int k1 = MAXIMUM(20, 0); cout << k1; return 0;}
Output:
Max (100, 1000):1000
Max (20, 0):20
Difference between Inline and Macro in C++ :
pp_pankaj
ashushrma378
C++
Difference Between
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++
Inline Functions in C++
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
|
[
{
"code": null,
"e": 24042,
"s": 24014,
"text": "\n28 Jun, 2020"
},
{
"code": null,
"e": 24399,
"s": 24042,
"text": "1. Inline :An inline function is a normal function that is defined by the inline keyword. An inline function is a short function that is expanded by the compiler. And its arguments are evaluated only once. An inline functions are the short length functions that are automatically made the inline functions without using the inline keyword inside the class."
},
{
"code": null,
"e": 24429,
"s": 24399,
"text": "Syntax of an Inline function:"
},
{
"code": null,
"e": 24508,
"s": 24429,
"text": "inline return_type function_name ( parameters )\n{ \n // inline function code\n}\n"
},
{
"code": null,
"e": 24539,
"s": 24508,
"text": "Example of an Inline function:"
},
{
"code": "#include <iostream>using namespace std; // Inline functioninline int Maximum(int a, int b){ return (a > b) ? a : b;} // Main function for the programint main(){ cout << \"Max (100, 1000):\" << Maximum(100, 1000) << endl; cout << \"Max (20, 0): \" << Maximum(20, 0) << endl; return 0;}",
"e": 24836,
"s": 24539,
"text": null
},
{
"code": null,
"e": 24844,
"s": 24836,
"text": "Output:"
},
{
"code": null,
"e": 24883,
"s": 24844,
"text": "Max (100, 1000): 1000\nMax (20, 0): 20 "
},
{
"code": null,
"e": 25160,
"s": 24883,
"text": "2. Macro :It is also called preprocessors directive. The macros are defined by the #define keyword. Before the program compilation, the preprocessor examines the program whenever the preprocessor detects the macros then preprocessor replaces the macro by the macro definition."
},
{
"code": null,
"e": 25177,
"s": 25160,
"text": "Syntax of Macro:"
},
{
"code": null,
"e": 25214,
"s": 25177,
"text": "#define MACRO_NAME Macro_definition "
},
{
"code": null,
"e": 25232,
"s": 25214,
"text": "Example of Macro:"
},
{
"code": "#include <iostream>using namespace std; // macro with parameter#define MAXIMUM(a, b) (a > b) ? a : b // Main function for the programint main(){ cout << \"Max (100, 1000):\"; int k = MAXIMUM(100, 1000); cout << k << endl; cout << \"Max (20, 0):\"; int k1 = MAXIMUM(20, 0); cout << k1; return 0;}",
"e": 25551,
"s": 25232,
"text": null
},
{
"code": null,
"e": 25559,
"s": 25551,
"text": "Output:"
},
{
"code": null,
"e": 25596,
"s": 25559,
"text": "Max (100, 1000):1000\nMax (20, 0):20 "
},
{
"code": null,
"e": 25641,
"s": 25596,
"text": "Difference between Inline and Macro in C++ :"
},
{
"code": null,
"e": 25651,
"s": 25641,
"text": "pp_pankaj"
},
{
"code": null,
"e": 25664,
"s": 25651,
"text": "ashushrma378"
},
{
"code": null,
"e": 25668,
"s": 25664,
"text": "C++"
},
{
"code": null,
"e": 25687,
"s": 25668,
"text": "Difference Between"
},
{
"code": null,
"e": 25691,
"s": 25687,
"text": "CPP"
},
{
"code": null,
"e": 25789,
"s": 25691,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25798,
"s": 25789,
"text": "Comments"
},
{
"code": null,
"e": 25811,
"s": 25798,
"text": "Old Comments"
},
{
"code": null,
"e": 25832,
"s": 25811,
"text": "Iterators in C++ STL"
},
{
"code": null,
"e": 25860,
"s": 25832,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 25893,
"s": 25860,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 25913,
"s": 25893,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 25937,
"s": 25913,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 25968,
"s": 25937,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 26008,
"s": 25968,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 26040,
"s": 26008,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 26101,
"s": 26040,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
Timer in C#
|
The namespace used to set a timer is System. Timers. The Timer class generates an event after a set interval, with an option to generate recurring events.
Firstly, create a timer object for 5 seconds interval β
timer = new System.Timers.Timer(5000);
Set elapsed event for the timer. This occurs when the interval elapses β
timer.Elapsed += OnTimedEvent;
Now start the timer.
timer.Enabled = true;
using System;
using System.Timers;
public class Demo {
private static Timer timer;
public static void Main() {
timer = new System.Timers.Timer();
timer.Interval = 5000;
timer.Elapsed += OnTimedEvent;
timer.AutoReset = true;
timer.Enabled = true;
Console.WriteLine("Press the Enter key to exit anytime... ");
Console.ReadLine();
}
private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e) {
Console.WriteLine("Raised: {0}", e.SignalTime);
}
}
|
[
{
"code": null,
"e": 1217,
"s": 1062,
"text": "The namespace used to set a timer is System. Timers. The Timer class generates an event after a set interval, with an option to generate recurring events."
},
{
"code": null,
"e": 1273,
"s": 1217,
"text": "Firstly, create a timer object for 5 seconds interval β"
},
{
"code": null,
"e": 1312,
"s": 1273,
"text": "timer = new System.Timers.Timer(5000);"
},
{
"code": null,
"e": 1385,
"s": 1312,
"text": "Set elapsed event for the timer. This occurs when the interval elapses β"
},
{
"code": null,
"e": 1416,
"s": 1385,
"text": "timer.Elapsed += OnTimedEvent;"
},
{
"code": null,
"e": 1437,
"s": 1416,
"text": "Now start the timer."
},
{
"code": null,
"e": 1459,
"s": 1437,
"text": "timer.Enabled = true;"
},
{
"code": null,
"e": 1993,
"s": 1459,
"text": "using System;\nusing System.Timers;\n\npublic class Demo {\n private static Timer timer;\n\n public static void Main() {\n timer = new System.Timers.Timer();\n timer.Interval = 5000;\n\n timer.Elapsed += OnTimedEvent;\n timer.AutoReset = true;\n timer.Enabled = true;\n\n Console.WriteLine(\"Press the Enter key to exit anytime... \");\n Console.ReadLine();\n }\n\n private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e) {\n Console.WriteLine(\"Raised: {0}\", e.SignalTime);\n }\n}"
}
] |
6 Examples to Master Python Generators | by Soner YΔ±ldΔ±rΔ±m | Towards Data Science
|
The generators in Python are one of those tools that we frequently use but do not talk about much. For instance, most for loops are accompanied with the range function which is a generator.
Generators allow for generating a sequence of values over time. The main advantage of using a generator is that we do not have to create the entire sequence at once and allocate memory. Instead, the generator returns one value at a time and waits until the next value is called.
In this article, we will go over 6 examples to demonstrate how generators are used in Python as well as some tips to keep in mind.
Letβs start with a simple yet frequently used generator. The range function is used for iterating over a range of values determined by the given start, stop, and step size.
range(5)out> range(0, 5)for i in range(5): print(i)01234
If you execute the range function, you will not get any value returned. However, we can iterate over it in a for loop to access the values in order. To provide the flow of numbers in a sequence, the range function keeps track of the last number and the step size.
We can also view the entire sequence by converting a generator to a list.
list(range(5))[0, 1, 2, 3, 4]
We can create our own generator functions. The syntax is quite similar to creating a normal function but there is a critical difference.
The following is a generator function that returns the cube of every other number in a given range starting from 1.
def mygenerator(n): for i in range(1, n, 2): yield i**3
The main difference between a generator and a normal function is that we do not use the return keyword. Instead, the yield keyword is used.
We can now use our generator in a for loop:
for i in mygenerator(10): print(i)1 27 125 343 729
Another way to create a generator is by using a generator expression. It is similar to a list comprehension.
mygenerator = (i**3 for i in range(1,10,2))mygenerator<generator object <genexpr> at 0x7f867be7b9d0>
We can now iterate over it.
for i in mygenerator: print(i)1 27 125 343 729
It is important to note that once we iterate over a generator and reach the end, we can not iterate over it again. For example, if we rerun the for loop above, it will not return anything.
This is not the case in example 2 because we had a generator function which creates a generator each time it is executed. You may notice that we do not have a function call in this example. Instead, we have a generator object.
We can iterate over a generator manually by using the next function. Letβs first create a new generator object.
def mygenerator(n): for i in range(1, n, 2): yield i * (i + 1)my_gen = mygenerator(6)
We can now use the next function to ask for the next value that the generator will return.
next(my_gen)2next(my_gen)12next(my_gen)30next(my_gen)> StopIteration error
If we call the next function on the generator after we reach the end, it will return a StopIteration error. The for loop does the same steps as we do with the next function. However, we do not get a StopIteration error when using a for loop because it automatically catches this error.
We often see the terms iterable and iterator. An iterable is an object that we can iterate over such as lists, sets, strings, and so on. However, we cannot take iterable objects as iterators.
There is a built-in Python function that converts an iterable to an iterator. Surprisingly, it is the iter function. For instance, we can iterate over strings but cannot use them as iterators. The iter function allows using strings as iterators.
my_string = "Python"next(my_string)> TypeError: 'str' object is not an iterator
Letβs convert it to an iterator and then call the next function again.
my_string_new = iter(my_string)next(my_string_new)'P'next(my_string_new)'y'
The iter function can also be used to convert a list to an iterator.
my_list = ['a', 'b', 'c', 'd', 'e']my_gen = iter(my_list)type(my_gen)list_iterator
Letβs use it in a for loop.
for i in my_gen: print(i)abcde
Generators are pretty useful when working with sequences that allocate a large amount of memory. Generators support an iteration protocol so when we call them, they do not return a value and exit.
After the next value in the sequence is generated, they automatically suspend and resume their execution state at the last point when the next value is asked for.
The advantage is that instead of having to compute the entire sequence at once, generators compute one value at a time and wait until the next value is called for.
Thank you for reading. Please let me know if you have any feedback.
|
[
{
"code": null,
"e": 362,
"s": 172,
"text": "The generators in Python are one of those tools that we frequently use but do not talk about much. For instance, most for loops are accompanied with the range function which is a generator."
},
{
"code": null,
"e": 641,
"s": 362,
"text": "Generators allow for generating a sequence of values over time. The main advantage of using a generator is that we do not have to create the entire sequence at once and allocate memory. Instead, the generator returns one value at a time and waits until the next value is called."
},
{
"code": null,
"e": 772,
"s": 641,
"text": "In this article, we will go over 6 examples to demonstrate how generators are used in Python as well as some tips to keep in mind."
},
{
"code": null,
"e": 945,
"s": 772,
"text": "Letβs start with a simple yet frequently used generator. The range function is used for iterating over a range of values determined by the given start, stop, and step size."
},
{
"code": null,
"e": 1004,
"s": 945,
"text": "range(5)out> range(0, 5)for i in range(5): print(i)01234"
},
{
"code": null,
"e": 1268,
"s": 1004,
"text": "If you execute the range function, you will not get any value returned. However, we can iterate over it in a for loop to access the values in order. To provide the flow of numbers in a sequence, the range function keeps track of the last number and the step size."
},
{
"code": null,
"e": 1342,
"s": 1268,
"text": "We can also view the entire sequence by converting a generator to a list."
},
{
"code": null,
"e": 1372,
"s": 1342,
"text": "list(range(5))[0, 1, 2, 3, 4]"
},
{
"code": null,
"e": 1509,
"s": 1372,
"text": "We can create our own generator functions. The syntax is quite similar to creating a normal function but there is a critical difference."
},
{
"code": null,
"e": 1625,
"s": 1509,
"text": "The following is a generator function that returns the cube of every other number in a given range starting from 1."
},
{
"code": null,
"e": 1688,
"s": 1625,
"text": "def mygenerator(n): for i in range(1, n, 2): yield i**3"
},
{
"code": null,
"e": 1828,
"s": 1688,
"text": "The main difference between a generator and a normal function is that we do not use the return keyword. Instead, the yield keyword is used."
},
{
"code": null,
"e": 1872,
"s": 1828,
"text": "We can now use our generator in a for loop:"
},
{
"code": null,
"e": 1925,
"s": 1872,
"text": "for i in mygenerator(10): print(i)1 27 125 343 729"
},
{
"code": null,
"e": 2034,
"s": 1925,
"text": "Another way to create a generator is by using a generator expression. It is similar to a list comprehension."
},
{
"code": null,
"e": 2135,
"s": 2034,
"text": "mygenerator = (i**3 for i in range(1,10,2))mygenerator<generator object <genexpr> at 0x7f867be7b9d0>"
},
{
"code": null,
"e": 2163,
"s": 2135,
"text": "We can now iterate over it."
},
{
"code": null,
"e": 2212,
"s": 2163,
"text": "for i in mygenerator: print(i)1 27 125 343 729"
},
{
"code": null,
"e": 2401,
"s": 2212,
"text": "It is important to note that once we iterate over a generator and reach the end, we can not iterate over it again. For example, if we rerun the for loop above, it will not return anything."
},
{
"code": null,
"e": 2628,
"s": 2401,
"text": "This is not the case in example 2 because we had a generator function which creates a generator each time it is executed. You may notice that we do not have a function call in this example. Instead, we have a generator object."
},
{
"code": null,
"e": 2740,
"s": 2628,
"text": "We can iterate over a generator manually by using the next function. Letβs first create a new generator object."
},
{
"code": null,
"e": 2833,
"s": 2740,
"text": "def mygenerator(n): for i in range(1, n, 2): yield i * (i + 1)my_gen = mygenerator(6)"
},
{
"code": null,
"e": 2924,
"s": 2833,
"text": "We can now use the next function to ask for the next value that the generator will return."
},
{
"code": null,
"e": 2999,
"s": 2924,
"text": "next(my_gen)2next(my_gen)12next(my_gen)30next(my_gen)> StopIteration error"
},
{
"code": null,
"e": 3285,
"s": 2999,
"text": "If we call the next function on the generator after we reach the end, it will return a StopIteration error. The for loop does the same steps as we do with the next function. However, we do not get a StopIteration error when using a for loop because it automatically catches this error."
},
{
"code": null,
"e": 3477,
"s": 3285,
"text": "We often see the terms iterable and iterator. An iterable is an object that we can iterate over such as lists, sets, strings, and so on. However, we cannot take iterable objects as iterators."
},
{
"code": null,
"e": 3723,
"s": 3477,
"text": "There is a built-in Python function that converts an iterable to an iterator. Surprisingly, it is the iter function. For instance, we can iterate over strings but cannot use them as iterators. The iter function allows using strings as iterators."
},
{
"code": null,
"e": 3803,
"s": 3723,
"text": "my_string = \"Python\"next(my_string)> TypeError: 'str' object is not an iterator"
},
{
"code": null,
"e": 3874,
"s": 3803,
"text": "Letβs convert it to an iterator and then call the next function again."
},
{
"code": null,
"e": 3950,
"s": 3874,
"text": "my_string_new = iter(my_string)next(my_string_new)'P'next(my_string_new)'y'"
},
{
"code": null,
"e": 4019,
"s": 3950,
"text": "The iter function can also be used to convert a list to an iterator."
},
{
"code": null,
"e": 4102,
"s": 4019,
"text": "my_list = ['a', 'b', 'c', 'd', 'e']my_gen = iter(my_list)type(my_gen)list_iterator"
},
{
"code": null,
"e": 4130,
"s": 4102,
"text": "Letβs use it in a for loop."
},
{
"code": null,
"e": 4163,
"s": 4130,
"text": "for i in my_gen: print(i)abcde"
},
{
"code": null,
"e": 4360,
"s": 4163,
"text": "Generators are pretty useful when working with sequences that allocate a large amount of memory. Generators support an iteration protocol so when we call them, they do not return a value and exit."
},
{
"code": null,
"e": 4523,
"s": 4360,
"text": "After the next value in the sequence is generated, they automatically suspend and resume their execution state at the last point when the next value is asked for."
},
{
"code": null,
"e": 4687,
"s": 4523,
"text": "The advantage is that instead of having to compute the entire sequence at once, generators compute one value at a time and wait until the next value is called for."
}
] |
Identifying Outliers with Local Outlier Probabilities | by Valentino Constantinou | Towards Data Science
|
Locating outliers is important in a variety of data science tasks, from performing predictive modeling to determining outliers in historical data. Many types of approaches exist to identifying outliers in your data. Local Outlier Probabilities, or LoOP, is just one approach. While not capable of detecting more complex anomalies that occur well within the distribution of the data, LoOP is an ideal approach for detecting anomalies that fall outside of the typical multivariate distribution.
The outlier score of each sample is called the Local Outlier Probability. It measures the local deviation of density of a given sample with respect to its neighbors as Local Outlier Factor (LOF) of which it is based, but provides normalized outlier scores in the range [0,1]. These outlier scores are directly interpretable as a probability of an object being an outlier. Since Local Outlier Probabilities provides scores in the range [0,1], it is straight forward to interpret the results according to the application.
Like LOF, it is local in that the anomaly score depends on how isolated the sample is with respect to the surrounding neighborhood. Locality is given by k-nearest neighbors, whose distance is used to estimate the local density. By comparing the local density of a sample to the local densities of its neighbors, one can identify samples that lie in regions of lower density compared to their neighbors and thus identify samples that may be outliers according to their Local Outlier Probability.
We can illustrate how LoOP works by using Iris dataset and the PyNomaly library, a Python implementation that also provides just-in-time (JIT) compilation via Numba for large datasets (it is Python only by default). The Iris dataset contains only 150 observations, 50 within each class of Iris flower. One of the classes, or Iris flower types, is linearly separable from the others β the other two are not linearly separable from one another. This can be seen by applying a clustering algorithm such as Density-Based Spatial Clustering of Applications with Noise (DBSCAN).
# library importsimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport pandas as pdfrom pydataset import datafrom sklearn.cluster import DBSCAN# import the data and remove any non-numeric columnsiris = pd.DataFrame(data('iris'))iris = pd.DataFrame(iris.drop('Species', 1))# apply DBSCAN clusteringdb = DBSCAN(eps=0.9, min_samples=10).fit(iris)iris['labels'] = db.labels_# and plot the clustersfig = plt.figure(figsize=(7, 7))ax = fig.add_subplot(111, projection='3d')ax.scatter(iris['Sepal.Width'], iris['Petal.Width'], iris['Sepal.Length'],c=iris['labels'], cmap='Set1', s=50)ax.set_xlabel('Sepal.Width')ax.set_ylabel('Petal.Width')ax.set_zlabel('Sepal.Length')plt.show()plt.clf()plt.cla()plt.close()
When applying LoOP to the data, it is intuitive to expect that values along the edges of the scatter field to be identified as more likely to be outliers since these fall outside the typical values in the dataβs distribution. By default, PyNomaly applies LoOP across all observations (illustrated with varying distance metrics used), but can also be applied with respect to each cluster if desired. Two parameters β the extent and n_neighbors (number of neighbors) β directly influence the resulting LoOP scores, and can be directly specified:
from PyNomaly import loop# using the same iris dataset as above...m = loop.LocalOutlierProbability(iris, extent=3, n_neighbors=20).fit()scores = m.local_outlier_probabilitiesprint(scores)
The extent parameter controls the sensitivity of the scoring in practice. The parameter corresponds to the statistical notion of an outlier defined as an object deviating more than a given lambda (extent) times the standard deviation from the mean. A value of 2 implies outliers deviating more than 2 standard deviations from the mean, and corresponds to 95.0% in the empirical βthree-sigmaβ rule. The question to ask is whether it is more reasonable to assume outliers in your data are 1, 2, or 3 standard deviations from the mean, and select the value likely most appropriate to your data and application.
The n_neighbors parameter, on the other hand, defines the number of neighbors to consider about each sample (neighborhood size) when determining its Local Outlier Probability with respect to the density of the sampleβs defined neighborhood. The idea number of neighbors to consider is dependent on the input data. However, the notion of an outlier implies it would be considered as such regardless of the number of neighbors considered. One potential approach is to use a number of different neighborhood sizes and average the results for reach observation. Those observations which rank highly with varying neighborhood sizes are more than likely outliers. Another is to select a value proportional to the number of observations, such an odd-valued integer close to the square root of the number of observations in your data. The ideal choice, again, varies depending on the data and its characteristics.
Local Outlier Probabilities (LoOP) is a useful approach to be aware of and to apply in certain contexts, and has since been extended to work in specific use cases such as with streaming data (an extension available in PyNomaly, together with more examples of LoOP in practice). This approach can help identify anomalies defined according to their suitability within the multivariate distribution of a set of data, and is often a great starting point for identifying less-complex data outliers (anomalies) in a practical, programmable, and interpretable way.
|
[
{
"code": null,
"e": 665,
"s": 172,
"text": "Locating outliers is important in a variety of data science tasks, from performing predictive modeling to determining outliers in historical data. Many types of approaches exist to identifying outliers in your data. Local Outlier Probabilities, or LoOP, is just one approach. While not capable of detecting more complex anomalies that occur well within the distribution of the data, LoOP is an ideal approach for detecting anomalies that fall outside of the typical multivariate distribution."
},
{
"code": null,
"e": 1185,
"s": 665,
"text": "The outlier score of each sample is called the Local Outlier Probability. It measures the local deviation of density of a given sample with respect to its neighbors as Local Outlier Factor (LOF) of which it is based, but provides normalized outlier scores in the range [0,1]. These outlier scores are directly interpretable as a probability of an object being an outlier. Since Local Outlier Probabilities provides scores in the range [0,1], it is straight forward to interpret the results according to the application."
},
{
"code": null,
"e": 1680,
"s": 1185,
"text": "Like LOF, it is local in that the anomaly score depends on how isolated the sample is with respect to the surrounding neighborhood. Locality is given by k-nearest neighbors, whose distance is used to estimate the local density. By comparing the local density of a sample to the local densities of its neighbors, one can identify samples that lie in regions of lower density compared to their neighbors and thus identify samples that may be outliers according to their Local Outlier Probability."
},
{
"code": null,
"e": 2253,
"s": 1680,
"text": "We can illustrate how LoOP works by using Iris dataset and the PyNomaly library, a Python implementation that also provides just-in-time (JIT) compilation via Numba for large datasets (it is Python only by default). The Iris dataset contains only 150 observations, 50 within each class of Iris flower. One of the classes, or Iris flower types, is linearly separable from the others β the other two are not linearly separable from one another. This can be seen by applying a clustering algorithm such as Density-Based Spatial Clustering of Applications with Noise (DBSCAN)."
},
{
"code": null,
"e": 2978,
"s": 2253,
"text": "# library importsimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport pandas as pdfrom pydataset import datafrom sklearn.cluster import DBSCAN# import the data and remove any non-numeric columnsiris = pd.DataFrame(data('iris'))iris = pd.DataFrame(iris.drop('Species', 1))# apply DBSCAN clusteringdb = DBSCAN(eps=0.9, min_samples=10).fit(iris)iris['labels'] = db.labels_# and plot the clustersfig = plt.figure(figsize=(7, 7))ax = fig.add_subplot(111, projection='3d')ax.scatter(iris['Sepal.Width'], iris['Petal.Width'], iris['Sepal.Length'],c=iris['labels'], cmap='Set1', s=50)ax.set_xlabel('Sepal.Width')ax.set_ylabel('Petal.Width')ax.set_zlabel('Sepal.Length')plt.show()plt.clf()plt.cla()plt.close()"
},
{
"code": null,
"e": 3522,
"s": 2978,
"text": "When applying LoOP to the data, it is intuitive to expect that values along the edges of the scatter field to be identified as more likely to be outliers since these fall outside the typical values in the dataβs distribution. By default, PyNomaly applies LoOP across all observations (illustrated with varying distance metrics used), but can also be applied with respect to each cluster if desired. Two parameters β the extent and n_neighbors (number of neighbors) β directly influence the resulting LoOP scores, and can be directly specified:"
},
{
"code": null,
"e": 3710,
"s": 3522,
"text": "from PyNomaly import loop# using the same iris dataset as above...m = loop.LocalOutlierProbability(iris, extent=3, n_neighbors=20).fit()scores = m.local_outlier_probabilitiesprint(scores)"
},
{
"code": null,
"e": 4318,
"s": 3710,
"text": "The extent parameter controls the sensitivity of the scoring in practice. The parameter corresponds to the statistical notion of an outlier defined as an object deviating more than a given lambda (extent) times the standard deviation from the mean. A value of 2 implies outliers deviating more than 2 standard deviations from the mean, and corresponds to 95.0% in the empirical βthree-sigmaβ rule. The question to ask is whether it is more reasonable to assume outliers in your data are 1, 2, or 3 standard deviations from the mean, and select the value likely most appropriate to your data and application."
},
{
"code": null,
"e": 5224,
"s": 4318,
"text": "The n_neighbors parameter, on the other hand, defines the number of neighbors to consider about each sample (neighborhood size) when determining its Local Outlier Probability with respect to the density of the sampleβs defined neighborhood. The idea number of neighbors to consider is dependent on the input data. However, the notion of an outlier implies it would be considered as such regardless of the number of neighbors considered. One potential approach is to use a number of different neighborhood sizes and average the results for reach observation. Those observations which rank highly with varying neighborhood sizes are more than likely outliers. Another is to select a value proportional to the number of observations, such an odd-valued integer close to the square root of the number of observations in your data. The ideal choice, again, varies depending on the data and its characteristics."
}
] |
Java & MySQL - Sample Code
|
This chapter provides an example of how to create a simple java based application to access MySQL database. This will show you how to open a database connection, execute a SQL query, and display the results.
All the steps mentioned in this template example, would be explained in subsequent chapters of this tutorial.
There are following six steps involved in building a JDBC application β
Import the packages: Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Import the packages: Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Open a connection: Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database.
Open a connection: Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database.
Execute a query: Requires using an object of type Statement for building and submitting an SQL statement to the database.
Execute a query: Requires using an object of type Statement for building and submitting an SQL statement to the database.
Extract data from result set β Requires that you use the appropriate ResultSet.getXXX() method to retrieve the data from the result set.
Extract data from result set β Requires that you use the appropriate ResultSet.getXXX() method to retrieve the data from the result set.
Clean up the environment β Requires explicitly closing all database resources versus relying on the JVM's garbage collection.
Clean up the environment β Requires explicitly closing all database resources versus relying on the JVM's garbage collection.
This sample example can serve as a template when you need to create your own JDBC application in the future.
This sample code has been written based on the environment and database setup done in the previous chapter.
Copy and paste the following example in TestApplication.java, compile and run as follows β
import java.sql.*;
public class TestApplication {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM Employees";
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(QUERY);) {
// Extract data from result set
while (rs.next()) {
// Retrieve by column name
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now let us compile the above example as follows β
C:\>javac TestApplication.java
C:\>
When you run TestApplication, it produces the following result β
C:\>java TestApplication
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2894,
"s": 2686,
"text": "This chapter provides an example of how to create a simple java based application to access MySQL database. This will show you how to open a database connection, execute a SQL query, and display the results."
},
{
"code": null,
"e": 3004,
"s": 2894,
"text": "All the steps mentioned in this template example, would be explained in subsequent chapters of this tutorial."
},
{
"code": null,
"e": 3076,
"s": 3004,
"text": "There are following six steps involved in building a JDBC application β"
},
{
"code": null,
"e": 3247,
"s": 3076,
"text": "Import the packages: Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 3418,
"s": 3247,
"text": "Import the packages: Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 3582,
"s": 3418,
"text": "Open a connection: Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database."
},
{
"code": null,
"e": 3746,
"s": 3582,
"text": "Open a connection: Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database."
},
{
"code": null,
"e": 3868,
"s": 3746,
"text": "Execute a query: Requires using an object of type Statement for building and submitting an SQL statement to the database."
},
{
"code": null,
"e": 3990,
"s": 3868,
"text": "Execute a query: Requires using an object of type Statement for building and submitting an SQL statement to the database."
},
{
"code": null,
"e": 4127,
"s": 3990,
"text": "Extract data from result set β Requires that you use the appropriate ResultSet.getXXX() method to retrieve the data from the result set."
},
{
"code": null,
"e": 4264,
"s": 4127,
"text": "Extract data from result set β Requires that you use the appropriate ResultSet.getXXX() method to retrieve the data from the result set."
},
{
"code": null,
"e": 4390,
"s": 4264,
"text": "Clean up the environment β Requires explicitly closing all database resources versus relying on the JVM's garbage collection."
},
{
"code": null,
"e": 4516,
"s": 4390,
"text": "Clean up the environment β Requires explicitly closing all database resources versus relying on the JVM's garbage collection."
},
{
"code": null,
"e": 4625,
"s": 4516,
"text": "This sample example can serve as a template when you need to create your own JDBC application in the future."
},
{
"code": null,
"e": 4733,
"s": 4625,
"text": "This sample code has been written based on the environment and database setup done in the previous chapter."
},
{
"code": null,
"e": 4824,
"s": 4733,
"text": "Copy and paste the following example in TestApplication.java, compile and run as follows β"
},
{
"code": null,
"e": 5807,
"s": 4824,
"text": "import java.sql.*;\n\npublic class TestApplication {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n static final String QUERY = \"SELECT id, first, last, age FROM Employees\";\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n Statement stmt = conn.createStatement();\n ResultSet rs = stmt.executeQuery(QUERY);) {\n // Extract data from result set\n while (rs.next()) {\n // Retrieve by column name\n System.out.print(\"ID: \" + rs.getInt(\"id\"));\n System.out.print(\", Age: \" + rs.getInt(\"age\"));\n System.out.print(\", First: \" + rs.getString(\"first\"));\n System.out.println(\", Last: \" + rs.getString(\"last\"));\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}"
},
{
"code": null,
"e": 5857,
"s": 5807,
"text": "Now let us compile the above example as follows β"
},
{
"code": null,
"e": 5894,
"s": 5857,
"text": "C:\\>javac TestApplication.java\nC:\\>\n"
},
{
"code": null,
"e": 5959,
"s": 5894,
"text": "When you run TestApplication, it produces the following result β"
},
{
"code": null,
"e": 6163,
"s": 5959,
"text": "C:\\>java TestApplication\nID: 100, Age: 18, First: Zara, Last: Ali\nID: 101, Age: 25, First: Mahnaz, Last: Fatma\nID: 102, Age: 30, First: Zaid, Last: Khan\nID: 103, Age: 28, First: Sumit, Last: Mittal\nC:\\>\n"
},
{
"code": null,
"e": 6196,
"s": 6163,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6212,
"s": 6196,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6245,
"s": 6212,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6261,
"s": 6245,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6296,
"s": 6261,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6310,
"s": 6296,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6344,
"s": 6310,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6358,
"s": 6344,
"text": " Tushar Kale"
},
{
"code": null,
"e": 6395,
"s": 6358,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 6410,
"s": 6395,
"text": " Monica Mittal"
},
{
"code": null,
"e": 6443,
"s": 6410,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6462,
"s": 6443,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6469,
"s": 6462,
"text": " Print"
},
{
"code": null,
"e": 6480,
"s": 6469,
"text": " Add Notes"
}
] |
What does abstract modifier in Java do?
|
An abstract keyword is used to declare methods abstract methods and abstract classes. Once a method is declared abstract we should not specify body for those.
public abstract class Sample{
public abstract demo(){
}
}
Sample.java:2: error: invalid method declaration; return type required
public abstract demo(){
^
1 error
And once a class is declared abstract it cannot be instantiated.
public abstract class Sample{
public abstract void demo();
public static void main(String args[]){
new Sample();
}
}
C:\Sample>javac Sample.java
Sample.java:4: error: Sample is abstract; cannot be instantiated
new Sample();
^
1 error
|
[
{
"code": null,
"e": 1221,
"s": 1062,
"text": "An abstract keyword is used to declare methods abstract methods and abstract classes. Once a method is declared abstract we should not specify body for those."
},
{
"code": null,
"e": 1285,
"s": 1221,
"text": "public abstract class Sample{\n public abstract demo(){\n }\n}"
},
{
"code": null,
"e": 1413,
"s": 1285,
"text": "Sample.java:2: error: invalid method declaration; return type required\n public abstract demo(){\n ^\n1 error\n"
},
{
"code": null,
"e": 1478,
"s": 1413,
"text": "And once a class is declared abstract it cannot be instantiated."
},
{
"code": null,
"e": 1610,
"s": 1478,
"text": "public abstract class Sample{\n public abstract void demo();\n public static void main(String args[]){\n new Sample();\n }\n}"
},
{
"code": null,
"e": 1734,
"s": 1610,
"text": "C:\\Sample>javac Sample.java\nSample.java:4: error: Sample is abstract; cannot be instantiated\n new Sample();\n ^\n1 error\n"
}
] |
How to display animated gif images in Android?
|
This example demonstrates how do I display animated gif images in android.
Step 1 β Create a new project in Android Studio, go to File β New Project and fill all required details to create a new project.
Add the following dependency in build.gradle: Module: app
implementation 'com.github.bumptech.glide:glide:4.9.0'
Step 2 β Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp"
tools:context=".MainActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/imageView"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:onClick="ShowGif"
android:textAlignment="center"
android:text="SHOW GIF"/>
</RelativeLayout>
Step 3 β Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void ShowGif(View view) {
ImageView imageView = findViewById(R.id.imageView);
Glide.with(this).load(R.drawable.tenor).into(imageView);
}
}
Step 4 β Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen β
Click here to download the project code.
|
[
{
"code": null,
"e": 1137,
"s": 1062,
"text": "This example demonstrates how do I display animated gif images in android."
},
{
"code": null,
"e": 1266,
"s": 1137,
"text": "Step 1 β Create a new project in Android Studio, go to File β New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1324,
"s": 1266,
"text": "Add the following dependency in build.gradle: Module: app"
},
{
"code": null,
"e": 1379,
"s": 1324,
"text": "implementation 'com.github.bumptech.glide:glide:4.9.0'"
},
{
"code": null,
"e": 1444,
"s": 1379,
"text": "Step 2 β Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2139,
"s": 1444,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"4dp\"\n tools:context=\".MainActivity\">\n <ImageView\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:id=\"@+id/imageView\"/>\n <Button\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentBottom=\"true\"\n android:onClick=\"ShowGif\"\n android:textAlignment=\"center\"\n android:text=\"SHOW GIF\"/>\n</RelativeLayout>"
},
{
"code": null,
"e": 2196,
"s": 2139,
"text": "Step 3 β Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2743,
"s": 2196,
"text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.ImageView;\nimport com.bumptech.glide.Glide;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n public void ShowGif(View view) {\n ImageView imageView = findViewById(R.id.imageView);\n Glide.with(this).load(R.drawable.tenor).into(imageView);\n }\n}"
},
{
"code": null,
"e": 2798,
"s": 2743,
"text": "Step 4 β Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3486,
"s": 2798,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 3837,
"s": 3486,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen β"
},
{
"code": null,
"e": 3878,
"s": 3837,
"text": "Click here to download the project code."
}
] |
Updating Strings in Python
|
You can "update" an existing string by (re)assigning a variable to another string. The new value can be related to its previous value or to a completely different string altogether. For example β
Live Demo
#!/usr/bin/python
var1 = 'Hello World!'
print "Updated String :- ", var1[:6] + 'Python'
When the above code is executed, it produces the following result β
Updated String :- Hello Python
|
[
{
"code": null,
"e": 1258,
"s": 1062,
"text": "You can \"update\" an existing string by (re)assigning a variable to another string. The new value can be related to its previous value or to a completely different string altogether. For example β"
},
{
"code": null,
"e": 1269,
"s": 1258,
"text": " Live Demo"
},
{
"code": null,
"e": 1357,
"s": 1269,
"text": "#!/usr/bin/python\nvar1 = 'Hello World!'\nprint \"Updated String :- \", var1[:6] + 'Python'"
},
{
"code": null,
"e": 1425,
"s": 1357,
"text": "When the above code is executed, it produces the following result β"
},
{
"code": null,
"e": 1457,
"s": 1425,
"text": "Updated String :- Hello Python\n"
}
] |
Graph Attention Networks Under the Hood | by Giuseppe Futia | Towards Data Science
|
Graph Neural Networks (GNNs) have emerged as the standard toolbox to learn from graph data. GNNs are able to drive improvements for high-impact problems in different fields, such as content recommendation or drug discovery. Unlike other types of data such as images, learning from graph data requires specific methods. As defined by Michael Bronstein:
[..] these methods are based on some form of message passing on the graph allowing different nodes to exchange information.
For accomplishing specific tasks on graphs (node classification, link prediction, etc.), a GNN layer computes the node and the edge representations through the so-called recursive neighborhood diffusion (or message passing). According to this principle, each graph node receives and aggregates features from its neighbors in order to represent the local graph structure: different types of GNN layers perform diverse aggregation strategies.
The simplest formulations of the GNN layer, such as Graph Convolutional Networks (GCNs) or GraphSage, execute an isotropic aggregation, where each neighbor contributes equally to update the representation of the central node. This blog post is dedicated to the analysis of Graph Attention Networks (GATs), which define an anisotropy operation in the recursive neighborhood diffusion. Exploiting the anisotropy paradigm, the learning capacity is improved by the attention mechanism, which assigns different importance to each neighbor's contribution.
If you are completely new to GNNs and related concepts, I invite you to read the following introductory article:
towardsdatascience.com
This warm-up is based on the GAT details reported by the Deep Graph Library website.
Before understanding the GAT layer's behavior, letβs recap the math behind the aggregation performed by the GCN layer.
N is the set of the one-hop neighbors of node i. This node could also be included among the neighbors by adding a self-loop.
c is a normalization constant based on the graph structure, which defines an isotropic average computation.
Ο is an activation function, which introduces non-linearity in the transformation.
W is the weight matrix of learnable parameters adopted for feature transformation.
The GAT layer expands the basic aggregation function of the GCN layer, assigning different importance to each edge through the attention coefficients.
Equation (1) is a linear transformation of the lower layer embedding h_i, and W is its learnable weight matrix. This transformation helps achieve a sufficient expressive power to transform the input features into high-level and dense features.
Equation (2) computes a pair-wise un-normalized attention score between two neighbors. Here, it first concatenates the z embeddings of the two nodes, where || denotes concatenation. Then, it takes a dot product of such concatenation and a learnable weight vector a. In the end, a LeakyReLU is applied to the result of the dot product. The attention score indicates the importance of a neighbor node in the message passing framework.
Equation (3) applies a softmax to normalize the attention scores on each nodeβs incoming edges. The softmax encodes the output of the previous step in a probability distribution. As a consequence, the attention scores are much more comparable across different nodes.
Equation (4) is similar to the GCN aggregation (see the equation at the beginning of the section). The embeddings from neighbors are aggregated together, scaled by the attention scores. The main consequence of this scaling process is to learn a different contribution from each neighborhood node.
The first step is to prepare the ingredients (matrices) to represent a simple graph and perform the linear transformation.
NumPy code
Output
----- One-hot vector representation of nodes. Shape(n,n)[[0 0 1 0 0] # node 1 [0 1 0 0 0] # node 2 [0 0 0 0 1] [1 0 0 0 0] [0 0 0 1 0]]----- Embedding dimension3----- Weight Matrix. Shape(emb, n)[[-0.4294049 0.57624235 -0.3047382 -0.11941829 -0.12942953] [ 0.19600584 0.5029172 0.3998854 -0.21561317 0.02834577] [-0.06529497 -0.31225734 0.03973776 0.47800217 -0.04941563]]----- Adjacency Matrix (undirected graph). Shape(n,n)[[1 1 1 0 1] [1 1 1 1 1] [1 1 1 1 0] [0 1 1 1 1] [1 1 0 1 1]]
The first matrix defines a one-hot encoded representation of the nodes (node 1 is shown in bold). Then, we define a weight matrix, exploiting the defined embedding dimension. I have highlighted the 3rd column vector of W because, as you will see shortly, this vector defines the updated representation of node 1 (a 1-value is initialized in the 3rd position). We can perform the linear transformation to achieve sufficient expressive power for node features starting from these ingredients. This step aims to transform the (one-hot encoded) input features into a low and dense representation.
NumPy code
Output
----- Linear Transformation. Shape(n, emb)[[-0.3047382 0.3998854 0.03973776] [ 0.57624235 0.5029172 -0.31225734] [-0.12942953 0.02834577 -0.04941563] [-0.4294049 0.19600584 -0.06529497] [-0.11941829 -0.21561317 0.47800217]]
The next operation is to introduce the self-attention coefficients for each edge. We concatenate the representation of the source node and the destination node's representation for representing edges. This concatenation process is enabled by the adjacency matrix A, which defines the relations between all the nodes in the graph.
NumPy code
Output
----- Concat hidden features to represent edges. Shape(len(emb.concat(emb)), number of edges)[[-0.3047382 0.3998854 0.03973776 -0.3047382 0.3998854 0.03973776] [-0.3047382 0.3998854 0.03973776 0.57624235 0.5029172 -0.31225734] [-0.3047382 0.3998854 0.03973776 -0.12942953 0.02834577 -0.04941563] [-0.3047382 0.3998854 0.03973776 -0.11941829 -0.21561317 0.47800217] [ 0.57624235 0.5029172 -0.31225734 -0.3047382 0.3998854 0.03973776] [ 0.57624235 0.5029172 -0.31225734 0.57624235 0.5029172 -0.31225734] [ 0.57624235 0.5029172 -0.31225734 -0.12942953 0.02834577 -0.04941563] [ 0.57624235 0.5029172 -0.31225734 -0.4294049 0.19600584 -0.06529497] [ 0.57624235 0.5029172 -0.31225734 -0.11941829 -0.21561317 0.47800217] [-0.12942953 0.02834577 -0.04941563 -0.3047382 0.3998854 0.03973776] [-0.12942953 0.02834577 -0.04941563 0.57624235 0.5029172 -0.31225734] [-0.12942953 0.02834577 -0.04941563 -0.12942953 0.02834577 -0.04941563] [-0.12942953 0.02834577 -0.04941563 -0.4294049 0.19600584 -0.06529497] [-0.4294049 0.19600584 -0.06529497 0.57624235 0.5029172 -0.31225734] [-0.4294049 0.19600584 -0.06529497 -0.12942953 0.02834577 -0.04941563] [-0.4294049 0.19600584 -0.06529497 -0.4294049 0.19600584 -0.06529497] [-0.4294049 0.19600584 -0.06529497 -0.11941829 -0.21561317 0.47800217] [-0.11941829 -0.21561317 0.47800217 -0.3047382 0.3998854 0.03973776] [-0.11941829 -0.21561317 0.47800217 0.57624235 0.5029172 -0.31225734] [-0.11941829 -0.21561317 0.47800217 -0.4294049 0.19600584 -0.06529497] [-0.11941829 -0.21561317 0.47800217 -0.11941829 -0.21561317 0.47800217]]
In the previous block, I have highlighted the 4 rows representing the 4 in-edges connected to node 1. The first 3 elements of each row define the embedding representation of node 1 neighbors, while the other 3 elements of each row define the embeddings of node 1 itself (as you can notice, the first row encodes a self-loop).
After this operation, we can introduce the attention coefficients and multiply them with the edge representation, resulting from the concatenation process. Finally, the Leaky Relu function is applied to the output of this product.
NumPy code
Output
----- Attention coefficients. Shape(1, len(emb.concat(emb)))[[0.09834683 0.42110763 0.95788953 0.53316528 0.69187711 0.31551563]]----- Edge representations combined with the attention coefficients. Shape(1, number of edges)[[ 0.30322275] [ 0.73315639] [ 0.11150219] [ 0.11445879] [ 0.09607946] [ 0.52601309] [-0.0956411 ] [-0.14458757] [-0.0926845 ] [ 0.07860653] [ 0.50854017] [-0.11311402] [-0.16206049] [ 0.53443082] [-0.08722337] [-0.13616985] [-0.08426678] [ 0.48206613] [ 0.91199976] [ 0.2413991 ] [ 0.29330217]]----- Leaky Relu. Shape(1, number of edges)[[ 3.03222751e-01] [ 7.33156386e-01] [ 1.11502195e-01] [ 1.14458791e-01] [ 9.60794571e-02] [ 5.26013092e-01] [-9.56410988e-04] [-1.44587571e-03] [-9.26845030e-04] [ 7.86065337e-02] [ 5.08540169e-01] [-1.13114022e-03] [-1.62060495e-03] [ 5.34430817e-01] [-8.72233739e-04] [-1.36169846e-03] [-8.42667781e-04] [ 4.82066128e-01] [ 9.11999763e-01] [ 2.41399100e-01] [ 2.93302168e-01]]
At the end of this process, we achieved a different score for each edge of the graph. In the upper block, I have highlighted the evolution of the coefficient associated with the first edge. Then, to make the coefficient easily comparable across different nodes, a softmax function is applied to all neighbors' contributions for every destination node.
NumPy code
Output
----- Edge scores as matrix. Shape(n,n)[[ 3.03222751e-01 7.33156386e-01 1.11502195e-01 0.00000000e+00 1.14458791e-01] [ 9.60794571e-02 5.26013092e-01 -9.56410988e-04 -1.44587571e-03 -9.26845030e-04] [ 7.86065337e-02 5.08540169e-01 -1.13114022e-03 -1.62060495e-03 0.00000000e+00] [ 0.00000000e+00 5.34430817e-01 -8.72233739e-04 -1.36169846e-03 -8.42667781e-04] [ 4.82066128e-01 9.11999763e-01 0.00000000e+00 2.41399100e-01 2.93302168e-01]]----- For each node, normalize the edge (or neighbor) contributions using softmax[0.26263543 0.21349717 0.20979916 0.31406823 0.21610715 0.17567419 0.1726313 0.1771592 0.25842816 0.27167844 0.24278118 0.24273876 0.24280162 0.23393014 0.23388927 0.23394984 0.29823075 0.25138555 0.22399017 0.22400903 0.30061525]----- Normalized edge score matrix. Shape(n,n)[[0.26263543 0.21349717 0.20979916 0. 0.31406823] [0.21610715 0.17567419 0.1726313 0.1771592 0.25842816] [0.27167844 0.24278118 0.24273876 0.24280162 0. ] [0. 0.23393014 0.23388927 0.23394984 0.29823075] [0.25138555 0.22399017 0. 0.22400903 0.30061525]]
To interpret the meaning of the last matrix defining the normalized edge scores, letβs recap the adjacency matrix's content.
----- Adjacency Matrix (undirected graph). Shape(n,n)[[1 1 1 0 1] [1 1 1 1 1] [1 1 1 1 0] [0 1 1 1 1] [1 1 0 1 1]]
As you can see, instead of having 1 values to define edges, we rescaled the contribution of each neighbor. The final step is to compute the neighborhood aggregation: the embeddings from neighbors are incorporated into the destination node, scaled by the attention scores.
NumPy code
Output
Neighborhood aggregation (GCN) scaled with attention scores (GAT). Shape(n, emb)[[-0.02166863 0.15062515 0.08352843] [-0.09390287 0.15866476 0.05716299] [-0.07856777 0.28521023 -0.09286313] [-0.03154513 0.10583032 0.04267501] [-0.07962369 0.19226439 0.069115 ]]
In the future article, I will describe the mechanisms behind the Multi-Head GAT Layer, and we will see some applications for the link prediction task.
The running version of the code is available in the following notebook. You will also find a DGL implementation, which is useful to check the correctness of the implementation.
The original paper on Graph Attention Networks from Petar VelicΜkovicΜ, Guillem Cucurull, Arantxa Casanova, Adriana Romero, Pietro LioΜ, Yoshua Bengiois available on arXiv.
For a deep explanation of the topic, I also suggest the video from Aleksa GordicΜ.
For further readings on Graph Representation Learning, you can follow my series at the following link: https://towardsdatascience.com/tagged/grl-series.
If you like my articles, you can support me using this link https://medium.com/@giuseppefutia/membership and becoming a Medium member.
|
[
{
"code": null,
"e": 523,
"s": 171,
"text": "Graph Neural Networks (GNNs) have emerged as the standard toolbox to learn from graph data. GNNs are able to drive improvements for high-impact problems in different fields, such as content recommendation or drug discovery. Unlike other types of data such as images, learning from graph data requires specific methods. As defined by Michael Bronstein:"
},
{
"code": null,
"e": 647,
"s": 523,
"text": "[..] these methods are based on some form of message passing on the graph allowing different nodes to exchange information."
},
{
"code": null,
"e": 1088,
"s": 647,
"text": "For accomplishing specific tasks on graphs (node classification, link prediction, etc.), a GNN layer computes the node and the edge representations through the so-called recursive neighborhood diffusion (or message passing). According to this principle, each graph node receives and aggregates features from its neighbors in order to represent the local graph structure: different types of GNN layers perform diverse aggregation strategies."
},
{
"code": null,
"e": 1638,
"s": 1088,
"text": "The simplest formulations of the GNN layer, such as Graph Convolutional Networks (GCNs) or GraphSage, execute an isotropic aggregation, where each neighbor contributes equally to update the representation of the central node. This blog post is dedicated to the analysis of Graph Attention Networks (GATs), which define an anisotropy operation in the recursive neighborhood diffusion. Exploiting the anisotropy paradigm, the learning capacity is improved by the attention mechanism, which assigns different importance to each neighbor's contribution."
},
{
"code": null,
"e": 1751,
"s": 1638,
"text": "If you are completely new to GNNs and related concepts, I invite you to read the following introductory article:"
},
{
"code": null,
"e": 1774,
"s": 1751,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1859,
"s": 1774,
"text": "This warm-up is based on the GAT details reported by the Deep Graph Library website."
},
{
"code": null,
"e": 1978,
"s": 1859,
"text": "Before understanding the GAT layer's behavior, letβs recap the math behind the aggregation performed by the GCN layer."
},
{
"code": null,
"e": 2103,
"s": 1978,
"text": "N is the set of the one-hop neighbors of node i. This node could also be included among the neighbors by adding a self-loop."
},
{
"code": null,
"e": 2211,
"s": 2103,
"text": "c is a normalization constant based on the graph structure, which defines an isotropic average computation."
},
{
"code": null,
"e": 2294,
"s": 2211,
"text": "Ο is an activation function, which introduces non-linearity in the transformation."
},
{
"code": null,
"e": 2377,
"s": 2294,
"text": "W is the weight matrix of learnable parameters adopted for feature transformation."
},
{
"code": null,
"e": 2528,
"s": 2377,
"text": "The GAT layer expands the basic aggregation function of the GCN layer, assigning different importance to each edge through the attention coefficients."
},
{
"code": null,
"e": 2772,
"s": 2528,
"text": "Equation (1) is a linear transformation of the lower layer embedding h_i, and W is its learnable weight matrix. This transformation helps achieve a sufficient expressive power to transform the input features into high-level and dense features."
},
{
"code": null,
"e": 3205,
"s": 2772,
"text": "Equation (2) computes a pair-wise un-normalized attention score between two neighbors. Here, it first concatenates the z embeddings of the two nodes, where || denotes concatenation. Then, it takes a dot product of such concatenation and a learnable weight vector a. In the end, a LeakyReLU is applied to the result of the dot product. The attention score indicates the importance of a neighbor node in the message passing framework."
},
{
"code": null,
"e": 3472,
"s": 3205,
"text": "Equation (3) applies a softmax to normalize the attention scores on each nodeβs incoming edges. The softmax encodes the output of the previous step in a probability distribution. As a consequence, the attention scores are much more comparable across different nodes."
},
{
"code": null,
"e": 3769,
"s": 3472,
"text": "Equation (4) is similar to the GCN aggregation (see the equation at the beginning of the section). The embeddings from neighbors are aggregated together, scaled by the attention scores. The main consequence of this scaling process is to learn a different contribution from each neighborhood node."
},
{
"code": null,
"e": 3892,
"s": 3769,
"text": "The first step is to prepare the ingredients (matrices) to represent a simple graph and perform the linear transformation."
},
{
"code": null,
"e": 3903,
"s": 3892,
"text": "NumPy code"
},
{
"code": null,
"e": 3910,
"s": 3903,
"text": "Output"
},
{
"code": null,
"e": 4407,
"s": 3910,
"text": "----- One-hot vector representation of nodes. Shape(n,n)[[0 0 1 0 0] # node 1 [0 1 0 0 0] # node 2 [0 0 0 0 1] [1 0 0 0 0] [0 0 0 1 0]]----- Embedding dimension3----- Weight Matrix. Shape(emb, n)[[-0.4294049 0.57624235 -0.3047382 -0.11941829 -0.12942953] [ 0.19600584 0.5029172 0.3998854 -0.21561317 0.02834577] [-0.06529497 -0.31225734 0.03973776 0.47800217 -0.04941563]]----- Adjacency Matrix (undirected graph). Shape(n,n)[[1 1 1 0 1] [1 1 1 1 1] [1 1 1 1 0] [0 1 1 1 1] [1 1 0 1 1]]"
},
{
"code": null,
"e": 5000,
"s": 4407,
"text": "The first matrix defines a one-hot encoded representation of the nodes (node 1 is shown in bold). Then, we define a weight matrix, exploiting the defined embedding dimension. I have highlighted the 3rd column vector of W because, as you will see shortly, this vector defines the updated representation of node 1 (a 1-value is initialized in the 3rd position). We can perform the linear transformation to achieve sufficient expressive power for node features starting from these ingredients. This step aims to transform the (one-hot encoded) input features into a low and dense representation."
},
{
"code": null,
"e": 5011,
"s": 5000,
"text": "NumPy code"
},
{
"code": null,
"e": 5018,
"s": 5011,
"text": "Output"
},
{
"code": null,
"e": 5252,
"s": 5018,
"text": "----- Linear Transformation. Shape(n, emb)[[-0.3047382 0.3998854 0.03973776] [ 0.57624235 0.5029172 -0.31225734] [-0.12942953 0.02834577 -0.04941563] [-0.4294049 0.19600584 -0.06529497] [-0.11941829 -0.21561317 0.47800217]]"
},
{
"code": null,
"e": 5582,
"s": 5252,
"text": "The next operation is to introduce the self-attention coefficients for each edge. We concatenate the representation of the source node and the destination node's representation for representing edges. This concatenation process is enabled by the adjacency matrix A, which defines the relations between all the nodes in the graph."
},
{
"code": null,
"e": 5593,
"s": 5582,
"text": "NumPy code"
},
{
"code": null,
"e": 5600,
"s": 5593,
"text": "Output"
},
{
"code": null,
"e": 7249,
"s": 5600,
"text": "----- Concat hidden features to represent edges. Shape(len(emb.concat(emb)), number of edges)[[-0.3047382 0.3998854 0.03973776 -0.3047382 0.3998854 0.03973776] [-0.3047382 0.3998854 0.03973776 0.57624235 0.5029172 -0.31225734] [-0.3047382 0.3998854 0.03973776 -0.12942953 0.02834577 -0.04941563] [-0.3047382 0.3998854 0.03973776 -0.11941829 -0.21561317 0.47800217] [ 0.57624235 0.5029172 -0.31225734 -0.3047382 0.3998854 0.03973776] [ 0.57624235 0.5029172 -0.31225734 0.57624235 0.5029172 -0.31225734] [ 0.57624235 0.5029172 -0.31225734 -0.12942953 0.02834577 -0.04941563] [ 0.57624235 0.5029172 -0.31225734 -0.4294049 0.19600584 -0.06529497] [ 0.57624235 0.5029172 -0.31225734 -0.11941829 -0.21561317 0.47800217] [-0.12942953 0.02834577 -0.04941563 -0.3047382 0.3998854 0.03973776] [-0.12942953 0.02834577 -0.04941563 0.57624235 0.5029172 -0.31225734] [-0.12942953 0.02834577 -0.04941563 -0.12942953 0.02834577 -0.04941563] [-0.12942953 0.02834577 -0.04941563 -0.4294049 0.19600584 -0.06529497] [-0.4294049 0.19600584 -0.06529497 0.57624235 0.5029172 -0.31225734] [-0.4294049 0.19600584 -0.06529497 -0.12942953 0.02834577 -0.04941563] [-0.4294049 0.19600584 -0.06529497 -0.4294049 0.19600584 -0.06529497] [-0.4294049 0.19600584 -0.06529497 -0.11941829 -0.21561317 0.47800217] [-0.11941829 -0.21561317 0.47800217 -0.3047382 0.3998854 0.03973776] [-0.11941829 -0.21561317 0.47800217 0.57624235 0.5029172 -0.31225734] [-0.11941829 -0.21561317 0.47800217 -0.4294049 0.19600584 -0.06529497] [-0.11941829 -0.21561317 0.47800217 -0.11941829 -0.21561317 0.47800217]]"
},
{
"code": null,
"e": 7575,
"s": 7249,
"text": "In the previous block, I have highlighted the 4 rows representing the 4 in-edges connected to node 1. The first 3 elements of each row define the embedding representation of node 1 neighbors, while the other 3 elements of each row define the embeddings of node 1 itself (as you can notice, the first row encodes a self-loop)."
},
{
"code": null,
"e": 7806,
"s": 7575,
"text": "After this operation, we can introduce the attention coefficients and multiply them with the edge representation, resulting from the concatenation process. Finally, the Leaky Relu function is applied to the output of this product."
},
{
"code": null,
"e": 7817,
"s": 7806,
"text": "NumPy code"
},
{
"code": null,
"e": 7824,
"s": 7817,
"text": "Output"
},
{
"code": null,
"e": 8765,
"s": 7824,
"text": "----- Attention coefficients. Shape(1, len(emb.concat(emb)))[[0.09834683 0.42110763 0.95788953 0.53316528 0.69187711 0.31551563]]----- Edge representations combined with the attention coefficients. Shape(1, number of edges)[[ 0.30322275] [ 0.73315639] [ 0.11150219] [ 0.11445879] [ 0.09607946] [ 0.52601309] [-0.0956411 ] [-0.14458757] [-0.0926845 ] [ 0.07860653] [ 0.50854017] [-0.11311402] [-0.16206049] [ 0.53443082] [-0.08722337] [-0.13616985] [-0.08426678] [ 0.48206613] [ 0.91199976] [ 0.2413991 ] [ 0.29330217]]----- Leaky Relu. Shape(1, number of edges)[[ 3.03222751e-01] [ 7.33156386e-01] [ 1.11502195e-01] [ 1.14458791e-01] [ 9.60794571e-02] [ 5.26013092e-01] [-9.56410988e-04] [-1.44587571e-03] [-9.26845030e-04] [ 7.86065337e-02] [ 5.08540169e-01] [-1.13114022e-03] [-1.62060495e-03] [ 5.34430817e-01] [-8.72233739e-04] [-1.36169846e-03] [-8.42667781e-04] [ 4.82066128e-01] [ 9.11999763e-01] [ 2.41399100e-01] [ 2.93302168e-01]]"
},
{
"code": null,
"e": 9117,
"s": 8765,
"text": "At the end of this process, we achieved a different score for each edge of the graph. In the upper block, I have highlighted the evolution of the coefficient associated with the first edge. Then, to make the coefficient easily comparable across different nodes, a softmax function is applied to all neighbors' contributions for every destination node."
},
{
"code": null,
"e": 9128,
"s": 9117,
"text": "NumPy code"
},
{
"code": null,
"e": 9135,
"s": 9128,
"text": "Output"
},
{
"code": null,
"e": 10236,
"s": 9135,
"text": "----- Edge scores as matrix. Shape(n,n)[[ 3.03222751e-01 7.33156386e-01 1.11502195e-01 0.00000000e+00 1.14458791e-01] [ 9.60794571e-02 5.26013092e-01 -9.56410988e-04 -1.44587571e-03 -9.26845030e-04] [ 7.86065337e-02 5.08540169e-01 -1.13114022e-03 -1.62060495e-03 0.00000000e+00] [ 0.00000000e+00 5.34430817e-01 -8.72233739e-04 -1.36169846e-03 -8.42667781e-04] [ 4.82066128e-01 9.11999763e-01 0.00000000e+00 2.41399100e-01 2.93302168e-01]]----- For each node, normalize the edge (or neighbor) contributions using softmax[0.26263543 0.21349717 0.20979916 0.31406823 0.21610715 0.17567419 0.1726313 0.1771592 0.25842816 0.27167844 0.24278118 0.24273876 0.24280162 0.23393014 0.23388927 0.23394984 0.29823075 0.25138555 0.22399017 0.22400903 0.30061525]----- Normalized edge score matrix. Shape(n,n)[[0.26263543 0.21349717 0.20979916 0. 0.31406823] [0.21610715 0.17567419 0.1726313 0.1771592 0.25842816] [0.27167844 0.24278118 0.24273876 0.24280162 0. ] [0. 0.23393014 0.23388927 0.23394984 0.29823075] [0.25138555 0.22399017 0. 0.22400903 0.30061525]]"
},
{
"code": null,
"e": 10361,
"s": 10236,
"text": "To interpret the meaning of the last matrix defining the normalized edge scores, letβs recap the adjacency matrix's content."
},
{
"code": null,
"e": 10476,
"s": 10361,
"text": "----- Adjacency Matrix (undirected graph). Shape(n,n)[[1 1 1 0 1] [1 1 1 1 1] [1 1 1 1 0] [0 1 1 1 1] [1 1 0 1 1]]"
},
{
"code": null,
"e": 10748,
"s": 10476,
"text": "As you can see, instead of having 1 values to define edges, we rescaled the contribution of each neighbor. The final step is to compute the neighborhood aggregation: the embeddings from neighbors are incorporated into the destination node, scaled by the attention scores."
},
{
"code": null,
"e": 10759,
"s": 10748,
"text": "NumPy code"
},
{
"code": null,
"e": 10766,
"s": 10759,
"text": "Output"
},
{
"code": null,
"e": 11038,
"s": 10766,
"text": "Neighborhood aggregation (GCN) scaled with attention scores (GAT). Shape(n, emb)[[-0.02166863 0.15062515 0.08352843] [-0.09390287 0.15866476 0.05716299] [-0.07856777 0.28521023 -0.09286313] [-0.03154513 0.10583032 0.04267501] [-0.07962369 0.19226439 0.069115 ]]"
},
{
"code": null,
"e": 11189,
"s": 11038,
"text": "In the future article, I will describe the mechanisms behind the Multi-Head GAT Layer, and we will see some applications for the link prediction task."
},
{
"code": null,
"e": 11366,
"s": 11189,
"text": "The running version of the code is available in the following notebook. You will also find a DGL implementation, which is useful to check the correctness of the implementation."
},
{
"code": null,
"e": 11539,
"s": 11366,
"text": "The original paper on Graph Attention Networks from Petar VelicΜkovicΜ, Guillem Cucurull, Arantxa Casanova, Adriana Romero, Pietro LioΜ, Yoshua Bengiois available on arXiv."
},
{
"code": null,
"e": 11622,
"s": 11539,
"text": "For a deep explanation of the topic, I also suggest the video from Aleksa GordicΜ."
},
{
"code": null,
"e": 11775,
"s": 11622,
"text": "For further readings on Graph Representation Learning, you can follow my series at the following link: https://towardsdatascience.com/tagged/grl-series."
}
] |
How to use pip to install python modules in easy way?
|
If you have Python 2 >=2.7.9 or Python 3 >=3.4 installed from python.org, you will already have pip and setuptools, but will need to upgrade to the latest version:
On Linux or macOS:
pip install -U pip setuptools
On Windows:
python -m pip install -U pip setuptools
If youβre using a Python install on Linux thatβs managed by the system package manager (e.g "yum", "apt-get" etc...), and you want to use the system package manager to install or upgrade pip, then see: https://packaging.python.org/guides/installing-using-linux-tools/
Otherwise:
Download get-pip.py from https://bootstrap.pypa.io/get-pip.py. Run python get-pip.py. This will install or upgrade pip.
Now you can use pip to install python packages. For example, To install the latest version of "SomeProject":
$ pip install 'SomeProject'
To install a specific version:
$ pip install 'SomeProject==1.4'
To install greater than or equal to one version and less than another:
$ pip install 'SomeProject>=1,<2'
|
[
{
"code": null,
"e": 1226,
"s": 1062,
"text": "If you have Python 2 >=2.7.9 or Python 3 >=3.4 installed from python.org, you will already have pip and setuptools, but will need to upgrade to the latest version:"
},
{
"code": null,
"e": 1245,
"s": 1226,
"text": "On Linux or macOS:"
},
{
"code": null,
"e": 1275,
"s": 1245,
"text": "pip install -U pip setuptools"
},
{
"code": null,
"e": 1287,
"s": 1275,
"text": "On Windows:"
},
{
"code": null,
"e": 1327,
"s": 1287,
"text": "python -m pip install -U pip setuptools"
},
{
"code": null,
"e": 1595,
"s": 1327,
"text": "If youβre using a Python install on Linux thatβs managed by the system package manager (e.g \"yum\", \"apt-get\" etc...), and you want to use the system package manager to install or upgrade pip, then see: https://packaging.python.org/guides/installing-using-linux-tools/"
},
{
"code": null,
"e": 1606,
"s": 1595,
"text": "Otherwise:"
},
{
"code": null,
"e": 1726,
"s": 1606,
"text": "Download get-pip.py from https://bootstrap.pypa.io/get-pip.py. Run python get-pip.py. This will install or upgrade pip."
},
{
"code": null,
"e": 1835,
"s": 1726,
"text": "Now you can use pip to install python packages. For example, To install the latest version of \"SomeProject\":"
},
{
"code": null,
"e": 1863,
"s": 1835,
"text": "$ pip install 'SomeProject'"
},
{
"code": null,
"e": 1894,
"s": 1863,
"text": "To install a specific version:"
},
{
"code": null,
"e": 1927,
"s": 1894,
"text": "$ pip install 'SomeProject==1.4'"
},
{
"code": null,
"e": 1998,
"s": 1927,
"text": "To install greater than or equal to one version and less than another:"
},
{
"code": null,
"e": 2032,
"s": 1998,
"text": "$ pip install 'SomeProject>=1,<2'"
}
] |
Get the longest and shortest string in an array JavaScript
|
We have an array of string literals like this β
const arr = ['Some', 'random', 'words', 'that', 'actually', 'form', 'a',
'sentence.'];
We are required to write a function that returns the longest and the shortest word from this array. We will use Array.prototype.reduce() method to keep track of the longest and shortest word in the array through a complete iteration.
The code for this will be β
const arr = ['Some', 'random', 'words', 'that', 'actually', 'form', 'a',
'sentence.'];
const findWords = (arr) => {
return arr.reduce((acc, val) => {
const { length: len } = val;
if(len > acc['longest']['length']){
acc['longest'] = val;
}else if(len < acc['shortest']['length']){
acc['shortest'] = val;
};
return acc;
}, {
longest: arr[0],
shortest: arr[0]
});
};
console.log(findWords(arr));
The output in the console will be β
{ longest: 'sentence.', shortest: 'a' }
|
[
{
"code": null,
"e": 1110,
"s": 1062,
"text": "We have an array of string literals like this β"
},
{
"code": null,
"e": 1197,
"s": 1110,
"text": "const arr = ['Some', 'random', 'words', 'that', 'actually', 'form', 'a',\n'sentence.'];"
},
{
"code": null,
"e": 1431,
"s": 1197,
"text": "We are required to write a function that returns the longest and the shortest word from this array. We will use Array.prototype.reduce() method to keep track of the longest and shortest word in the array through a complete iteration."
},
{
"code": null,
"e": 1459,
"s": 1431,
"text": "The code for this will be β"
},
{
"code": null,
"e": 1921,
"s": 1459,
"text": "const arr = ['Some', 'random', 'words', 'that', 'actually', 'form', 'a',\n'sentence.'];\nconst findWords = (arr) => {\n return arr.reduce((acc, val) => {\n const { length: len } = val;\n if(len > acc['longest']['length']){\n acc['longest'] = val;\n }else if(len < acc['shortest']['length']){\n acc['shortest'] = val;\n };\n return acc;\n }, {\n longest: arr[0],\n shortest: arr[0]\n });\n};\nconsole.log(findWords(arr));"
},
{
"code": null,
"e": 1957,
"s": 1921,
"text": "The output in the console will be β"
},
{
"code": null,
"e": 1997,
"s": 1957,
"text": "{ longest: 'sentence.', shortest: 'a' }"
}
] |
Extract csv file specific columns to list in Python
|
To extract csv file for specific columns to list in Python, we can use Pandas read_csv() method.
Make a list of columns that have to be extracted.
Make a list of columns that have to be extracted.
Use read_csv() method to extract the csv file into data frame.
Use read_csv() method to extract the csv file into data frame.
Print the exracted data.
Print the exracted data.
Plot the data frame using plot() method.
Plot the data frame using plot() method.
To display the figure, use show() method.
To display the figure, use show() method.
import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
columns = ["Name", "Marks"]
df = pd.read_csv("input.csv", usecols=columns)
print("Contents in csv file:\n", df)
plt.plot(df.Name, df.Marks)
plt.show()
The csv file contains the following data β
When we execute the code, it will extract the data from the csv file and show the following plot β
|
[
{
"code": null,
"e": 1159,
"s": 1062,
"text": "To extract csv file for specific columns to list in Python, we can use Pandas read_csv() method."
},
{
"code": null,
"e": 1209,
"s": 1159,
"text": "Make a list of columns that have to be extracted."
},
{
"code": null,
"e": 1259,
"s": 1209,
"text": "Make a list of columns that have to be extracted."
},
{
"code": null,
"e": 1322,
"s": 1259,
"text": "Use read_csv() method to extract the csv file into data frame."
},
{
"code": null,
"e": 1385,
"s": 1322,
"text": "Use read_csv() method to extract the csv file into data frame."
},
{
"code": null,
"e": 1410,
"s": 1385,
"text": "Print the exracted data."
},
{
"code": null,
"e": 1435,
"s": 1410,
"text": "Print the exracted data."
},
{
"code": null,
"e": 1476,
"s": 1435,
"text": "Plot the data frame using plot() method."
},
{
"code": null,
"e": 1517,
"s": 1476,
"text": "Plot the data frame using plot() method."
},
{
"code": null,
"e": 1559,
"s": 1517,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1601,
"s": 1559,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1896,
"s": 1601,
"text": "import pandas as pd\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\ncolumns = [\"Name\", \"Marks\"]\ndf = pd.read_csv(\"input.csv\", usecols=columns)\nprint(\"Contents in csv file:\\n\", df)\nplt.plot(df.Name, df.Marks)\nplt.show()"
},
{
"code": null,
"e": 1939,
"s": 1896,
"text": "The csv file contains the following data β"
},
{
"code": null,
"e": 2038,
"s": 1939,
"text": "When we execute the code, it will extract the data from the csv file and show the following plot β"
}
] |
Behave - Quick Guide
|
Behave is a tool used for Behaviour driven development (BDD) in Python programming language. In an Agile development framework, BDD creates a culture where testers, developers, business analysts, and other stakeholders of the project can contribute towards the software development.
In short, both technical and non-technical individuals have a role to play towards the overall project. Behave has tests developed in plain text with the implementation logic in Python.
The BDD format begins with the description of the characteristics of the software similar to a story.
It then continues with the development and carries out the following tasks β
Developing a failing test case for characteristics.
Developing a failing test case for characteristics.
Implement the logic for a test to pass.
Implement the logic for a test to pass.
Code refactor to fulfil the project guidelines.
Code refactor to fulfil the project guidelines.
There are numerous libraries for BDD like the Mocha which supports JavaScript, Cucumber which supports Java/Ruby, and Behave which supports Python, and so on.
In this tutorial, we shall discuss in detail about Behave.
Let us see a basic structure of a BDD. It mainly consists of the feature file, the step definition file, and so on.
The feature file in Behave can be as follows β
Feature β Verify book name added in Library.
Scenario β Verify Book name.
Given β Book details.
Then β Verify book name.
Following is the corresponding definition file in Behave tool β
from behave import *
@given('Book details')
def impl_bk(context):
print('Book details entered')
@then('Verify book name')
def impl_bk(context):
print('Verify book name')
The output obtained after running the feature file is as follows β
The output shows the Feature and Scenario names, along with the test results, and the duration of the respective test execution.
Behave installation can be done by the following ways β
For Behave installation, we should have pip β the package installer for the Python language installed in our system. The pip is installed by default, if the Python version is greater than 2(upto 2.7.9).
To install pip, run the below mentioned command β
pip install pip
To install pip with Behave, run the command given below β
pip install behave
The following screen will appear on your computer β
We can update an existing version of Behave with the following command β
pip install βU behave
We can also use the easy_install for the Behave installation.
To install Setuptools, run the below mentioned commandβ
pip install setuptools
Now, for the Behave installation, run the command stated below:
easy_install behave
We can update an existing version of behave with the command given below:
easy_install βU behave
Post unpacking of the source distribution of Behave, type the new generated directory 'behave-<version>' and execute the below mentioned command β
python setup.py install
We should first have the pip installed in the system.
Later on, to install the latest version of Behave with Git repository, run the below mentioned command β
pip install git+https://github.com/behave/behave
If we use the PyCharm Editor for writing the Behave code, we should have the Professional version of PyCharm along with the Gherkin plugin installed with it.
Behave has a collection of command line arguments and it can also be outlined from the configuration files. The values set in the configuration files are used automatically, however, it can be overruled by the command line arguments.
Let us discuss some of the command line arguments β
βc, --no-color
βc, --no-color
Impair the usage of the ANSI color escapes.
--color -
--color -
Utilise the ANSI color escapes. This is an in-built characteristic and can overrule a setting in the configuration file.
βd, --dry-run
βd, --dry-run
Summons the formatter without running the steps.
-D, --define
-D, --define
Declares the customised information for the config.userdata dictionary.
βe, --exclude Pattern
βe, --exclude Pattern
Exclude feature files which are identical to a pattern of regular expression from the execution.
βi, --include Pattern
βi, --include Pattern
Include feature files which are identical to a pattern of regular expression during the execution.
--no-junit
--no-junit
Omit JUnit reports as output.
--junit
--junit
Add JUnit reports as output. When JUnit is turned on, every stdout and stderr will be a part of the junit report. (Irrespective of the -capture/-no-capture options).
βf, --format
βf, --format
Define a formatter. If omitted, the in-built formatter is utilised. The βformat-help command shall display all the available formats.
-steps-catalog
-steps-catalog
Displays a catalogue of all the existing step definitions.
βk, --no-skipped
βk, --no-skipped
Exclude skipped steps from printing in console.
no-snippets
no-snippets
Exclude snippets from printing in console for the steps, which are still not implemented.
--snippets
--snippets
Include snippets, while printing in console for the steps which are still not implemented. This is an in-built characteristic and can overrule a configuration file setting.
βm, --no-multiline
βm, --no-multiline
Exclude multiple lines tables and strings under steps.
--multiline
--multiline
Include multiple lines tables and strings under steps. This is an in-built characteristic and can overrule a configuration file setting.
βn, --name
βn, --name
Include the feature elements, which are identical to the specified name in the run. If the option is provided multiple times, it shall match with all the names.
--no-capture
--no-capture
Exclude stdout from capturing.
--capture
--capture
Include stdout. This is an in-built characteristic and can overrule a configuration file setting.
--no-capture-stderr
--no-capture-stderr
Exclude stderr from capturing.
--capture-stderr
--capture-stderr
Include stderr. This is an in-built characteristic and can overrule a configuration file setting.
--no-logcapture
--no-logcapture
Exclude log from capturing.
--logcapture
--logcapture
Include log capturing. Every log for a step will be present and available during the failures. This is an in-built characteristic and can overrule a configuration file setting.
--logging-level
--logging-level
Mention the logging level that shall be captured. The default value is INFO.
--logging-format
--logging-format
Mention the user-defined format for printing statements. The default value is %(levelname)s:%(name)s:%(message)s.
--logging-datefmt
--logging-datefmt
Mention the user-defined date and time format for printing statements.
--logging-filter
--logging-filter
Mention if the statements are to be filtered or not. All the statements are captured by default. In case the output is too lengthy, we can utilise the option to filter out the unnecessary output.
--logging-clear-handlers
--logging-clear-handlers
Remove all the handlers which are used for logging.
--no-summary
--no-summary
Exclude summary post the execution.
-summary
-summary
Include summary post the execution.
βo, --outfile
βo, --outfile
Write the given file instead of using stdout.
βq, --quiet
βq, --quiet
Alias are used for βno-snippets βno-source.
βs, --no-source
βs, --no-source
Exclude printing the file and the line of step definition along with steps.
--show-source
--show-source
Include printing the file and the line of step definition along with the steps. This is an in-built characteristic and can overrule a configuration file setting.
--stage
--stage
--stop
--stop
Terminate executing tests after encountering the first failure.
βt, --tags
βt, --tags
Include the features/scenarios having tags, which are identical to TAG_EXPRESSION in the execution.
βT, --no-timings
βT, --no-timings
Exclude printing duration of execution for each step.
--show-timings
--show-timings
Capture the duration taken by each step to complete in seconds in the console. This is an in-built characteristic and can overrule a configuration file setting.
βv, --verbose
βv, --verbose
Displays the loaded features and files.
βw, --wip
βw, --wip
Execute the scenarios having the wip tag. Moreover, we have to use the plain formatter and not record the stdout or log output and terminate post first failure.
βx, --expand
βx, --expand
Flatten the table of Scenario Outline in output.
--lang
--lang
Utilise keywords for a language except English.
--lang-list
--lang-list
Displays all the languages present in βlang.
--lang-help
--lang-help
Displays all the translations acquired for a single language.
--tags-help
--tags-help
Display help for tag statements.
--version
--version
Displays version.
junit βdirectory
junit βdirectory
This is the directory location where the Junit reports are stored.
--show-skipped
--show-skipped
Include skipped steps while printing in console. This is an in-built characteristic and can overrule a configuration file setting.
Behave configuration files are known as the .behaverc/behave.ini/setup.cfg/tox.ini(any one and is set as per user choice).
The files can be located in the following places β
The present working directory.
The present working directory.
User home directory.
User home directory.
For Windows users, in the directory %APPDATA%.
For Windows users, in the directory %APPDATA%.
The command behave βv, shall display all the configuration details. The configuration files should begin with the keyword [behave] and follow Windows INI style format.
For example,
[behave]
format = plain
dry_run = false
Types of configuration parameters in Behave include the following β
Text β To assign a text to the configuration setting.
Text β To assign a text to the configuration setting.
Bool β Assigns Boolean value to the configuration setting. The text defines the behaviour (true values include 1, true, yes, and on). The false values include 0, false, no, and off).
Bool β Assigns Boolean value to the configuration setting. The text defines the behaviour (true values include 1, true, yes, and on). The false values include 0, false, no, and off).
Sequence<text> β To accept multiple values on new lines.
Sequence<text> β To accept multiple values on new lines.
For example, tag expression can be as follows β
tags=@a, ~@b
@c
This is equivalent to the following tag expression β
--tags @a, ~@b --tags @c
Some of the configuration parameters in Behave are explained below β
color β bool
color β bool
Utilise ANSI color escapes. This is an in-built characteristic and can overrule a setting in the configuration file.
dry_run β bool
dry_run β bool
Calls the formatters without running the steps.
userdata_defines β sequence<text>
userdata_defines β sequence<text>
Declares the customised data for the config.userdata dictionary.
exclude_re β text
exclude_re β text
Exclude the feature files which are identical to a pattern of regular expression from the execution.
include_re β text
include_re β text
Include the feature files which are identical to a pattern of regular expression during the execution.
junit β bool
junit β bool
Add JUnit reports as output. When JUnit is turned on, every stdout and stderr will be a part of the junit report. (Irrespective of the -capture/-no-capture options).
junit_directory β text
junit_directory β text
This is the directory location where the JUnit reports are stored.
default_format β text
default_format β text
Declare default formatter. The default value is pretty.
format: sequence<text>
format: sequence<text>
Define a formatter. If omitted, the in-built formatter is utilised. The βformat-help command shall display all the available formats.
steps_catalog β bool
steps_catalog β bool
Displays a catalogue of all the existing step definitions.
scenario_outline_annotation_schema: text
scenario_outline_annotation_schema: text
Mention annotation schema for scenario outline.
show_skipped β bool
show_skipped β bool
Include the skipped steps while printing in console. This is an in-built characteristic and can overrule a configuration file setting.
show_snippets β bool
show_snippets β bool
Include snippets while printing in console for the steps, which are still not implemented. This is an in-built characteristic and can overrule a configuration file setting.
show_multiline β bool
show_multiline β bool
Include multiple lines tables and strings under steps. This is an in-built characteristic and can overrule a configuration file setting.
name β sequence<text>
name β sequence<text>
Include the feature elements which are identical to the specified name in the run. If the option is provided multiple times, it shall match all the specified names.
stdout_capture β bool
stdout_capture β bool
Include stdout. This is an in-built characteristic and can overrule a configuration file setting.
stderr_capture β bool
stderr_capture β bool
Include stderr. This is an in-built characteristic and can overrule a configuration file setting.
log_capture β bool
log_capture β bool
Include log capturing. Every log for a step will be present and available during the failures. This is an in-built characteristic and can overrule a configuration file setting.
logging_level β text
logging_level β text
Mention the logging level to be captured. The default value is INFO.
logging_format β text
logging_format β text
Mention user-defined format for printing statements. The default value is %(levelname)s:%(name)s:%(message)s.
logging_datefmt β text
logging_datefmt β text
Mention user-defined date and time format for printing statements.
logging_filter β text
logging_filter β text
Mention the statements which are to be filtered. All the statements are captured by default. In case the output is too lengthy, we can utilise the option to filter out the unnecessary output.
logging_clear_handlers : bool
logging_clear_handlers : bool
Remove all the handlers which are used for logging.
summary β bool
summary β bool
Include a summary post the execution.
outfiles β sequence<text>
outfiles β sequence<text>
Write the given file instead of using stdout.
paths β sequence<text>
paths β sequence<text>
Mention the default paths of feature files.
quiet β bool
quiet β bool
Alias is used for βno-snippets βno-source.
show-source β bool
show-source β bool
Include printing the file and the line of step definition along with steps. This is an in-built characteristic and can overrule a configuration file setting.
stage β text
stage β text
Describes the present stage of the test. The stage name is utilised as the name affix for the environment file along with the directory for steps.
stop β bool
stop β bool
Terminate executing tests after encountering the first failure.
tags β sequence<text>
tags β sequence<text>
Include the features/scenarios having tags which are identical to TAG_EXPRESSION in the execution.
default_tags β text
default_tags β text
Declare the default tags if they are not given.
show_timings β bool
show_timings β bool
Capture the duration taken by each step to complete in seconds in the console. This is an in-built characteristic and can overrule a configuration file setting.
verbose β bool
verbose β bool
Displays the loaded features and files.
wip β bool
wip β bool
Execute the scenarios having the wip tag. Moreover, we have to use the plain formatter and not record the stdout or log output and terminate post first failure.
expand β bool
expand β bool
Flatten the table of Scenario Outline in output.
lang β text
lang β text
Utilise keywords for a language except English.
Behave works with three different file types, which are as follows β
Feature files which are created by a Business analyst or any project stakeholder and contains behaviour related use cases.
Feature files which are created by a Business analyst or any project stakeholder and contains behaviour related use cases.
Step Implementation file for the scenarios defined in the feature file.
Step Implementation file for the scenarios defined in the feature file.
Environment Setup files where, the pre/post conditions are to be executed prior and post the steps, features, scenarios, and so on.
Environment Setup files where, the pre/post conditions are to be executed prior and post the steps, features, scenarios, and so on.
A feature file should be within a folder called as the features. Also, there should be a sub-directory steps within the features directory.
We can launch the feature file with various command line arguments. These are explained below β
If no information is available, all the feature files within the features directory shall be loaded for execution in Behave.
If no information is available, all the feature files within the features directory shall be loaded for execution in Behave.
If the path of the features directory is provided, then it is mandatory to have at least one feature file (with .feature extension) and a sub-directory named steps within the features directory.
If the path of the features directory is provided, then it is mandatory to have at least one feature file (with .feature extension) and a sub-directory named steps within the features directory.
Also, if the environment.py is present, it should be within the directory that has the steps directory and not within the steps directory.
Also, if the environment.py is present, it should be within the directory that has the steps directory and not within the steps directory.
If the path to a feature file is provided, then it instructs Behave to search for it. To get the corresponding steps directory for that feature file, the parent directory is searched.
If the path to a feature file is provided, then it instructs Behave to search for it. To get the corresponding steps directory for that feature file, the parent directory is searched.
If not found in the current parent directory, then it searches its parents. This shall continue until it reaches the file system root. Also, if the environment.py is present, it should be within the directory that has the steps directory and not within the steps directory.
If not found in the current parent directory, then it searches its parents. This shall continue until it reaches the file system root. Also, if the environment.py is present, it should be within the directory that has the steps directory and not within the steps directory.
Gherkin keywords in Behave are listed below β
Features
Features
Scenario
Scenario
Steps
Steps
Background
Background
Scenario Outline
Scenario Outline
Text
Text
Table
Table
Tags
Tags
Given
Given
When
When
Then
Then
But
But
And
And
Feature files are written in Gherkin language. It is in plain text and created by non- technical members of the team (business analyst). Feature files can be used for both automation testing and documentation.
Line endings finish statements are included in Behave. We can use tabs/spaces for indentation. Majority of lines begin with the keywords like Scenario, Given, Then, and so on. Comments can be added in any location within the file. They start with/without spaces, followed by # symbol along with text.
Let us discuss some key Gherkin keywords.
A Feature consists of Scenarios. They may/may not contain description, background, and a group of tags.
The structure of a feature file is as follows β
Feature β Verify book name added in Library
Scenario β Verify Book name
Given Book details
Then Verify book name
The name of the feature should have a description for the feature which is being tested. However, a lengthy description is not mandatory and a description is only added to remove ambiguity in the feature name.
A Background is added to have a group of steps. It is close to a Scenario. We can add a context to the multiple Scenarios with Background. It is run prior to every Scenario of a feature, but post the execution of before hooks.
Background is generally used for executing preconditions like login Scenarios or database connection, and so on.
A Background description can be added for better human readability. A Background can appear only a single time in a feature file and it must be declared prior to a Scenario or Scenario Outline.
A Background should not be used to create a complex state (only, if it cannot be avoided). This segment should be brief and authentic. Also, we should avoid having a large number of scenarios within one feature file.
The feature file with Background keyword is as follows β
Feature: Payment Process
Background:
Given launch application
Then Input credentials
Scenario: Credit card transaction
Given user is on credit card payment screen
Then user should be able to complete credit card payment
Scenario: Debit card transaction
Given user is on debit card payment screen
Then user should be able to complete debit card payment
A Scenario defines a behaviour of the application that is being tested. It has a title to describe its objective. Its description can be added for better human readability.
A Scenario may have multiple steps, which begins with the keywords Given, Then, When, and so on. It is recommended to have a Scenario to check a single characteristic or an expected result.
Feature File with Scenario
The feature file with Scenario keyword is as follows:
Feature β Payment Process
Scenario β Credit card transaction
Given user is on credit card payment screen
Then user should be able to complete credit card payment
Scenario Outline
A Scenario Outline is used if we have a group of similar criteria and the results to be passed in a Scenario. A Scenario Outline is accompanied with an Examples table and can have multiple Examples tables.
The tests get executed once for every row found after the header row within the Examples table. The values to be tested are represented by their names enclosed in brackets<>. These names should match with the Examples table header.
It helps to reduce the lines of code as it eliminates the repeating steps and orders our tests.
The feature file with Scenario Outline keyword is as follows β
Feature β User information
Scenario Outline: Check login functionality
Given user enters <email> and <password>
Then user should be logged in
Following is an example of the feature file with Scenario Outline β
Examples: Credentials
| email | password |
| qa@gmail.com | pwd1 |
| qe@gmail.com | pwd2 |
The same test gets executed with a varied set of parameters.
A step starting the keyword Given is used to place the system in a familiar circumstance prior to the interaction of the user with the system (similar to a precondition). It is recommended not to describe a user action in the Given step.
A Given step can be added for setting the configuration in the database, log in to the application, and so on.
Feature File with Given
The feature file with Given keyword is as follows β
Feature β Payment Process
Scenario β Credit card transaction
Given user is on credit card payment screen
Then user should be able to complete credit card payment
A step starting with the keyword When is used to add the essential task to be performed by the user. With this, there is a user communication with the system that brings about the changes to systemβs state or an impact elsewhere.
Feature File with When
The feature file with When keyword is as follows β
Feature β Payment Process
Scenario β Credit card transaction
Given user is on credit card payment screen
When user clicks on the Payment with Credit Card button
Then user should be able to complete credit card payment
A step starting with the keyword Then is used to get the expected results. The results observed (ideally in form of an output - messages, reports, and so on) in this step should be connected to a business scenario and the feature file where it is present.
It is recommended not to use the Then steps for database scenarios as it is essentially used to describe an aftermath which is noticeable to the end user.
Feature File with Then
The feature file with When keyword is as follows β
Feature β Payment Process
Scenario β Credit card transaction
Given user is on credit card payment screen
When user clicks on the Payment with Credit Card button
Then user should be able to complete credit card payment
If we have multiple Given, When, Then consecutive steps, we can use And and But steps. It brings better readability to the user.
Feature File with multiple consecutive Then/Given steps
The feature file with multiple consecutive Then/Given steps in Behave is as follows β
Feature β Verify book names added in Library
Scenario β Verify Book name
Given Book1 details
Given Book2 details
Then Verify book names
Then Verify newly added book names should not be in Delete History
Feature File without multiple Then/Given steps
The feature file without multiple Then/Given steps is as follows β
Feature β Verify book names added in Library
Scenario β Verify Book name
Given Book1 details
And Book2 details
Then Verify book names
But Verify newly added book names should not be in Delete History
A step can have a text and data table associated with it. We can add a data table with a step. It is recommended to have the table data indented and it is mandatory to have an equal column number for each line.
A column data should be separated by the | symbol.
Feature File with Table
The feature file with table keyword is as follows β
Feature β User Registration
Scenario β User enters registration details
When User enters name and password
| name |password |
| t1 | pwd |
| t2 | pwd1 |
Then user should be able to complete registration
A table is accessible to the implementation Python code with the .table attribute within the context variable (passed in the step function). A table is an instance of Table.
Implementation logic for Table
Given below is an implementation logic for .table attribute in Table β
@when('User enters name and password')
def step_impl(context):
for r in context.table:
model.delete_usr(name=r['name'], password=r['password'])
A block of text after a step enclosed in """ will be linked with that step. Here, the indentation is parsed. All the whitespaces at the beginning are removed from the text. Also, all the succeeding lines must have at least a minimum whitespace as the starting line.
A text is accessible to the implementation Python code with the .text attribute within the context variable (passed in the step function).
Feature File with Text
The feature file with text keyword is as follows β
Feature β Verify book name added in Library
Scenario β Verify Book name
Given Book details
"""
Text added for a step
"""
Then Verify book name
A section of a feature file can be tagged so that the Behave is capable of verifying only a certain section of the feature file. A Scenario, Feature, Scenario Outline can only be tagged.
Also, a tag which is used for a feature shall be inherited by all its Scenarios and Scenario Outlines. Tags are placed before a Scenario or a Feature that we want to tag. We can also have multiple tags separated by spaces within a line. A tag begins with @ followed by the tag name.
Feature File with tags
The feature file with tags keyword is as follows:
@payment
@high
Feature β Payment Process
Scenario β Credit card transaction
Given user is on credit card payment screen
Then user should be able to complete credit card payment
Tags help to manage the test execution by excluding/including the specific scenarios or features depending on the tag.
Behave works with three different file types, as explained earlier. These files are as follows β
Feature files which are created by the Business analyst or any project stakeholder and contains behaviour related use cases.
Feature files which are created by the Business analyst or any project stakeholder and contains behaviour related use cases.
Step Implementation file for the scenarios defined in the feature file.
Step Implementation file for the scenarios defined in the feature file.
Environment Setup files where the pre/post conditions are to be executed prior and post steps, features, scenarios, and so on.
Environment Setup files where the pre/post conditions are to be executed prior and post steps, features, scenarios, and so on.
A Feature file should be within a folder called as the features. Also, there should be a sub-directory steps within the features directory.
The following screen will appear on your computer β
We can launch the feature file with various command line arguments, as explained below β
If no information is available, all the feature files within the features directory shall be loaded for the execution in Behave.
If no information is available, all the feature files within the features directory shall be loaded for the execution in Behave.
If the path of the features directory is provided, then it is mandatory to have at least one feature file (with .feature extension) and a sub-directory named steps within the features directory.
If the path of the features directory is provided, then it is mandatory to have at least one feature file (with .feature extension) and a sub-directory named steps within the features directory.
Also, if the environment.py is present, it should be within the directory that has the steps directory and not within the steps directory.
Also, if the environment.py is present, it should be within the directory that has the steps directory and not within the steps directory.
If the path to a feature file is provided, then it instructs Behave to search for it. To get the corresponding steps directory for that feature file, the parent directory is searched.
If the path to a feature file is provided, then it instructs Behave to search for it. To get the corresponding steps directory for that feature file, the parent directory is searched.
If not found in the current parent directory, then it searches its parents. This shall continue until it reaches the file system root. Also, if the environment.py is present it should be within the directory that has the steps directory and not within the steps directory.
If not found in the current parent directory, then it searches its parents. This shall continue until it reaches the file system root. Also, if the environment.py is present it should be within the directory that has the steps directory and not within the steps directory.
A Feature consists of Scenarios. They may/may not contain a description, background, and a group of tags.
A structure of a feature file is as follows β
Feature File
The format of a feature file is as follows β
Feature β Verify book name added in Library
Scenario β Verify Book name
Given Book details
Then Verify book name
Corresponding Step Implementation File.
The corresponding step implementation file looks like the one mentioned below β
from behave import *
@given('Book details')
def impl_bk(context):
print('Book details entered')
@then('Verify book name')
def impl_bk(context):
print('Verify book name')
Output
The output obtained after running the feature file is as follows β
The output shows the Feature and Scenario names, along with the test results and duration of the test execution.
The steps of a Scenario in the feature file in Behave should have implementation logic written in Python. This is known as the implementation/step definition file (.py extension) and should be present within the steps directory.
All the necessary imports are present in this file. The steps directory should be a part of the features directory.
The following screen will appear on your computer β
The step definition file contains Python functions which define the steps in the feature file. At the start of the Python functions, it is mandatory to have decorators which begins with @given, @when, and so on. These decorators compare and match with the Given, Then, When, and other steps in the feature file.
Feature File
The feature file is as follows β
Feature β Verify book name added in Library
Scenario β Verify Book name
Given Book details
Then Verify book name
Corresponding Step Implementation File
The corresponding step implementation file looks like the one mentioned below β
from behave import *
@given('Book details')
def impl_bk(context):
print('Book details entered')
@then('Verify book name')
def impl_bk(context):
print('Verify book name')
Output
The output obtained after running the feature file is as follows β
The output shows the Feature and Scenario names, along with test results, and duration of test execution.
Let us create a basic Behave test.
Feature File
The feature file for the Feature titled Payment Types is as follows β
Feature β Payment Types
Scenario β Verify user has two payment options
Given User is on Payment screen
When User clicks on Payment types
Then User should get Types Cheque and Cash
Corresponding Step Implementation File
The corresponding step implementation file for the above mentioned feature is as follows β
from behave import *
@given('User is on Payment screen')
def impl_bkpy(context):
print('User is on Payment screen')
@when('User clicks on Payment types')
def impl_bkpy(context):
print('User clicks on Payment types')
@then('User should get Types Cheque and Cash')
def impl_bkpy(context):
print('User should get Types Cheque and Cash')
Project Structure
The project structure for the feature βPayment Typesβ is as follows β
Output
The output obtained after running the feature file is as mentioned below and the command used here is behave
The output shows the Feature and Scenario names, along with test results, and duration of test execution.
Python Console output is given below β
We have the option to utilise other languages apart from English in the feature file. This is because, the majority of BDD tools have the support for internationalisation. The important fact is that the keywords - Then, When, Given can be described in other native languages like Spanish, French, and so on.
In that case, the developer can implement the step definitions in other languages as well. The list of all the languages can be obtained with the command: behave --lang-list.
The following screen will appear on your computer after using the command behave --lang-list β
Some more languages included in Behave are mentioned below β
A feature file can be associated with a particular language. At this time, the BDD framework chooses the keywords for that specific language. The language can be set as default in the configuration file.
Behave configuration files can be either, .behaverc or behave.ini files. The value for the parameter lang should be set to da in the configuration file, if we want the language to be to Danish.
The feature file set up for selecting a particular language is given below and the language used as an example is Danish (da).
[behave]
lang = da
We can pass parameters to steps in Behave. Let us see a feature file containing steps having multiple parameters where the varied values have been set. This is helpful in making the automation implementation easier, since the total step definitions is lessened.
Feature File
Consider an example of feature file as given below β
Feature β Schedule
Scenario β Verify Day and Night Schedule
Given I reach office at "day" shift
And I reach office at "night" shift
The feature file contains almost the similar steps as in the Given and in the And steps. The only difference is that in the day and night shift timings. Instead of repeating the implementations for almost the similar steps, we can pass parameters to the steps in the step definition file.
Please Note β We have kept the day and night parameters in double-quoted text (single-quoted text can also be used) in the feature file. In the step implementation, we shall pass the parameter enclosed in {}.
Also, the parameter is passed as one of the arguments to the implementation method.
Corresponding Step Implementation File
The corresponding step implementation file is as follows β
from behave import *
@given('I reach office at "{time}" shift')
def step_implpy(context, time):
print("Shift is: {}".format(time))
Output
The output obtained after running the feature file is as follows and the command used is behave --no-capture -f plainβ
The output shows Shift is: day and Shift is: night printed. Here, the parameters day and night are passed from the step.
A Scenario Outline is used if we have a group of similar criteria and the results are to be passed in a Scenario. A Scenario Outline is accompanied with an Examples table. A Scenario Outline can have multiple Examples tables.
The tests get executed once for every row found (after the header row) within the Examples table. The values to be tested are represented by their names enclosed in brackets<>. These names should match with the Examples table header.
It helps to reduce the lines of code (eliminates repeating steps) and orders our tests.
Feature File
The feature file for scenario outline is as follows β
Feature β User information
Scenario Outline: Check login functionality
Given user enters "<name>" and "<password>"
Then user should be logged in
Examples: Credentials
| name | password |
| user1 | pwd1 |
| user2 | pwd2 |
Please Note: We have kept the name and password parameters enclosed in "<>". These parameters are column headers provided below the Examples section. In the step implementation, we shall pass the parameters enclosed in "{}".
Also, these parameters need to be passed as arguments to the implementation method.
Corresponding Step Implementation File
The corresponding step implementation file is as follows β
from behave import *
@given('user enters "{name}" and "{password}"')
def step_implpy(context, name, password):
print("Username for login: {}".format(name))
print("Password for login: {}".format(password))
@then('user should be logged in')
def step_implpy(context):
pass
Output
The output is obtained after running the feature file and the command used is behave --no-capture -f plain.
The output shows Username for login: user1, Password for login: pwd1 and Username for login: user2, Password for login: pwd2 printed. Here, the two data sets were passed from the Examples.
A block of text after a step enclosed in """ will be linked with that step. Here, the indentation is parsed. All the whitespaces at the beginning are removed from the text and all the succeeding lines must have at least a minimum whitespace as the starting line.
A text is accessible to the implementation Python code with the .text attribute within the context variable (passed in the step function).
Feature File
The feature file for feature titled User information is as follows β
Feature β User information
Scenario β Check login functionality
Given user enters name and password
"""
Tutorialspoint Behave
Topic β Multiline Text
"""
Then user should be logged in
Corresponding Step Implementation File
The corresponding step implementation file for the feature is as follows β
from behave import *
@given('user enters name and password')
def step_impl(context):
#access multiline text with .text attribute
print("Multiline Text: " + context.text)
@then('user should be logged in')
def step_impl(context):
pass
Output
The output obtained after running the feature file is mentioned below and the command used is behave --no-capture -f plain.
The output shows the multiline text printed.
A step can have a text and data table associated with it. We can add a data table with a step. It is recommended to have the table data indented and it is mandatory to have an equal column number for each line.
A column data should be separated by the | symbol.
Feature File with Table (Login.feature)
The feature file is as mentioned below β
Feature β User Information
Scenario β Check login functionality
Given Collection of credentials
| username |password |
| user1 | pwd1 |
| user2 | pwd2 |
Then user should be logged in
A table is accessible to the implementation Python code with the .table attribute within the context variable (passed in the step function). A table is an instance of Table. We can use the set up table to facilitate setting up the test.
Python code
The python code to access table.(login_module.py) is as follows β
class Deprt(object):
def __init__(self, username, ms=None):
if not ms:
ms = []
self.username = username
self.ms = ms
def m_addition(self, usernane):
assert usernane not in self.ms
self.ms.append(usernane)
class LModel(object):
def __init__(self):
self.loginusrs = []f
self.passwords = {}
def usr_addition(self, username, password):
assert username not in self.loginusrs
if password not in self.passwords:
self.passwords[password] = Deprt(password)
self.passwords[password].m_addition(username)
Corresponding Step Implementation File(step_implg.py)
The file is as follows β
from behave import *
from features.steps.login_module import LModel
@given('Collection of credentials')
def step_impl(context):
model = getattr(context, "model", None)
if not model:
context.model = LModel()
#iterate rows of table
for r in context.table:
context.model.usr_addition(r["username"], password=r["password"])
@then('user should be logged in')
def step_impl(context):
pass
Project setup
The project set up for the file in Python project is as follows
Output
The output obtained after running the feature file is given below and the command used is behave --no-capture -f plain.
The output shows the step up table printed.
We can substitute multiple steps in a Scenario with one macro step. This helps us not to repeat the same code in the step definition file. A BDD framework has the capability to invoke multiple steps from the step definition.
Feature File with Similar Steps
The feature file with the similar steps is as follows β
Feature β Payment Module
Scenario β Verify message after payment
Given User is on payment screen
When User enters payment details
And User completes payment
Then User should get success message
Scenario β Verify new users can process payment
Given User keys in payment info and submits
Then success message should get displayed
In the feature file, we have two Scenario with similar steps. In Behave, we can execute more than one step in a single step. This can be done with the help of context.execute_steps method in the step implementation file.
Corresponding Step Implementation File
The corresponding step implementation file for the above mentioned feature file is as follows β
from behave import *
@given('User is on payment screen')
def is_on_payment_screen(context):
print('User is on payment screen')
@when('User enters payment details')
def enters_payment_details(context):
print('When User enters payment details')
@when('User completes payment')
def completes_payment(context):
print('When User completes payment')
@then('User should get success message')
def get_success_message(context):
print('Then User should get success message')
@given('User keys in payment info and submits')
def payment_info_and_submits(context):
#passing steps within steps with context.execute_steps
context.execute_steps(u"""
Given User is on payment screen
When User enters payment details
And User completes payment
""")
@then('success message should get displayed')
def success_message(context):
print('Then success message should get displayed')
Output
The output obtained after running the feature file is given below and the command used is behave --no-capture -f plain.
The continued output is as follows β
The output shows that the new users of Scenario Verify can process the payment by having the steps executed from the Scenario Verify new users can process payment.
A Background is added to have a group of steps. It is close to a Scenario. We can add a context to multiple Scenarios with Background. It is run prior to every Scenario of a feature, but post the execution of before hooks.
Background is generally used for executing preconditions like login Scenarios or database connection, and so on.
A Background description can be added for the better human readability. It can appear only for a single time in a feature file and must be declared prior to a Scenario or Scenario Outline.
A Background should not be used to create a complex state (only if it cannot be avoided). This segment should be brief and authentic. Also, we should avoid having a large number of scenarios within one feature file.
Feature File with Background
The feature file with background for the feature titled payment process is as follows β
Feature β Payment Process
Background:
Given launch application
Then Input credentials
Scenario β Credit card transaction
Given user is on credit card payment screen
Then user should be able to complete credit card payment
Scenario β Debit card transaction
Given user is on debit card payment screen
Then user should be able to complete debit card payment
Corresponding Step Implementation File
The file is given below β
from behave import *
@given('launch application')
def launch_application(context):
print('launch application')
@then('Input credentials')
def input_credentials(context):
print('Input credentials')
@given('user is on credit card payment screen')
def credit_card_pay(context):
print('User is on credit card payment screen')
@then('user should be able to complete credit card payment')
def credit_card_pay_comp(context):
print('user should be able to complete credit card pay')
@given('user is on debit card payment screen')
def debit_card_pay(context):
print('User is on debit card payment screen')
@then('user should be able to complete debit card payment')
def debit_card_pay_comp(context):
print('user should be able to complete debit card payment')
Output
The output obtained after running the feature file is mentioned below and the command used here is behave --no-capture -f plain.
The continued output is as follows β
The output shows the Background steps (Given Launch applications & Then Input Credentials) running twice before each of the Scenarios.
There are two types of Data Types in Behave, which are Predefined and User-defined. Let us first understand what are the predefined data types.
Behave utilises the parse module for the parsing parameters in the step definitions. Let us explore some of the parse types that have support for step definitions and do not need be registered like user-defined data types.
w (of str type) β Underscore & letters.
w (of str type) β Underscore & letters.
W (of str type) β Underscore & non-letters.
W (of str type) β Underscore & non-letters.
s (of str type) β Whitespace.
s (of str type) β Whitespace.
S (of str type) β Non - Whitespace.
S (of str type) β Non - Whitespace.
d (of int type) β Digits.
d (of int type) β Digits.
D (of str type) β Non - Digits.
D (of str type) β Non - Digits.
n (of int type) β Numbers having thousands separators.
n (of int type) β Numbers having thousands separators.
% (of float type) β Percentage. (translated to value/100.0)
% (of float type) β Percentage. (translated to value/100.0)
f (of float type) β Fixed β point numbers.
f (of float type) β Fixed β point numbers.
e (of float type) β Floating β point numbers along with exponent.
e (of float type) β Floating β point numbers along with exponent.
g (of float type) β Number format.
g (of float type) β Number format.
b (of int type) β Numbers in binary.
b (of int type) β Numbers in binary.
(of int type) β Numbers in octal.
(of int type) β Numbers in octal.
x (of int type) β Numbers in hexadecimal.
x (of int type) β Numbers in hexadecimal.
ti (of datetime type) β Time in ISO 8601 date/time format.
ti (of datetime type) β Time in ISO 8601 date/time format.
te (of datetime type) β Time in RFC 2822 email data/time format.
te (of datetime type) β Time in RFC 2822 email data/time format.
tg (of datetime type) β Time in Global data/time format.
tg (of datetime type) β Time in Global data/time format.
ta (of datetime type) β Time in US data/time format.
ta (of datetime type) β Time in US data/time format.
tc (of datetime type) β ctime() data/time format.
tc (of datetime type) β ctime() data/time format.
th (of datetime type) β Time in HTTP log data/time format.
th (of datetime type) β Time in HTTP log data/time format.
tt (of time type)
tt (of time type)
In the step implementation, we shall pass the parameter: data type enclosed in "{}".
Feature File with % data type
The feature file with % data type is as follows β
Feature β Payment Process
Scenario Outline: Credit card transaction
Given user is on credit card payment screen
When user makes a payment of "<p>" percent of total
Examples: Amounts
| p |
|80% |
|90% |
Corresponding Step Implementation File
The file is as follows β
from behave import *
@given('user is on credit card payment screen')
def credit_card_pay(context):
print('User is on credit card payment screen')
#passing parameter in % datatype enclosed in {}
@when('user makes a payment of "{p:%}" percent of total')
def step_impl(context, p):
print('Number is: ')
print(p)
Output
The output is obtained after running the feature file and the command used is behave --no-capture -f plain.
The continued output is as follows β
The output shows 0.8 and 0.9 which is obtained from the % data type to represent 80% and 90% values passed from the feature file.
Behave also has the user-defined data types. The method register_type is used to register a user defined type that can be parsed for any type conversion at the time of matching the step.
Feature File
The feature file for feature titled payment process is as follows β
Feature β Payment Process
Scenario Outline: Credit card transaction
Given user is on credit card payment screen
When user makes a payment of "<amount>" of total
Examples: Amounts
|amount |
|75 |
|85 |
In the step implementation, we shall pass the parameter: user-defined datatype enclosed in "{}". The method register_type is used to register a user defined type that can be parsed for any type conversion at the time of matching the step.
Corresponding Step Implementation File
The file is as follows β
from behave import *
from behave import register_type
#convert parsed text to float
def parse_percent(t):
return float(t)
#register user-defined type
register_type(Float=parse_percent)
@given('user is on credit card payment screen')
def credit_card_pay(context):
print('User is on credit card payment screen')
@when('user makes a payment of "{amount:Float}" of total')
def step_impl(context, amount):
print('Number is: ')
print(amount)
Output
The output is obtained after running the feature file and the command used is behave --no-capture -f plain.
The continued output is as follows β
The output shows 75.0 and 85.0 which have been converted to float values (with the help of user-defined conversion). These parameters are passed as the integer types from the feature file.
A section of a feature file can be tagged so that the Behave is capable of verifying only a certain section of the feature file. A Scenario, Feature, Scenario Outline can only be tagged.
Also, a tag which is used for a feature shall be inherited by all its Scenarios and the Scenario Outlines. Tags are placed before a Scenario or a Feature that we want to tag. We can also have multiple tags which are separated by spaces within a line.
A tag begins with @ and is followed by the tag name.
Feature File with tags (Payment.feature)
The feature file with tags is as follows β
@high
Feature β Payment Process
@creditpayment
Scenario β Credit card transaction
Given user is on credit card payment screen
Then user should be able to complete credit card payment
@debitpayment
Scenario β Debit card transaction
Given user is on debit card payment screen
Then user should be able to complete debit card payment
Tags help to manage the test execution by excluding/including the specific scenarios or features depending on the tag.
In the above example, to run a specific scenario with tag creditpayment, we have to run the below mentioned command β
behave payment.feature --tags=creditpayment
To run the feature with tag high and execute all the Scenarios, we have to run the following command β
behave payment.feature --tags=high
If run the command stated below, it means that the command shall execute the Scenarios which are tagged with creditpayment or debitpayment.
behave payment.feature --tags= creditpayment, debitpayment
If run the command given below, it means that the command shall execute both the Scenarios which are tagged with creditpayment and debitpayment.
behave payment.feature --tags= creditpayment --tags=debitpayment
If run the command mentioned below, it means that the command shall not execute the Scenario which is tagged with creditpayment.
behave payment.feature --tags= ~ creditpayment
Hence, the Feature File with tags(Payment.feature) will now be as follows β
@high
Feature β Payment Process
@creditpayment @payment
Scenario β Credit card transaction
Given user is on credit card payment screen
@debitpayment @payment
Scenario β Debit card transaction
Given user is on debit card payment screen
Scenario β Cheque transaction
Given user is on cheque payment screen
Corresponding Step Implementation File
The file is as follows β
from behave import *
@given('user is on credit card payment screen')
def credit_card_pay(context):
print('User is on credit card payment screen')
@given('user is on debit card payment screen')
def debit_card_pay(context):
print('user is on debit card payment screen')
@given('user is on cheque payment screen')
def cheque_pay(context):
print('user is on cheque payment screen')
Output
The output obtained after running the feature file is mentioned below. Here, we have used the command behave --no-capture Payment.feature --tags=payment.
The output shows two scenarios passed, as there are two Scenarios in the features file having Scenario tag with payment.
When we use the command behave --no-capture Payment.feature --tags=~creditpayment, the output is as follows β
The output shows two scenarios passed, as there are two Scenarios in the features file not having Scenario tag with creditpayment.
When we use the command behave --no-capture Payment.feature --tags=high, the output is given below β
The output shows three scenarios passed, as there are three Scenarios in the features file not having features tagged with high.
Use the command behave --no-capture Payment.feature --tags=payment,creditpayment to get the below mentioned output β
The output shows two scenarios passed, as there are two Scenarios in the features file not having Scenario tagged with payment or creditpayment.
Enumeration is used to map the multiple distinctive string based words to the values.
We may require a user-defined data type having the following characteristics β
A handful of words must be matched.
A handful of words must be matched.
Pre-defined values prior to the test execution.
Pre-defined values prior to the test execution.
For the above scenarios, enumeration based on string can be used.
Feature File
Consider a feature file for the Feature titled payment process, as mentioned below β
Feature β Payment Process
Scenario β Response
When User asks "Is payment done?"
Then response is "No"
In the step implementation file, TypeBuilder.make_enum function evaluates a regular expression pattern for the provided enumeration of words or strings. The method register_type is used to register a user defined type that can be parsed for any type conversion at the time of matching the step.
Also, we shall pass the parameter: user-defined enum datatype enclosed in "{}".
Corresponding Step Implementation File
The step implementation file for the above Feature is as follows β
from behave import *
from behave import register_type
from parse_type import TypeBuilder
# -- ENUM: Yields True (for "yes"), False (for "no")
parse_response = TypeBuilder.make_enum({"yes": True, "no": False})
register_type(Response=parse_response)
@when('User asks "{q}"')
def step_question(context, q):
print("Question is: ")
print(q)
@then('response is "{a:Response}"')
def step_answer(context, a):
print("Answer is: ")
print(a)
Output
The output obtained after running the feature file is mentioned below. Here, we have used the command behave --no-capture -f plain.
The output shows Is payment done? and False. The output False comes from the enumeration data type.
There are three types of Step Matchers in Behave. They are explained below β
ParseMatcher (parse) β Based on the parse module.
ParseMatcher (parse) β Based on the parse module.
extended ParseMatcher(cfparse) β Allows cardinality syntax.
extended ParseMatcher(cfparse) β Allows cardinality syntax.
RegexMatcher (re) β Based on regular expressions for matching patterns.
RegexMatcher (re) β Based on regular expressions for matching patterns.
It is the in-built step matcher which has the below mentioned features:
Simple to use and comprehend.
Simple to use and comprehend.
Predefined and user-defined data types support this matcher.
Predefined and user-defined data types support this matcher.
Re-utilises regular expressions with the help of data types.
Re-utilises regular expressions with the help of data types.
Conceals the complexity of regular expression.
Conceals the complexity of regular expression.
It extends the Parse Matcher. It has additional features along with the features of Parse matcher.
The additional features include β
Comprehends the cardinality field syntax.
Comprehends the cardinality field syntax.
Generates missing type converters for the fields with cardinality field parts.
Generates missing type converters for the fields with cardinality field parts.
Built on parse-type.
Built on parse-type.
It has the below features β
Backward compatible to Cucumber.
Backward compatible to Cucumber.
Easier to use compared to a parse matcher.
Easier to use compared to a parse matcher.
Let us understand the parse matchers in detail.
There are maybe steps in the feature file having almost similar phrases. Behave has the parsing ability. The method use_step_parser is used for this and we have to pass the parser type as a parameter to that method.
For parse matchers, we have to pass the parameter parse. It utilises the parse for regular expressions parsing and matching.
Feature File (almost Given similar steps)
The feature file for the similar steps is as follows β
Feature β Payment Process
Scenario β Check Debit transactions
Given user is on "debit" screen
When user makes a payment
Scenario β Check Credit transactions
Given user is on "credit" screen
Corresponding Step Implementation File
The step implementation file is as follows β
from behave import *
#define parser type
use_step_matcher("parse")
@given('user is on "{p}" screen')
def step_impl(context, p):
print(p)
@when('user makes a payment')
def step_pay_complete(context):
pass
Output
The output obtained after running the feature file is mentioned below. Here, we have used the command behave --no-capture -f plain.
The output shows debit and credit. These two values have been passed with almost similar Given steps in the feature file. In step implementation, we have parsed both the steps.
Let us have an overall view of the syntax of regular expressions β
Dot (.) β Equivalent to any character.
Dot (.) β Equivalent to any character.
Caret (^) β Equivalent to beginning of string. (^...)
Caret (^) β Equivalent to beginning of string. (^...)
Dollar Sign ()βEquivalenttoendofstring.(...)
Dollar Sign ()βEquivalenttoendofstring.(...)
| β Expression x| y, matches x or y.
| β Expression x| y, matches x or y.
\ β Escape character.
\ β Escape character.
\. β Matches dot. (.)
\. β Matches dot. (.)
\\ β Matches backslash. (\)
\\ β Matches backslash. (\)
[...] β Declares a set of characters. ([A-Za-z])
[...] β Declares a set of characters. ([A-Za-z])
\d β Matches digit. ([0-9])
\d β Matches digit. ([0-9])
\D β Matches non-digit.
\D β Matches non-digit.
\s β Matches whitespace character.
\s β Matches whitespace character.
\S β Matches non - whitespace character.
\S β Matches non - whitespace character.
\w β Matches alphanumeric.
\w β Matches alphanumeric.
\W β Matches non-alphanumeric.
\W β Matches non-alphanumeric.
(...) β Group a pattern of regular expression.
(...) β Group a pattern of regular expression.
\number β Matches text of previous group by index. (\1)
\number β Matches text of previous group by index. (\1)
(? P<name>...) β Matches pattern and stores it in the name parameter.
(? P<name>...) β Matches pattern and stores it in the name parameter.
(?P=name) β Matches all text which was matched by the previous group name.
(?P=name) β Matches all text which was matched by the previous group name.
(?:...) β Matches a pattern, however cannot capture text.
(?:...) β Matches a pattern, however cannot capture text.
(?#...) β Comment (not considered). Narrates details of pattern.
(?#...) β Comment (not considered). Narrates details of pattern.
In case a character, character set or group needs to repeat multiple times, it is mandatory to provide the cardinality of the pattern of regular expression.
? : Pattern having cardinality 0... 1:not mandatory(question mark)
? : Pattern having cardinality 0... 1:not mandatory(question mark)
- : Pattern having cardinality 0 or more, 0..( asterisk)
- : Pattern having cardinality 0 or more, 0..( asterisk)
+ - : Pattern having cardinality 1 or more, 1..(plus)
+ - : Pattern having cardinality 1 or more, 1..(plus)
{n}: Matches a pattern for n repetitions.
{n}: Matches a pattern for n repetitions.
{a ,b}: Matches from a to b for a pattern repetitions.
{a ,b}: Matches from a to b for a pattern repetitions.
[A-Za-z]+ : Matches multiple alphabetical characters.
[A-Za-z]+ : Matches multiple alphabetical characters.
There are maybe steps in the feature file having almost the similar phrases. Behave has the parsing ability. The method use_step_parser is used for this and we have to pass the parser type as a parameter to that method.
For regular expression matchers, we have to pass the parameter re. The parameter (? P<name>...) is utilised to obtain parameters from the step definition.
Feature File (almost similar steps)
The feature file for similar steps is as follows β
Feature β Payment Process
Scenario β Check Debit transactions
Given user is on "debit" screen
Scenario β Check Credit transactions
Given user is on "credit" screen
Corresponding Step Implementation File
The step implementation file is as follows β
from behave import *
#define parser type
use_step_matcher("re")
#regular expression parsing
@given('user is on "(?P<payment>.*)" screen')
def step_impl(context, payment):
print("Screen type: ")
print(payment)
Output
The output obtained after running the feature file is as follows. Here, we have used the command behave --no-capture -f plain.
The output shows the debit and credit. These two values have been passed with almost the similar steps in the feature file. In step implementation, we have parsed both the steps with regular expression.
There are maybe steps in the feature file having almost similar phrases. Behave has the parsing ability so that one step definition can cover these steps. The method use_step_parser is used for this and we have to pass the parser type as a parameter to that method.
For extended parse matchers, we have to pass the parameter cfparse. It has the Cardinality Field (CF) support. By default, it generates the missing type converters for connected cardinality (if type converter for cardinality equal to one is given).
It can support the below parse expressions β
{values:Type+} β Cardinality=1..N, many
{values:Type+} β Cardinality=1..N, many
{values:Type*} β Cardinality=0..N, many0
{values:Type*} β Cardinality=0..N, many0
{values:Type?} β Cardinality=0..1, optional
{values:Type?} β Cardinality=0..1, optional
Feature File (almost similar steps)
The feature file with almost similar steps is as follows β
Feature β Payment Process
Scenario β Check Debit transactions
Given user is on "debit" screen
Scenario β Check Credit transactions
Given user is on "credit" screen
The method register_type is used to register a user defined type that can be parsed for any type conversion at the time of matching the step.
Corresponding Step Implementation File
The step implementation file is given below β
from behave import *
import parse
#define parse type
use_step_matcher("cfparse")
# for whitespace characters
@parse.with_pattern(r"x\s+")
def parse_string(s):
#type converter for "x" succeeded by single/multiple spaces
return s.strip()
#register user-defined datatype
register_type(x_=parse_string)
#optional part :x_? cardinality field in parse expression
@given('user is on {:x_?}{payment} screen')
def step_payment(context, x_, payment):
print("Payment type: ")
print(payment)
Output
The output obtained after running the feature file is given below and the command used is behave --no-capture -f plain.
The output shows the debit and credit. These two values have been passed with almost similar steps in the feature file. In step implementation, we have parsed both the steps with cardinality fields within parse expression.
There are maybe steps in the feature file having almost similar phrases. For instance,
Given user makes payment of 100 INR
And user makes payment of 10 Dollar
Here, we can have different step definitions to differentiate the INR and Dollar. For this, we can use the multi-method approach, where it is mandatory to have varied regular expressions for the dissimilar data types.
Feature File (almost similar steps)
Consider the feature file as given below β
Feature β Multi-Methods
Scenario β Purchase
Given User is on shop
When user purchases 3 shirts
And user purchases 4 pants
In the step implementation file, TypeBuilder.make_choice function evaluates a regular expression pattern for the provided choices. The method register_type is used to register a user defined type that can be parsed for any type conversion at the time of matching the step.
Also, we shall pass the parameter: user-defined datatype enclosed in "{}".
Corresponding Step Implementation File
The step implementation file is as follows β
from behave import *
from behave import register_type
from parse_type import TypeBuilder
parse_dress = TypeBuilder.make_choice(["shirts", "t-shirts"])
#register user-defined datatype
register_type(Dress=parse_dress)
parse_pant = TypeBuilder.make_choice(["pants", "gowns"])
#register user-defined datatype
register_type(Pant=parse_pant)
@given("User is on shop")
def step_user_shop(context):
pass
# multiple methods being used .
@when(u"user purchases {count:n} {d:Dress}")
def step_dress(context, count, d):
print("User purchased: ")
print(d)
print("Count is:")
print(count)
@when(u"user purchases {count:n} {p:Pant}")
def step_pant(context, count, p):
print("User purchased: ")
print(p)
print("Count is:")
print(count)
Output
The output obtained after running the feature file is given below and the command used is behave --no-capture -f plain.
The output shows the purchase items and their counts. These two values have been passed with almost similar steps (but dissimilar data types) in the feature file. In step implementation, we have used multiple methods to obtain the values.
Step functions are created in the Python files which exist within the steps directory. Every Python file (having extension as .py) inside that directory gets imported to get the step implementations.
Once the feature files get triggered for execution, the implementation files get loaded. The step functions are associated with the step decorators.
The step implementations must begin with the import, by using the command mentioned below β
from behave import *
This will import multiple decorators described in Behave to help us to locate our step functions. The decorators like the given, when, then, and so on accepts one string argument.
For example, consider the code given herewith β
@given('user is on admin screen')
def step_impl(context):
pass
The above code shall match the Given step of the below feature file, which is as follows β
Feature β Admin Module
Scenario β Admin verification
Given user is on admin screen
The steps starting with And/But in the feature file are renamed to their earlier step keyword.
For example, consider the feature file given below β
Feature β Admin Module
Scenario β Admin verification
Given user is on admin screen
And user is on history screen
Then user should be able to see admin name
But user should not able to check history
The And step shall be renamed to the Given step and the But step shall be renamed to the earlier step keyword. All these are handled internally.
If there are more than one And/But steps consecutively, they would inherit the keyword of non And or But keyword.
The step function having the step decorator shall have a minimum one parameter. The first parameter is known as the context variable. Other parameters come from step parameters (if required).
For example, refer the step function as per the step parameter.
@given('user is on admin screen')
def step_impl(context):
pass
Project Structure
The project structure for the feature is as follows β
We can have parameters within the step names. These parameters can be taken care of by the regular expressions or by the default or extended parser with the help of the use_step_matcher method.
Modify the parameter matcher in parsing the step text. There are multiple in-built parsers present in Behave, as explained below β
parse β It gives an easy parser that restores regular expression for the step parameters with plain syntax. For example, {parameter: type}. It allows type conversion with type converters.
parse β It gives an easy parser that restores regular expression for the step parameters with plain syntax. For example, {parameter: type}. It allows type conversion with type converters.
cfparse β It has the Cardinality Field (CF) support. By default, it generates the missing type converters for connected cardinality (if type converter for cardinality equal to one is given). It can support the below parse expressions β
{values:Type+} β Cardinality=1..N, many
{values:Type*} β Cardinality=0..N, many0
{values:Type?} β Cardinality=0..1, optional
It allows type conversion with type converters.
cfparse β It has the Cardinality Field (CF) support. By default, it generates the missing type converters for connected cardinality (if type converter for cardinality equal to one is given). It can support the below parse expressions β
{values:Type+} β Cardinality=1..N, many
{values:Type*} β Cardinality=0..N, many0
{values:Type?} β Cardinality=0..1, optional
It allows type conversion with type converters.
re β It utilises the complete regular expressions to parse the clause. We have to take the help of the named groups (? P<name>...) to declare variables obtained from the text and then feed it to the step ().
re β It utilises the complete regular expressions to parse the clause. We have to take the help of the named groups (? P<name>...) to declare variables obtained from the text and then feed it to the step ().
We can have our customised matcher along with new data types with the help of the register_type method.
Registers a user defined type for parsing during type conversion at the time of step matching.
It extracts the parameters out of step names.
pattern β The pattern matching associated with the step function.
pattern β The pattern matching associated with the step function.
func β The step function is the pattern is associated with.
func β The step function is the pattern is associated with.
check_match(step) β To match with the step name provided.
check_match(step) β To match with the step name provided.
describe(schema=None) β Give description in form of text of the function or matcher object.
describe(schema=None) β Give description in form of text of the function or matcher object.
regex_pattern: Yields the utilised textual regex expression.
regex_pattern: Yields the utilised textual regex expression.
An argument for a step name in the feature file obtained with step decorator parameters.
The attributes are as follows β
original β The original text which is matched in the name of the step.
original β The original text which is matched in the name of the step.
value β The value of the argument which is type converted.
value β The value of the argument which is type converted.
name β The argument name. The value is set to None, if the parameter is not given.
name β The argument name. The value is set to None, if the parameter is not given.
start β The starting index of the argument in step name.
start β The starting index of the argument in step name.
end β The ending index of the argument in step name.
end β The ending index of the argument in step name.
A step in the feature file which is parameter-matched and obtained with step decorator parameters.
The attributes are as follows β
func β The step function which is applicable to the given match.
func β The step function which is applicable to the given match.
arguments β The argument list the instances having the matched parameter obtained from the name of the step.
arguments β The argument list the instances having the matched parameter obtained from the name of the step.
We can run a Behave test, by running the command line arguments, or we can create a runner script. This script gives the provision of running the test and generating the corresponding report.
We can do a re-try and execute the failed test. Also, before executing the entire suite, the runner script is capable of making an application programming interface (API) call and ensuring that there are no issues with the API.
Follow the steps given below to create and execute a runner script successfully in Behave.
Step 1 β Create a runner script (runner.py) within the features folder.
The following screen will appear on your computer β
Step 2 β Runner Script Implementation to run tests
The runner script can be implemented to run the tests by using the below mentioned code β
import subprocess
if __name__ == '__main__':
#command line args along with error capture on failure with check true
s = subprocess.run('behave --no-capture',shell=True, check=True)
Step 3 β Execute the runner script
Execute runner.py file with command python3 runner.py (if Python version is 3). The following screen will appear on your computer:
Step 4 β Parametrise runner script by passing command line arguments.
The runner script implementation to run tests can be done as follows β
import argparse
import subprocess
if __name__ == '__main__':
p = argparse.ArgumentParser()
#--testdir command line argument added
p.add_argument('--testdir', required=False, help="File path")
a = p.parse_args()
testdir = a.testdir
#complete command
c= f'behave --no-capture {testdir}'
s = subprocess.run(c, shell=True, check=True)
Step 5 β Execute the runner script
Execute runner.py file with command python3 runner.py --testdir=features.
We can exclude the executing files by its filename from execution.
Suppose, we have more than one feature file within the features folder. The following screen can be seen on the computer β
On executing the command behave, the output will be as follows β
If we have to only run the feature file Payment.feature and exclude Payment1.feature, we have to pass the command line argument --e or --exclude followed by pattern of the regular expression.
On executing the command behave --exclude *1.feature, the output is as follows β
The output shows one feature passed along with the Payment.feature file name. Also, Payment1.feature is not included in the run.
We can rerun failed Scenarios in the feature file in Behave. This is taken care with the help of the formatters.
All the available formatters in Behave can be seen with the command given below β
behave βf help
You can see the following screen after using the command β
The rerun formatter is used to capture the failing scenario and output it in a separate file. Let us take an example, where we have 1 failed feature.
Then capture the failed feature in another feature file with the command β
behave βf rerun βo failed_features.feature
You can see the following β
The failed_features.feature file gets generated within the project. It contains the feature file name Payment1.feature where we have a failure.
To re-trigger only failed Scenario, we have to run the command stated below β
behave @failed_features.feature
You will see the following screen β
Report generation is one of the most important steps towards the test automation framework. At the end of the execution, we cannot rely on the console output rather we should have a detailed report.
It should have the information on the count of tests that passed, failed, skipped, feature and scenario breakdown. Behave does not produce an in-built report but it can output in multiple formats and we can utilize the third-party tools to generate a report.
All the available formatters in Behave are displayed with the command β
behave --format help
When you use the command, the following screen will appear on your computer β
Some of the common Behave reports are β
Allure Report.
Allure Report.
Output JSON Report.
Output JSON Report.
JUnit Report
JUnit Report
Let us execute a test having two feature files with the below test results β
Project folder structure for the above test will be as follows β
Step 1 β Execute the command
To create a JUnit report, run the command given below β
behave --junit
Step 2 β Report folder generation
A folder called as the reports gets generated within the project, having the name TESTS-<feature file name>.xml.
Here, Payment and Payment1 are the names of the feature files.
Step 3 β Report generation to a specific folder
To generate the reports to a specific folder, say my_reports. We have to run the below mentioned command β
behave --junit --junit-directory my_reports
A folder called the my_reports gets generated within the project which contains the reports.
We can create the Behave JSON report. The JSON is actually a formatter.
Let us execute a test having two feature files with the below test results β
Project folder structure for the above test is as follows β
Step 1 β Execute the command
To create a JSON output in console, run the command β
behave -f json
The following screen will appear β
Step 2 β Output in readable format
To create a JSON output in a more readable format, run the following command β
behave -f json.pretty
Some portion of the output captured in the below image β
Step 3 β Report generation to a specific folder
To generate the reports to a specific folder say, my_reports.json, we have to run the following command β
behave βf json.pretty βo my_reports.json
The following image represents the screen that will appear on your computer.
A folder called the my_reports.json gets generated within the project, having details of all the features which are executed.
To generate Allure reports in Behave, first we have to install Allure in the system. For installation from the command line in Linux, run the following commands one after the other β
sudo apt-add-repository ppa:qameta/allure
sudo apt-get update
sudo apt-get install allure
For Mac users, installation is done with the Homebrew with the following command β
brew install allure
For Windows, Allure is installed from the Scoop installer. Run the below command to download and install Scoop and finally, execute it in the PowerShell β
scoop install allure
To update Allure distribution installations from Scoop, run the below command from the installation directory of Scoop β
\bin\checkver.ps1 allure -u
Finally, run the command given below β
scoop update allure
After Allure has been installed, we have to get the Allure-Behave integration plugin for Python. For this, run the following command β
pip install allure-behave
To verify if Allure has been installed successfully, run the command stated below β
allure
Let us execute a test having two feature files with the below test results β
Project folder structure for the above test is as follows β
Step 1 β Report generation to a specific folder
To generate the reports to a specific folder, say my_allure, we have to run the following command β
behave -f allure_behave.formatter:AllureFormatter βo my_allure
You will get the screen as shown below β
A folder called the my_allure gets generated within the project, having files with .json extension.
Step 2 β Start the web server
To start the web server, run the command given below β
allure serve my_allure
Here, the my_allure is the directory which contains the allure json files.
Simultaneously, a browser gets opened, with the Allure report as shown below β
We can also click on individual features and find their breakdowns, as shown below β
Behave setup and teardown functions are implemented in a file called the environment.py which is within the same directory that contains the steps folder. The setup functions include β browser open, database connection, configurations, and so on.
The teardown functions include browser closure, database connection termination, reversing changes, and so on.
The environment.py file contains the following functions β
before_feature(context, feature) β Executes prior every feature.
before_feature(context, feature) β Executes prior every feature.
before_scenario(context, scenario) β Executes prior every scenario.
before_scenario(context, scenario) β Executes prior every scenario.
before_step(context, step) β Executes prior every step.
before_step(context, step) β Executes prior every step.
before_tag(context, tag) β Executes prior every tag.
before_tag(context, tag) β Executes prior every tag.
before_all(context) β Executes prior everything.
before_all(context) β Executes prior everything.
after_feature(context, feature) β Executes post every feature.
after_feature(context, feature) β Executes post every feature.
after_scenario(context, scenario) β Executes post every scenario.
after_scenario(context, scenario) β Executes post every scenario.
after_step(context, step) β Executes post every step.
after_step(context, step) β Executes post every step.
after_tag(context, tag) β Executes post every tag.
after_tag(context, tag) β Executes post every tag.
after_all(context) β Executes post everything.
after_all(context) β Executes post everything.
The above functions are used as hooks in Behave. Project structure should be as follows β
Feature File with hooks (Payment.feature)
The feature file with hooks for Payment.feature is as follows β
Feature β Payment Process
Scenario β Verify transactions
Given user makes a payment of 100 INR And user makes a payment of 10 Dollar
Feature File with hooks (Payment1.feature)
Given below is the feature file with hooks for Payment1.feature β
Feature β Administration Process
Scenario β Verify admin transactions
Given user is on admin screen
Corresponding step Implementation File
The step implementation file is as follows β
from behave import *
from parse_type import TypeBuilder
parse_amt = TypeBuilder.make_choice(["100", "10"])
register_type(Amt=parse_amt)
parse_curr = TypeBuilder.make_choice(["INR", "Dollar"])
register_type(Curn=parse_curr)
@given("user makes a payment of {n:Amt} {t:Curn}")
def step_payment(context, n, t):
pass
@given('user is on admin screen')
def step_admin(context):
pass
Step 4 β Hooks in environment.py file
The hooks in environment.py file are as follows:
# before all
def before_all(context):
print('Before all executed')
# before every scenario
def before_scenario(scenario, context):
print('Before scenario executed')
# after every feature
def after_feature(scenario, context):
print('After feature executed')
# after all
def after_all(context):
print('After all executed')
Output
The output obtained after running the feature files is as follows β
Behave scripts can be debugged by dry running the test steps. The dry run helps to go over all the test steps without actually running it. It helps to determine the un-defined steps in the step definition file.
It verifies if there are any missing import statements, syntax errors, and so on. All these issues get detected in a quick time by dry run. If we are doing mass updates or any configuration changes, dry running helps to detect any errors in a short time.
If we would have to run an entire suite for debugging, that would be time consuming. In Behave, we can do a debug by dry run with the help of the below mentioned command β
behave --no-capture --dry-run
You will get the screen as shown below β
The output shows 3 untested which shows the count of the test steps.
Let us dry run feature files having unimplemented steps, as shown below β
The output clearly defines the un-defined steps in the step definition file obtained by dry run.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2579,
"s": 2296,
"text": "Behave is a tool used for Behaviour driven development (BDD) in Python programming language. In an Agile development framework, BDD creates a culture where testers, developers, business analysts, and other stakeholders of the project can contribute towards the software development."
},
{
"code": null,
"e": 2765,
"s": 2579,
"text": "In short, both technical and non-technical individuals have a role to play towards the overall project. Behave has tests developed in plain text with the implementation logic in Python."
},
{
"code": null,
"e": 2867,
"s": 2765,
"text": "The BDD format begins with the description of the characteristics of the software similar to a story."
},
{
"code": null,
"e": 2944,
"s": 2867,
"text": "It then continues with the development and carries out the following tasks β"
},
{
"code": null,
"e": 2996,
"s": 2944,
"text": "Developing a failing test case for characteristics."
},
{
"code": null,
"e": 3048,
"s": 2996,
"text": "Developing a failing test case for characteristics."
},
{
"code": null,
"e": 3088,
"s": 3048,
"text": "Implement the logic for a test to pass."
},
{
"code": null,
"e": 3128,
"s": 3088,
"text": "Implement the logic for a test to pass."
},
{
"code": null,
"e": 3176,
"s": 3128,
"text": "Code refactor to fulfil the project guidelines."
},
{
"code": null,
"e": 3224,
"s": 3176,
"text": "Code refactor to fulfil the project guidelines."
},
{
"code": null,
"e": 3383,
"s": 3224,
"text": "There are numerous libraries for BDD like the Mocha which supports JavaScript, Cucumber which supports Java/Ruby, and Behave which supports Python, and so on."
},
{
"code": null,
"e": 3442,
"s": 3383,
"text": "In this tutorial, we shall discuss in detail about Behave."
},
{
"code": null,
"e": 3558,
"s": 3442,
"text": "Let us see a basic structure of a BDD. It mainly consists of the feature file, the step definition file, and so on."
},
{
"code": null,
"e": 3605,
"s": 3558,
"text": "The feature file in Behave can be as follows β"
},
{
"code": null,
"e": 3727,
"s": 3605,
"text": "Feature β Verify book name added in Library.\nScenario β Verify Book name.\nGiven β Book details.\nThen β Verify book name.\n"
},
{
"code": null,
"e": 3791,
"s": 3727,
"text": "Following is the corresponding definition file in Behave tool β"
},
{
"code": null,
"e": 3967,
"s": 3791,
"text": "from behave import *\n@given('Book details')\ndef impl_bk(context):\n print('Book details entered')\n@then('Verify book name')\ndef impl_bk(context):\n print('Verify book name')"
},
{
"code": null,
"e": 4034,
"s": 3967,
"text": "The output obtained after running the feature file is as follows β"
},
{
"code": null,
"e": 4163,
"s": 4034,
"text": "The output shows the Feature and Scenario names, along with the test results, and the duration of the respective test execution."
},
{
"code": null,
"e": 4219,
"s": 4163,
"text": "Behave installation can be done by the following ways β"
},
{
"code": null,
"e": 4422,
"s": 4219,
"text": "For Behave installation, we should have pip β the package installer for the Python language installed in our system. The pip is installed by default, if the Python version is greater than 2(upto 2.7.9)."
},
{
"code": null,
"e": 4472,
"s": 4422,
"text": "To install pip, run the below mentioned command β"
},
{
"code": null,
"e": 4489,
"s": 4472,
"text": "pip install pip\n"
},
{
"code": null,
"e": 4547,
"s": 4489,
"text": "To install pip with Behave, run the command given below β"
},
{
"code": null,
"e": 4567,
"s": 4547,
"text": "pip install behave\n"
},
{
"code": null,
"e": 4619,
"s": 4567,
"text": "The following screen will appear on your computer β"
},
{
"code": null,
"e": 4692,
"s": 4619,
"text": "We can update an existing version of Behave with the following command β"
},
{
"code": null,
"e": 4715,
"s": 4692,
"text": "pip install βU behave\n"
},
{
"code": null,
"e": 4777,
"s": 4715,
"text": "We can also use the easy_install for the Behave installation."
},
{
"code": null,
"e": 4833,
"s": 4777,
"text": "To install Setuptools, run the below mentioned commandβ"
},
{
"code": null,
"e": 4857,
"s": 4833,
"text": "pip install setuptools\n"
},
{
"code": null,
"e": 4921,
"s": 4857,
"text": "Now, for the Behave installation, run the command stated below:"
},
{
"code": null,
"e": 4942,
"s": 4921,
"text": "easy_install behave\n"
},
{
"code": null,
"e": 5016,
"s": 4942,
"text": "We can update an existing version of behave with the command given below:"
},
{
"code": null,
"e": 5040,
"s": 5016,
"text": "easy_install βU behave\n"
},
{
"code": null,
"e": 5187,
"s": 5040,
"text": "Post unpacking of the source distribution of Behave, type the new generated directory 'behave-<version>' and execute the below mentioned command β"
},
{
"code": null,
"e": 5212,
"s": 5187,
"text": "python setup.py install\n"
},
{
"code": null,
"e": 5266,
"s": 5212,
"text": "We should first have the pip installed in the system."
},
{
"code": null,
"e": 5371,
"s": 5266,
"text": "Later on, to install the latest version of Behave with Git repository, run the below mentioned command β"
},
{
"code": null,
"e": 5421,
"s": 5371,
"text": "pip install git+https://github.com/behave/behave\n"
},
{
"code": null,
"e": 5579,
"s": 5421,
"text": "If we use the PyCharm Editor for writing the Behave code, we should have the Professional version of PyCharm along with the Gherkin plugin installed with it."
},
{
"code": null,
"e": 5813,
"s": 5579,
"text": "Behave has a collection of command line arguments and it can also be outlined from the configuration files. The values set in the configuration files are used automatically, however, it can be overruled by the command line arguments."
},
{
"code": null,
"e": 5865,
"s": 5813,
"text": "Let us discuss some of the command line arguments β"
},
{
"code": null,
"e": 5880,
"s": 5865,
"text": "βc, --no-color"
},
{
"code": null,
"e": 5895,
"s": 5880,
"text": "βc, --no-color"
},
{
"code": null,
"e": 5939,
"s": 5895,
"text": "Impair the usage of the ANSI color escapes."
},
{
"code": null,
"e": 5949,
"s": 5939,
"text": "--color -"
},
{
"code": null,
"e": 5959,
"s": 5949,
"text": "--color -"
},
{
"code": null,
"e": 6080,
"s": 5959,
"text": "Utilise the ANSI color escapes. This is an in-built characteristic and can overrule a setting in the configuration file."
},
{
"code": null,
"e": 6094,
"s": 6080,
"text": "βd, --dry-run"
},
{
"code": null,
"e": 6108,
"s": 6094,
"text": "βd, --dry-run"
},
{
"code": null,
"e": 6157,
"s": 6108,
"text": "Summons the formatter without running the steps."
},
{
"code": null,
"e": 6170,
"s": 6157,
"text": "-D, --define"
},
{
"code": null,
"e": 6183,
"s": 6170,
"text": "-D, --define"
},
{
"code": null,
"e": 6255,
"s": 6183,
"text": "Declares the customised information for the config.userdata dictionary."
},
{
"code": null,
"e": 6277,
"s": 6255,
"text": "βe, --exclude Pattern"
},
{
"code": null,
"e": 6299,
"s": 6277,
"text": "βe, --exclude Pattern"
},
{
"code": null,
"e": 6396,
"s": 6299,
"text": "Exclude feature files which are identical to a pattern of regular expression from the execution."
},
{
"code": null,
"e": 6418,
"s": 6396,
"text": "βi, --include Pattern"
},
{
"code": null,
"e": 6440,
"s": 6418,
"text": "βi, --include Pattern"
},
{
"code": null,
"e": 6539,
"s": 6440,
"text": "Include feature files which are identical to a pattern of regular expression during the execution."
},
{
"code": null,
"e": 6550,
"s": 6539,
"text": "--no-junit"
},
{
"code": null,
"e": 6561,
"s": 6550,
"text": "--no-junit"
},
{
"code": null,
"e": 6591,
"s": 6561,
"text": "Omit JUnit reports as output."
},
{
"code": null,
"e": 6599,
"s": 6591,
"text": "--junit"
},
{
"code": null,
"e": 6607,
"s": 6599,
"text": "--junit"
},
{
"code": null,
"e": 6773,
"s": 6607,
"text": "Add JUnit reports as output. When JUnit is turned on, every stdout and stderr will be a part of the junit report. (Irrespective of the -capture/-no-capture options)."
},
{
"code": null,
"e": 6786,
"s": 6773,
"text": "βf, --format"
},
{
"code": null,
"e": 6799,
"s": 6786,
"text": "βf, --format"
},
{
"code": null,
"e": 6933,
"s": 6799,
"text": "Define a formatter. If omitted, the in-built formatter is utilised. The βformat-help command shall display all the available formats."
},
{
"code": null,
"e": 6948,
"s": 6933,
"text": "-steps-catalog"
},
{
"code": null,
"e": 6963,
"s": 6948,
"text": "-steps-catalog"
},
{
"code": null,
"e": 7022,
"s": 6963,
"text": "Displays a catalogue of all the existing step definitions."
},
{
"code": null,
"e": 7039,
"s": 7022,
"text": "βk, --no-skipped"
},
{
"code": null,
"e": 7056,
"s": 7039,
"text": "βk, --no-skipped"
},
{
"code": null,
"e": 7104,
"s": 7056,
"text": "Exclude skipped steps from printing in console."
},
{
"code": null,
"e": 7116,
"s": 7104,
"text": "no-snippets"
},
{
"code": null,
"e": 7128,
"s": 7116,
"text": "no-snippets"
},
{
"code": null,
"e": 7218,
"s": 7128,
"text": "Exclude snippets from printing in console for the steps, which are still not implemented."
},
{
"code": null,
"e": 7229,
"s": 7218,
"text": "--snippets"
},
{
"code": null,
"e": 7240,
"s": 7229,
"text": "--snippets"
},
{
"code": null,
"e": 7413,
"s": 7240,
"text": "Include snippets, while printing in console for the steps which are still not implemented. This is an in-built characteristic and can overrule a configuration file setting."
},
{
"code": null,
"e": 7432,
"s": 7413,
"text": "βm, --no-multiline"
},
{
"code": null,
"e": 7451,
"s": 7432,
"text": "βm, --no-multiline"
},
{
"code": null,
"e": 7506,
"s": 7451,
"text": "Exclude multiple lines tables and strings under steps."
},
{
"code": null,
"e": 7518,
"s": 7506,
"text": "--multiline"
},
{
"code": null,
"e": 7530,
"s": 7518,
"text": "--multiline"
},
{
"code": null,
"e": 7667,
"s": 7530,
"text": "Include multiple lines tables and strings under steps. This is an in-built characteristic and can overrule a configuration file setting."
},
{
"code": null,
"e": 7678,
"s": 7667,
"text": "βn, --name"
},
{
"code": null,
"e": 7689,
"s": 7678,
"text": "βn, --name"
},
{
"code": null,
"e": 7850,
"s": 7689,
"text": "Include the feature elements, which are identical to the specified name in the run. If the option is provided multiple times, it shall match with all the names."
},
{
"code": null,
"e": 7863,
"s": 7850,
"text": "--no-capture"
},
{
"code": null,
"e": 7876,
"s": 7863,
"text": "--no-capture"
},
{
"code": null,
"e": 7907,
"s": 7876,
"text": "Exclude stdout from capturing."
},
{
"code": null,
"e": 7917,
"s": 7907,
"text": "--capture"
},
{
"code": null,
"e": 7927,
"s": 7917,
"text": "--capture"
},
{
"code": null,
"e": 8025,
"s": 7927,
"text": "Include stdout. This is an in-built characteristic and can overrule a configuration file setting."
},
{
"code": null,
"e": 8045,
"s": 8025,
"text": "--no-capture-stderr"
},
{
"code": null,
"e": 8065,
"s": 8045,
"text": "--no-capture-stderr"
},
{
"code": null,
"e": 8096,
"s": 8065,
"text": "Exclude stderr from capturing."
},
{
"code": null,
"e": 8113,
"s": 8096,
"text": "--capture-stderr"
},
{
"code": null,
"e": 8130,
"s": 8113,
"text": "--capture-stderr"
},
{
"code": null,
"e": 8228,
"s": 8130,
"text": "Include stderr. This is an in-built characteristic and can overrule a configuration file setting."
},
{
"code": null,
"e": 8244,
"s": 8228,
"text": "--no-logcapture"
},
{
"code": null,
"e": 8260,
"s": 8244,
"text": "--no-logcapture"
},
{
"code": null,
"e": 8288,
"s": 8260,
"text": "Exclude log from capturing."
},
{
"code": null,
"e": 8301,
"s": 8288,
"text": "--logcapture"
},
{
"code": null,
"e": 8314,
"s": 8301,
"text": "--logcapture"
},
{
"code": null,
"e": 8491,
"s": 8314,
"text": "Include log capturing. Every log for a step will be present and available during the failures. This is an in-built characteristic and can overrule a configuration file setting."
},
{
"code": null,
"e": 8507,
"s": 8491,
"text": "--logging-level"
},
{
"code": null,
"e": 8523,
"s": 8507,
"text": "--logging-level"
},
{
"code": null,
"e": 8600,
"s": 8523,
"text": "Mention the logging level that shall be captured. The default value is INFO."
},
{
"code": null,
"e": 8617,
"s": 8600,
"text": "--logging-format"
},
{
"code": null,
"e": 8634,
"s": 8617,
"text": "--logging-format"
},
{
"code": null,
"e": 8748,
"s": 8634,
"text": "Mention the user-defined format for printing statements. The default value is %(levelname)s:%(name)s:%(message)s."
},
{
"code": null,
"e": 8766,
"s": 8748,
"text": "--logging-datefmt"
},
{
"code": null,
"e": 8784,
"s": 8766,
"text": "--logging-datefmt"
},
{
"code": null,
"e": 8855,
"s": 8784,
"text": "Mention the user-defined date and time format for printing statements."
},
{
"code": null,
"e": 8872,
"s": 8855,
"text": "--logging-filter"
},
{
"code": null,
"e": 8889,
"s": 8872,
"text": "--logging-filter"
},
{
"code": null,
"e": 9085,
"s": 8889,
"text": "Mention if the statements are to be filtered or not. All the statements are captured by default. In case the output is too lengthy, we can utilise the option to filter out the unnecessary output."
},
{
"code": null,
"e": 9110,
"s": 9085,
"text": "--logging-clear-handlers"
},
{
"code": null,
"e": 9135,
"s": 9110,
"text": "--logging-clear-handlers"
},
{
"code": null,
"e": 9187,
"s": 9135,
"text": "Remove all the handlers which are used for logging."
},
{
"code": null,
"e": 9200,
"s": 9187,
"text": "--no-summary"
},
{
"code": null,
"e": 9213,
"s": 9200,
"text": "--no-summary"
},
{
"code": null,
"e": 9249,
"s": 9213,
"text": "Exclude summary post the execution."
},
{
"code": null,
"e": 9258,
"s": 9249,
"text": "-summary"
},
{
"code": null,
"e": 9267,
"s": 9258,
"text": "-summary"
},
{
"code": null,
"e": 9303,
"s": 9267,
"text": "Include summary post the execution."
},
{
"code": null,
"e": 9317,
"s": 9303,
"text": "βo, --outfile"
},
{
"code": null,
"e": 9331,
"s": 9317,
"text": "βo, --outfile"
},
{
"code": null,
"e": 9377,
"s": 9331,
"text": "Write the given file instead of using stdout."
},
{
"code": null,
"e": 9389,
"s": 9377,
"text": "βq, --quiet"
},
{
"code": null,
"e": 9401,
"s": 9389,
"text": "βq, --quiet"
},
{
"code": null,
"e": 9445,
"s": 9401,
"text": "Alias are used for βno-snippets βno-source."
},
{
"code": null,
"e": 9461,
"s": 9445,
"text": "βs, --no-source"
},
{
"code": null,
"e": 9477,
"s": 9461,
"text": "βs, --no-source"
},
{
"code": null,
"e": 9553,
"s": 9477,
"text": "Exclude printing the file and the line of step definition along with steps."
},
{
"code": null,
"e": 9567,
"s": 9553,
"text": "--show-source"
},
{
"code": null,
"e": 9581,
"s": 9567,
"text": "--show-source"
},
{
"code": null,
"e": 9743,
"s": 9581,
"text": "Include printing the file and the line of step definition along with the steps. This is an in-built characteristic and can overrule a configuration file setting."
},
{
"code": null,
"e": 9751,
"s": 9743,
"text": "--stage"
},
{
"code": null,
"e": 9759,
"s": 9751,
"text": "--stage"
},
{
"code": null,
"e": 9766,
"s": 9759,
"text": "--stop"
},
{
"code": null,
"e": 9773,
"s": 9766,
"text": "--stop"
},
{
"code": null,
"e": 9837,
"s": 9773,
"text": "Terminate executing tests after encountering the first failure."
},
{
"code": null,
"e": 9848,
"s": 9837,
"text": "βt, --tags"
},
{
"code": null,
"e": 9859,
"s": 9848,
"text": "βt, --tags"
},
{
"code": null,
"e": 9959,
"s": 9859,
"text": "Include the features/scenarios having tags, which are identical to TAG_EXPRESSION in the execution."
},
{
"code": null,
"e": 9976,
"s": 9959,
"text": "βT, --no-timings"
},
{
"code": null,
"e": 9993,
"s": 9976,
"text": "βT, --no-timings"
},
{
"code": null,
"e": 10047,
"s": 9993,
"text": "Exclude printing duration of execution for each step."
},
{
"code": null,
"e": 10062,
"s": 10047,
"text": "--show-timings"
},
{
"code": null,
"e": 10077,
"s": 10062,
"text": "--show-timings"
},
{
"code": null,
"e": 10238,
"s": 10077,
"text": "Capture the duration taken by each step to complete in seconds in the console. This is an in-built characteristic and can overrule a configuration file setting."
},
{
"code": null,
"e": 10252,
"s": 10238,
"text": "βv, --verbose"
},
{
"code": null,
"e": 10266,
"s": 10252,
"text": "βv, --verbose"
},
{
"code": null,
"e": 10306,
"s": 10266,
"text": "Displays the loaded features and files."
},
{
"code": null,
"e": 10316,
"s": 10306,
"text": "βw, --wip"
},
{
"code": null,
"e": 10326,
"s": 10316,
"text": "βw, --wip"
},
{
"code": null,
"e": 10487,
"s": 10326,
"text": "Execute the scenarios having the wip tag. Moreover, we have to use the plain formatter and not record the stdout or log output and terminate post first failure."
},
{
"code": null,
"e": 10500,
"s": 10487,
"text": "βx, --expand"
},
{
"code": null,
"e": 10513,
"s": 10500,
"text": "βx, --expand"
},
{
"code": null,
"e": 10562,
"s": 10513,
"text": "Flatten the table of Scenario Outline in output."
},
{
"code": null,
"e": 10569,
"s": 10562,
"text": "--lang"
},
{
"code": null,
"e": 10576,
"s": 10569,
"text": "--lang"
},
{
"code": null,
"e": 10624,
"s": 10576,
"text": "Utilise keywords for a language except English."
},
{
"code": null,
"e": 10636,
"s": 10624,
"text": "--lang-list"
},
{
"code": null,
"e": 10648,
"s": 10636,
"text": "--lang-list"
},
{
"code": null,
"e": 10693,
"s": 10648,
"text": "Displays all the languages present in βlang."
},
{
"code": null,
"e": 10705,
"s": 10693,
"text": "--lang-help"
},
{
"code": null,
"e": 10717,
"s": 10705,
"text": "--lang-help"
},
{
"code": null,
"e": 10779,
"s": 10717,
"text": "Displays all the translations acquired for a single language."
},
{
"code": null,
"e": 10791,
"s": 10779,
"text": "--tags-help"
},
{
"code": null,
"e": 10803,
"s": 10791,
"text": "--tags-help"
},
{
"code": null,
"e": 10836,
"s": 10803,
"text": "Display help for tag statements."
},
{
"code": null,
"e": 10846,
"s": 10836,
"text": "--version"
},
{
"code": null,
"e": 10856,
"s": 10846,
"text": "--version"
},
{
"code": null,
"e": 10874,
"s": 10856,
"text": "Displays version."
},
{
"code": null,
"e": 10891,
"s": 10874,
"text": "junit βdirectory"
},
{
"code": null,
"e": 10908,
"s": 10891,
"text": "junit βdirectory"
},
{
"code": null,
"e": 10975,
"s": 10908,
"text": "This is the directory location where the Junit reports are stored."
},
{
"code": null,
"e": 10990,
"s": 10975,
"text": "--show-skipped"
},
{
"code": null,
"e": 11005,
"s": 10990,
"text": "--show-skipped"
},
{
"code": null,
"e": 11136,
"s": 11005,
"text": "Include skipped steps while printing in console. This is an in-built characteristic and can overrule a configuration file setting."
},
{
"code": null,
"e": 11259,
"s": 11136,
"text": "Behave configuration files are known as the .behaverc/behave.ini/setup.cfg/tox.ini(any one and is set as per user choice)."
},
{
"code": null,
"e": 11310,
"s": 11259,
"text": "The files can be located in the following places β"
},
{
"code": null,
"e": 11341,
"s": 11310,
"text": "The present working directory."
},
{
"code": null,
"e": 11372,
"s": 11341,
"text": "The present working directory."
},
{
"code": null,
"e": 11393,
"s": 11372,
"text": "User home directory."
},
{
"code": null,
"e": 11414,
"s": 11393,
"text": "User home directory."
},
{
"code": null,
"e": 11461,
"s": 11414,
"text": "For Windows users, in the directory %APPDATA%."
},
{
"code": null,
"e": 11508,
"s": 11461,
"text": "For Windows users, in the directory %APPDATA%."
},
{
"code": null,
"e": 11676,
"s": 11508,
"text": "The command behave βv, shall display all the configuration details. The configuration files should begin with the keyword [behave] and follow Windows INI style format."
},
{
"code": null,
"e": 11689,
"s": 11676,
"text": "For example,"
},
{
"code": null,
"e": 11730,
"s": 11689,
"text": "[behave]\nformat = plain\ndry_run = false\n"
},
{
"code": null,
"e": 11798,
"s": 11730,
"text": "Types of configuration parameters in Behave include the following β"
},
{
"code": null,
"e": 11852,
"s": 11798,
"text": "Text β To assign a text to the configuration setting."
},
{
"code": null,
"e": 11906,
"s": 11852,
"text": "Text β To assign a text to the configuration setting."
},
{
"code": null,
"e": 12089,
"s": 11906,
"text": "Bool β Assigns Boolean value to the configuration setting. The text defines the behaviour (true values include 1, true, yes, and on). The false values include 0, false, no, and off)."
},
{
"code": null,
"e": 12272,
"s": 12089,
"text": "Bool β Assigns Boolean value to the configuration setting. The text defines the behaviour (true values include 1, true, yes, and on). The false values include 0, false, no, and off)."
},
{
"code": null,
"e": 12329,
"s": 12272,
"text": "Sequence<text> β To accept multiple values on new lines."
},
{
"code": null,
"e": 12386,
"s": 12329,
"text": "Sequence<text> β To accept multiple values on new lines."
},
{
"code": null,
"e": 12434,
"s": 12386,
"text": "For example, tag expression can be as follows β"
},
{
"code": null,
"e": 12460,
"s": 12434,
"text": "tags=@a, ~@b\n @c\n"
},
{
"code": null,
"e": 12513,
"s": 12460,
"text": "This is equivalent to the following tag expression β"
},
{
"code": null,
"e": 12539,
"s": 12513,
"text": "--tags @a, ~@b --tags @c\n"
},
{
"code": null,
"e": 12608,
"s": 12539,
"text": "Some of the configuration parameters in Behave are explained below β"
},
{
"code": null,
"e": 12621,
"s": 12608,
"text": "color β bool"
},
{
"code": null,
"e": 12634,
"s": 12621,
"text": "color β bool"
},
{
"code": null,
"e": 12751,
"s": 12634,
"text": "Utilise ANSI color escapes. This is an in-built characteristic and can overrule a setting in the configuration file."
},
{
"code": null,
"e": 12766,
"s": 12751,
"text": "dry_run β bool"
},
{
"code": null,
"e": 12781,
"s": 12766,
"text": "dry_run β bool"
},
{
"code": null,
"e": 12829,
"s": 12781,
"text": "Calls the formatters without running the steps."
},
{
"code": null,
"e": 12863,
"s": 12829,
"text": "userdata_defines β sequence<text>"
},
{
"code": null,
"e": 12897,
"s": 12863,
"text": "userdata_defines β sequence<text>"
},
{
"code": null,
"e": 12962,
"s": 12897,
"text": "Declares the customised data for the config.userdata dictionary."
},
{
"code": null,
"e": 12980,
"s": 12962,
"text": "exclude_re β text"
},
{
"code": null,
"e": 12998,
"s": 12980,
"text": "exclude_re β text"
},
{
"code": null,
"e": 13099,
"s": 12998,
"text": "Exclude the feature files which are identical to a pattern of regular expression from the execution."
},
{
"code": null,
"e": 13117,
"s": 13099,
"text": "include_re β text"
},
{
"code": null,
"e": 13135,
"s": 13117,
"text": "include_re β text"
},
{
"code": null,
"e": 13238,
"s": 13135,
"text": "Include the feature files which are identical to a pattern of regular expression during the execution."
},
{
"code": null,
"e": 13251,
"s": 13238,
"text": "junit β bool"
},
{
"code": null,
"e": 13264,
"s": 13251,
"text": "junit β bool"
},
{
"code": null,
"e": 13430,
"s": 13264,
"text": "Add JUnit reports as output. When JUnit is turned on, every stdout and stderr will be a part of the junit report. (Irrespective of the -capture/-no-capture options)."
},
{
"code": null,
"e": 13453,
"s": 13430,
"text": "junit_directory β text"
},
{
"code": null,
"e": 13476,
"s": 13453,
"text": "junit_directory β text"
},
{
"code": null,
"e": 13543,
"s": 13476,
"text": "This is the directory location where the JUnit reports are stored."
},
{
"code": null,
"e": 13565,
"s": 13543,
"text": "default_format β text"
},
{
"code": null,
"e": 13587,
"s": 13565,
"text": "default_format β text"
},
{
"code": null,
"e": 13643,
"s": 13587,
"text": "Declare default formatter. The default value is pretty."
},
{
"code": null,
"e": 13666,
"s": 13643,
"text": "format: sequence<text>"
},
{
"code": null,
"e": 13689,
"s": 13666,
"text": "format: sequence<text>"
},
{
"code": null,
"e": 13823,
"s": 13689,
"text": "Define a formatter. If omitted, the in-built formatter is utilised. The βformat-help command shall display all the available formats."
},
{
"code": null,
"e": 13844,
"s": 13823,
"text": "steps_catalog β bool"
},
{
"code": null,
"e": 13865,
"s": 13844,
"text": "steps_catalog β bool"
},
{
"code": null,
"e": 13924,
"s": 13865,
"text": "Displays a catalogue of all the existing step definitions."
},
{
"code": null,
"e": 13965,
"s": 13924,
"text": "scenario_outline_annotation_schema: text"
},
{
"code": null,
"e": 14006,
"s": 13965,
"text": "scenario_outline_annotation_schema: text"
},
{
"code": null,
"e": 14054,
"s": 14006,
"text": "Mention annotation schema for scenario outline."
},
{
"code": null,
"e": 14074,
"s": 14054,
"text": "show_skipped β bool"
},
{
"code": null,
"e": 14094,
"s": 14074,
"text": "show_skipped β bool"
},
{
"code": null,
"e": 14229,
"s": 14094,
"text": "Include the skipped steps while printing in console. This is an in-built characteristic and can overrule a configuration file setting."
},
{
"code": null,
"e": 14250,
"s": 14229,
"text": "show_snippets β bool"
},
{
"code": null,
"e": 14271,
"s": 14250,
"text": "show_snippets β bool"
},
{
"code": null,
"e": 14444,
"s": 14271,
"text": "Include snippets while printing in console for the steps, which are still not implemented. This is an in-built characteristic and can overrule a configuration file setting."
},
{
"code": null,
"e": 14466,
"s": 14444,
"text": "show_multiline β bool"
},
{
"code": null,
"e": 14488,
"s": 14466,
"text": "show_multiline β bool"
},
{
"code": null,
"e": 14625,
"s": 14488,
"text": "Include multiple lines tables and strings under steps. This is an in-built characteristic and can overrule a configuration file setting."
},
{
"code": null,
"e": 14647,
"s": 14625,
"text": "name β sequence<text>"
},
{
"code": null,
"e": 14669,
"s": 14647,
"text": "name β sequence<text>"
},
{
"code": null,
"e": 14834,
"s": 14669,
"text": "Include the feature elements which are identical to the specified name in the run. If the option is provided multiple times, it shall match all the specified names."
},
{
"code": null,
"e": 14856,
"s": 14834,
"text": "stdout_capture β bool"
},
{
"code": null,
"e": 14878,
"s": 14856,
"text": "stdout_capture β bool"
},
{
"code": null,
"e": 14976,
"s": 14878,
"text": "Include stdout. This is an in-built characteristic and can overrule a configuration file setting."
},
{
"code": null,
"e": 14998,
"s": 14976,
"text": "stderr_capture β bool"
},
{
"code": null,
"e": 15020,
"s": 14998,
"text": "stderr_capture β bool"
},
{
"code": null,
"e": 15118,
"s": 15020,
"text": "Include stderr. This is an in-built characteristic and can overrule a configuration file setting."
},
{
"code": null,
"e": 15137,
"s": 15118,
"text": "log_capture β bool"
},
{
"code": null,
"e": 15156,
"s": 15137,
"text": "log_capture β bool"
},
{
"code": null,
"e": 15333,
"s": 15156,
"text": "Include log capturing. Every log for a step will be present and available during the failures. This is an in-built characteristic and can overrule a configuration file setting."
},
{
"code": null,
"e": 15354,
"s": 15333,
"text": "logging_level β text"
},
{
"code": null,
"e": 15375,
"s": 15354,
"text": "logging_level β text"
},
{
"code": null,
"e": 15444,
"s": 15375,
"text": "Mention the logging level to be captured. The default value is INFO."
},
{
"code": null,
"e": 15466,
"s": 15444,
"text": "logging_format β text"
},
{
"code": null,
"e": 15488,
"s": 15466,
"text": "logging_format β text"
},
{
"code": null,
"e": 15598,
"s": 15488,
"text": "Mention user-defined format for printing statements. The default value is %(levelname)s:%(name)s:%(message)s."
},
{
"code": null,
"e": 15621,
"s": 15598,
"text": "logging_datefmt β text"
},
{
"code": null,
"e": 15644,
"s": 15621,
"text": "logging_datefmt β text"
},
{
"code": null,
"e": 15711,
"s": 15644,
"text": "Mention user-defined date and time format for printing statements."
},
{
"code": null,
"e": 15733,
"s": 15711,
"text": "logging_filter β text"
},
{
"code": null,
"e": 15755,
"s": 15733,
"text": "logging_filter β text"
},
{
"code": null,
"e": 15947,
"s": 15755,
"text": "Mention the statements which are to be filtered. All the statements are captured by default. In case the output is too lengthy, we can utilise the option to filter out the unnecessary output."
},
{
"code": null,
"e": 15977,
"s": 15947,
"text": "logging_clear_handlers : bool"
},
{
"code": null,
"e": 16007,
"s": 15977,
"text": "logging_clear_handlers : bool"
},
{
"code": null,
"e": 16059,
"s": 16007,
"text": "Remove all the handlers which are used for logging."
},
{
"code": null,
"e": 16074,
"s": 16059,
"text": "summary β bool"
},
{
"code": null,
"e": 16089,
"s": 16074,
"text": "summary β bool"
},
{
"code": null,
"e": 16127,
"s": 16089,
"text": "Include a summary post the execution."
},
{
"code": null,
"e": 16153,
"s": 16127,
"text": "outfiles β sequence<text>"
},
{
"code": null,
"e": 16179,
"s": 16153,
"text": "outfiles β sequence<text>"
},
{
"code": null,
"e": 16225,
"s": 16179,
"text": "Write the given file instead of using stdout."
},
{
"code": null,
"e": 16248,
"s": 16225,
"text": "paths β sequence<text>"
},
{
"code": null,
"e": 16271,
"s": 16248,
"text": "paths β sequence<text>"
},
{
"code": null,
"e": 16315,
"s": 16271,
"text": "Mention the default paths of feature files."
},
{
"code": null,
"e": 16328,
"s": 16315,
"text": "quiet β bool"
},
{
"code": null,
"e": 16341,
"s": 16328,
"text": "quiet β bool"
},
{
"code": null,
"e": 16384,
"s": 16341,
"text": "Alias is used for βno-snippets βno-source."
},
{
"code": null,
"e": 16403,
"s": 16384,
"text": "show-source β bool"
},
{
"code": null,
"e": 16422,
"s": 16403,
"text": "show-source β bool"
},
{
"code": null,
"e": 16580,
"s": 16422,
"text": "Include printing the file and the line of step definition along with steps. This is an in-built characteristic and can overrule a configuration file setting."
},
{
"code": null,
"e": 16593,
"s": 16580,
"text": "stage β text"
},
{
"code": null,
"e": 16606,
"s": 16593,
"text": "stage β text"
},
{
"code": null,
"e": 16753,
"s": 16606,
"text": "Describes the present stage of the test. The stage name is utilised as the name affix for the environment file along with the directory for steps."
},
{
"code": null,
"e": 16765,
"s": 16753,
"text": "stop β bool"
},
{
"code": null,
"e": 16777,
"s": 16765,
"text": "stop β bool"
},
{
"code": null,
"e": 16841,
"s": 16777,
"text": "Terminate executing tests after encountering the first failure."
},
{
"code": null,
"e": 16863,
"s": 16841,
"text": "tags β sequence<text>"
},
{
"code": null,
"e": 16885,
"s": 16863,
"text": "tags β sequence<text>"
},
{
"code": null,
"e": 16984,
"s": 16885,
"text": "Include the features/scenarios having tags which are identical to TAG_EXPRESSION in the execution."
},
{
"code": null,
"e": 17004,
"s": 16984,
"text": "default_tags β text"
},
{
"code": null,
"e": 17024,
"s": 17004,
"text": "default_tags β text"
},
{
"code": null,
"e": 17072,
"s": 17024,
"text": "Declare the default tags if they are not given."
},
{
"code": null,
"e": 17092,
"s": 17072,
"text": "show_timings β bool"
},
{
"code": null,
"e": 17112,
"s": 17092,
"text": "show_timings β bool"
},
{
"code": null,
"e": 17273,
"s": 17112,
"text": "Capture the duration taken by each step to complete in seconds in the console. This is an in-built characteristic and can overrule a configuration file setting."
},
{
"code": null,
"e": 17288,
"s": 17273,
"text": "verbose β bool"
},
{
"code": null,
"e": 17303,
"s": 17288,
"text": "verbose β bool"
},
{
"code": null,
"e": 17343,
"s": 17303,
"text": "Displays the loaded features and files."
},
{
"code": null,
"e": 17354,
"s": 17343,
"text": "wip β bool"
},
{
"code": null,
"e": 17365,
"s": 17354,
"text": "wip β bool"
},
{
"code": null,
"e": 17526,
"s": 17365,
"text": "Execute the scenarios having the wip tag. Moreover, we have to use the plain formatter and not record the stdout or log output and terminate post first failure."
},
{
"code": null,
"e": 17540,
"s": 17526,
"text": "expand β bool"
},
{
"code": null,
"e": 17554,
"s": 17540,
"text": "expand β bool"
},
{
"code": null,
"e": 17603,
"s": 17554,
"text": "Flatten the table of Scenario Outline in output."
},
{
"code": null,
"e": 17615,
"s": 17603,
"text": "lang β text"
},
{
"code": null,
"e": 17627,
"s": 17615,
"text": "lang β text"
},
{
"code": null,
"e": 17675,
"s": 17627,
"text": "Utilise keywords for a language except English."
},
{
"code": null,
"e": 17744,
"s": 17675,
"text": "Behave works with three different file types, which are as follows β"
},
{
"code": null,
"e": 17867,
"s": 17744,
"text": "Feature files which are created by a Business analyst or any project stakeholder and contains behaviour related use cases."
},
{
"code": null,
"e": 17990,
"s": 17867,
"text": "Feature files which are created by a Business analyst or any project stakeholder and contains behaviour related use cases."
},
{
"code": null,
"e": 18062,
"s": 17990,
"text": "Step Implementation file for the scenarios defined in the feature file."
},
{
"code": null,
"e": 18134,
"s": 18062,
"text": "Step Implementation file for the scenarios defined in the feature file."
},
{
"code": null,
"e": 18266,
"s": 18134,
"text": "Environment Setup files where, the pre/post conditions are to be executed prior and post the steps, features, scenarios, and so on."
},
{
"code": null,
"e": 18398,
"s": 18266,
"text": "Environment Setup files where, the pre/post conditions are to be executed prior and post the steps, features, scenarios, and so on."
},
{
"code": null,
"e": 18538,
"s": 18398,
"text": "A feature file should be within a folder called as the features. Also, there should be a sub-directory steps within the features directory."
},
{
"code": null,
"e": 18634,
"s": 18538,
"text": "We can launch the feature file with various command line arguments. These are explained below β"
},
{
"code": null,
"e": 18759,
"s": 18634,
"text": "If no information is available, all the feature files within the features directory shall be loaded for execution in Behave."
},
{
"code": null,
"e": 18884,
"s": 18759,
"text": "If no information is available, all the feature files within the features directory shall be loaded for execution in Behave."
},
{
"code": null,
"e": 19079,
"s": 18884,
"text": "If the path of the features directory is provided, then it is mandatory to have at least one feature file (with .feature extension) and a sub-directory named steps within the features directory."
},
{
"code": null,
"e": 19274,
"s": 19079,
"text": "If the path of the features directory is provided, then it is mandatory to have at least one feature file (with .feature extension) and a sub-directory named steps within the features directory."
},
{
"code": null,
"e": 19413,
"s": 19274,
"text": "Also, if the environment.py is present, it should be within the directory that has the steps directory and not within the steps directory."
},
{
"code": null,
"e": 19552,
"s": 19413,
"text": "Also, if the environment.py is present, it should be within the directory that has the steps directory and not within the steps directory."
},
{
"code": null,
"e": 19736,
"s": 19552,
"text": "If the path to a feature file is provided, then it instructs Behave to search for it. To get the corresponding steps directory for that feature file, the parent directory is searched."
},
{
"code": null,
"e": 19920,
"s": 19736,
"text": "If the path to a feature file is provided, then it instructs Behave to search for it. To get the corresponding steps directory for that feature file, the parent directory is searched."
},
{
"code": null,
"e": 20194,
"s": 19920,
"text": "If not found in the current parent directory, then it searches its parents. This shall continue until it reaches the file system root. Also, if the environment.py is present, it should be within the directory that has the steps directory and not within the steps directory."
},
{
"code": null,
"e": 20468,
"s": 20194,
"text": "If not found in the current parent directory, then it searches its parents. This shall continue until it reaches the file system root. Also, if the environment.py is present, it should be within the directory that has the steps directory and not within the steps directory."
},
{
"code": null,
"e": 20514,
"s": 20468,
"text": "Gherkin keywords in Behave are listed below β"
},
{
"code": null,
"e": 20523,
"s": 20514,
"text": "Features"
},
{
"code": null,
"e": 20532,
"s": 20523,
"text": "Features"
},
{
"code": null,
"e": 20541,
"s": 20532,
"text": "Scenario"
},
{
"code": null,
"e": 20550,
"s": 20541,
"text": "Scenario"
},
{
"code": null,
"e": 20556,
"s": 20550,
"text": "Steps"
},
{
"code": null,
"e": 20562,
"s": 20556,
"text": "Steps"
},
{
"code": null,
"e": 20573,
"s": 20562,
"text": "Background"
},
{
"code": null,
"e": 20584,
"s": 20573,
"text": "Background"
},
{
"code": null,
"e": 20601,
"s": 20584,
"text": "Scenario Outline"
},
{
"code": null,
"e": 20618,
"s": 20601,
"text": "Scenario Outline"
},
{
"code": null,
"e": 20623,
"s": 20618,
"text": "Text"
},
{
"code": null,
"e": 20628,
"s": 20623,
"text": "Text"
},
{
"code": null,
"e": 20634,
"s": 20628,
"text": "Table"
},
{
"code": null,
"e": 20640,
"s": 20634,
"text": "Table"
},
{
"code": null,
"e": 20645,
"s": 20640,
"text": "Tags"
},
{
"code": null,
"e": 20650,
"s": 20645,
"text": "Tags"
},
{
"code": null,
"e": 20656,
"s": 20650,
"text": "Given"
},
{
"code": null,
"e": 20662,
"s": 20656,
"text": "Given"
},
{
"code": null,
"e": 20667,
"s": 20662,
"text": "When"
},
{
"code": null,
"e": 20672,
"s": 20667,
"text": "When"
},
{
"code": null,
"e": 20677,
"s": 20672,
"text": "Then"
},
{
"code": null,
"e": 20682,
"s": 20677,
"text": "Then"
},
{
"code": null,
"e": 20686,
"s": 20682,
"text": "But"
},
{
"code": null,
"e": 20690,
"s": 20686,
"text": "But"
},
{
"code": null,
"e": 20694,
"s": 20690,
"text": "And"
},
{
"code": null,
"e": 20698,
"s": 20694,
"text": "And"
},
{
"code": null,
"e": 20908,
"s": 20698,
"text": "Feature files are written in Gherkin language. It is in plain text and created by non- technical members of the team (business analyst). Feature files can be used for both automation testing and documentation."
},
{
"code": null,
"e": 21209,
"s": 20908,
"text": "Line endings finish statements are included in Behave. We can use tabs/spaces for indentation. Majority of lines begin with the keywords like Scenario, Given, Then, and so on. Comments can be added in any location within the file. They start with/without spaces, followed by # symbol along with text."
},
{
"code": null,
"e": 21251,
"s": 21209,
"text": "Let us discuss some key Gherkin keywords."
},
{
"code": null,
"e": 21355,
"s": 21251,
"text": "A Feature consists of Scenarios. They may/may not contain description, background, and a group of tags."
},
{
"code": null,
"e": 21403,
"s": 21355,
"text": "The structure of a feature file is as follows β"
},
{
"code": null,
"e": 21517,
"s": 21403,
"text": "Feature β Verify book name added in Library\nScenario β Verify Book name\nGiven Book details\nThen Verify book name\n"
},
{
"code": null,
"e": 21727,
"s": 21517,
"text": "The name of the feature should have a description for the feature which is being tested. However, a lengthy description is not mandatory and a description is only added to remove ambiguity in the feature name."
},
{
"code": null,
"e": 21954,
"s": 21727,
"text": "A Background is added to have a group of steps. It is close to a Scenario. We can add a context to the multiple Scenarios with Background. It is run prior to every Scenario of a feature, but post the execution of before hooks."
},
{
"code": null,
"e": 22067,
"s": 21954,
"text": "Background is generally used for executing preconditions like login Scenarios or database connection, and so on."
},
{
"code": null,
"e": 22261,
"s": 22067,
"text": "A Background description can be added for better human readability. A Background can appear only a single time in a feature file and it must be declared prior to a Scenario or Scenario Outline."
},
{
"code": null,
"e": 22478,
"s": 22261,
"text": "A Background should not be used to create a complex state (only, if it cannot be avoided). This segment should be brief and authentic. Also, we should avoid having a large number of scenarios within one feature file."
},
{
"code": null,
"e": 22535,
"s": 22478,
"text": "The feature file with Background keyword is as follows β"
},
{
"code": null,
"e": 22933,
"s": 22535,
"text": "Feature: Payment Process\n Background:\n Given launch application\n Then Input credentials\n Scenario: Credit card transaction\n Given user is on credit card payment screen\n Then user should be able to complete credit card payment\n Scenario: Debit card transaction\n Given user is on debit card payment screen\n Then user should be able to complete debit card payment\n"
},
{
"code": null,
"e": 23106,
"s": 22933,
"text": "A Scenario defines a behaviour of the application that is being tested. It has a title to describe its objective. Its description can be added for better human readability."
},
{
"code": null,
"e": 23296,
"s": 23106,
"text": "A Scenario may have multiple steps, which begins with the keywords Given, Then, When, and so on. It is recommended to have a Scenario to check a single characteristic or an expected result."
},
{
"code": null,
"e": 23323,
"s": 23296,
"text": "Feature File with Scenario"
},
{
"code": null,
"e": 23377,
"s": 23323,
"text": "The feature file with Scenario keyword is as follows:"
},
{
"code": null,
"e": 23552,
"s": 23377,
"text": "Feature β Payment Process\n Scenario β Credit card transaction\n Given user is on credit card payment screen\n Then user should be able to complete credit card payment\n"
},
{
"code": null,
"e": 23569,
"s": 23552,
"text": "Scenario Outline"
},
{
"code": null,
"e": 23775,
"s": 23569,
"text": "A Scenario Outline is used if we have a group of similar criteria and the results to be passed in a Scenario. A Scenario Outline is accompanied with an Examples table and can have multiple Examples tables."
},
{
"code": null,
"e": 24007,
"s": 23775,
"text": "The tests get executed once for every row found after the header row within the Examples table. The values to be tested are represented by their names enclosed in brackets<>. These names should match with the Examples table header."
},
{
"code": null,
"e": 24103,
"s": 24007,
"text": "It helps to reduce the lines of code as it eliminates the repeating steps and orders our tests."
},
{
"code": null,
"e": 24166,
"s": 24103,
"text": "The feature file with Scenario Outline keyword is as follows β"
},
{
"code": null,
"e": 24315,
"s": 24166,
"text": "Feature β User information\nScenario Outline: Check login functionality\n Given user enters <email> and <password>\n Then user should be logged in\n"
},
{
"code": null,
"e": 24383,
"s": 24315,
"text": "Following is an example of the feature file with Scenario Outline β"
},
{
"code": null,
"e": 24502,
"s": 24383,
"text": "Examples: Credentials\n | email | password |\n | qa@gmail.com | pwd1 |\n | qe@gmail.com | pwd2 |\n"
},
{
"code": null,
"e": 24563,
"s": 24502,
"text": "The same test gets executed with a varied set of parameters."
},
{
"code": null,
"e": 24801,
"s": 24563,
"text": "A step starting the keyword Given is used to place the system in a familiar circumstance prior to the interaction of the user with the system (similar to a precondition). It is recommended not to describe a user action in the Given step."
},
{
"code": null,
"e": 24912,
"s": 24801,
"text": "A Given step can be added for setting the configuration in the database, log in to the application, and so on."
},
{
"code": null,
"e": 24936,
"s": 24912,
"text": "Feature File with Given"
},
{
"code": null,
"e": 24988,
"s": 24936,
"text": "The feature file with Given keyword is as follows β"
},
{
"code": null,
"e": 25169,
"s": 24988,
"text": "Feature β Payment Process\n Scenario β Credit card transaction\n Given user is on credit card payment screen\n Then user should be able to complete credit card payment\n"
},
{
"code": null,
"e": 25399,
"s": 25169,
"text": "A step starting with the keyword When is used to add the essential task to be performed by the user. With this, there is a user communication with the system that brings about the changes to systemβs state or an impact elsewhere."
},
{
"code": null,
"e": 25422,
"s": 25399,
"text": "Feature File with When"
},
{
"code": null,
"e": 25473,
"s": 25422,
"text": "The feature file with When keyword is as follows β"
},
{
"code": null,
"e": 25716,
"s": 25473,
"text": "Feature β Payment Process\n Scenario β Credit card transaction\n Given user is on credit card payment screen\n When user clicks on the Payment with Credit Card button\n Then user should be able to complete credit card payment\n"
},
{
"code": null,
"e": 25972,
"s": 25716,
"text": "A step starting with the keyword Then is used to get the expected results. The results observed (ideally in form of an output - messages, reports, and so on) in this step should be connected to a business scenario and the feature file where it is present."
},
{
"code": null,
"e": 26127,
"s": 25972,
"text": "It is recommended not to use the Then steps for database scenarios as it is essentially used to describe an aftermath which is noticeable to the end user."
},
{
"code": null,
"e": 26150,
"s": 26127,
"text": "Feature File with Then"
},
{
"code": null,
"e": 26201,
"s": 26150,
"text": "The feature file with When keyword is as follows β"
},
{
"code": null,
"e": 26441,
"s": 26201,
"text": "Feature β Payment Process\n Scenario β Credit card transaction\n Given user is on credit card payment screen\n When user clicks on the Payment with Credit Card button\n Then user should be able to complete credit card payment\n"
},
{
"code": null,
"e": 26570,
"s": 26441,
"text": "If we have multiple Given, When, Then consecutive steps, we can use And and But steps. It brings better readability to the user."
},
{
"code": null,
"e": 26626,
"s": 26570,
"text": "Feature File with multiple consecutive Then/Given steps"
},
{
"code": null,
"e": 26712,
"s": 26626,
"text": "The feature file with multiple consecutive Then/Given steps in Behave is as follows β"
},
{
"code": null,
"e": 26943,
"s": 26712,
"text": "Feature β Verify book names added in Library\n Scenario β Verify Book name\n Given Book1 details\n Given Book2 details\n Then Verify book names\n Then Verify newly added book names should not be in Delete History\n"
},
{
"code": null,
"e": 26990,
"s": 26943,
"text": "Feature File without multiple Then/Given steps"
},
{
"code": null,
"e": 27057,
"s": 26990,
"text": "The feature file without multiple Then/Given steps is as follows β"
},
{
"code": null,
"e": 27288,
"s": 27057,
"text": "Feature β Verify book names added in Library\n Scenario β Verify Book name\n Given Book1 details\n And Book2 details\n Then Verify book names\n But Verify newly added book names should not be in Delete History\n"
},
{
"code": null,
"e": 27499,
"s": 27288,
"text": "A step can have a text and data table associated with it. We can add a data table with a step. It is recommended to have the table data indented and it is mandatory to have an equal column number for each line."
},
{
"code": null,
"e": 27550,
"s": 27499,
"text": "A column data should be separated by the | symbol."
},
{
"code": null,
"e": 27574,
"s": 27550,
"text": "Feature File with Table"
},
{
"code": null,
"e": 27626,
"s": 27574,
"text": "The feature file with table keyword is as follows β"
},
{
"code": null,
"e": 27862,
"s": 27626,
"text": "Feature β User Registration\nScenario β User enters registration details\n When User enters name and password\n | name |password |\n | t1 | pwd |\n | t2 | pwd1 |\nThen user should be able to complete registration\n"
},
{
"code": null,
"e": 28036,
"s": 27862,
"text": "A table is accessible to the implementation Python code with the .table attribute within the context variable (passed in the step function). A table is an instance of Table."
},
{
"code": null,
"e": 28067,
"s": 28036,
"text": "Implementation logic for Table"
},
{
"code": null,
"e": 28138,
"s": 28067,
"text": "Given below is an implementation logic for .table attribute in Table β"
},
{
"code": null,
"e": 28292,
"s": 28138,
"text": "@when('User enters name and password')\ndef step_impl(context):\n for r in context.table:\n model.delete_usr(name=r['name'], password=r['password'])\n"
},
{
"code": null,
"e": 28558,
"s": 28292,
"text": "A block of text after a step enclosed in \"\"\" will be linked with that step. Here, the indentation is parsed. All the whitespaces at the beginning are removed from the text. Also, all the succeeding lines must have at least a minimum whitespace as the starting line."
},
{
"code": null,
"e": 28697,
"s": 28558,
"text": "A text is accessible to the implementation Python code with the .text attribute within the context variable (passed in the step function)."
},
{
"code": null,
"e": 28720,
"s": 28697,
"text": "Feature File with Text"
},
{
"code": null,
"e": 28771,
"s": 28720,
"text": "The feature file with text keyword is as follows β"
},
{
"code": null,
"e": 28962,
"s": 28771,
"text": "Feature β Verify book name added in Library\n \n Scenario β Verify Book name\n Given Book details\n \"\"\"\n Text added for a step\n \"\"\"\n Then Verify book name\n"
},
{
"code": null,
"e": 29149,
"s": 28962,
"text": "A section of a feature file can be tagged so that the Behave is capable of verifying only a certain section of the feature file. A Scenario, Feature, Scenario Outline can only be tagged."
},
{
"code": null,
"e": 29432,
"s": 29149,
"text": "Also, a tag which is used for a feature shall be inherited by all its Scenarios and Scenario Outlines. Tags are placed before a Scenario or a Feature that we want to tag. We can also have multiple tags separated by spaces within a line. A tag begins with @ followed by the tag name."
},
{
"code": null,
"e": 29455,
"s": 29432,
"text": "Feature File with tags"
},
{
"code": null,
"e": 29505,
"s": 29455,
"text": "The feature file with tags keyword is as follows:"
},
{
"code": null,
"e": 29695,
"s": 29505,
"text": "@payment\n@high\nFeature β Payment Process\n Scenario β Credit card transaction\n Given user is on credit card payment screen\n Then user should be able to complete credit card payment\n"
},
{
"code": null,
"e": 29814,
"s": 29695,
"text": "Tags help to manage the test execution by excluding/including the specific scenarios or features depending on the tag."
},
{
"code": null,
"e": 29911,
"s": 29814,
"text": "Behave works with three different file types, as explained earlier. These files are as follows β"
},
{
"code": null,
"e": 30036,
"s": 29911,
"text": "Feature files which are created by the Business analyst or any project stakeholder and contains behaviour related use cases."
},
{
"code": null,
"e": 30161,
"s": 30036,
"text": "Feature files which are created by the Business analyst or any project stakeholder and contains behaviour related use cases."
},
{
"code": null,
"e": 30233,
"s": 30161,
"text": "Step Implementation file for the scenarios defined in the feature file."
},
{
"code": null,
"e": 30305,
"s": 30233,
"text": "Step Implementation file for the scenarios defined in the feature file."
},
{
"code": null,
"e": 30432,
"s": 30305,
"text": "Environment Setup files where the pre/post conditions are to be executed prior and post steps, features, scenarios, and so on."
},
{
"code": null,
"e": 30559,
"s": 30432,
"text": "Environment Setup files where the pre/post conditions are to be executed prior and post steps, features, scenarios, and so on."
},
{
"code": null,
"e": 30699,
"s": 30559,
"text": "A Feature file should be within a folder called as the features. Also, there should be a sub-directory steps within the features directory."
},
{
"code": null,
"e": 30751,
"s": 30699,
"text": "The following screen will appear on your computer β"
},
{
"code": null,
"e": 30840,
"s": 30751,
"text": "We can launch the feature file with various command line arguments, as explained below β"
},
{
"code": null,
"e": 30969,
"s": 30840,
"text": "If no information is available, all the feature files within the features directory shall be loaded for the execution in Behave."
},
{
"code": null,
"e": 31098,
"s": 30969,
"text": "If no information is available, all the feature files within the features directory shall be loaded for the execution in Behave."
},
{
"code": null,
"e": 31293,
"s": 31098,
"text": "If the path of the features directory is provided, then it is mandatory to have at least one feature file (with .feature extension) and a sub-directory named steps within the features directory."
},
{
"code": null,
"e": 31488,
"s": 31293,
"text": "If the path of the features directory is provided, then it is mandatory to have at least one feature file (with .feature extension) and a sub-directory named steps within the features directory."
},
{
"code": null,
"e": 31627,
"s": 31488,
"text": "Also, if the environment.py is present, it should be within the directory that has the steps directory and not within the steps directory."
},
{
"code": null,
"e": 31766,
"s": 31627,
"text": "Also, if the environment.py is present, it should be within the directory that has the steps directory and not within the steps directory."
},
{
"code": null,
"e": 31950,
"s": 31766,
"text": "If the path to a feature file is provided, then it instructs Behave to search for it. To get the corresponding steps directory for that feature file, the parent directory is searched."
},
{
"code": null,
"e": 32134,
"s": 31950,
"text": "If the path to a feature file is provided, then it instructs Behave to search for it. To get the corresponding steps directory for that feature file, the parent directory is searched."
},
{
"code": null,
"e": 32407,
"s": 32134,
"text": "If not found in the current parent directory, then it searches its parents. This shall continue until it reaches the file system root. Also, if the environment.py is present it should be within the directory that has the steps directory and not within the steps directory."
},
{
"code": null,
"e": 32680,
"s": 32407,
"text": "If not found in the current parent directory, then it searches its parents. This shall continue until it reaches the file system root. Also, if the environment.py is present it should be within the directory that has the steps directory and not within the steps directory."
},
{
"code": null,
"e": 32786,
"s": 32680,
"text": "A Feature consists of Scenarios. They may/may not contain a description, background, and a group of tags."
},
{
"code": null,
"e": 32832,
"s": 32786,
"text": "A structure of a feature file is as follows β"
},
{
"code": null,
"e": 32845,
"s": 32832,
"text": "Feature File"
},
{
"code": null,
"e": 32890,
"s": 32845,
"text": "The format of a feature file is as follows β"
},
{
"code": null,
"e": 33019,
"s": 32890,
"text": "Feature β Verify book name added in Library\n Scenario β Verify Book name\n Given Book details\n Then Verify book name\n"
},
{
"code": null,
"e": 33059,
"s": 33019,
"text": "Corresponding Step Implementation File."
},
{
"code": null,
"e": 33139,
"s": 33059,
"text": "The corresponding step implementation file looks like the one mentioned below β"
},
{
"code": null,
"e": 33321,
"s": 33139,
"text": "from behave import *\n@given('Book details')\ndef impl_bk(context):\n print('Book details entered')\n@then('Verify book name')\ndef impl_bk(context):\n print('Verify book name')"
},
{
"code": null,
"e": 33328,
"s": 33321,
"text": "Output"
},
{
"code": null,
"e": 33395,
"s": 33328,
"text": "The output obtained after running the feature file is as follows β"
},
{
"code": null,
"e": 33508,
"s": 33395,
"text": "The output shows the Feature and Scenario names, along with the test results and duration of the test execution."
},
{
"code": null,
"e": 33737,
"s": 33508,
"text": "The steps of a Scenario in the feature file in Behave should have implementation logic written in Python. This is known as the implementation/step definition file (.py extension) and should be present within the steps directory."
},
{
"code": null,
"e": 33853,
"s": 33737,
"text": "All the necessary imports are present in this file. The steps directory should be a part of the features directory."
},
{
"code": null,
"e": 33905,
"s": 33853,
"text": "The following screen will appear on your computer β"
},
{
"code": null,
"e": 34217,
"s": 33905,
"text": "The step definition file contains Python functions which define the steps in the feature file. At the start of the Python functions, it is mandatory to have decorators which begins with @given, @when, and so on. These decorators compare and match with the Given, Then, When, and other steps in the feature file."
},
{
"code": null,
"e": 34230,
"s": 34217,
"text": "Feature File"
},
{
"code": null,
"e": 34263,
"s": 34230,
"text": "The feature file is as follows β"
},
{
"code": null,
"e": 34392,
"s": 34263,
"text": "Feature β Verify book name added in Library\n Scenario β Verify Book name\n Given Book details\n Then Verify book name\n"
},
{
"code": null,
"e": 34431,
"s": 34392,
"text": "Corresponding Step Implementation File"
},
{
"code": null,
"e": 34511,
"s": 34431,
"text": "The corresponding step implementation file looks like the one mentioned below β"
},
{
"code": null,
"e": 34693,
"s": 34511,
"text": "from behave import *\n@given('Book details')\ndef impl_bk(context):\n print('Book details entered')\n@then('Verify book name')\ndef impl_bk(context):\n print('Verify book name')"
},
{
"code": null,
"e": 34700,
"s": 34693,
"text": "Output"
},
{
"code": null,
"e": 34767,
"s": 34700,
"text": "The output obtained after running the feature file is as follows β"
},
{
"code": null,
"e": 34873,
"s": 34767,
"text": "The output shows the Feature and Scenario names, along with test results, and duration of test execution."
},
{
"code": null,
"e": 34908,
"s": 34873,
"text": "Let us create a basic Behave test."
},
{
"code": null,
"e": 34921,
"s": 34908,
"text": "Feature File"
},
{
"code": null,
"e": 34991,
"s": 34921,
"text": "The feature file for the Feature titled Payment Types is as follows β"
},
{
"code": null,
"e": 35197,
"s": 34991,
"text": "Feature β Payment Types\n \n Scenario β Verify user has two payment options\n Given User is on Payment screen\n When User clicks on Payment types\n Then User should get Types Cheque and Cash\n"
},
{
"code": null,
"e": 35236,
"s": 35197,
"text": "Corresponding Step Implementation File"
},
{
"code": null,
"e": 35327,
"s": 35236,
"text": "The corresponding step implementation file for the above mentioned feature is as follows β"
},
{
"code": null,
"e": 35679,
"s": 35327,
"text": "from behave import *\n@given('User is on Payment screen')\ndef impl_bkpy(context):\n print('User is on Payment screen')\n@when('User clicks on Payment types')\ndef impl_bkpy(context):\n print('User clicks on Payment types')\n@then('User should get Types Cheque and Cash')\ndef impl_bkpy(context):\n print('User should get Types Cheque and Cash')"
},
{
"code": null,
"e": 35697,
"s": 35679,
"text": "Project Structure"
},
{
"code": null,
"e": 35767,
"s": 35697,
"text": "The project structure for the feature βPayment Typesβ is as follows β"
},
{
"code": null,
"e": 35774,
"s": 35767,
"text": "Output"
},
{
"code": null,
"e": 35883,
"s": 35774,
"text": "The output obtained after running the feature file is as mentioned below and the command used here is behave"
},
{
"code": null,
"e": 35989,
"s": 35883,
"text": "The output shows the Feature and Scenario names, along with test results, and duration of test execution."
},
{
"code": null,
"e": 36028,
"s": 35989,
"text": "Python Console output is given below β"
},
{
"code": null,
"e": 36336,
"s": 36028,
"text": "We have the option to utilise other languages apart from English in the feature file. This is because, the majority of BDD tools have the support for internationalisation. The important fact is that the keywords - Then, When, Given can be described in other native languages like Spanish, French, and so on."
},
{
"code": null,
"e": 36511,
"s": 36336,
"text": "In that case, the developer can implement the step definitions in other languages as well. The list of all the languages can be obtained with the command: behave --lang-list."
},
{
"code": null,
"e": 36606,
"s": 36511,
"text": "The following screen will appear on your computer after using the command behave --lang-list β"
},
{
"code": null,
"e": 36667,
"s": 36606,
"text": "Some more languages included in Behave are mentioned below β"
},
{
"code": null,
"e": 36871,
"s": 36667,
"text": "A feature file can be associated with a particular language. At this time, the BDD framework chooses the keywords for that specific language. The language can be set as default in the configuration file."
},
{
"code": null,
"e": 37065,
"s": 36871,
"text": "Behave configuration files can be either, .behaverc or behave.ini files. The value for the parameter lang should be set to da in the configuration file, if we want the language to be to Danish."
},
{
"code": null,
"e": 37192,
"s": 37065,
"text": "The feature file set up for selecting a particular language is given below and the language used as an example is Danish (da)."
},
{
"code": null,
"e": 37212,
"s": 37192,
"text": "[behave]\nlang = da\n"
},
{
"code": null,
"e": 37474,
"s": 37212,
"text": "We can pass parameters to steps in Behave. Let us see a feature file containing steps having multiple parameters where the varied values have been set. This is helpful in making the automation implementation easier, since the total step definitions is lessened."
},
{
"code": null,
"e": 37487,
"s": 37474,
"text": "Feature File"
},
{
"code": null,
"e": 37540,
"s": 37487,
"text": "Consider an example of feature file as given below β"
},
{
"code": null,
"e": 37682,
"s": 37540,
"text": "Feature β Schedule\n Scenario β Verify Day and Night Schedule\n Given I reach office at \"day\" shift\n And I reach office at \"night\" shift\n"
},
{
"code": null,
"e": 37971,
"s": 37682,
"text": "The feature file contains almost the similar steps as in the Given and in the And steps. The only difference is that in the day and night shift timings. Instead of repeating the implementations for almost the similar steps, we can pass parameters to the steps in the step definition file."
},
{
"code": null,
"e": 38180,
"s": 37971,
"text": "Please Note β We have kept the day and night parameters in double-quoted text (single-quoted text can also be used) in the feature file. In the step implementation, we shall pass the parameter enclosed in {}."
},
{
"code": null,
"e": 38264,
"s": 38180,
"text": "Also, the parameter is passed as one of the arguments to the implementation method."
},
{
"code": null,
"e": 38303,
"s": 38264,
"text": "Corresponding Step Implementation File"
},
{
"code": null,
"e": 38362,
"s": 38303,
"text": "The corresponding step implementation file is as follows β"
},
{
"code": null,
"e": 38499,
"s": 38362,
"text": "from behave import *\n@given('I reach office at \"{time}\" shift')\ndef step_implpy(context, time):\n print(\"Shift is: {}\".format(time))"
},
{
"code": null,
"e": 38506,
"s": 38499,
"text": "Output"
},
{
"code": null,
"e": 38625,
"s": 38506,
"text": "The output obtained after running the feature file is as follows and the command used is behave --no-capture -f plainβ"
},
{
"code": null,
"e": 38746,
"s": 38625,
"text": "The output shows Shift is: day and Shift is: night printed. Here, the parameters day and night are passed from the step."
},
{
"code": null,
"e": 38972,
"s": 38746,
"text": "A Scenario Outline is used if we have a group of similar criteria and the results are to be passed in a Scenario. A Scenario Outline is accompanied with an Examples table. A Scenario Outline can have multiple Examples tables."
},
{
"code": null,
"e": 39206,
"s": 38972,
"text": "The tests get executed once for every row found (after the header row) within the Examples table. The values to be tested are represented by their names enclosed in brackets<>. These names should match with the Examples table header."
},
{
"code": null,
"e": 39294,
"s": 39206,
"text": "It helps to reduce the lines of code (eliminates repeating steps) and orders our tests."
},
{
"code": null,
"e": 39307,
"s": 39294,
"text": "Feature File"
},
{
"code": null,
"e": 39361,
"s": 39307,
"text": "The feature file for scenario outline is as follows β"
},
{
"code": null,
"e": 39622,
"s": 39361,
"text": "Feature β User information\nScenario Outline: Check login functionality\n Given user enters \"<name>\" and \"<password>\"\n Then user should be logged in\n Examples: Credentials\n | name | password |\n | user1 | pwd1 |\n | user2 | pwd2 |\n"
},
{
"code": null,
"e": 39847,
"s": 39622,
"text": "Please Note: We have kept the name and password parameters enclosed in \"<>\". These parameters are column headers provided below the Examples section. In the step implementation, we shall pass the parameters enclosed in \"{}\"."
},
{
"code": null,
"e": 39931,
"s": 39847,
"text": "Also, these parameters need to be passed as arguments to the implementation method."
},
{
"code": null,
"e": 39970,
"s": 39931,
"text": "Corresponding Step Implementation File"
},
{
"code": null,
"e": 40029,
"s": 39970,
"text": "The corresponding step implementation file is as follows β"
},
{
"code": null,
"e": 40320,
"s": 40029,
"text": "from behave import *\n@given('user enters \"{name}\" and \"{password}\"')\ndef step_implpy(context, name, password):\n print(\"Username for login: {}\".format(name))\n print(\"Password for login: {}\".format(password))\n@then('user should be logged in')\ndef step_implpy(context):\n pass"
},
{
"code": null,
"e": 40327,
"s": 40320,
"text": "Output"
},
{
"code": null,
"e": 40435,
"s": 40327,
"text": "The output is obtained after running the feature file and the command used is behave --no-capture -f plain."
},
{
"code": null,
"e": 40624,
"s": 40435,
"text": "The output shows Username for login: user1, Password for login: pwd1 and Username for login: user2, Password for login: pwd2 printed. Here, the two data sets were passed from the Examples."
},
{
"code": null,
"e": 40887,
"s": 40624,
"text": "A block of text after a step enclosed in \"\"\" will be linked with that step. Here, the indentation is parsed. All the whitespaces at the beginning are removed from the text and all the succeeding lines must have at least a minimum whitespace as the starting line."
},
{
"code": null,
"e": 41026,
"s": 40887,
"text": "A text is accessible to the implementation Python code with the .text attribute within the context variable (passed in the step function)."
},
{
"code": null,
"e": 41039,
"s": 41026,
"text": "Feature File"
},
{
"code": null,
"e": 41108,
"s": 41039,
"text": "The feature file for feature titled User information is as follows β"
},
{
"code": null,
"e": 41335,
"s": 41108,
"text": "Feature β User information\nScenario β Check login functionality\n Given user enters name and password\n \"\"\"\n Tutorialspoint Behave\n Topic β Multiline Text\n \"\"\"\n Then user should be logged in\n"
},
{
"code": null,
"e": 41374,
"s": 41335,
"text": "Corresponding Step Implementation File"
},
{
"code": null,
"e": 41449,
"s": 41374,
"text": "The corresponding step implementation file for the feature is as follows β"
},
{
"code": null,
"e": 41694,
"s": 41449,
"text": "from behave import *\n@given('user enters name and password')\ndef step_impl(context):\n#access multiline text with .text attribute\n print(\"Multiline Text: \" + context.text)\n@then('user should be logged in')\ndef step_impl(context):\n pass"
},
{
"code": null,
"e": 41701,
"s": 41694,
"text": "Output"
},
{
"code": null,
"e": 41825,
"s": 41701,
"text": "The output obtained after running the feature file is mentioned below and the command used is behave --no-capture -f plain."
},
{
"code": null,
"e": 41870,
"s": 41825,
"text": "The output shows the multiline text printed."
},
{
"code": null,
"e": 42081,
"s": 41870,
"text": "A step can have a text and data table associated with it. We can add a data table with a step. It is recommended to have the table data indented and it is mandatory to have an equal column number for each line."
},
{
"code": null,
"e": 42132,
"s": 42081,
"text": "A column data should be separated by the | symbol."
},
{
"code": null,
"e": 42172,
"s": 42132,
"text": "Feature File with Table (Login.feature)"
},
{
"code": null,
"e": 42213,
"s": 42172,
"text": "The feature file is as mentioned below β"
},
{
"code": null,
"e": 42433,
"s": 42213,
"text": "Feature β User Information\nScenario β Check login functionality\n Given Collection of credentials\n | username |password |\n | user1 | pwd1 |\n | user2 | pwd2 |\n Then user should be logged in\n"
},
{
"code": null,
"e": 42670,
"s": 42433,
"text": "A table is accessible to the implementation Python code with the .table attribute within the context variable (passed in the step function). A table is an instance of Table. We can use the set up table to facilitate setting up the test."
},
{
"code": null,
"e": 42682,
"s": 42670,
"text": "Python code"
},
{
"code": null,
"e": 42748,
"s": 42682,
"text": "The python code to access table.(login_module.py) is as follows β"
},
{
"code": null,
"e": 43332,
"s": 42748,
"text": "class Deprt(object):\n def __init__(self, username, ms=None):\n if not ms:\n ms = []\n self.username = username\n self.ms = ms\n def m_addition(self, usernane):\n assert usernane not in self.ms\n self.ms.append(usernane)\nclass LModel(object):\n def __init__(self):\n self.loginusrs = []f\n self.passwords = {}\n def usr_addition(self, username, password):\n assert username not in self.loginusrs\n if password not in self.passwords:\n self.passwords[password] = Deprt(password)\n self.passwords[password].m_addition(username)"
},
{
"code": null,
"e": 43386,
"s": 43332,
"text": "Corresponding Step Implementation File(step_implg.py)"
},
{
"code": null,
"e": 43411,
"s": 43386,
"text": "The file is as follows β"
},
{
"code": null,
"e": 43822,
"s": 43411,
"text": "from behave import *\nfrom features.steps.login_module import LModel\n@given('Collection of credentials')\ndef step_impl(context):\n model = getattr(context, \"model\", None)\n if not model:\n context.model = LModel()\n #iterate rows of table\n for r in context.table:\n context.model.usr_addition(r[\"username\"], password=r[\"password\"])\n@then('user should be logged in')\ndef step_impl(context):\n pass"
},
{
"code": null,
"e": 43836,
"s": 43822,
"text": "Project setup"
},
{
"code": null,
"e": 43900,
"s": 43836,
"text": "The project set up for the file in Python project is as follows"
},
{
"code": null,
"e": 43907,
"s": 43900,
"text": "Output"
},
{
"code": null,
"e": 44027,
"s": 43907,
"text": "The output obtained after running the feature file is given below and the command used is behave --no-capture -f plain."
},
{
"code": null,
"e": 44071,
"s": 44027,
"text": "The output shows the step up table printed."
},
{
"code": null,
"e": 44296,
"s": 44071,
"text": "We can substitute multiple steps in a Scenario with one macro step. This helps us not to repeat the same code in the step definition file. A BDD framework has the capability to invoke multiple steps from the step definition."
},
{
"code": null,
"e": 44328,
"s": 44296,
"text": "Feature File with Similar Steps"
},
{
"code": null,
"e": 44384,
"s": 44328,
"text": "The feature file with the similar steps is as follows β"
},
{
"code": null,
"e": 44755,
"s": 44384,
"text": "Feature β Payment Module\n Scenario β Verify message after payment\n Given User is on payment screen\n When User enters payment details\n And User completes payment\n Then User should get success message\n Scenario β Verify new users can process payment\n Given User keys in payment info and submits\n Then success message should get displayed\n"
},
{
"code": null,
"e": 44976,
"s": 44755,
"text": "In the feature file, we have two Scenario with similar steps. In Behave, we can execute more than one step in a single step. This can be done with the help of context.execute_steps method in the step implementation file."
},
{
"code": null,
"e": 45015,
"s": 44976,
"text": "Corresponding Step Implementation File"
},
{
"code": null,
"e": 45111,
"s": 45015,
"text": "The corresponding step implementation file for the above mentioned feature file is as follows β"
},
{
"code": null,
"e": 46014,
"s": 45111,
"text": "from behave import *\n@given('User is on payment screen')\ndef is_on_payment_screen(context):\n print('User is on payment screen')\n@when('User enters payment details')\ndef enters_payment_details(context):\n print('When User enters payment details')\n@when('User completes payment')\ndef completes_payment(context):\n print('When User completes payment')\n@then('User should get success message')\ndef get_success_message(context):\n print('Then User should get success message')\n @given('User keys in payment info and submits')\ndef payment_info_and_submits(context):\n#passing steps within steps with context.execute_steps\n context.execute_steps(u\"\"\"\n Given User is on payment screen\n When User enters payment details\n And User completes payment\n \"\"\")\n@then('success message should get displayed')\ndef success_message(context):\n print('Then success message should get displayed')"
},
{
"code": null,
"e": 46021,
"s": 46014,
"text": "Output"
},
{
"code": null,
"e": 46141,
"s": 46021,
"text": "The output obtained after running the feature file is given below and the command used is behave --no-capture -f plain."
},
{
"code": null,
"e": 46178,
"s": 46141,
"text": "The continued output is as follows β"
},
{
"code": null,
"e": 46342,
"s": 46178,
"text": "The output shows that the new users of Scenario Verify can process the payment by having the steps executed from the Scenario Verify new users can process payment."
},
{
"code": null,
"e": 46565,
"s": 46342,
"text": "A Background is added to have a group of steps. It is close to a Scenario. We can add a context to multiple Scenarios with Background. It is run prior to every Scenario of a feature, but post the execution of before hooks."
},
{
"code": null,
"e": 46678,
"s": 46565,
"text": "Background is generally used for executing preconditions like login Scenarios or database connection, and so on."
},
{
"code": null,
"e": 46867,
"s": 46678,
"text": "A Background description can be added for the better human readability. It can appear only for a single time in a feature file and must be declared prior to a Scenario or Scenario Outline."
},
{
"code": null,
"e": 47083,
"s": 46867,
"text": "A Background should not be used to create a complex state (only if it cannot be avoided). This segment should be brief and authentic. Also, we should avoid having a large number of scenarios within one feature file."
},
{
"code": null,
"e": 47112,
"s": 47083,
"text": "Feature File with Background"
},
{
"code": null,
"e": 47200,
"s": 47112,
"text": "The feature file with background for the feature titled payment process is as follows β"
},
{
"code": null,
"e": 47601,
"s": 47200,
"text": "Feature β Payment Process\n Background:\n Given launch application\n Then Input credentials\n Scenario β Credit card transaction\n Given user is on credit card payment screen\n Then user should be able to complete credit card payment\n Scenario β Debit card transaction\n Given user is on debit card payment screen\n Then user should be able to complete debit card payment\n"
},
{
"code": null,
"e": 47640,
"s": 47601,
"text": "Corresponding Step Implementation File"
},
{
"code": null,
"e": 47666,
"s": 47640,
"text": "The file is given below β"
},
{
"code": null,
"e": 48435,
"s": 47666,
"text": "from behave import *\n@given('launch application')\ndef launch_application(context):\n print('launch application')\n@then('Input credentials')\ndef input_credentials(context):\n print('Input credentials')\n@given('user is on credit card payment screen')\ndef credit_card_pay(context):\n print('User is on credit card payment screen')\n@then('user should be able to complete credit card payment')\ndef credit_card_pay_comp(context):\n print('user should be able to complete credit card pay')\n@given('user is on debit card payment screen')\ndef debit_card_pay(context):\n print('User is on debit card payment screen')\n@then('user should be able to complete debit card payment')\ndef debit_card_pay_comp(context):\n print('user should be able to complete debit card payment')"
},
{
"code": null,
"e": 48442,
"s": 48435,
"text": "Output"
},
{
"code": null,
"e": 48571,
"s": 48442,
"text": "The output obtained after running the feature file is mentioned below and the command used here is behave --no-capture -f plain."
},
{
"code": null,
"e": 48608,
"s": 48571,
"text": "The continued output is as follows β"
},
{
"code": null,
"e": 48743,
"s": 48608,
"text": "The output shows the Background steps (Given Launch applications & Then Input Credentials) running twice before each of the Scenarios."
},
{
"code": null,
"e": 48887,
"s": 48743,
"text": "There are two types of Data Types in Behave, which are Predefined and User-defined. Let us first understand what are the predefined data types."
},
{
"code": null,
"e": 49110,
"s": 48887,
"text": "Behave utilises the parse module for the parsing parameters in the step definitions. Let us explore some of the parse types that have support for step definitions and do not need be registered like user-defined data types."
},
{
"code": null,
"e": 49150,
"s": 49110,
"text": "w (of str type) β Underscore & letters."
},
{
"code": null,
"e": 49190,
"s": 49150,
"text": "w (of str type) β Underscore & letters."
},
{
"code": null,
"e": 49234,
"s": 49190,
"text": "W (of str type) β Underscore & non-letters."
},
{
"code": null,
"e": 49278,
"s": 49234,
"text": "W (of str type) β Underscore & non-letters."
},
{
"code": null,
"e": 49308,
"s": 49278,
"text": "s (of str type) β Whitespace."
},
{
"code": null,
"e": 49338,
"s": 49308,
"text": "s (of str type) β Whitespace."
},
{
"code": null,
"e": 49374,
"s": 49338,
"text": "S (of str type) β Non - Whitespace."
},
{
"code": null,
"e": 49410,
"s": 49374,
"text": "S (of str type) β Non - Whitespace."
},
{
"code": null,
"e": 49436,
"s": 49410,
"text": "d (of int type) β Digits."
},
{
"code": null,
"e": 49462,
"s": 49436,
"text": "d (of int type) β Digits."
},
{
"code": null,
"e": 49494,
"s": 49462,
"text": "D (of str type) β Non - Digits."
},
{
"code": null,
"e": 49526,
"s": 49494,
"text": "D (of str type) β Non - Digits."
},
{
"code": null,
"e": 49581,
"s": 49526,
"text": "n (of int type) β Numbers having thousands separators."
},
{
"code": null,
"e": 49636,
"s": 49581,
"text": "n (of int type) β Numbers having thousands separators."
},
{
"code": null,
"e": 49696,
"s": 49636,
"text": "% (of float type) β Percentage. (translated to value/100.0)"
},
{
"code": null,
"e": 49756,
"s": 49696,
"text": "% (of float type) β Percentage. (translated to value/100.0)"
},
{
"code": null,
"e": 49799,
"s": 49756,
"text": "f (of float type) β Fixed β point numbers."
},
{
"code": null,
"e": 49842,
"s": 49799,
"text": "f (of float type) β Fixed β point numbers."
},
{
"code": null,
"e": 49908,
"s": 49842,
"text": "e (of float type) β Floating β point numbers along with exponent."
},
{
"code": null,
"e": 49974,
"s": 49908,
"text": "e (of float type) β Floating β point numbers along with exponent."
},
{
"code": null,
"e": 50009,
"s": 49974,
"text": "g (of float type) β Number format."
},
{
"code": null,
"e": 50044,
"s": 50009,
"text": "g (of float type) β Number format."
},
{
"code": null,
"e": 50081,
"s": 50044,
"text": "b (of int type) β Numbers in binary."
},
{
"code": null,
"e": 50118,
"s": 50081,
"text": "b (of int type) β Numbers in binary."
},
{
"code": null,
"e": 50152,
"s": 50118,
"text": "(of int type) β Numbers in octal."
},
{
"code": null,
"e": 50186,
"s": 50152,
"text": "(of int type) β Numbers in octal."
},
{
"code": null,
"e": 50228,
"s": 50186,
"text": "x (of int type) β Numbers in hexadecimal."
},
{
"code": null,
"e": 50270,
"s": 50228,
"text": "x (of int type) β Numbers in hexadecimal."
},
{
"code": null,
"e": 50329,
"s": 50270,
"text": "ti (of datetime type) β Time in ISO 8601 date/time format."
},
{
"code": null,
"e": 50388,
"s": 50329,
"text": "ti (of datetime type) β Time in ISO 8601 date/time format."
},
{
"code": null,
"e": 50453,
"s": 50388,
"text": "te (of datetime type) β Time in RFC 2822 email data/time format."
},
{
"code": null,
"e": 50518,
"s": 50453,
"text": "te (of datetime type) β Time in RFC 2822 email data/time format."
},
{
"code": null,
"e": 50575,
"s": 50518,
"text": "tg (of datetime type) β Time in Global data/time format."
},
{
"code": null,
"e": 50632,
"s": 50575,
"text": "tg (of datetime type) β Time in Global data/time format."
},
{
"code": null,
"e": 50685,
"s": 50632,
"text": "ta (of datetime type) β Time in US data/time format."
},
{
"code": null,
"e": 50738,
"s": 50685,
"text": "ta (of datetime type) β Time in US data/time format."
},
{
"code": null,
"e": 50788,
"s": 50738,
"text": "tc (of datetime type) β ctime() data/time format."
},
{
"code": null,
"e": 50838,
"s": 50788,
"text": "tc (of datetime type) β ctime() data/time format."
},
{
"code": null,
"e": 50897,
"s": 50838,
"text": "th (of datetime type) β Time in HTTP log data/time format."
},
{
"code": null,
"e": 50956,
"s": 50897,
"text": "th (of datetime type) β Time in HTTP log data/time format."
},
{
"code": null,
"e": 50974,
"s": 50956,
"text": "tt (of time type)"
},
{
"code": null,
"e": 50992,
"s": 50974,
"text": "tt (of time type)"
},
{
"code": null,
"e": 51077,
"s": 50992,
"text": "In the step implementation, we shall pass the parameter: data type enclosed in \"{}\"."
},
{
"code": null,
"e": 51107,
"s": 51077,
"text": "Feature File with % data type"
},
{
"code": null,
"e": 51157,
"s": 51107,
"text": "The feature file with % data type is as follows β"
},
{
"code": null,
"e": 51403,
"s": 51157,
"text": "Feature β Payment Process\n Scenario Outline: Credit card transaction\n Given user is on credit card payment screen\n When user makes a payment of \"<p>\" percent of total\n Examples: Amounts\n | p |\n |80% |\n |90% |\n"
},
{
"code": null,
"e": 51442,
"s": 51403,
"text": "Corresponding Step Implementation File"
},
{
"code": null,
"e": 51467,
"s": 51442,
"text": "The file is as follows β"
},
{
"code": null,
"e": 51785,
"s": 51467,
"text": "from behave import *\n@given('user is on credit card payment screen')\ndef credit_card_pay(context):\n print('User is on credit card payment screen')\n#passing parameter in % datatype enclosed in {}\n@when('user makes a payment of \"{p:%}\" percent of total')\ndef step_impl(context, p):\n print('Number is: ')\n print(p)"
},
{
"code": null,
"e": 51792,
"s": 51785,
"text": "Output"
},
{
"code": null,
"e": 51900,
"s": 51792,
"text": "The output is obtained after running the feature file and the command used is behave --no-capture -f plain."
},
{
"code": null,
"e": 51937,
"s": 51900,
"text": "The continued output is as follows β"
},
{
"code": null,
"e": 52067,
"s": 51937,
"text": "The output shows 0.8 and 0.9 which is obtained from the % data type to represent 80% and 90% values passed from the feature file."
},
{
"code": null,
"e": 52254,
"s": 52067,
"text": "Behave also has the user-defined data types. The method register_type is used to register a user defined type that can be parsed for any type conversion at the time of matching the step."
},
{
"code": null,
"e": 52267,
"s": 52254,
"text": "Feature File"
},
{
"code": null,
"e": 52335,
"s": 52267,
"text": "The feature file for feature titled payment process is as follows β"
},
{
"code": null,
"e": 52596,
"s": 52335,
"text": "Feature β Payment Process\n Scenario Outline: Credit card transaction\n Given user is on credit card payment screen\n When user makes a payment of \"<amount>\" of total\n Examples: Amounts\n |amount |\n |75 |\n |85 |\n"
},
{
"code": null,
"e": 52835,
"s": 52596,
"text": "In the step implementation, we shall pass the parameter: user-defined datatype enclosed in \"{}\". The method register_type is used to register a user defined type that can be parsed for any type conversion at the time of matching the step."
},
{
"code": null,
"e": 52874,
"s": 52835,
"text": "Corresponding Step Implementation File"
},
{
"code": null,
"e": 52899,
"s": 52874,
"text": "The file is as follows β"
},
{
"code": null,
"e": 53347,
"s": 52899,
"text": "from behave import *\nfrom behave import register_type\n#convert parsed text to float\ndef parse_percent(t):\n return float(t)\n#register user-defined type\nregister_type(Float=parse_percent)\n@given('user is on credit card payment screen')\ndef credit_card_pay(context):\n print('User is on credit card payment screen')\n@when('user makes a payment of \"{amount:Float}\" of total')\ndef step_impl(context, amount):\n print('Number is: ')\n print(amount)"
},
{
"code": null,
"e": 53354,
"s": 53347,
"text": "Output"
},
{
"code": null,
"e": 53462,
"s": 53354,
"text": "The output is obtained after running the feature file and the command used is behave --no-capture -f plain."
},
{
"code": null,
"e": 53499,
"s": 53462,
"text": "The continued output is as follows β"
},
{
"code": null,
"e": 53688,
"s": 53499,
"text": "The output shows 75.0 and 85.0 which have been converted to float values (with the help of user-defined conversion). These parameters are passed as the integer types from the feature file."
},
{
"code": null,
"e": 53875,
"s": 53688,
"text": "A section of a feature file can be tagged so that the Behave is capable of verifying only a certain section of the feature file. A Scenario, Feature, Scenario Outline can only be tagged."
},
{
"code": null,
"e": 54126,
"s": 53875,
"text": "Also, a tag which is used for a feature shall be inherited by all its Scenarios and the Scenario Outlines. Tags are placed before a Scenario or a Feature that we want to tag. We can also have multiple tags which are separated by spaces within a line."
},
{
"code": null,
"e": 54179,
"s": 54126,
"text": "A tag begins with @ and is followed by the tag name."
},
{
"code": null,
"e": 54220,
"s": 54179,
"text": "Feature File with tags (Payment.feature)"
},
{
"code": null,
"e": 54263,
"s": 54220,
"text": "The feature file with tags is as follows β"
},
{
"code": null,
"e": 54630,
"s": 54263,
"text": "@high\nFeature β Payment Process\n@creditpayment\n Scenario β Credit card transaction\n Given user is on credit card payment screen\n Then user should be able to complete credit card payment\n@debitpayment\n Scenario β Debit card transaction\n Given user is on debit card payment screen\n Then user should be able to complete debit card payment\n"
},
{
"code": null,
"e": 54749,
"s": 54630,
"text": "Tags help to manage the test execution by excluding/including the specific scenarios or features depending on the tag."
},
{
"code": null,
"e": 54867,
"s": 54749,
"text": "In the above example, to run a specific scenario with tag creditpayment, we have to run the below mentioned command β"
},
{
"code": null,
"e": 54912,
"s": 54867,
"text": "behave payment.feature --tags=creditpayment\n"
},
{
"code": null,
"e": 55015,
"s": 54912,
"text": "To run the feature with tag high and execute all the Scenarios, we have to run the following command β"
},
{
"code": null,
"e": 55051,
"s": 55015,
"text": "behave payment.feature --tags=high\n"
},
{
"code": null,
"e": 55191,
"s": 55051,
"text": "If run the command stated below, it means that the command shall execute the Scenarios which are tagged with creditpayment or debitpayment."
},
{
"code": null,
"e": 55251,
"s": 55191,
"text": "behave payment.feature --tags= creditpayment, debitpayment\n"
},
{
"code": null,
"e": 55396,
"s": 55251,
"text": "If run the command given below, it means that the command shall execute both the Scenarios which are tagged with creditpayment and debitpayment."
},
{
"code": null,
"e": 55462,
"s": 55396,
"text": "behave payment.feature --tags= creditpayment --tags=debitpayment\n"
},
{
"code": null,
"e": 55591,
"s": 55462,
"text": "If run the command mentioned below, it means that the command shall not execute the Scenario which is tagged with creditpayment."
},
{
"code": null,
"e": 55639,
"s": 55591,
"text": "behave payment.feature --tags= ~ creditpayment\n"
},
{
"code": null,
"e": 55715,
"s": 55639,
"text": "Hence, the Feature File with tags(Payment.feature) will now be as follows β"
},
{
"code": null,
"e": 56050,
"s": 55715,
"text": "@high\nFeature β Payment Process\n@creditpayment @payment\n Scenario β Credit card transaction\n Given user is on credit card payment screen\n@debitpayment @payment\n Scenario β Debit card transaction\n Given user is on debit card payment screen\n Scenario β Cheque transaction\n Given user is on cheque payment screen\n"
},
{
"code": null,
"e": 56089,
"s": 56050,
"text": "Corresponding Step Implementation File"
},
{
"code": null,
"e": 56114,
"s": 56089,
"text": "The file is as follows β"
},
{
"code": null,
"e": 56501,
"s": 56114,
"text": "from behave import *\n@given('user is on credit card payment screen')\ndef credit_card_pay(context):\n print('User is on credit card payment screen')\n@given('user is on debit card payment screen')\ndef debit_card_pay(context):\n print('user is on debit card payment screen')\n@given('user is on cheque payment screen')\ndef cheque_pay(context):\n print('user is on cheque payment screen')"
},
{
"code": null,
"e": 56508,
"s": 56501,
"text": "Output"
},
{
"code": null,
"e": 56662,
"s": 56508,
"text": "The output obtained after running the feature file is mentioned below. Here, we have used the command behave --no-capture Payment.feature --tags=payment."
},
{
"code": null,
"e": 56783,
"s": 56662,
"text": "The output shows two scenarios passed, as there are two Scenarios in the features file having Scenario tag with payment."
},
{
"code": null,
"e": 56893,
"s": 56783,
"text": "When we use the command behave --no-capture Payment.feature --tags=~creditpayment, the output is as follows β"
},
{
"code": null,
"e": 57024,
"s": 56893,
"text": "The output shows two scenarios passed, as there are two Scenarios in the features file not having Scenario tag with creditpayment."
},
{
"code": null,
"e": 57125,
"s": 57024,
"text": "When we use the command behave --no-capture Payment.feature --tags=high, the output is given below β"
},
{
"code": null,
"e": 57254,
"s": 57125,
"text": "The output shows three scenarios passed, as there are three Scenarios in the features file not having features tagged with high."
},
{
"code": null,
"e": 57371,
"s": 57254,
"text": "Use the command behave --no-capture Payment.feature --tags=payment,creditpayment to get the below mentioned output β"
},
{
"code": null,
"e": 57516,
"s": 57371,
"text": "The output shows two scenarios passed, as there are two Scenarios in the features file not having Scenario tagged with payment or creditpayment."
},
{
"code": null,
"e": 57602,
"s": 57516,
"text": "Enumeration is used to map the multiple distinctive string based words to the values."
},
{
"code": null,
"e": 57681,
"s": 57602,
"text": "We may require a user-defined data type having the following characteristics β"
},
{
"code": null,
"e": 57717,
"s": 57681,
"text": "A handful of words must be matched."
},
{
"code": null,
"e": 57753,
"s": 57717,
"text": "A handful of words must be matched."
},
{
"code": null,
"e": 57801,
"s": 57753,
"text": "Pre-defined values prior to the test execution."
},
{
"code": null,
"e": 57849,
"s": 57801,
"text": "Pre-defined values prior to the test execution."
},
{
"code": null,
"e": 57915,
"s": 57849,
"text": "For the above scenarios, enumeration based on string can be used."
},
{
"code": null,
"e": 57928,
"s": 57915,
"text": "Feature File"
},
{
"code": null,
"e": 58013,
"s": 57928,
"text": "Consider a feature file for the Feature titled payment process, as mentioned below β"
},
{
"code": null,
"e": 58128,
"s": 58013,
"text": "Feature β Payment Process\nScenario β Response\n When User asks \"Is payment done?\"\n Then response is \"No\"\n"
},
{
"code": null,
"e": 58423,
"s": 58128,
"text": "In the step implementation file, TypeBuilder.make_enum function evaluates a regular expression pattern for the provided enumeration of words or strings. The method register_type is used to register a user defined type that can be parsed for any type conversion at the time of matching the step."
},
{
"code": null,
"e": 58503,
"s": 58423,
"text": "Also, we shall pass the parameter: user-defined enum datatype enclosed in \"{}\"."
},
{
"code": null,
"e": 58542,
"s": 58503,
"text": "Corresponding Step Implementation File"
},
{
"code": null,
"e": 58609,
"s": 58542,
"text": "The step implementation file for the above Feature is as follows β"
},
{
"code": null,
"e": 59052,
"s": 58609,
"text": "from behave import *\nfrom behave import register_type\nfrom parse_type import TypeBuilder\n# -- ENUM: Yields True (for \"yes\"), False (for \"no\")\nparse_response = TypeBuilder.make_enum({\"yes\": True, \"no\": False})\nregister_type(Response=parse_response)\n@when('User asks \"{q}\"')\ndef step_question(context, q):\n print(\"Question is: \")\n print(q)\n@then('response is \"{a:Response}\"')\ndef step_answer(context, a):\n print(\"Answer is: \")\n print(a)"
},
{
"code": null,
"e": 59059,
"s": 59052,
"text": "Output"
},
{
"code": null,
"e": 59191,
"s": 59059,
"text": "The output obtained after running the feature file is mentioned below. Here, we have used the command behave --no-capture -f plain."
},
{
"code": null,
"e": 59291,
"s": 59191,
"text": "The output shows Is payment done? and False. The output False comes from the enumeration data type."
},
{
"code": null,
"e": 59368,
"s": 59291,
"text": "There are three types of Step Matchers in Behave. They are explained below β"
},
{
"code": null,
"e": 59418,
"s": 59368,
"text": "ParseMatcher (parse) β Based on the parse module."
},
{
"code": null,
"e": 59468,
"s": 59418,
"text": "ParseMatcher (parse) β Based on the parse module."
},
{
"code": null,
"e": 59528,
"s": 59468,
"text": "extended ParseMatcher(cfparse) β Allows cardinality syntax."
},
{
"code": null,
"e": 59588,
"s": 59528,
"text": "extended ParseMatcher(cfparse) β Allows cardinality syntax."
},
{
"code": null,
"e": 59660,
"s": 59588,
"text": "RegexMatcher (re) β Based on regular expressions for matching patterns."
},
{
"code": null,
"e": 59732,
"s": 59660,
"text": "RegexMatcher (re) β Based on regular expressions for matching patterns."
},
{
"code": null,
"e": 59804,
"s": 59732,
"text": "It is the in-built step matcher which has the below mentioned features:"
},
{
"code": null,
"e": 59834,
"s": 59804,
"text": "Simple to use and comprehend."
},
{
"code": null,
"e": 59864,
"s": 59834,
"text": "Simple to use and comprehend."
},
{
"code": null,
"e": 59925,
"s": 59864,
"text": "Predefined and user-defined data types support this matcher."
},
{
"code": null,
"e": 59986,
"s": 59925,
"text": "Predefined and user-defined data types support this matcher."
},
{
"code": null,
"e": 60047,
"s": 59986,
"text": "Re-utilises regular expressions with the help of data types."
},
{
"code": null,
"e": 60108,
"s": 60047,
"text": "Re-utilises regular expressions with the help of data types."
},
{
"code": null,
"e": 60155,
"s": 60108,
"text": "Conceals the complexity of regular expression."
},
{
"code": null,
"e": 60202,
"s": 60155,
"text": "Conceals the complexity of regular expression."
},
{
"code": null,
"e": 60301,
"s": 60202,
"text": "It extends the Parse Matcher. It has additional features along with the features of Parse matcher."
},
{
"code": null,
"e": 60335,
"s": 60301,
"text": "The additional features include β"
},
{
"code": null,
"e": 60377,
"s": 60335,
"text": "Comprehends the cardinality field syntax."
},
{
"code": null,
"e": 60419,
"s": 60377,
"text": "Comprehends the cardinality field syntax."
},
{
"code": null,
"e": 60498,
"s": 60419,
"text": "Generates missing type converters for the fields with cardinality field parts."
},
{
"code": null,
"e": 60577,
"s": 60498,
"text": "Generates missing type converters for the fields with cardinality field parts."
},
{
"code": null,
"e": 60598,
"s": 60577,
"text": "Built on parse-type."
},
{
"code": null,
"e": 60619,
"s": 60598,
"text": "Built on parse-type."
},
{
"code": null,
"e": 60647,
"s": 60619,
"text": "It has the below features β"
},
{
"code": null,
"e": 60680,
"s": 60647,
"text": "Backward compatible to Cucumber."
},
{
"code": null,
"e": 60713,
"s": 60680,
"text": "Backward compatible to Cucumber."
},
{
"code": null,
"e": 60756,
"s": 60713,
"text": "Easier to use compared to a parse matcher."
},
{
"code": null,
"e": 60799,
"s": 60756,
"text": "Easier to use compared to a parse matcher."
},
{
"code": null,
"e": 60847,
"s": 60799,
"text": "Let us understand the parse matchers in detail."
},
{
"code": null,
"e": 61063,
"s": 60847,
"text": "There are maybe steps in the feature file having almost similar phrases. Behave has the parsing ability. The method use_step_parser is used for this and we have to pass the parser type as a parameter to that method."
},
{
"code": null,
"e": 61188,
"s": 61063,
"text": "For parse matchers, we have to pass the parameter parse. It utilises the parse for regular expressions parsing and matching."
},
{
"code": null,
"e": 61230,
"s": 61188,
"text": "Feature File (almost Given similar steps)"
},
{
"code": null,
"e": 61285,
"s": 61230,
"text": "The feature file for the similar steps is as follows β"
},
{
"code": null,
"e": 61494,
"s": 61285,
"text": "Feature β Payment Process\nScenario β Check Debit transactions\n Given user is on \"debit\" screen\n When user makes a payment\nScenario β Check Credit transactions\n Given user is on \"credit\" screen\n"
},
{
"code": null,
"e": 61533,
"s": 61494,
"text": "Corresponding Step Implementation File"
},
{
"code": null,
"e": 61578,
"s": 61533,
"text": "The step implementation file is as follows β"
},
{
"code": null,
"e": 61788,
"s": 61578,
"text": "from behave import *\n#define parser type\nuse_step_matcher(\"parse\")\n@given('user is on \"{p}\" screen')\ndef step_impl(context, p):\n print(p)\n@when('user makes a payment')\ndef step_pay_complete(context):\n pass"
},
{
"code": null,
"e": 61795,
"s": 61788,
"text": "Output"
},
{
"code": null,
"e": 61927,
"s": 61795,
"text": "The output obtained after running the feature file is mentioned below. Here, we have used the command behave --no-capture -f plain."
},
{
"code": null,
"e": 62104,
"s": 61927,
"text": "The output shows debit and credit. These two values have been passed with almost similar Given steps in the feature file. In step implementation, we have parsed both the steps."
},
{
"code": null,
"e": 62171,
"s": 62104,
"text": "Let us have an overall view of the syntax of regular expressions β"
},
{
"code": null,
"e": 62210,
"s": 62171,
"text": "Dot (.) β Equivalent to any character."
},
{
"code": null,
"e": 62249,
"s": 62210,
"text": "Dot (.) β Equivalent to any character."
},
{
"code": null,
"e": 62303,
"s": 62249,
"text": "Caret (^) β Equivalent to beginning of string. (^...)"
},
{
"code": null,
"e": 62357,
"s": 62303,
"text": "Caret (^) β Equivalent to beginning of string. (^...)"
},
{
"code": null,
"e": 62402,
"s": 62357,
"text": "Dollar Sign ()βEquivalenttoendofstring.(...)"
},
{
"code": null,
"e": 62447,
"s": 62402,
"text": "Dollar Sign ()βEquivalenttoendofstring.(...)"
},
{
"code": null,
"e": 62484,
"s": 62447,
"text": "| β Expression x| y, matches x or y."
},
{
"code": null,
"e": 62521,
"s": 62484,
"text": "| β Expression x| y, matches x or y."
},
{
"code": null,
"e": 62543,
"s": 62521,
"text": "\\ β Escape character."
},
{
"code": null,
"e": 62565,
"s": 62543,
"text": "\\ β Escape character."
},
{
"code": null,
"e": 62587,
"s": 62565,
"text": "\\. β Matches dot. (.)"
},
{
"code": null,
"e": 62609,
"s": 62587,
"text": "\\. β Matches dot. (.)"
},
{
"code": null,
"e": 62637,
"s": 62609,
"text": "\\\\ β Matches backslash. (\\)"
},
{
"code": null,
"e": 62665,
"s": 62637,
"text": "\\\\ β Matches backslash. (\\)"
},
{
"code": null,
"e": 62714,
"s": 62665,
"text": "[...] β Declares a set of characters. ([A-Za-z])"
},
{
"code": null,
"e": 62763,
"s": 62714,
"text": "[...] β Declares a set of characters. ([A-Za-z])"
},
{
"code": null,
"e": 62791,
"s": 62763,
"text": "\\d β Matches digit. ([0-9])"
},
{
"code": null,
"e": 62819,
"s": 62791,
"text": "\\d β Matches digit. ([0-9])"
},
{
"code": null,
"e": 62843,
"s": 62819,
"text": "\\D β Matches non-digit."
},
{
"code": null,
"e": 62867,
"s": 62843,
"text": "\\D β Matches non-digit."
},
{
"code": null,
"e": 62902,
"s": 62867,
"text": "\\s β Matches whitespace character."
},
{
"code": null,
"e": 62937,
"s": 62902,
"text": "\\s β Matches whitespace character."
},
{
"code": null,
"e": 62978,
"s": 62937,
"text": "\\S β Matches non - whitespace character."
},
{
"code": null,
"e": 63019,
"s": 62978,
"text": "\\S β Matches non - whitespace character."
},
{
"code": null,
"e": 63046,
"s": 63019,
"text": "\\w β Matches alphanumeric."
},
{
"code": null,
"e": 63073,
"s": 63046,
"text": "\\w β Matches alphanumeric."
},
{
"code": null,
"e": 63104,
"s": 63073,
"text": "\\W β Matches non-alphanumeric."
},
{
"code": null,
"e": 63135,
"s": 63104,
"text": "\\W β Matches non-alphanumeric."
},
{
"code": null,
"e": 63182,
"s": 63135,
"text": "(...) β Group a pattern of regular expression."
},
{
"code": null,
"e": 63229,
"s": 63182,
"text": "(...) β Group a pattern of regular expression."
},
{
"code": null,
"e": 63285,
"s": 63229,
"text": "\\number β Matches text of previous group by index. (\\1)"
},
{
"code": null,
"e": 63341,
"s": 63285,
"text": "\\number β Matches text of previous group by index. (\\1)"
},
{
"code": null,
"e": 63411,
"s": 63341,
"text": "(? P<name>...) β Matches pattern and stores it in the name parameter."
},
{
"code": null,
"e": 63481,
"s": 63411,
"text": "(? P<name>...) β Matches pattern and stores it in the name parameter."
},
{
"code": null,
"e": 63556,
"s": 63481,
"text": "(?P=name) β Matches all text which was matched by the previous group name."
},
{
"code": null,
"e": 63631,
"s": 63556,
"text": "(?P=name) β Matches all text which was matched by the previous group name."
},
{
"code": null,
"e": 63689,
"s": 63631,
"text": "(?:...) β Matches a pattern, however cannot capture text."
},
{
"code": null,
"e": 63747,
"s": 63689,
"text": "(?:...) β Matches a pattern, however cannot capture text."
},
{
"code": null,
"e": 63812,
"s": 63747,
"text": "(?#...) β Comment (not considered). Narrates details of pattern."
},
{
"code": null,
"e": 63877,
"s": 63812,
"text": "(?#...) β Comment (not considered). Narrates details of pattern."
},
{
"code": null,
"e": 64034,
"s": 63877,
"text": "In case a character, character set or group needs to repeat multiple times, it is mandatory to provide the cardinality of the pattern of regular expression."
},
{
"code": null,
"e": 64101,
"s": 64034,
"text": "? : Pattern having cardinality 0... 1:not mandatory(question mark)"
},
{
"code": null,
"e": 64168,
"s": 64101,
"text": "? : Pattern having cardinality 0... 1:not mandatory(question mark)"
},
{
"code": null,
"e": 64225,
"s": 64168,
"text": "- : Pattern having cardinality 0 or more, 0..( asterisk)"
},
{
"code": null,
"e": 64282,
"s": 64225,
"text": "- : Pattern having cardinality 0 or more, 0..( asterisk)"
},
{
"code": null,
"e": 64336,
"s": 64282,
"text": "+ - : Pattern having cardinality 1 or more, 1..(plus)"
},
{
"code": null,
"e": 64390,
"s": 64336,
"text": "+ - : Pattern having cardinality 1 or more, 1..(plus)"
},
{
"code": null,
"e": 64432,
"s": 64390,
"text": "{n}: Matches a pattern for n repetitions."
},
{
"code": null,
"e": 64474,
"s": 64432,
"text": "{n}: Matches a pattern for n repetitions."
},
{
"code": null,
"e": 64529,
"s": 64474,
"text": "{a ,b}: Matches from a to b for a pattern repetitions."
},
{
"code": null,
"e": 64584,
"s": 64529,
"text": "{a ,b}: Matches from a to b for a pattern repetitions."
},
{
"code": null,
"e": 64638,
"s": 64584,
"text": "[A-Za-z]+ : Matches multiple alphabetical characters."
},
{
"code": null,
"e": 64692,
"s": 64638,
"text": "[A-Za-z]+ : Matches multiple alphabetical characters."
},
{
"code": null,
"e": 64912,
"s": 64692,
"text": "There are maybe steps in the feature file having almost the similar phrases. Behave has the parsing ability. The method use_step_parser is used for this and we have to pass the parser type as a parameter to that method."
},
{
"code": null,
"e": 65067,
"s": 64912,
"text": "For regular expression matchers, we have to pass the parameter re. The parameter (? P<name>...) is utilised to obtain parameters from the step definition."
},
{
"code": null,
"e": 65103,
"s": 65067,
"text": "Feature File (almost similar steps)"
},
{
"code": null,
"e": 65154,
"s": 65103,
"text": "The feature file for similar steps is as follows β"
},
{
"code": null,
"e": 65334,
"s": 65154,
"text": "Feature β Payment Process\nScenario β Check Debit transactions\n Given user is on \"debit\" screen\n Scenario β Check Credit transactions\n Given user is on \"credit\" screen\n"
},
{
"code": null,
"e": 65373,
"s": 65334,
"text": "Corresponding Step Implementation File"
},
{
"code": null,
"e": 65418,
"s": 65373,
"text": "The step implementation file is as follows β"
},
{
"code": null,
"e": 65633,
"s": 65418,
"text": "from behave import *\n#define parser type\nuse_step_matcher(\"re\")\n#regular expression parsing\n@given('user is on \"(?P<payment>.*)\" screen')\ndef step_impl(context, payment):\n print(\"Screen type: \")\n print(payment)"
},
{
"code": null,
"e": 65640,
"s": 65633,
"text": "Output"
},
{
"code": null,
"e": 65767,
"s": 65640,
"text": "The output obtained after running the feature file is as follows. Here, we have used the command behave --no-capture -f plain."
},
{
"code": null,
"e": 65970,
"s": 65767,
"text": "The output shows the debit and credit. These two values have been passed with almost the similar steps in the feature file. In step implementation, we have parsed both the steps with regular expression."
},
{
"code": null,
"e": 66236,
"s": 65970,
"text": "There are maybe steps in the feature file having almost similar phrases. Behave has the parsing ability so that one step definition can cover these steps. The method use_step_parser is used for this and we have to pass the parser type as a parameter to that method."
},
{
"code": null,
"e": 66485,
"s": 66236,
"text": "For extended parse matchers, we have to pass the parameter cfparse. It has the Cardinality Field (CF) support. By default, it generates the missing type converters for connected cardinality (if type converter for cardinality equal to one is given)."
},
{
"code": null,
"e": 66530,
"s": 66485,
"text": "It can support the below parse expressions β"
},
{
"code": null,
"e": 66570,
"s": 66530,
"text": "{values:Type+} β Cardinality=1..N, many"
},
{
"code": null,
"e": 66610,
"s": 66570,
"text": "{values:Type+} β Cardinality=1..N, many"
},
{
"code": null,
"e": 66651,
"s": 66610,
"text": "{values:Type*} β Cardinality=0..N, many0"
},
{
"code": null,
"e": 66692,
"s": 66651,
"text": "{values:Type*} β Cardinality=0..N, many0"
},
{
"code": null,
"e": 66736,
"s": 66692,
"text": "{values:Type?} β Cardinality=0..1, optional"
},
{
"code": null,
"e": 66780,
"s": 66736,
"text": "{values:Type?} β Cardinality=0..1, optional"
},
{
"code": null,
"e": 66816,
"s": 66780,
"text": "Feature File (almost similar steps)"
},
{
"code": null,
"e": 66875,
"s": 66816,
"text": "The feature file with almost similar steps is as follows β"
},
{
"code": null,
"e": 67055,
"s": 66875,
"text": "Feature β Payment Process\nScenario β Check Debit transactions\n Given user is on \"debit\" screen\n Scenario β Check Credit transactions\n Given user is on \"credit\" screen\n"
},
{
"code": null,
"e": 67197,
"s": 67055,
"text": "The method register_type is used to register a user defined type that can be parsed for any type conversion at the time of matching the step."
},
{
"code": null,
"e": 67236,
"s": 67197,
"text": "Corresponding Step Implementation File"
},
{
"code": null,
"e": 67282,
"s": 67236,
"text": "The step implementation file is given below β"
},
{
"code": null,
"e": 67771,
"s": 67282,
"text": "from behave import *\nimport parse\n#define parse type\nuse_step_matcher(\"cfparse\")\n# for whitespace characters\n@parse.with_pattern(r\"x\\s+\")\ndef parse_string(s):\n#type converter for \"x\" succeeded by single/multiple spaces\n return s.strip()\n#register user-defined datatype\nregister_type(x_=parse_string)\n#optional part :x_? cardinality field in parse expression\n@given('user is on {:x_?}{payment} screen')\ndef step_payment(context, x_, payment):\n print(\"Payment type: \")\n print(payment)"
},
{
"code": null,
"e": 67778,
"s": 67771,
"text": "Output"
},
{
"code": null,
"e": 67898,
"s": 67778,
"text": "The output obtained after running the feature file is given below and the command used is behave --no-capture -f plain."
},
{
"code": null,
"e": 68121,
"s": 67898,
"text": "The output shows the debit and credit. These two values have been passed with almost similar steps in the feature file. In step implementation, we have parsed both the steps with cardinality fields within parse expression."
},
{
"code": null,
"e": 68208,
"s": 68121,
"text": "There are maybe steps in the feature file having almost similar phrases. For instance,"
},
{
"code": null,
"e": 68281,
"s": 68208,
"text": "Given user makes payment of 100 INR\nAnd user makes payment of 10 Dollar\n"
},
{
"code": null,
"e": 68499,
"s": 68281,
"text": "Here, we can have different step definitions to differentiate the INR and Dollar. For this, we can use the multi-method approach, where it is mandatory to have varied regular expressions for the dissimilar data types."
},
{
"code": null,
"e": 68535,
"s": 68499,
"text": "Feature File (almost similar steps)"
},
{
"code": null,
"e": 68578,
"s": 68535,
"text": "Consider the feature file as given below β"
},
{
"code": null,
"e": 68722,
"s": 68578,
"text": "Feature β Multi-Methods\n Scenario β Purchase\n Given User is on shop\n When user purchases 3 shirts\n And user purchases 4 pants\n"
},
{
"code": null,
"e": 68995,
"s": 68722,
"text": "In the step implementation file, TypeBuilder.make_choice function evaluates a regular expression pattern for the provided choices. The method register_type is used to register a user defined type that can be parsed for any type conversion at the time of matching the step."
},
{
"code": null,
"e": 69070,
"s": 68995,
"text": "Also, we shall pass the parameter: user-defined datatype enclosed in \"{}\"."
},
{
"code": null,
"e": 69109,
"s": 69070,
"text": "Corresponding Step Implementation File"
},
{
"code": null,
"e": 69154,
"s": 69109,
"text": "The step implementation file is as follows β"
},
{
"code": null,
"e": 69928,
"s": 69154,
"text": "from behave import *\nfrom behave import register_type\nfrom parse_type import TypeBuilder\nparse_dress = TypeBuilder.make_choice([\"shirts\", \"t-shirts\"])\n#register user-defined datatype\nregister_type(Dress=parse_dress)\nparse_pant = TypeBuilder.make_choice([\"pants\", \"gowns\"])\n#register user-defined datatype\nregister_type(Pant=parse_pant)\n@given(\"User is on shop\")\ndef step_user_shop(context):\n pass\n# multiple methods being used .\n@when(u\"user purchases {count:n} {d:Dress}\")\ndef step_dress(context, count, d):\n print(\"User purchased: \")\n print(d)\n print(\"Count is:\")\n print(count)\n@when(u\"user purchases {count:n} {p:Pant}\")\ndef step_pant(context, count, p):\n print(\"User purchased: \")\n print(p)\n print(\"Count is:\")\n print(count)"
},
{
"code": null,
"e": 69935,
"s": 69928,
"text": "Output"
},
{
"code": null,
"e": 70055,
"s": 69935,
"text": "The output obtained after running the feature file is given below and the command used is behave --no-capture -f plain."
},
{
"code": null,
"e": 70294,
"s": 70055,
"text": "The output shows the purchase items and their counts. These two values have been passed with almost similar steps (but dissimilar data types) in the feature file. In step implementation, we have used multiple methods to obtain the values."
},
{
"code": null,
"e": 70494,
"s": 70294,
"text": "Step functions are created in the Python files which exist within the steps directory. Every Python file (having extension as .py) inside that directory gets imported to get the step implementations."
},
{
"code": null,
"e": 70643,
"s": 70494,
"text": "Once the feature files get triggered for execution, the implementation files get loaded. The step functions are associated with the step decorators."
},
{
"code": null,
"e": 70735,
"s": 70643,
"text": "The step implementations must begin with the import, by using the command mentioned below β"
},
{
"code": null,
"e": 70757,
"s": 70735,
"text": "from behave import *\n"
},
{
"code": null,
"e": 70937,
"s": 70757,
"text": "This will import multiple decorators described in Behave to help us to locate our step functions. The decorators like the given, when, then, and so on accepts one string argument."
},
{
"code": null,
"e": 70985,
"s": 70937,
"text": "For example, consider the code given herewith β"
},
{
"code": null,
"e": 71055,
"s": 70985,
"text": "@given('user is on admin screen')\ndef step_impl(context):\n pass\n"
},
{
"code": null,
"e": 71146,
"s": 71055,
"text": "The above code shall match the Given step of the below feature file, which is as follows β"
},
{
"code": null,
"e": 71236,
"s": 71146,
"text": "Feature β Admin Module\nScenario β Admin verification\n Given user is on admin screen\n"
},
{
"code": null,
"e": 71331,
"s": 71236,
"text": "The steps starting with And/But in the feature file are renamed to their earlier step keyword."
},
{
"code": null,
"e": 71384,
"s": 71331,
"text": "For example, consider the feature file given below β"
},
{
"code": null,
"e": 71612,
"s": 71384,
"text": "Feature β Admin Module\nScenario β Admin verification\n Given user is on admin screen\n And user is on history screen\n Then user should be able to see admin name\n But user should not able to check history\n"
},
{
"code": null,
"e": 71757,
"s": 71612,
"text": "The And step shall be renamed to the Given step and the But step shall be renamed to the earlier step keyword. All these are handled internally."
},
{
"code": null,
"e": 71871,
"s": 71757,
"text": "If there are more than one And/But steps consecutively, they would inherit the keyword of non And or But keyword."
},
{
"code": null,
"e": 72063,
"s": 71871,
"text": "The step function having the step decorator shall have a minimum one parameter. The first parameter is known as the context variable. Other parameters come from step parameters (if required)."
},
{
"code": null,
"e": 72127,
"s": 72063,
"text": "For example, refer the step function as per the step parameter."
},
{
"code": null,
"e": 72197,
"s": 72127,
"text": "@given('user is on admin screen')\ndef step_impl(context):\n pass\n"
},
{
"code": null,
"e": 72215,
"s": 72197,
"text": "Project Structure"
},
{
"code": null,
"e": 72269,
"s": 72215,
"text": "The project structure for the feature is as follows β"
},
{
"code": null,
"e": 72463,
"s": 72269,
"text": "We can have parameters within the step names. These parameters can be taken care of by the regular expressions or by the default or extended parser with the help of the use_step_matcher method."
},
{
"code": null,
"e": 72594,
"s": 72463,
"text": "Modify the parameter matcher in parsing the step text. There are multiple in-built parsers present in Behave, as explained below β"
},
{
"code": null,
"e": 72782,
"s": 72594,
"text": "parse β It gives an easy parser that restores regular expression for the step parameters with plain syntax. For example, {parameter: type}. It allows type conversion with type converters."
},
{
"code": null,
"e": 72970,
"s": 72782,
"text": "parse β It gives an easy parser that restores regular expression for the step parameters with plain syntax. For example, {parameter: type}. It allows type conversion with type converters."
},
{
"code": null,
"e": 73380,
"s": 72970,
"text": "cfparse β It has the Cardinality Field (CF) support. By default, it generates the missing type converters for connected cardinality (if type converter for cardinality equal to one is given). It can support the below parse expressions β\n{values:Type+} β Cardinality=1..N, many\n{values:Type*} β Cardinality=0..N, many0\n{values:Type?} β Cardinality=0..1, optional\nIt allows type conversion with type converters.\n"
},
{
"code": null,
"e": 73616,
"s": 73380,
"text": "cfparse β It has the Cardinality Field (CF) support. By default, it generates the missing type converters for connected cardinality (if type converter for cardinality equal to one is given). It can support the below parse expressions β"
},
{
"code": null,
"e": 73656,
"s": 73616,
"text": "{values:Type+} β Cardinality=1..N, many"
},
{
"code": null,
"e": 73697,
"s": 73656,
"text": "{values:Type*} β Cardinality=0..N, many0"
},
{
"code": null,
"e": 73741,
"s": 73697,
"text": "{values:Type?} β Cardinality=0..1, optional"
},
{
"code": null,
"e": 73789,
"s": 73741,
"text": "It allows type conversion with type converters."
},
{
"code": null,
"e": 73997,
"s": 73789,
"text": "re β It utilises the complete regular expressions to parse the clause. We have to take the help of the named groups (? P<name>...) to declare variables obtained from the text and then feed it to the step ()."
},
{
"code": null,
"e": 74205,
"s": 73997,
"text": "re β It utilises the complete regular expressions to parse the clause. We have to take the help of the named groups (? P<name>...) to declare variables obtained from the text and then feed it to the step ()."
},
{
"code": null,
"e": 74309,
"s": 74205,
"text": "We can have our customised matcher along with new data types with the help of the register_type method."
},
{
"code": null,
"e": 74404,
"s": 74309,
"text": "Registers a user defined type for parsing during type conversion at the time of step matching."
},
{
"code": null,
"e": 74450,
"s": 74404,
"text": "It extracts the parameters out of step names."
},
{
"code": null,
"e": 74516,
"s": 74450,
"text": "pattern β The pattern matching associated with the step function."
},
{
"code": null,
"e": 74582,
"s": 74516,
"text": "pattern β The pattern matching associated with the step function."
},
{
"code": null,
"e": 74642,
"s": 74582,
"text": "func β The step function is the pattern is associated with."
},
{
"code": null,
"e": 74702,
"s": 74642,
"text": "func β The step function is the pattern is associated with."
},
{
"code": null,
"e": 74760,
"s": 74702,
"text": "check_match(step) β To match with the step name provided."
},
{
"code": null,
"e": 74818,
"s": 74760,
"text": "check_match(step) β To match with the step name provided."
},
{
"code": null,
"e": 74910,
"s": 74818,
"text": "describe(schema=None) β Give description in form of text of the function or matcher object."
},
{
"code": null,
"e": 75002,
"s": 74910,
"text": "describe(schema=None) β Give description in form of text of the function or matcher object."
},
{
"code": null,
"e": 75063,
"s": 75002,
"text": "regex_pattern: Yields the utilised textual regex expression."
},
{
"code": null,
"e": 75124,
"s": 75063,
"text": "regex_pattern: Yields the utilised textual regex expression."
},
{
"code": null,
"e": 75213,
"s": 75124,
"text": "An argument for a step name in the feature file obtained with step decorator parameters."
},
{
"code": null,
"e": 75245,
"s": 75213,
"text": "The attributes are as follows β"
},
{
"code": null,
"e": 75316,
"s": 75245,
"text": "original β The original text which is matched in the name of the step."
},
{
"code": null,
"e": 75387,
"s": 75316,
"text": "original β The original text which is matched in the name of the step."
},
{
"code": null,
"e": 75446,
"s": 75387,
"text": "value β The value of the argument which is type converted."
},
{
"code": null,
"e": 75505,
"s": 75446,
"text": "value β The value of the argument which is type converted."
},
{
"code": null,
"e": 75588,
"s": 75505,
"text": "name β The argument name. The value is set to None, if the parameter is not given."
},
{
"code": null,
"e": 75671,
"s": 75588,
"text": "name β The argument name. The value is set to None, if the parameter is not given."
},
{
"code": null,
"e": 75728,
"s": 75671,
"text": "start β The starting index of the argument in step name."
},
{
"code": null,
"e": 75785,
"s": 75728,
"text": "start β The starting index of the argument in step name."
},
{
"code": null,
"e": 75838,
"s": 75785,
"text": "end β The ending index of the argument in step name."
},
{
"code": null,
"e": 75891,
"s": 75838,
"text": "end β The ending index of the argument in step name."
},
{
"code": null,
"e": 75990,
"s": 75891,
"text": "A step in the feature file which is parameter-matched and obtained with step decorator parameters."
},
{
"code": null,
"e": 76022,
"s": 75990,
"text": "The attributes are as follows β"
},
{
"code": null,
"e": 76087,
"s": 76022,
"text": "func β The step function which is applicable to the given match."
},
{
"code": null,
"e": 76152,
"s": 76087,
"text": "func β The step function which is applicable to the given match."
},
{
"code": null,
"e": 76261,
"s": 76152,
"text": "arguments β The argument list the instances having the matched parameter obtained from the name of the step."
},
{
"code": null,
"e": 76370,
"s": 76261,
"text": "arguments β The argument list the instances having the matched parameter obtained from the name of the step."
},
{
"code": null,
"e": 76562,
"s": 76370,
"text": "We can run a Behave test, by running the command line arguments, or we can create a runner script. This script gives the provision of running the test and generating the corresponding report."
},
{
"code": null,
"e": 76790,
"s": 76562,
"text": "We can do a re-try and execute the failed test. Also, before executing the entire suite, the runner script is capable of making an application programming interface (API) call and ensuring that there are no issues with the API."
},
{
"code": null,
"e": 76881,
"s": 76790,
"text": "Follow the steps given below to create and execute a runner script successfully in Behave."
},
{
"code": null,
"e": 76953,
"s": 76881,
"text": "Step 1 β Create a runner script (runner.py) within the features folder."
},
{
"code": null,
"e": 77005,
"s": 76953,
"text": "The following screen will appear on your computer β"
},
{
"code": null,
"e": 77056,
"s": 77005,
"text": "Step 2 β Runner Script Implementation to run tests"
},
{
"code": null,
"e": 77146,
"s": 77056,
"text": "The runner script can be implemented to run the tests by using the below mentioned code β"
},
{
"code": null,
"e": 77334,
"s": 77146,
"text": "import subprocess\nif __name__ == '__main__':\n#command line args along with error capture on failure with check true\n s = subprocess.run('behave --no-capture',shell=True, check=True)\n"
},
{
"code": null,
"e": 77369,
"s": 77334,
"text": "Step 3 β Execute the runner script"
},
{
"code": null,
"e": 77500,
"s": 77369,
"text": "Execute runner.py file with command python3 runner.py (if Python version is 3). The following screen will appear on your computer:"
},
{
"code": null,
"e": 77570,
"s": 77500,
"text": "Step 4 β Parametrise runner script by passing command line arguments."
},
{
"code": null,
"e": 77641,
"s": 77570,
"text": "The runner script implementation to run tests can be done as follows β"
},
{
"code": null,
"e": 77996,
"s": 77641,
"text": "import argparse\nimport subprocess\nif __name__ == '__main__':\n p = argparse.ArgumentParser()\n #--testdir command line argument added\n p.add_argument('--testdir', required=False, help=\"File path\")\n a = p.parse_args()\n testdir = a.testdir\n #complete command\n c= f'behave --no-capture {testdir}'\n s = subprocess.run(c, shell=True, check=True)\n"
},
{
"code": null,
"e": 78031,
"s": 77996,
"text": "Step 5 β Execute the runner script"
},
{
"code": null,
"e": 78105,
"s": 78031,
"text": "Execute runner.py file with command python3 runner.py --testdir=features."
},
{
"code": null,
"e": 78172,
"s": 78105,
"text": "We can exclude the executing files by its filename from execution."
},
{
"code": null,
"e": 78295,
"s": 78172,
"text": "Suppose, we have more than one feature file within the features folder. The following screen can be seen on the computer β"
},
{
"code": null,
"e": 78360,
"s": 78295,
"text": "On executing the command behave, the output will be as follows β"
},
{
"code": null,
"e": 78552,
"s": 78360,
"text": "If we have to only run the feature file Payment.feature and exclude Payment1.feature, we have to pass the command line argument --e or --exclude followed by pattern of the regular expression."
},
{
"code": null,
"e": 78633,
"s": 78552,
"text": "On executing the command behave --exclude *1.feature, the output is as follows β"
},
{
"code": null,
"e": 78762,
"s": 78633,
"text": "The output shows one feature passed along with the Payment.feature file name. Also, Payment1.feature is not included in the run."
},
{
"code": null,
"e": 78875,
"s": 78762,
"text": "We can rerun failed Scenarios in the feature file in Behave. This is taken care with the help of the formatters."
},
{
"code": null,
"e": 78957,
"s": 78875,
"text": "All the available formatters in Behave can be seen with the command given below β"
},
{
"code": null,
"e": 78973,
"s": 78957,
"text": "behave βf help\n"
},
{
"code": null,
"e": 79032,
"s": 78973,
"text": "You can see the following screen after using the command β"
},
{
"code": null,
"e": 79182,
"s": 79032,
"text": "The rerun formatter is used to capture the failing scenario and output it in a separate file. Let us take an example, where we have 1 failed feature."
},
{
"code": null,
"e": 79257,
"s": 79182,
"text": "Then capture the failed feature in another feature file with the command β"
},
{
"code": null,
"e": 79301,
"s": 79257,
"text": "behave βf rerun βo failed_features.feature\n"
},
{
"code": null,
"e": 79329,
"s": 79301,
"text": "You can see the following β"
},
{
"code": null,
"e": 79473,
"s": 79329,
"text": "The failed_features.feature file gets generated within the project. It contains the feature file name Payment1.feature where we have a failure."
},
{
"code": null,
"e": 79551,
"s": 79473,
"text": "To re-trigger only failed Scenario, we have to run the command stated below β"
},
{
"code": null,
"e": 79584,
"s": 79551,
"text": "behave @failed_features.feature\n"
},
{
"code": null,
"e": 79620,
"s": 79584,
"text": "You will see the following screen β"
},
{
"code": null,
"e": 79819,
"s": 79620,
"text": "Report generation is one of the most important steps towards the test automation framework. At the end of the execution, we cannot rely on the console output rather we should have a detailed report."
},
{
"code": null,
"e": 80078,
"s": 79819,
"text": "It should have the information on the count of tests that passed, failed, skipped, feature and scenario breakdown. Behave does not produce an in-built report but it can output in multiple formats and we can utilize the third-party tools to generate a report."
},
{
"code": null,
"e": 80150,
"s": 80078,
"text": "All the available formatters in Behave are displayed with the command β"
},
{
"code": null,
"e": 80172,
"s": 80150,
"text": "behave --format help\n"
},
{
"code": null,
"e": 80250,
"s": 80172,
"text": "When you use the command, the following screen will appear on your computer β"
},
{
"code": null,
"e": 80290,
"s": 80250,
"text": "Some of the common Behave reports are β"
},
{
"code": null,
"e": 80305,
"s": 80290,
"text": "Allure Report."
},
{
"code": null,
"e": 80320,
"s": 80305,
"text": "Allure Report."
},
{
"code": null,
"e": 80340,
"s": 80320,
"text": "Output JSON Report."
},
{
"code": null,
"e": 80360,
"s": 80340,
"text": "Output JSON Report."
},
{
"code": null,
"e": 80373,
"s": 80360,
"text": "JUnit Report"
},
{
"code": null,
"e": 80386,
"s": 80373,
"text": "JUnit Report"
},
{
"code": null,
"e": 80463,
"s": 80386,
"text": "Let us execute a test having two feature files with the below test results β"
},
{
"code": null,
"e": 80528,
"s": 80463,
"text": "Project folder structure for the above test will be as follows β"
},
{
"code": null,
"e": 80557,
"s": 80528,
"text": "Step 1 β Execute the command"
},
{
"code": null,
"e": 80613,
"s": 80557,
"text": "To create a JUnit report, run the command given below β"
},
{
"code": null,
"e": 80630,
"s": 80613,
"text": "behave --junit \n"
},
{
"code": null,
"e": 80664,
"s": 80630,
"text": "Step 2 β Report folder generation"
},
{
"code": null,
"e": 80777,
"s": 80664,
"text": "A folder called as the reports gets generated within the project, having the name TESTS-<feature file name>.xml."
},
{
"code": null,
"e": 80840,
"s": 80777,
"text": "Here, Payment and Payment1 are the names of the feature files."
},
{
"code": null,
"e": 80888,
"s": 80840,
"text": "Step 3 β Report generation to a specific folder"
},
{
"code": null,
"e": 80995,
"s": 80888,
"text": "To generate the reports to a specific folder, say my_reports. We have to run the below mentioned command β"
},
{
"code": null,
"e": 81040,
"s": 80995,
"text": "behave --junit --junit-directory my_reports\n"
},
{
"code": null,
"e": 81133,
"s": 81040,
"text": "A folder called the my_reports gets generated within the project which contains the reports."
},
{
"code": null,
"e": 81205,
"s": 81133,
"text": "We can create the Behave JSON report. The JSON is actually a formatter."
},
{
"code": null,
"e": 81282,
"s": 81205,
"text": "Let us execute a test having two feature files with the below test results β"
},
{
"code": null,
"e": 81342,
"s": 81282,
"text": "Project folder structure for the above test is as follows β"
},
{
"code": null,
"e": 81371,
"s": 81342,
"text": "Step 1 β Execute the command"
},
{
"code": null,
"e": 81425,
"s": 81371,
"text": "To create a JSON output in console, run the command β"
},
{
"code": null,
"e": 81441,
"s": 81425,
"text": "behave -f json\n"
},
{
"code": null,
"e": 81476,
"s": 81441,
"text": "The following screen will appear β"
},
{
"code": null,
"e": 81511,
"s": 81476,
"text": "Step 2 β Output in readable format"
},
{
"code": null,
"e": 81590,
"s": 81511,
"text": "To create a JSON output in a more readable format, run the following command β"
},
{
"code": null,
"e": 81613,
"s": 81590,
"text": "behave -f json.pretty\n"
},
{
"code": null,
"e": 81670,
"s": 81613,
"text": "Some portion of the output captured in the below image β"
},
{
"code": null,
"e": 81718,
"s": 81670,
"text": "Step 3 β Report generation to a specific folder"
},
{
"code": null,
"e": 81824,
"s": 81718,
"text": "To generate the reports to a specific folder say, my_reports.json, we have to run the following command β"
},
{
"code": null,
"e": 81866,
"s": 81824,
"text": "behave βf json.pretty βo my_reports.json\n"
},
{
"code": null,
"e": 81943,
"s": 81866,
"text": "The following image represents the screen that will appear on your computer."
},
{
"code": null,
"e": 82069,
"s": 81943,
"text": "A folder called the my_reports.json gets generated within the project, having details of all the features which are executed."
},
{
"code": null,
"e": 82252,
"s": 82069,
"text": "To generate Allure reports in Behave, first we have to install Allure in the system. For installation from the command line in Linux, run the following commands one after the other β"
},
{
"code": null,
"e": 82343,
"s": 82252,
"text": "sudo apt-add-repository ppa:qameta/allure\nsudo apt-get update\nsudo apt-get install allure\n"
},
{
"code": null,
"e": 82426,
"s": 82343,
"text": "For Mac users, installation is done with the Homebrew with the following command β"
},
{
"code": null,
"e": 82447,
"s": 82426,
"text": "brew install allure\n"
},
{
"code": null,
"e": 82602,
"s": 82447,
"text": "For Windows, Allure is installed from the Scoop installer. Run the below command to download and install Scoop and finally, execute it in the PowerShell β"
},
{
"code": null,
"e": 82624,
"s": 82602,
"text": "scoop install allure\n"
},
{
"code": null,
"e": 82745,
"s": 82624,
"text": "To update Allure distribution installations from Scoop, run the below command from the installation directory of Scoop β"
},
{
"code": null,
"e": 82774,
"s": 82745,
"text": "\\bin\\checkver.ps1 allure -u\n"
},
{
"code": null,
"e": 82813,
"s": 82774,
"text": "Finally, run the command given below β"
},
{
"code": null,
"e": 82834,
"s": 82813,
"text": "scoop update allure\n"
},
{
"code": null,
"e": 82969,
"s": 82834,
"text": "After Allure has been installed, we have to get the Allure-Behave integration plugin for Python. For this, run the following command β"
},
{
"code": null,
"e": 82996,
"s": 82969,
"text": "pip install allure-behave\n"
},
{
"code": null,
"e": 83080,
"s": 82996,
"text": "To verify if Allure has been installed successfully, run the command stated below β"
},
{
"code": null,
"e": 83088,
"s": 83080,
"text": "allure\n"
},
{
"code": null,
"e": 83165,
"s": 83088,
"text": "Let us execute a test having two feature files with the below test results β"
},
{
"code": null,
"e": 83225,
"s": 83165,
"text": "Project folder structure for the above test is as follows β"
},
{
"code": null,
"e": 83273,
"s": 83225,
"text": "Step 1 β Report generation to a specific folder"
},
{
"code": null,
"e": 83373,
"s": 83273,
"text": "To generate the reports to a specific folder, say my_allure, we have to run the following command β"
},
{
"code": null,
"e": 83437,
"s": 83373,
"text": "behave -f allure_behave.formatter:AllureFormatter βo my_allure\n"
},
{
"code": null,
"e": 83478,
"s": 83437,
"text": "You will get the screen as shown below β"
},
{
"code": null,
"e": 83578,
"s": 83478,
"text": "A folder called the my_allure gets generated within the project, having files with .json extension."
},
{
"code": null,
"e": 83608,
"s": 83578,
"text": "Step 2 β Start the web server"
},
{
"code": null,
"e": 83663,
"s": 83608,
"text": "To start the web server, run the command given below β"
},
{
"code": null,
"e": 83687,
"s": 83663,
"text": "allure serve my_allure\n"
},
{
"code": null,
"e": 83762,
"s": 83687,
"text": "Here, the my_allure is the directory which contains the allure json files."
},
{
"code": null,
"e": 83841,
"s": 83762,
"text": "Simultaneously, a browser gets opened, with the Allure report as shown below β"
},
{
"code": null,
"e": 83926,
"s": 83841,
"text": "We can also click on individual features and find their breakdowns, as shown below β"
},
{
"code": null,
"e": 84173,
"s": 83926,
"text": "Behave setup and teardown functions are implemented in a file called the environment.py which is within the same directory that contains the steps folder. The setup functions include β browser open, database connection, configurations, and so on."
},
{
"code": null,
"e": 84284,
"s": 84173,
"text": "The teardown functions include browser closure, database connection termination, reversing changes, and so on."
},
{
"code": null,
"e": 84343,
"s": 84284,
"text": "The environment.py file contains the following functions β"
},
{
"code": null,
"e": 84408,
"s": 84343,
"text": "before_feature(context, feature) β Executes prior every feature."
},
{
"code": null,
"e": 84473,
"s": 84408,
"text": "before_feature(context, feature) β Executes prior every feature."
},
{
"code": null,
"e": 84541,
"s": 84473,
"text": "before_scenario(context, scenario) β Executes prior every scenario."
},
{
"code": null,
"e": 84609,
"s": 84541,
"text": "before_scenario(context, scenario) β Executes prior every scenario."
},
{
"code": null,
"e": 84665,
"s": 84609,
"text": "before_step(context, step) β Executes prior every step."
},
{
"code": null,
"e": 84721,
"s": 84665,
"text": "before_step(context, step) β Executes prior every step."
},
{
"code": null,
"e": 84774,
"s": 84721,
"text": "before_tag(context, tag) β Executes prior every tag."
},
{
"code": null,
"e": 84827,
"s": 84774,
"text": "before_tag(context, tag) β Executes prior every tag."
},
{
"code": null,
"e": 84876,
"s": 84827,
"text": "before_all(context) β Executes prior everything."
},
{
"code": null,
"e": 84925,
"s": 84876,
"text": "before_all(context) β Executes prior everything."
},
{
"code": null,
"e": 84988,
"s": 84925,
"text": "after_feature(context, feature) β Executes post every feature."
},
{
"code": null,
"e": 85051,
"s": 84988,
"text": "after_feature(context, feature) β Executes post every feature."
},
{
"code": null,
"e": 85117,
"s": 85051,
"text": "after_scenario(context, scenario) β Executes post every scenario."
},
{
"code": null,
"e": 85183,
"s": 85117,
"text": "after_scenario(context, scenario) β Executes post every scenario."
},
{
"code": null,
"e": 85237,
"s": 85183,
"text": "after_step(context, step) β Executes post every step."
},
{
"code": null,
"e": 85291,
"s": 85237,
"text": "after_step(context, step) β Executes post every step."
},
{
"code": null,
"e": 85342,
"s": 85291,
"text": "after_tag(context, tag) β Executes post every tag."
},
{
"code": null,
"e": 85393,
"s": 85342,
"text": "after_tag(context, tag) β Executes post every tag."
},
{
"code": null,
"e": 85440,
"s": 85393,
"text": "after_all(context) β Executes post everything."
},
{
"code": null,
"e": 85487,
"s": 85440,
"text": "after_all(context) β Executes post everything."
},
{
"code": null,
"e": 85577,
"s": 85487,
"text": "The above functions are used as hooks in Behave. Project structure should be as follows β"
},
{
"code": null,
"e": 85619,
"s": 85577,
"text": "Feature File with hooks (Payment.feature)"
},
{
"code": null,
"e": 85683,
"s": 85619,
"text": "The feature file with hooks for Payment.feature is as follows β"
},
{
"code": null,
"e": 85826,
"s": 85683,
"text": "Feature β Payment Process\nScenario β Verify transactions\n Given user makes a payment of 100 INR And user makes a payment of 10 Dollar\n"
},
{
"code": null,
"e": 85869,
"s": 85826,
"text": "Feature File with hooks (Payment1.feature)"
},
{
"code": null,
"e": 85935,
"s": 85869,
"text": "Given below is the feature file with hooks for Payment1.feature β"
},
{
"code": null,
"e": 86045,
"s": 85935,
"text": "Feature β Administration Process\nScenario β Verify admin transactions\n Given user is on admin screen\n"
},
{
"code": null,
"e": 86084,
"s": 86045,
"text": "Corresponding step Implementation File"
},
{
"code": null,
"e": 86129,
"s": 86084,
"text": "The step implementation file is as follows β"
},
{
"code": null,
"e": 86511,
"s": 86129,
"text": "from behave import *\nfrom parse_type import TypeBuilder\nparse_amt = TypeBuilder.make_choice([\"100\", \"10\"])\nregister_type(Amt=parse_amt)\nparse_curr = TypeBuilder.make_choice([\"INR\", \"Dollar\"])\nregister_type(Curn=parse_curr)\n@given(\"user makes a payment of {n:Amt} {t:Curn}\")\ndef step_payment(context, n, t):\n pass\n@given('user is on admin screen')\ndef step_admin(context):\n pass"
},
{
"code": null,
"e": 86549,
"s": 86511,
"text": "Step 4 β Hooks in environment.py file"
},
{
"code": null,
"e": 86598,
"s": 86549,
"text": "The hooks in environment.py file are as follows:"
},
{
"code": null,
"e": 86931,
"s": 86598,
"text": "# before all\ndef before_all(context):\n print('Before all executed')\n# before every scenario\ndef before_scenario(scenario, context):\n print('Before scenario executed')\n# after every feature\ndef after_feature(scenario, context):\n print('After feature executed')\n# after all\ndef after_all(context):\n print('After all executed')"
},
{
"code": null,
"e": 86938,
"s": 86931,
"text": "Output"
},
{
"code": null,
"e": 87006,
"s": 86938,
"text": "The output obtained after running the feature files is as follows β"
},
{
"code": null,
"e": 87217,
"s": 87006,
"text": "Behave scripts can be debugged by dry running the test steps. The dry run helps to go over all the test steps without actually running it. It helps to determine the un-defined steps in the step definition file."
},
{
"code": null,
"e": 87472,
"s": 87217,
"text": "It verifies if there are any missing import statements, syntax errors, and so on. All these issues get detected in a quick time by dry run. If we are doing mass updates or any configuration changes, dry running helps to detect any errors in a short time."
},
{
"code": null,
"e": 87644,
"s": 87472,
"text": "If we would have to run an entire suite for debugging, that would be time consuming. In Behave, we can do a debug by dry run with the help of the below mentioned command β"
},
{
"code": null,
"e": 87675,
"s": 87644,
"text": "behave --no-capture --dry-run\n"
},
{
"code": null,
"e": 87716,
"s": 87675,
"text": "You will get the screen as shown below β"
},
{
"code": null,
"e": 87785,
"s": 87716,
"text": "The output shows 3 untested which shows the count of the test steps."
},
{
"code": null,
"e": 87859,
"s": 87785,
"text": "Let us dry run feature files having unimplemented steps, as shown below β"
},
{
"code": null,
"e": 87956,
"s": 87859,
"text": "The output clearly defines the un-defined steps in the step definition file obtained by dry run."
},
{
"code": null,
"e": 87963,
"s": 87956,
"text": " Print"
},
{
"code": null,
"e": 87974,
"s": 87963,
"text": " Add Notes"
}
] |
How to convert a MySQL date to JavaScript date?
|
To convert a MySQL date to JavaScript, use Date.parse.
You can try to run the following code to convert MySQL date to JavaScript date β
Live Demo
<!DOCTYPE html>
<html>
<body>
<script>
var MySQL_date = '2017-12-31 11:55:17';
document.write("MySQL Date: "+MySQL_date);
var jsDate = new Date(Date.parse(MySQL_date.replace(/[-]/g,'/')));
document.write("<br>JavaScript Date: "+jsDate);
</script>
</body>
</html>
MySQL Date: 2017-12-31 11:55:17
JavaScript Date: Sun Dec 31 2017 11:55:17 GMT+0530 (India Standard Time)
|
[
{
"code": null,
"e": 1117,
"s": 1062,
"text": "To convert a MySQL date to JavaScript, use Date.parse."
},
{
"code": null,
"e": 1198,
"s": 1117,
"text": "You can try to run the following code to convert MySQL date to JavaScript date β"
},
{
"code": null,
"e": 1208,
"s": 1198,
"text": "Live Demo"
},
{
"code": null,
"e": 1526,
"s": 1208,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <script>\n var MySQL_date = '2017-12-31 11:55:17';\n document.write(\"MySQL Date: \"+MySQL_date);\n\n var jsDate = new Date(Date.parse(MySQL_date.replace(/[-]/g,'/')));\n document.write(\"<br>JavaScript Date: \"+jsDate);\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 1631,
"s": 1526,
"text": "MySQL Date: 2017-12-31 11:55:17\nJavaScript Date: Sun Dec 31 2017 11:55:17 GMT+0530 (India Standard Time)"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.