title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
DynamoDB – Data Types | 01 Aug, 2020
DynamoDB supports many different data types for attributes within a table. They can be categorized as follows:
Scalar Types – A scalar type can represent exactly one value. The scalar types are number, string, binary, Boolean, and null.
Document Types – A document type can represent a complex structure with nested attributes, such as you would find in a JSON document. The document types are lists and maps.
Set Types – A set type can represent multiple scalar values. The set types are string set, number set, and binary set.
When you create a table or a secondary index, you must specify the names and data types of each primary key attribute (partition key and sort key). Furthermore, each primary key attribute must be defined as type string, number, or binary.
DynamoDB is a NoSQL database and is schemaless. This means that, other than the primary key attributes, you don’t have to define any attributes or data types when you create tables. By comparison, relational databases require you to define the names and data types of each column when you create a table.
The following are descriptions of each data type, along with examples in JSON format.
The scalar types are number, string, binary, Boolean, and null.
Number:
Numbers can be positive, negative, or zero. Numbers can have up to 38 digits of precision. Exceeding this results in an exception.
Positive range: 1E-130 to 9.9999999999999999999999999999999999999E+125
Negative range: -9.9999999999999999999999999999999999999E+125 to -1E-130
In DynamoDB, numbers are represented as variable length. Leading and trailing zeroes are trimmed.
All numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
Note: If number precision is required the numbers can be passed to DynamoDB as a string type which can be later converted into number type.
You can use the number data type to represent a date or a timestamp. One way to do this is by using epoch time ie, the number of seconds since 00:00:00 UTC on 1 January 1970.
String:
Strings are Unicode with UTF-8 binary encoding. The minimum length of a string can be zero, if the attribute is not used as a key for an index or table, and is constrained by the maximum DynamoDB item size limit of 400 KB.
The following additional constraints apply to primary key attributes that are defined as type string:
For a simple primary key, the maximum length of the first attribute value (the partition key) is 2048 bytes.
For a composite primary key, the maximum length of the second attribute value (the sort key) is 1024 bytes.
DynamoDB collates and compares strings using the bytes of the underlying UTF-8 string encoding. For example, “a” (0x61) is greater than “A” (0x41), and “¿” (0xC2BF) is greater than “z” (0x7A).
You can use the string data type to represent a date or a timestamp. One way to do this is by using ISO 8601 strings, as shown in these examples:
2020-06-12
2020-06-12T17:42:34Z
2020612T174234Z
Binary:
Binary type attributes can store any binary data, such as compressed text, encrypted data, or images. Whenever DynamoDB compares binary values, it treats each byte of the binary data as unsigned.
The length of a binary attribute can be zero, if the attribute is not used as a key for an index or table, and is constrained by the maximum DynamoDB item size limit of 400 KB.
If you define a primary key attribute as a binary type attribute, the following additional constraints apply:
For a simple primary key, the maximum length of the first attribute value (the partition key) is 2048 bytes.
For a composite primary key, the maximum length of the second attribute value (the sort key) is 1024 bytes.
Your applications must encode binary values in base64-encoded format before sending them to DynamoDB. Upon receipt of these values, DynamoDB decodes the data into an unsigned byte array and uses that as the length of the binary attribute.
The following example is a binary attribute, using base64-encoded text.
dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk
Boolean:
A Boolean type attribute can store either true or false.
Null:
Null represents an attribute with an unknown or undefined state.
The document types are list and map. These data types can be nested within each other, to represent complex data structures up to 32 levels deep.
There is no limit on the number of values in a list or a map, as long as the item containing the values fits within the DynamoDB item size limit (400 KB).
An attribute value can be an empty string or empty binary value if the attribute is not used for a table or index key. An attribute value cannot be an empty set (string set, number set, or binary set), however, empty lists and maps are allowed. Empty string and binary values are allowed within lists and maps.
List:
A list type attribute can store an ordered collection of values. Lists are enclosed in square brackets: [ ... ]
A list is similar to a JSON array. There are no restrictions on the data types that can be stored in a list element, and the elements in a list element do not have to be of the same type.
The following example shows a list that contains two strings and a number.
FavoriteStuff: ["Cola", "Coffee", 3.14159]
Map:
A map type attribute can store an unordered collection of name-value pairs. Maps are enclosed in curly braces: { ... }
A map is similar to a JSON object. There are no restrictions on the data types that can be stored in a map element, and the elements in a map do not have to be of the same type.
Maps are ideal for storing JSON documents in DynamoDB. The following example shows a map that contains a string, a number, and a nested list that contains another map.
{
Day: "Monday",
UnreadEmails: 42,
ItemsOnMyDesk: [
"Coffee Cup",
"Telephone",
{
Pens: { Quantity : 3},
Pencils: { Quantity : 2},
Erasers: { Quantity : 1}
}
]
}
DynamoDB supports types that represent sets of number, string, or binary values. All the elements within a set must be of the same type. For example, an attribute of type Number Set can only contain numbers; String sets can only contain strings; and so on.
There is no limit on the number of values in a set, as long as the item containing the values fits within the DynamoDB item size limit (400 KB).
Each value within a set must be unique. The order of the values within a set is not preserved. Therefore, your applications must not rely on any particular order of elements within the set. DynamoDB does not support empty sets, however, empty string and binary values are allowed within a set.
The following example shows a string set, a number set, and a binary set:
["Black", "Green", "Red"]
[42.2, -19, 7.5, 3.14]
["U3Vubnk=", "UmFpbnk=", "U25vd3k="]
DynamoDB-Basics
DynamoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 140,
"s": 28,
"text": " DynamoDB supports many different data types for attributes within a table. They can be categorized as follows:"
},
{
"code": null,
"e": 266,
"s": 140,
"text": "Scalar Types – A scalar type can represent exactly one value. The scalar types are number, string, binary, Boolean, and null."
},
{
"code": null,
"e": 439,
"s": 266,
"text": "Document Types – A document type can represent a complex structure with nested attributes, such as you would find in a JSON document. The document types are lists and maps."
},
{
"code": null,
"e": 558,
"s": 439,
"text": "Set Types – A set type can represent multiple scalar values. The set types are string set, number set, and binary set."
},
{
"code": null,
"e": 797,
"s": 558,
"text": "When you create a table or a secondary index, you must specify the names and data types of each primary key attribute (partition key and sort key). Furthermore, each primary key attribute must be defined as type string, number, or binary."
},
{
"code": null,
"e": 1102,
"s": 797,
"text": "DynamoDB is a NoSQL database and is schemaless. This means that, other than the primary key attributes, you don’t have to define any attributes or data types when you create tables. By comparison, relational databases require you to define the names and data types of each column when you create a table."
},
{
"code": null,
"e": 1188,
"s": 1102,
"text": "The following are descriptions of each data type, along with examples in JSON format."
},
{
"code": null,
"e": 1252,
"s": 1188,
"text": "The scalar types are number, string, binary, Boolean, and null."
},
{
"code": null,
"e": 1260,
"s": 1252,
"text": "Number:"
},
{
"code": null,
"e": 1391,
"s": 1260,
"text": "Numbers can be positive, negative, or zero. Numbers can have up to 38 digits of precision. Exceeding this results in an exception."
},
{
"code": null,
"e": 1462,
"s": 1391,
"text": "Positive range: 1E-130 to 9.9999999999999999999999999999999999999E+125"
},
{
"code": null,
"e": 1535,
"s": 1462,
"text": "Negative range: -9.9999999999999999999999999999999999999E+125 to -1E-130"
},
{
"code": null,
"e": 1633,
"s": 1535,
"text": "In DynamoDB, numbers are represented as variable length. Leading and trailing zeroes are trimmed."
},
{
"code": null,
"e": 1840,
"s": 1633,
"text": "All numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations."
},
{
"code": null,
"e": 1980,
"s": 1840,
"text": "Note: If number precision is required the numbers can be passed to DynamoDB as a string type which can be later converted into number type."
},
{
"code": null,
"e": 2156,
"s": 1980,
"text": "You can use the number data type to represent a date or a timestamp. One way to do this is by using epoch time ie, the number of seconds since 00:00:00 UTC on 1 January 1970. "
},
{
"code": null,
"e": 2164,
"s": 2156,
"text": "String:"
},
{
"code": null,
"e": 2387,
"s": 2164,
"text": "Strings are Unicode with UTF-8 binary encoding. The minimum length of a string can be zero, if the attribute is not used as a key for an index or table, and is constrained by the maximum DynamoDB item size limit of 400 KB."
},
{
"code": null,
"e": 2489,
"s": 2387,
"text": "The following additional constraints apply to primary key attributes that are defined as type string:"
},
{
"code": null,
"e": 2598,
"s": 2489,
"text": "For a simple primary key, the maximum length of the first attribute value (the partition key) is 2048 bytes."
},
{
"code": null,
"e": 2706,
"s": 2598,
"text": "For a composite primary key, the maximum length of the second attribute value (the sort key) is 1024 bytes."
},
{
"code": null,
"e": 2899,
"s": 2706,
"text": "DynamoDB collates and compares strings using the bytes of the underlying UTF-8 string encoding. For example, “a” (0x61) is greater than “A” (0x41), and “¿” (0xC2BF) is greater than “z” (0x7A)."
},
{
"code": null,
"e": 3045,
"s": 2899,
"text": "You can use the string data type to represent a date or a timestamp. One way to do this is by using ISO 8601 strings, as shown in these examples:"
},
{
"code": null,
"e": 3056,
"s": 3045,
"text": "2020-06-12"
},
{
"code": null,
"e": 3077,
"s": 3056,
"text": "2020-06-12T17:42:34Z"
},
{
"code": null,
"e": 3093,
"s": 3077,
"text": "2020612T174234Z"
},
{
"code": null,
"e": 3101,
"s": 3093,
"text": "Binary:"
},
{
"code": null,
"e": 3297,
"s": 3101,
"text": "Binary type attributes can store any binary data, such as compressed text, encrypted data, or images. Whenever DynamoDB compares binary values, it treats each byte of the binary data as unsigned."
},
{
"code": null,
"e": 3474,
"s": 3297,
"text": "The length of a binary attribute can be zero, if the attribute is not used as a key for an index or table, and is constrained by the maximum DynamoDB item size limit of 400 KB."
},
{
"code": null,
"e": 3584,
"s": 3474,
"text": "If you define a primary key attribute as a binary type attribute, the following additional constraints apply:"
},
{
"code": null,
"e": 3693,
"s": 3584,
"text": "For a simple primary key, the maximum length of the first attribute value (the partition key) is 2048 bytes."
},
{
"code": null,
"e": 3801,
"s": 3693,
"text": "For a composite primary key, the maximum length of the second attribute value (the sort key) is 1024 bytes."
},
{
"code": null,
"e": 4040,
"s": 3801,
"text": "Your applications must encode binary values in base64-encoded format before sending them to DynamoDB. Upon receipt of these values, DynamoDB decodes the data into an unsigned byte array and uses that as the length of the binary attribute."
},
{
"code": null,
"e": 4112,
"s": 4040,
"text": "The following example is a binary attribute, using base64-encoded text."
},
{
"code": null,
"e": 4173,
"s": 4112,
"text": "dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk\n \n"
},
{
"code": null,
"e": 4182,
"s": 4173,
"text": "Boolean:"
},
{
"code": null,
"e": 4239,
"s": 4182,
"text": "A Boolean type attribute can store either true or false."
},
{
"code": null,
"e": 4245,
"s": 4239,
"text": "Null:"
},
{
"code": null,
"e": 4310,
"s": 4245,
"text": "Null represents an attribute with an unknown or undefined state."
},
{
"code": null,
"e": 4456,
"s": 4310,
"text": "The document types are list and map. These data types can be nested within each other, to represent complex data structures up to 32 levels deep."
},
{
"code": null,
"e": 4611,
"s": 4456,
"text": "There is no limit on the number of values in a list or a map, as long as the item containing the values fits within the DynamoDB item size limit (400 KB)."
},
{
"code": null,
"e": 4922,
"s": 4611,
"text": "An attribute value can be an empty string or empty binary value if the attribute is not used for a table or index key. An attribute value cannot be an empty set (string set, number set, or binary set), however, empty lists and maps are allowed. Empty string and binary values are allowed within lists and maps."
},
{
"code": null,
"e": 4928,
"s": 4922,
"text": "List:"
},
{
"code": null,
"e": 5040,
"s": 4928,
"text": "A list type attribute can store an ordered collection of values. Lists are enclosed in square brackets: [ ... ]"
},
{
"code": null,
"e": 5228,
"s": 5040,
"text": "A list is similar to a JSON array. There are no restrictions on the data types that can be stored in a list element, and the elements in a list element do not have to be of the same type."
},
{
"code": null,
"e": 5303,
"s": 5228,
"text": "The following example shows a list that contains two strings and a number."
},
{
"code": null,
"e": 5368,
"s": 5303,
"text": "FavoriteStuff: [\"Cola\", \"Coffee\", 3.14159]\n \n"
},
{
"code": null,
"e": 5373,
"s": 5368,
"text": "Map:"
},
{
"code": null,
"e": 5492,
"s": 5373,
"text": "A map type attribute can store an unordered collection of name-value pairs. Maps are enclosed in curly braces: { ... }"
},
{
"code": null,
"e": 5670,
"s": 5492,
"text": "A map is similar to a JSON object. There are no restrictions on the data types that can be stored in a map element, and the elements in a map do not have to be of the same type."
},
{
"code": null,
"e": 5838,
"s": 5670,
"text": "Maps are ideal for storing JSON documents in DynamoDB. The following example shows a map that contains a string, a number, and a nested list that contains another map."
},
{
"code": null,
"e": 6104,
"s": 5838,
"text": "{\n Day: \"Monday\",\n UnreadEmails: 42,\n ItemsOnMyDesk: [\n \"Coffee Cup\",\n \"Telephone\",\n {\n Pens: { Quantity : 3},\n Pencils: { Quantity : 2},\n Erasers: { Quantity : 1}\n }\n ]\n}\n \n"
},
{
"code": null,
"e": 6361,
"s": 6104,
"text": "DynamoDB supports types that represent sets of number, string, or binary values. All the elements within a set must be of the same type. For example, an attribute of type Number Set can only contain numbers; String sets can only contain strings; and so on."
},
{
"code": null,
"e": 6506,
"s": 6361,
"text": "There is no limit on the number of values in a set, as long as the item containing the values fits within the DynamoDB item size limit (400 KB)."
},
{
"code": null,
"e": 6800,
"s": 6506,
"text": "Each value within a set must be unique. The order of the values within a set is not preserved. Therefore, your applications must not rely on any particular order of elements within the set. DynamoDB does not support empty sets, however, empty string and binary values are allowed within a set."
},
{
"code": null,
"e": 6874,
"s": 6800,
"text": "The following example shows a string set, a number set, and a binary set:"
},
{
"code": null,
"e": 6964,
"s": 6874,
"text": "[\"Black\", \"Green\", \"Red\"]\n\n[42.2, -19, 7.5, 3.14]\n\n[\"U3Vubnk=\", \"UmFpbnk=\", \"U25vd3k=\"] \n"
},
{
"code": null,
"e": 6980,
"s": 6964,
"text": "DynamoDB-Basics"
},
{
"code": null,
"e": 6989,
"s": 6980,
"text": "DynamoDB"
}
] |
Node.js urlSearchParams.get() Method | 07 Oct, 2021
The urlSearchParams.get() method is an inbuilt application programming interface of class URLSearchParams within url module which is used to get the value for particular name entry present in the URL search params object.
Syntax:
const urlSearchParams.get( name )
Parameter: This method takes the name as a parameter.
Return value: This method returns the value for particular name entry present in the url search params object.
Below programs illustrates the use of urlSearchParams.get() method in Node.js:
Example 1: Filename: app.js
// Node.js program to demonstrate the // URLSearchParams.get() method // Importing the module 'url'const http = require('url'); // Creating and initializing // URLSearchParams objectconst params = new URLSearchParams(); // Appending value in the objectparams.append('A', 'Book');params.append('B', 'Pen');params.append('C', 'Pencile'); // Getting the value for entry 'A'// by using get() apiconst value = params.get('A'); // Display the resultconsole.log("value for A is " + value);
Run app.js file using the following command:
node app.js
Output:
value for A is Book
Example 2: Filename: app.js
// Node.js program to demonstrate the // URLSearchParams.get() method // Importing the module 'url'const http = require('url'); // Creating and initializing// URLSearchParams objectconst params = new URLSearchParams(); // Appending value in the objectparams.append('A', 'Book');params.append('B', 'Pen');params.append('C', 'Pencile'); // Getting the value for entry 'A'// by using get() apiconst value = params.get('a'); // Display the resultconsole.log("value for a is " + value);
Run app.js file using the following command:
node app.js
Output:
value for a is null
Reference: https://nodejs.org/dist/latest-v14.x/docs/api/url.html#url_urlsearchparams_get_name
Node-URL
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Node.js and React.js
JWT Authentication with Node.js
How to connect Node.js with React.js ?
Node.js fs.existsSync() Method
Express.js express.urlencoded() Function
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to create footer to stay at the bottom of a Web page?
How to set the default value for an HTML <select> element ?
How do you run JavaScript script through the Terminal? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 250,
"s": 28,
"text": "The urlSearchParams.get() method is an inbuilt application programming interface of class URLSearchParams within url module which is used to get the value for particular name entry present in the URL search params object."
},
{
"code": null,
"e": 258,
"s": 250,
"text": "Syntax:"
},
{
"code": null,
"e": 292,
"s": 258,
"text": "const urlSearchParams.get( name )"
},
{
"code": null,
"e": 346,
"s": 292,
"text": "Parameter: This method takes the name as a parameter."
},
{
"code": null,
"e": 457,
"s": 346,
"text": "Return value: This method returns the value for particular name entry present in the url search params object."
},
{
"code": null,
"e": 536,
"s": 457,
"text": "Below programs illustrates the use of urlSearchParams.get() method in Node.js:"
},
{
"code": null,
"e": 564,
"s": 536,
"text": "Example 1: Filename: app.js"
},
{
"code": "// Node.js program to demonstrate the // URLSearchParams.get() method // Importing the module 'url'const http = require('url'); // Creating and initializing // URLSearchParams objectconst params = new URLSearchParams(); // Appending value in the objectparams.append('A', 'Book');params.append('B', 'Pen');params.append('C', 'Pencile'); // Getting the value for entry 'A'// by using get() apiconst value = params.get('A'); // Display the resultconsole.log(\"value for A is \" + value);",
"e": 1053,
"s": 564,
"text": null
},
{
"code": null,
"e": 1098,
"s": 1053,
"text": "Run app.js file using the following command:"
},
{
"code": null,
"e": 1110,
"s": 1098,
"text": "node app.js"
},
{
"code": null,
"e": 1118,
"s": 1110,
"text": "Output:"
},
{
"code": null,
"e": 1139,
"s": 1118,
"text": "value for A is Book\n"
},
{
"code": null,
"e": 1167,
"s": 1139,
"text": "Example 2: Filename: app.js"
},
{
"code": "// Node.js program to demonstrate the // URLSearchParams.get() method // Importing the module 'url'const http = require('url'); // Creating and initializing// URLSearchParams objectconst params = new URLSearchParams(); // Appending value in the objectparams.append('A', 'Book');params.append('B', 'Pen');params.append('C', 'Pencile'); // Getting the value for entry 'A'// by using get() apiconst value = params.get('a'); // Display the resultconsole.log(\"value for a is \" + value);",
"e": 1656,
"s": 1167,
"text": null
},
{
"code": null,
"e": 1701,
"s": 1656,
"text": "Run app.js file using the following command:"
},
{
"code": null,
"e": 1713,
"s": 1701,
"text": "node app.js"
},
{
"code": null,
"e": 1721,
"s": 1713,
"text": "Output:"
},
{
"code": null,
"e": 1742,
"s": 1721,
"text": "value for a is null\n"
},
{
"code": null,
"e": 1837,
"s": 1742,
"text": "Reference: https://nodejs.org/dist/latest-v14.x/docs/api/url.html#url_urlsearchparams_get_name"
},
{
"code": null,
"e": 1846,
"s": 1837,
"text": "Node-URL"
},
{
"code": null,
"e": 1854,
"s": 1846,
"text": "Node.js"
},
{
"code": null,
"e": 1871,
"s": 1854,
"text": "Web Technologies"
},
{
"code": null,
"e": 1969,
"s": 1871,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2009,
"s": 1969,
"text": "Difference between Node.js and React.js"
},
{
"code": null,
"e": 2041,
"s": 2009,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 2080,
"s": 2041,
"text": "How to connect Node.js with React.js ?"
},
{
"code": null,
"e": 2111,
"s": 2080,
"text": "Node.js fs.existsSync() Method"
},
{
"code": null,
"e": 2152,
"s": 2111,
"text": "Express.js express.urlencoded() Function"
},
{
"code": null,
"e": 2202,
"s": 2152,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2264,
"s": 2202,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2322,
"s": 2264,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 2382,
"s": 2322,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
Structure and Members of the Java Program | 20 Aug, 2021
When we are writing any program in any language we need to follow a standard structure for writing the program which is recommended by the language experts. A java program may contain many classes of which only one class will have a main method. Class will contain data members and methods that operate on the data members of the class. To write a Java program, we first need to define classes and then put them together. Generally a standard java program consists of following blocks as shown in below figure.
Explanation: 1. Package is a collection of classes, interfaces and sub packages. In a java program if we are using any pre-defined classes and interfaces then it is the responsibility of the java programmer to import that particular package containing such specific classes and interface. In java by default java.lang.* package is imported by every program. 2. Class is a keyword used for developing user defined data types. Every java program must starts with a prototype of class. The class has been declared public, means all classes can access the class from all packages. Generally, however, we will declare classes in java without specifying a modifier. 3. Class name is the name given to that class. Every class name is treated as one kind of user defined data type. 4. Data Members represents either instance members or static members. 5. Constructor function is called when an object of the class is created. It is a block of code that initializes the newly created object. The constructor simply has the same name as the name of the class name. A constructor does not have a return type. A constructor is called automatically when a new instance of an object is created. In the following code, the constructor bird() prints a message.
When we create the object of the bird class as shown above: bird b = new bird(); The new keyword here creates the object of class bird and invokes the constructor to initialize this newly created object. Constructor and method are different because the constructor is used to initialize the object of a class while the method is used to perform a task by implementing java code. Constructors cannot be declared as abstract, final, static and synchronized while methods can be declared. Constructors do not have return types while methods do. 6. User-defined methods represent either instance (or) static and they will be selected depends on the class name and these methods are used for performing the operations either once (or) repeatedly. All the user-defined methods of a class contain logic for a specific problem. These methods are known as Business logic methods. 7. All java program starts its execution with main() method so main() method is known as the backbone of the program. The Java Virtual Machine starts running any java program by executing main() method first. 8. Java’s main() method is not returning any value so its return type must be void. 9. Also main() method executes only once throughout the life of the Java program and before the object creation so its nature must be static. 10. The main() method is accessed in all the java programs, its access specifier must be public (universal). 11. Each and every main() method of java must take an array of objects of String class as an argument. 12. The block of statements are set of executable statements written for calling user-defined methods of the class. 13. If we have multiple java files then the naming convention of class file in java is that, whichever class is containing main() method, that class name will be given as the file name with an extension (dot) .java. Types of Data Members: Java Class is a collection of data members and functions. Any java program may contain two types of data members. They are; 1. Instance or non-static data members 2. Static or class data members The following table describes the difference between the two.
Types of Methods: In java program generally we may define two types of methods apart from constructor. They are; 1. Instance or non –static methods 2. Static or class methods The following table describes the difference between the two.
The following example named TestGVP.java demonstrates the use of different members of the java class.
Java
// Java code to show structures and// members of Java Programpublic class classMember{ // Static memberstatic int staticNum = 0; // Instance memberint instanceNum; /* below constructor increments the staticnumber and initialize instance number */public classMember(int i) //Constructor method{ instanceNum = i; staticNum++;} /* The show method display the value in the staticNum and instanceNum */public void show() //instance method{ System.out.println("Value of Static Number is:" + staticNum + "\nValue of Instance number is:"+ instanceNum);} // To find cubepublic static int cube() //Static method{ return staticNum * staticNum * staticNum;} // Driver codepublic static void main(String args[]){ classMember gvp1 = new classMember(2); System.out.println("Value after gvp1 object creation: "); gvp1.show(); classMember gvp2 = new classMember(4); System.out.println("Value after gvp2 object creation: "); gvp2.show(); // static method can be accessed by class name int cub=classMember.cube(); System.out.println("Cube of the Static number is: "+ cub);}}
Output :
VinodDesai
simranarora5sos
java-basics
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate any Map in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
Stack Class in Java
Initialize an ArrayList in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n20 Aug, 2021"
},
{
"code": null,
"e": 563,
"s": 52,
"text": "When we are writing any program in any language we need to follow a standard structure for writing the program which is recommended by the language experts. A java program may contain many classes of which only one class will have a main method. Class will contain data members and methods that operate on the data members of the class. To write a Java program, we first need to define classes and then put them together. Generally a standard java program consists of following blocks as shown in below figure."
},
{
"code": null,
"e": 1809,
"s": 563,
"text": "Explanation: 1. Package is a collection of classes, interfaces and sub packages. In a java program if we are using any pre-defined classes and interfaces then it is the responsibility of the java programmer to import that particular package containing such specific classes and interface. In java by default java.lang.* package is imported by every program. 2. Class is a keyword used for developing user defined data types. Every java program must starts with a prototype of class. The class has been declared public, means all classes can access the class from all packages. Generally, however, we will declare classes in java without specifying a modifier. 3. Class name is the name given to that class. Every class name is treated as one kind of user defined data type. 4. Data Members represents either instance members or static members. 5. Constructor function is called when an object of the class is created. It is a block of code that initializes the newly created object. The constructor simply has the same name as the name of the class name. A constructor does not have a return type. A constructor is called automatically when a new instance of an object is created. In the following code, the constructor bird() prints a message. "
},
{
"code": null,
"e": 3940,
"s": 1809,
"text": "When we create the object of the bird class as shown above: bird b = new bird(); The new keyword here creates the object of class bird and invokes the constructor to initialize this newly created object. Constructor and method are different because the constructor is used to initialize the object of a class while the method is used to perform a task by implementing java code. Constructors cannot be declared as abstract, final, static and synchronized while methods can be declared. Constructors do not have return types while methods do. 6. User-defined methods represent either instance (or) static and they will be selected depends on the class name and these methods are used for performing the operations either once (or) repeatedly. All the user-defined methods of a class contain logic for a specific problem. These methods are known as Business logic methods. 7. All java program starts its execution with main() method so main() method is known as the backbone of the program. The Java Virtual Machine starts running any java program by executing main() method first. 8. Java’s main() method is not returning any value so its return type must be void. 9. Also main() method executes only once throughout the life of the Java program and before the object creation so its nature must be static. 10. The main() method is accessed in all the java programs, its access specifier must be public (universal). 11. Each and every main() method of java must take an array of objects of String class as an argument. 12. The block of statements are set of executable statements written for calling user-defined methods of the class. 13. If we have multiple java files then the naming convention of class file in java is that, whichever class is containing main() method, that class name will be given as the file name with an extension (dot) .java. Types of Data Members: Java Class is a collection of data members and functions. Any java program may contain two types of data members. They are; 1. Instance or non-static data members 2. Static or class data members The following table describes the difference between the two. "
},
{
"code": null,
"e": 4178,
"s": 3940,
"text": "Types of Methods: In java program generally we may define two types of methods apart from constructor. They are; 1. Instance or non –static methods 2. Static or class methods The following table describes the difference between the two. "
},
{
"code": null,
"e": 4281,
"s": 4178,
"text": "The following example named TestGVP.java demonstrates the use of different members of the java class. "
},
{
"code": null,
"e": 4286,
"s": 4281,
"text": "Java"
},
{
"code": "// Java code to show structures and// members of Java Programpublic class classMember{ // Static memberstatic int staticNum = 0; // Instance memberint instanceNum; /* below constructor increments the staticnumber and initialize instance number */public classMember(int i) //Constructor method{ instanceNum = i; staticNum++;} /* The show method display the value in the staticNum and instanceNum */public void show() //instance method{ System.out.println(\"Value of Static Number is:\" + staticNum + \"\\nValue of Instance number is:\"+ instanceNum);} // To find cubepublic static int cube() //Static method{ return staticNum * staticNum * staticNum;} // Driver codepublic static void main(String args[]){ classMember gvp1 = new classMember(2); System.out.println(\"Value after gvp1 object creation: \"); gvp1.show(); classMember gvp2 = new classMember(4); System.out.println(\"Value after gvp2 object creation: \"); gvp2.show(); // static method can be accessed by class name int cub=classMember.cube(); System.out.println(\"Cube of the Static number is: \"+ cub);}}",
"e": 5414,
"s": 4286,
"text": null
},
{
"code": null,
"e": 5423,
"s": 5414,
"text": "Output :"
},
{
"code": null,
"e": 5434,
"s": 5423,
"text": "VinodDesai"
},
{
"code": null,
"e": 5450,
"s": 5434,
"text": "simranarora5sos"
},
{
"code": null,
"e": 5462,
"s": 5450,
"text": "java-basics"
},
{
"code": null,
"e": 5467,
"s": 5462,
"text": "Java"
},
{
"code": null,
"e": 5472,
"s": 5467,
"text": "Java"
},
{
"code": null,
"e": 5570,
"s": 5472,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5601,
"s": 5570,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 5631,
"s": 5601,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 5649,
"s": 5631,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 5669,
"s": 5649,
"text": "Collections in Java"
},
{
"code": null,
"e": 5684,
"s": 5669,
"text": "Stream In Java"
},
{
"code": null,
"e": 5716,
"s": 5684,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 5740,
"s": 5716,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 5752,
"s": 5740,
"text": "Set in Java"
},
{
"code": null,
"e": 5772,
"s": 5752,
"text": "Stack Class in Java"
}
] |
Authentication using Python requests | 05 Mar, 2020
Authentication refers to giving a user permissions to access a particular resource. Since, everyone can’t be allowed to access data from every URL, one would require authentication primarily. To achieve this authentication, typically one provides authentication data through Authorization header or a custom header defined by server.
Example –
# import requests moduleimport requestsfrom requests.auth import HTTPBasicAuth # Making a get requestresponse = requests.get('https://api.github.com / user, ', auth = HTTPBasicAuth('user', 'pass')) # print request objectprint(response)
Replace “user” and “pass” with your username and password. It will authenticate the request and return a response 200 or else it will return error 403.If you an invalid username or password, it will return an error as –
Digest AuthenticationAnother very popular form of HTTP Authentication is Digest Authentication, and Requests supports this out of the box as well:
>>> from requests.auth import HTTPDigestAuth
>>> url = 'https://httpbin.org/digest-auth/auth/user/pass'
>>> requests.get(url, auth=HTTPDigestAuth('user', 'pass'))
OAuth 1 AuthenticationA common form of authentication for several web APIs is OAuth. The requests-oauthlib library allows Requests users to easily make OAuth 1 authenticated requests:
>>> import requests
>>> from requests_oauthlib import OAuth1
>>> url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
>>> auth = OAuth1('YOUR_APP_KEY', 'YOUR_APP_SECRET',
... 'USER_OAUTH_TOKEN', 'USER_OAUTH_TOKEN_SECRET')
>>> requests.get(url, auth=auth)
For more information on how to OAuth flow works, please see the official OAuth website. For examples and documentation on requests-oauthlib, please see the requests_oauthlib repository on GitHub
OAuth 2 and OpenID Connect AuthenticationThe requests-oauthlib library also handles OAuth 2, the authentication mechanism underpinning OpenID Connect. See the requests-oauthlib OAuth2 documentation for details of the various OAuth 2 credential management flows:
Web Application Flow
Mobile Application Flow
Legacy Application Flow
Backend Application Flow
Other AuthenticationRequests is designed to allow other forms of authentication to be easily and quickly plugged in. Members of the open-source community frequently write authentication handlers for more complicated or less commonly-used forms of authentication. Some of the best have been brought together under the Requests organization, including:
Kerberos
NTLM.
If you want to use any of these forms of authentication, go straight to their GitHub page and follow the instructions.
Python-requests
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
How to drop one or multiple columns in Pandas Dataframe | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n05 Mar, 2020"
},
{
"code": null,
"e": 388,
"s": 54,
"text": "Authentication refers to giving a user permissions to access a particular resource. Since, everyone can’t be allowed to access data from every URL, one would require authentication primarily. To achieve this authentication, typically one provides authentication data through Authorization header or a custom header defined by server."
},
{
"code": null,
"e": 398,
"s": 388,
"text": "Example –"
},
{
"code": "# import requests moduleimport requestsfrom requests.auth import HTTPBasicAuth # Making a get requestresponse = requests.get('https://api.github.com / user, ', auth = HTTPBasicAuth('user', 'pass')) # print request objectprint(response)",
"e": 647,
"s": 398,
"text": null
},
{
"code": null,
"e": 867,
"s": 647,
"text": "Replace “user” and “pass” with your username and password. It will authenticate the request and return a response 200 or else it will return error 403.If you an invalid username or password, it will return an error as –"
},
{
"code": null,
"e": 1014,
"s": 867,
"text": "Digest AuthenticationAnother very popular form of HTTP Authentication is Digest Authentication, and Requests supports this out of the box as well:"
},
{
"code": null,
"e": 1178,
"s": 1014,
"text": ">>> from requests.auth import HTTPDigestAuth\n>>> url = 'https://httpbin.org/digest-auth/auth/user/pass'\n>>> requests.get(url, auth=HTTPDigestAuth('user', 'pass'))\n"
},
{
"code": null,
"e": 1362,
"s": 1178,
"text": "OAuth 1 AuthenticationA common form of authentication for several web APIs is OAuth. The requests-oauthlib library allows Requests users to easily make OAuth 1 authenticated requests:"
},
{
"code": null,
"e": 1649,
"s": 1362,
"text": ">>> import requests\n>>> from requests_oauthlib import OAuth1\n\n>>> url = 'https://api.twitter.com/1.1/account/verify_credentials.json'\n>>> auth = OAuth1('YOUR_APP_KEY', 'YOUR_APP_SECRET',\n... 'USER_OAUTH_TOKEN', 'USER_OAUTH_TOKEN_SECRET')\n\n>>> requests.get(url, auth=auth)\n"
},
{
"code": null,
"e": 1844,
"s": 1649,
"text": "For more information on how to OAuth flow works, please see the official OAuth website. For examples and documentation on requests-oauthlib, please see the requests_oauthlib repository on GitHub"
},
{
"code": null,
"e": 2106,
"s": 1844,
"text": "OAuth 2 and OpenID Connect AuthenticationThe requests-oauthlib library also handles OAuth 2, the authentication mechanism underpinning OpenID Connect. See the requests-oauthlib OAuth2 documentation for details of the various OAuth 2 credential management flows:"
},
{
"code": null,
"e": 2127,
"s": 2106,
"text": "Web Application Flow"
},
{
"code": null,
"e": 2151,
"s": 2127,
"text": "Mobile Application Flow"
},
{
"code": null,
"e": 2175,
"s": 2151,
"text": "Legacy Application Flow"
},
{
"code": null,
"e": 2200,
"s": 2175,
"text": "Backend Application Flow"
},
{
"code": null,
"e": 2551,
"s": 2200,
"text": "Other AuthenticationRequests is designed to allow other forms of authentication to be easily and quickly plugged in. Members of the open-source community frequently write authentication handlers for more complicated or less commonly-used forms of authentication. Some of the best have been brought together under the Requests organization, including:"
},
{
"code": null,
"e": 2560,
"s": 2551,
"text": "Kerberos"
},
{
"code": null,
"e": 2566,
"s": 2560,
"text": "NTLM."
},
{
"code": null,
"e": 2685,
"s": 2566,
"text": "If you want to use any of these forms of authentication, go straight to their GitHub page and follow the instructions."
},
{
"code": null,
"e": 2701,
"s": 2685,
"text": "Python-requests"
},
{
"code": null,
"e": 2708,
"s": 2701,
"text": "Python"
},
{
"code": null,
"e": 2806,
"s": 2708,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2848,
"s": 2806,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2870,
"s": 2848,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2896,
"s": 2870,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2928,
"s": 2896,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2957,
"s": 2928,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2984,
"s": 2957,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3005,
"s": 2984,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3028,
"s": 3005,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3064,
"s": 3028,
"text": "Convert integer to string in Python"
}
] |
JavaScript | Window print() Method | 22 Nov, 2021
Page print in JavaScript is a simple code in JavaScript used to print the content of the web pages.
The print() method prints the contents of the current window.
It basically opens Print dialog box which lets you choose between various printing options.
Syntax:
window.print()
Parameters: No parameters required Returns: This function do not return anythingThe following Javascript code shows a print button and then it shows the property of that webpage in a sheet in which you are going to print it. The JavaScript print function window.print() is used here to perform the functionality. Example :
HTML
<!DOCTYPE html><html> <head> <title> HTML | DOM Window Print() method </title> <script type="text/javascript"> </script> </head> <body> <h2>HI GEEKSFORGEEKS USER'S</h2> <form> <input type="button" value="Print" onclick="window.print()" /> </form> </body><html>
Output :
But the web pages are not limited to text only. There are other things too in the webpages like images consisting of different colors, etc. Printing such pages can be done by the following ways :
Make a copy of the page and leave out unwanted text and graphics, then link that to the printer-friendly page from the original. This means that the whole page will be printed as you have seen the page it will be printed as it is without any change in it, if you will see an advertisement it will also be printed in it
If you do not want to keep an extra copy of a page, then you can mark your printable text using proper comments like PRINT STARTS HERE ..... PRINT ENDS HERE and then you can use PERL or any other script in the background to purge printable text and display for final printing. This means that the selected portion will be printed
Supported Browser: The browser supported by Window print() Method are listed below:
Google Chrome 1 and above
Internet Explorer 5 and above
Firefox 1 and above
Opera 6 and above
Safari 1.1 and above
ysachin2314
javascript-functions
JavaScript-Misc
Web technologies
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 130,
"s": 28,
"text": "Page print in JavaScript is a simple code in JavaScript used to print the content of the web pages. "
},
{
"code": null,
"e": 192,
"s": 130,
"text": "The print() method prints the contents of the current window."
},
{
"code": null,
"e": 284,
"s": 192,
"text": "It basically opens Print dialog box which lets you choose between various printing options."
},
{
"code": null,
"e": 294,
"s": 284,
"text": "Syntax: "
},
{
"code": null,
"e": 309,
"s": 294,
"text": "window.print()"
},
{
"code": null,
"e": 634,
"s": 309,
"text": "Parameters: No parameters required Returns: This function do not return anythingThe following Javascript code shows a print button and then it shows the property of that webpage in a sheet in which you are going to print it. The JavaScript print function window.print() is used here to perform the functionality. Example : "
},
{
"code": null,
"e": 639,
"s": 634,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML | DOM Window Print() method </title> <script type=\"text/javascript\"> </script> </head> <body> <h2>HI GEEKSFORGEEKS USER'S</h2> <form> <input type=\"button\" value=\"Print\" onclick=\"window.print()\" /> </form> </body><html>",
"e": 951,
"s": 639,
"text": null
},
{
"code": null,
"e": 961,
"s": 951,
"text": "Output : "
},
{
"code": null,
"e": 1159,
"s": 961,
"text": "But the web pages are not limited to text only. There are other things too in the webpages like images consisting of different colors, etc. Printing such pages can be done by the following ways : "
},
{
"code": null,
"e": 1478,
"s": 1159,
"text": "Make a copy of the page and leave out unwanted text and graphics, then link that to the printer-friendly page from the original. This means that the whole page will be printed as you have seen the page it will be printed as it is without any change in it, if you will see an advertisement it will also be printed in it"
},
{
"code": null,
"e": 1808,
"s": 1478,
"text": "If you do not want to keep an extra copy of a page, then you can mark your printable text using proper comments like PRINT STARTS HERE ..... PRINT ENDS HERE and then you can use PERL or any other script in the background to purge printable text and display for final printing. This means that the selected portion will be printed"
},
{
"code": null,
"e": 1894,
"s": 1808,
"text": "Supported Browser: The browser supported by Window print() Method are listed below: "
},
{
"code": null,
"e": 1920,
"s": 1894,
"text": "Google Chrome 1 and above"
},
{
"code": null,
"e": 1950,
"s": 1920,
"text": "Internet Explorer 5 and above"
},
{
"code": null,
"e": 1970,
"s": 1950,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 1988,
"s": 1970,
"text": "Opera 6 and above"
},
{
"code": null,
"e": 2009,
"s": 1988,
"text": "Safari 1.1 and above"
},
{
"code": null,
"e": 2023,
"s": 2011,
"text": "ysachin2314"
},
{
"code": null,
"e": 2044,
"s": 2023,
"text": "javascript-functions"
},
{
"code": null,
"e": 2060,
"s": 2044,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 2077,
"s": 2060,
"text": "Web technologies"
},
{
"code": null,
"e": 2088,
"s": 2077,
"text": "JavaScript"
}
] |
Calendar getInstance() Method in Java with Examples | 18 Feb, 2019
The getInstance() method in Calendar class is used to get a calendar using the current time zone and locale of the system.
Syntax:
public static Calendar getInstance()
Parameters: The method does not take any parameters.
Return Value: The method returns the calendar.
Below program illustrates the working of getInstance() Method of Calendar class:Example:
// Java code to illustrate// getGreatestMinimum() method import java.util.*;public class Java_Calendar_Demo { public static void main(String args[]) { // Creating a calendar Calendar calndr = Calendar.getInstance(); // Display the date and time System.out.print("The system" + " date and time is: " + calndr.getTime()); }}
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#getInstance()
Java-Calendar
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Feb, 2019"
},
{
"code": null,
"e": 151,
"s": 28,
"text": "The getInstance() method in Calendar class is used to get a calendar using the current time zone and locale of the system."
},
{
"code": null,
"e": 159,
"s": 151,
"text": "Syntax:"
},
{
"code": null,
"e": 196,
"s": 159,
"text": "public static Calendar getInstance()"
},
{
"code": null,
"e": 249,
"s": 196,
"text": "Parameters: The method does not take any parameters."
},
{
"code": null,
"e": 296,
"s": 249,
"text": "Return Value: The method returns the calendar."
},
{
"code": null,
"e": 385,
"s": 296,
"text": "Below program illustrates the working of getInstance() Method of Calendar class:Example:"
},
{
"code": "// Java code to illustrate// getGreatestMinimum() method import java.util.*;public class Java_Calendar_Demo { public static void main(String args[]) { // Creating a calendar Calendar calndr = Calendar.getInstance(); // Display the date and time System.out.print(\"The system\" + \" date and time is: \" + calndr.getTime()); }}",
"e": 772,
"s": 385,
"text": null
},
{
"code": null,
"e": 863,
"s": 772,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#getInstance()"
},
{
"code": null,
"e": 877,
"s": 863,
"text": "Java-Calendar"
},
{
"code": null,
"e": 892,
"s": 877,
"text": "Java-Functions"
},
{
"code": null,
"e": 897,
"s": 892,
"text": "Java"
},
{
"code": null,
"e": 902,
"s": 897,
"text": "Java"
},
{
"code": null,
"e": 1000,
"s": 902,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1051,
"s": 1000,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 1082,
"s": 1051,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 1101,
"s": 1082,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 1131,
"s": 1101,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 1146,
"s": 1131,
"text": "Stream In Java"
},
{
"code": null,
"e": 1164,
"s": 1146,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 1184,
"s": 1164,
"text": "Collections in Java"
},
{
"code": null,
"e": 1208,
"s": 1184,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 1240,
"s": 1208,
"text": "Multidimensional Arrays in Java"
}
] |
BinaryOperator Interface in Java | The BinaryOperator interface represents an operation upon two operands of the same type, producing a result of the same type as the operands.
Following are the methods −
Let us now see an example −
Live Demo
import java.util.function.BinaryOperator;
public class Demo {
public static void main(String args[]) {
BinaryOperator<Integer>
operator = BinaryOperator
.maxBy(
(x, y) -> (x > y) ? 1 : ((x == y) ? 0 : -1));
System.out.println(operator.apply(120, 5));
}
}
This will produce the following output −
120
Let us now see another example −
Live Demo
import java.util.function.BinaryOperator;
public class Demo {
public static void main(String args[]) {
BinaryOperator<Integer> operator = (x, y) -> x * y;
System.out.println(operator.apply(5, 7));
}
}
This will produce the following output −
35 | [
{
"code": null,
"e": 1204,
"s": 1062,
"text": "The BinaryOperator interface represents an operation upon two operands of the same type, producing a result of the same type as the operands."
},
{
"code": null,
"e": 1232,
"s": 1204,
"text": "Following are the methods −"
},
{
"code": null,
"e": 1260,
"s": 1232,
"text": "Let us now see an example −"
},
{
"code": null,
"e": 1271,
"s": 1260,
"text": " Live Demo"
},
{
"code": null,
"e": 1564,
"s": 1271,
"text": "import java.util.function.BinaryOperator;\npublic class Demo {\n public static void main(String args[]) {\n BinaryOperator<Integer>\n operator = BinaryOperator\n .maxBy(\n (x, y) -> (x > y) ? 1 : ((x == y) ? 0 : -1));\n System.out.println(operator.apply(120, 5));\n }\n}"
},
{
"code": null,
"e": 1605,
"s": 1564,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1609,
"s": 1605,
"text": "120"
},
{
"code": null,
"e": 1642,
"s": 1609,
"text": "Let us now see another example −"
},
{
"code": null,
"e": 1653,
"s": 1642,
"text": " Live Demo"
},
{
"code": null,
"e": 1872,
"s": 1653,
"text": "import java.util.function.BinaryOperator;\npublic class Demo {\n public static void main(String args[]) {\n BinaryOperator<Integer> operator = (x, y) -> x * y;\n System.out.println(operator.apply(5, 7));\n }\n}"
},
{
"code": null,
"e": 1913,
"s": 1872,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1916,
"s": 1913,
"text": "35"
}
] |
Middle of Three | Practice | GeeksforGeeks | Given three distinct numbers A, B and C. Find the number with value in middle (Try to do it with minimum comparisons).
Example 1:
Input:
A = 978, B = 518, C = 300
Output:
518
Explanation:
Since 518>300 and 518<978, so
518 is the middle element.
Example 2:
Input:
A = 162, B = 934, C = 200
Output:
200
Exaplanation:
Since 200>162 && 200<934,
So, 200 is the middle element.
Your Task:
You don't need to read input or print anything.Your task is to complete the function middle() which takes three integers A,B and C as input parameters and returns the number which has middle value.
Expected Time Complexity:O(1)
Expected Auxillary Space:O(1)
Constraints:
1<=A,B,C<=109
A,B,C are distinct.
0
itsmemritu5 days ago
return (A+B+C)-( min(A,min(B,C)) + max(A,max(B,C)));
0
mayank180919991 week ago
int middle(int A, int B, int C){
//code here//Position this line where user code will be pasted.
vector<int>v;
v.push_back(A);
v.push_back(B);
v.push_back(C);
sort(v.begin(),v.end());
return v[1];
}
0
ashutos17sharma89892 weeks ago
PriorityQueue<Integer> p = new PriorityQueue<>((a,b) -> b-a); p.add(A); p.add(B); p.add(C); p.poll(); return p.peek();
0
rjpatil20012 weeks ago
int middle(int A, int B, int C){ //code here//Position this line where user code will be pasted. vector<int> ans; ans.push_back(A); ans.push_back(B); ans.push_back(C); sort(ans.begin(), ans.end()); return ans[1]; }
+1
kartikeyashokgautam2 weeks ago
JAVA Soution
int middle(int A, int B, int C){ if(A>B && A<C || A<B && A>C) return A; else if(B>A && B<C || B<A && B>C) return B; return C; }
0
kmohannayak123 weeks ago
Easy Java Solution
----------------------------
class Solution{ int middle(int A, int B, int C){ //code here int arr[]={A,B,C}; Arrays.sort(arr); int mid=arr[1]; return mid; }}
0
siddharthpaul20063 weeks ago
int middle(int a, int b, int c){ //code here//Position this line where user code will be pasted. if((a>b and a<c) or (a>c and a<b)){ return a; } else if((b>a and b<c) or (b>c and b<a)){ return b; } else if((c>a and c<b) or (c>b and c<a)){ return c; } }
0
aks190620003 weeks ago
int middle(int A, int B, int C)
{
//code here int a[]={A,B,C}; Arrays.sort(a); return(a[1]);
}
+3
ansarizia93351 month ago
class Solution{ public: int middle(int A, int B, int C){ //code here//Position this line where user code will be pasted. long long a=A,b=B,c=C; if((a-b)*(a-c)<=0) return a; else if((b-c)*(b-a)<=0) return b; else return c; }};
0
dev1711 month ago
3 COMPARISON WITHOUT USING ANY MIN MAX FUNCTION.
Note a comparison is when any logical operator is used such as
‘==’, '>' ,'>','≥','≤'.
so at max only 3 comparisons will be made ..
int middle(int A, int B, int C){
int min=A,max=A,mid=A;
if(B>C){ //1st Comp
if(max<B){ //2nd comp
max=B;
}else{
mid=B;
}
if(min>C){ //3rd comp
min=C;
}else{
mid=C;
}
}else{
if(max<C){ //2nd comp
max=C;
}else{
mid=C;
}
if(min>B){ //3rd comp
min=B;
}else{
mid=B;
}
}
return mid;
}
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": 357,
"s": 238,
"text": "Given three distinct numbers A, B and C. Find the number with value in middle (Try to do it with minimum comparisons)."
},
{
"code": null,
"e": 369,
"s": 357,
"text": "\nExample 1:"
},
{
"code": null,
"e": 485,
"s": 369,
"text": "Input:\nA = 978, B = 518, C = 300\nOutput:\n518\nExplanation:\nSince 518>300 and 518<978, so \n518 is the middle element."
},
{
"code": null,
"e": 497,
"s": 485,
"text": "\nExample 2:"
},
{
"code": null,
"e": 613,
"s": 497,
"text": "Input:\nA = 162, B = 934, C = 200\nOutput:\n200\nExaplanation:\nSince 200>162 && 200<934,\nSo, 200 is the middle element."
},
{
"code": null,
"e": 823,
"s": 613,
"text": "\nYour Task:\nYou don't need to read input or print anything.Your task is to complete the function middle() which takes three integers A,B and C as input parameters and returns the number which has middle value."
},
{
"code": null,
"e": 934,
"s": 823,
"text": "\nExpected Time Complexity:O(1)\nExpected Auxillary Space:O(1)\n\n\nConstraints:\n1<=A,B,C<=109\nA,B,C are distinct. "
},
{
"code": null,
"e": 936,
"s": 934,
"text": "0"
},
{
"code": null,
"e": 957,
"s": 936,
"text": "itsmemritu5 days ago"
},
{
"code": null,
"e": 1010,
"s": 957,
"text": "return (A+B+C)-( min(A,min(B,C)) + max(A,max(B,C)));"
},
{
"code": null,
"e": 1012,
"s": 1010,
"text": "0"
},
{
"code": null,
"e": 1037,
"s": 1012,
"text": "mayank180919991 week ago"
},
{
"code": null,
"e": 1296,
"s": 1037,
"text": " int middle(int A, int B, int C){\n //code here//Position this line where user code will be pasted.\n vector<int>v;\n v.push_back(A);\n v.push_back(B);\n v.push_back(C);\n sort(v.begin(),v.end());\n return v[1];\n }"
},
{
"code": null,
"e": 1298,
"s": 1296,
"text": "0"
},
{
"code": null,
"e": 1329,
"s": 1298,
"text": "ashutos17sharma89892 weeks ago"
},
{
"code": null,
"e": 1482,
"s": 1329,
"text": " PriorityQueue<Integer> p = new PriorityQueue<>((a,b) -> b-a); p.add(A); p.add(B); p.add(C); p.poll(); return p.peek();"
},
{
"code": null,
"e": 1484,
"s": 1482,
"text": "0"
},
{
"code": null,
"e": 1507,
"s": 1484,
"text": "rjpatil20012 weeks ago"
},
{
"code": null,
"e": 1773,
"s": 1507,
"text": "int middle(int A, int B, int C){ //code here//Position this line where user code will be pasted. vector<int> ans; ans.push_back(A); ans.push_back(B); ans.push_back(C); sort(ans.begin(), ans.end()); return ans[1]; }"
},
{
"code": null,
"e": 1776,
"s": 1773,
"text": "+1"
},
{
"code": null,
"e": 1807,
"s": 1776,
"text": "kartikeyashokgautam2 weeks ago"
},
{
"code": null,
"e": 1823,
"s": 1807,
"text": "JAVA Soution "
},
{
"code": null,
"e": 1985,
"s": 1823,
"text": "int middle(int A, int B, int C){ if(A>B && A<C || A<B && A>C) return A; else if(B>A && B<C || B<A && B>C) return B; return C; }"
},
{
"code": null,
"e": 1987,
"s": 1985,
"text": "0"
},
{
"code": null,
"e": 2012,
"s": 1987,
"text": "kmohannayak123 weeks ago"
},
{
"code": null,
"e": 2031,
"s": 2012,
"text": "Easy Java Solution"
},
{
"code": null,
"e": 2060,
"s": 2031,
"text": "----------------------------"
},
{
"code": null,
"e": 2223,
"s": 2060,
"text": "class Solution{ int middle(int A, int B, int C){ //code here int arr[]={A,B,C}; Arrays.sort(arr); int mid=arr[1]; return mid; }}"
},
{
"code": null,
"e": 2225,
"s": 2223,
"text": "0"
},
{
"code": null,
"e": 2254,
"s": 2225,
"text": "siddharthpaul20063 weeks ago"
},
{
"code": null,
"e": 2582,
"s": 2254,
"text": " int middle(int a, int b, int c){ //code here//Position this line where user code will be pasted. if((a>b and a<c) or (a>c and a<b)){ return a; } else if((b>a and b<c) or (b>c and b<a)){ return b; } else if((c>a and c<b) or (c>b and c<a)){ return c; } }"
},
{
"code": null,
"e": 2584,
"s": 2582,
"text": "0"
},
{
"code": null,
"e": 2607,
"s": 2584,
"text": "aks190620003 weeks ago"
},
{
"code": null,
"e": 2639,
"s": 2607,
"text": "int middle(int A, int B, int C)"
},
{
"code": null,
"e": 2641,
"s": 2639,
"text": "{"
},
{
"code": null,
"e": 2725,
"s": 2641,
"text": " //code here int a[]={A,B,C}; Arrays.sort(a); return(a[1]);"
},
{
"code": null,
"e": 2727,
"s": 2725,
"text": "}"
},
{
"code": null,
"e": 2730,
"s": 2727,
"text": "+3"
},
{
"code": null,
"e": 2755,
"s": 2730,
"text": "ansarizia93351 month ago"
},
{
"code": null,
"e": 3034,
"s": 2755,
"text": "class Solution{ public: int middle(int A, int B, int C){ //code here//Position this line where user code will be pasted. long long a=A,b=B,c=C; if((a-b)*(a-c)<=0) return a; else if((b-c)*(b-a)<=0) return b; else return c; }};"
},
{
"code": null,
"e": 3036,
"s": 3034,
"text": "0"
},
{
"code": null,
"e": 3054,
"s": 3036,
"text": "dev1711 month ago"
},
{
"code": null,
"e": 3103,
"s": 3054,
"text": "3 COMPARISON WITHOUT USING ANY MIN MAX FUNCTION."
},
{
"code": null,
"e": 3166,
"s": 3103,
"text": "Note a comparison is when any logical operator is used such as"
},
{
"code": null,
"e": 3190,
"s": 3166,
"text": "‘==’, '>' ,'>','≥','≤'."
},
{
"code": null,
"e": 3235,
"s": 3190,
"text": "so at max only 3 comparisons will be made .."
},
{
"code": null,
"e": 3828,
"s": 3235,
"text": " int middle(int A, int B, int C){\n int min=A,max=A,mid=A;\n if(B>C){ \t\t\t//1st Comp\n if(max<B){\t\t//2nd comp\n max=B;\n }else{\n mid=B;\n }\n if(min>C){\t\t//3rd comp\n min=C;\n }else{\n mid=C;\n }\n }else{\n if(max<C){\t\t\t//2nd comp\n max=C;\n }else{\n mid=C;\n }\n if(min>B){\t\t\t//3rd comp\n min=B;\n }else{\n mid=B;\n }\n }\n return mid;\n }"
},
{
"code": null,
"e": 3974,
"s": 3828,
"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": 4010,
"s": 3974,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4020,
"s": 4010,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4030,
"s": 4020,
"text": "\nContest\n"
},
{
"code": null,
"e": 4093,
"s": 4030,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4241,
"s": 4093,
"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": 4449,
"s": 4241,
"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": 4555,
"s": 4449,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
An easy introduction to Pytorch for Neural Networks | by George Seif | Towards Data Science | Want to be inspired? Come join my Super Quotes newsletter. 😎
Deep Learning has reignited the public interest in AI. The reason is simple: Deep Learning just works. It’s given us the ability to build technologies that we previously weren’t able to. It’s created new business opportunities and improved the technology world as a whole.
To do Deep Learning, you’re going to need to know how to code, especially with Python. From there, there’s a big ever-growing set of Deep Learning libraries to choose from: TensorFlow, Keras, MXNet, MatConvNet and, quite recently, Pytorch!
Very shortly after its release, Pytorch rapidly gained popularity. People were calling it the TensorFlow killer, since it was so much more user-friendly and easier to use. Indeed, you’re about to see just how easy it is to get up and running in Deep Learning with Pytorch.
At its core, the development of Pytorch was aimed at being as similar to Python’s Numpy as possible. Doing so would allow an easy and smooth interaction between regular Python code, Numpy, and Pytorch allowing for faster and easier coding.
To get started, we can install Pytorch via pip:
pip3 install torch torchvision
If you’re interested in looking at specific features, the Pytorch docs are amazing.
The most basic building block of any Deep Learning library is the tensor. Tensors are matrix-like data structures very similar in function and properties to Numpy arrays. In fact, for most purposes you can think of them exactly like Numpy arrays. The most important difference between the two is that the implementation of tensors in modern Deep Learning libraries can run on CPU or GPU (very fast).
In PyTorch, tensors can be declared using the simple Tensor object:
import torch x = torch.Tensor(3, 3)
The above code creates a tensor of size (3, 3) — i.e. 3 rows and 3 columns, filled with floating point zeros:
0. 0. 0.0. 0. 0.0. 0. 0.[torch.FloatTensor of size 3x3]
We can also create tensors filled random floating point values:
x = torch.rand(3, 3)print(x)"""Prints out:tensor([[0.5264, 0.1839, 0.9907], [0.0343, 0.9839, 0.9294], [0.6938, 0.6755, 0.2258]])"""
Multiplying tensors, adding them, and other basic math is super easy with Pytorch:
x = torch.ones(3,3)y = torch.ones(3,3) * 4z = x + yprint(z)"""Prints out:tensor([[5., 5., 5.], [5., 5., 5.], [5., 5., 5.]])"""
Even Numpy-like slicing functions are available with Pytorch tensors!
x = torch.ones(3,3) * 5y = x[:, :2]print(y)"""Prints out:tensor([[5., 5.], [5., 5.], [5., 5.]])"""
So Pytorch tensors can very much be used and worked with in the same way as Numpy arrays. Now we’ll look at how we can build Deep Networks with these easy Pytorch tensors as our building blocks!
With Pytorch, neural networks are defined as Python classes. The class which defines the network extends the torch.nn.Module from the Torch library. Let’s create a class for a Convolutional Neural Network (CNN) which we’ll apply on the MNIST dataset.
Check out the code below which defines our network!
The two most important functions in a Pytorch network class are the __init__() and the forward() functions. The __init__() is used to define any network layers that your model will use. The forward() function is where you actually set up the model by stacking all the layers together.
For our model, we’ve defined 2 convolutional layers in the init function, one of which we’ll re-use a few times (conv2). We have a max-pooling layer and a global average pooling layer to be applied near the end. Finally we have our Full-Connected (FC) layers and a softmax to get the final output probabilities.
In the forward function, we define exactly how our layers stack up together to form the full model. It’s a standard network with stacked conv, pooling, and FC layers. The beauty of Pytorch is that we can print out the shape and result of any tensor within the intermediate layers with just a simple print statement wherever you want in the forward() function!
Time to get our data ready for training! We’ll starting but getting the necessary imports ready, initialise parameters, and making sure Pytorch is setup to use the GPU. The line below which uses torch.device() checks if Pytorch was installed with CUDA support and if so uses the GPU!
We can retrieve the MNIST dataset straight from Pytroch. We’ll download the data and put the train and test sets into separate tensors. Once that data is loaded, we’ll pass it to a torch DataLoader which just gets it ready to pass to the model with a specific batch size and optional shuffling.
It’s training time!
The optimzer (we’ll use Adam) and loss function (we’ll use cross entropy) are defined quite similarly to other deep learning libraries like TensorFlow, Keras, and MXNet.
In Pytorch, all network models and datasets much be explicitly transferred from CPU to GPU. We do this by applying the .to() function to our model below. Later, we’ll do the same for our image data.
Finally, we can write out our training loop. Check out the code below to see how it works!
All Pytorch training loops will go through each epoch and each batch in the training data loader.On each loop iteration, the image data and labels are transferred to the GPU.Each training loop also explicitly applies the forward pass, backward pass, and optimisation steps.The model is applied to the images in the batch and then the loss for that batch is calculated.The gradients are calculated and back-propagated through the network
All Pytorch training loops will go through each epoch and each batch in the training data loader.
On each loop iteration, the image data and labels are transferred to the GPU.
Each training loop also explicitly applies the forward pass, backward pass, and optimisation steps.
The model is applied to the images in the batch and then the loss for that batch is calculated.
The gradients are calculated and back-propagated through the network
Testing a network’s performance in Pytorch sets up a similar loop as in the training phase. The main difference being that we don’t need to do a backward propagation of the gradients. We’ll still do the forward-pass and just get the label with the maximum probability at the output of the network.
In this case, after 10 epochs our network got an accuracy of 99.06% on the test set!
To save the model to disk to use later, just use the torch.save() function and voila!
Follow me on twitter where I post all about the latest and greatest AI, Technology, and Science! Connect with me on LinkedIn too! | [
{
"code": null,
"e": 232,
"s": 171,
"text": "Want to be inspired? Come join my Super Quotes newsletter. 😎"
},
{
"code": null,
"e": 505,
"s": 232,
"text": "Deep Learning has reignited the public interest in AI. The reason is simple: Deep Learning just works. It’s given us the ability to build technologies that we previously weren’t able to. It’s created new business opportunities and improved the technology world as a whole."
},
{
"code": null,
"e": 745,
"s": 505,
"text": "To do Deep Learning, you’re going to need to know how to code, especially with Python. From there, there’s a big ever-growing set of Deep Learning libraries to choose from: TensorFlow, Keras, MXNet, MatConvNet and, quite recently, Pytorch!"
},
{
"code": null,
"e": 1018,
"s": 745,
"text": "Very shortly after its release, Pytorch rapidly gained popularity. People were calling it the TensorFlow killer, since it was so much more user-friendly and easier to use. Indeed, you’re about to see just how easy it is to get up and running in Deep Learning with Pytorch."
},
{
"code": null,
"e": 1258,
"s": 1018,
"text": "At its core, the development of Pytorch was aimed at being as similar to Python’s Numpy as possible. Doing so would allow an easy and smooth interaction between regular Python code, Numpy, and Pytorch allowing for faster and easier coding."
},
{
"code": null,
"e": 1306,
"s": 1258,
"text": "To get started, we can install Pytorch via pip:"
},
{
"code": null,
"e": 1337,
"s": 1306,
"text": "pip3 install torch torchvision"
},
{
"code": null,
"e": 1421,
"s": 1337,
"text": "If you’re interested in looking at specific features, the Pytorch docs are amazing."
},
{
"code": null,
"e": 1821,
"s": 1421,
"text": "The most basic building block of any Deep Learning library is the tensor. Tensors are matrix-like data structures very similar in function and properties to Numpy arrays. In fact, for most purposes you can think of them exactly like Numpy arrays. The most important difference between the two is that the implementation of tensors in modern Deep Learning libraries can run on CPU or GPU (very fast)."
},
{
"code": null,
"e": 1889,
"s": 1821,
"text": "In PyTorch, tensors can be declared using the simple Tensor object:"
},
{
"code": null,
"e": 1925,
"s": 1889,
"text": "import torch x = torch.Tensor(3, 3)"
},
{
"code": null,
"e": 2035,
"s": 1925,
"text": "The above code creates a tensor of size (3, 3) — i.e. 3 rows and 3 columns, filled with floating point zeros:"
},
{
"code": null,
"e": 2097,
"s": 2035,
"text": "0. 0. 0.0. 0. 0.0. 0. 0.[torch.FloatTensor of size 3x3]"
},
{
"code": null,
"e": 2161,
"s": 2097,
"text": "We can also create tensors filled random floating point values:"
},
{
"code": null,
"e": 2307,
"s": 2161,
"text": "x = torch.rand(3, 3)print(x)\"\"\"Prints out:tensor([[0.5264, 0.1839, 0.9907], [0.0343, 0.9839, 0.9294], [0.6938, 0.6755, 0.2258]])\"\"\""
},
{
"code": null,
"e": 2390,
"s": 2307,
"text": "Multiplying tensors, adding them, and other basic math is super easy with Pytorch:"
},
{
"code": null,
"e": 2531,
"s": 2390,
"text": "x = torch.ones(3,3)y = torch.ones(3,3) * 4z = x + yprint(z)\"\"\"Prints out:tensor([[5., 5., 5.], [5., 5., 5.], [5., 5., 5.]])\"\"\""
},
{
"code": null,
"e": 2601,
"s": 2531,
"text": "Even Numpy-like slicing functions are available with Pytorch tensors!"
},
{
"code": null,
"e": 2714,
"s": 2601,
"text": "x = torch.ones(3,3) * 5y = x[:, :2]print(y)\"\"\"Prints out:tensor([[5., 5.], [5., 5.], [5., 5.]])\"\"\""
},
{
"code": null,
"e": 2909,
"s": 2714,
"text": "So Pytorch tensors can very much be used and worked with in the same way as Numpy arrays. Now we’ll look at how we can build Deep Networks with these easy Pytorch tensors as our building blocks!"
},
{
"code": null,
"e": 3160,
"s": 2909,
"text": "With Pytorch, neural networks are defined as Python classes. The class which defines the network extends the torch.nn.Module from the Torch library. Let’s create a class for a Convolutional Neural Network (CNN) which we’ll apply on the MNIST dataset."
},
{
"code": null,
"e": 3212,
"s": 3160,
"text": "Check out the code below which defines our network!"
},
{
"code": null,
"e": 3497,
"s": 3212,
"text": "The two most important functions in a Pytorch network class are the __init__() and the forward() functions. The __init__() is used to define any network layers that your model will use. The forward() function is where you actually set up the model by stacking all the layers together."
},
{
"code": null,
"e": 3809,
"s": 3497,
"text": "For our model, we’ve defined 2 convolutional layers in the init function, one of which we’ll re-use a few times (conv2). We have a max-pooling layer and a global average pooling layer to be applied near the end. Finally we have our Full-Connected (FC) layers and a softmax to get the final output probabilities."
},
{
"code": null,
"e": 4169,
"s": 3809,
"text": "In the forward function, we define exactly how our layers stack up together to form the full model. It’s a standard network with stacked conv, pooling, and FC layers. The beauty of Pytorch is that we can print out the shape and result of any tensor within the intermediate layers with just a simple print statement wherever you want in the forward() function!"
},
{
"code": null,
"e": 4453,
"s": 4169,
"text": "Time to get our data ready for training! We’ll starting but getting the necessary imports ready, initialise parameters, and making sure Pytorch is setup to use the GPU. The line below which uses torch.device() checks if Pytorch was installed with CUDA support and if so uses the GPU!"
},
{
"code": null,
"e": 4748,
"s": 4453,
"text": "We can retrieve the MNIST dataset straight from Pytroch. We’ll download the data and put the train and test sets into separate tensors. Once that data is loaded, we’ll pass it to a torch DataLoader which just gets it ready to pass to the model with a specific batch size and optional shuffling."
},
{
"code": null,
"e": 4768,
"s": 4748,
"text": "It’s training time!"
},
{
"code": null,
"e": 4938,
"s": 4768,
"text": "The optimzer (we’ll use Adam) and loss function (we’ll use cross entropy) are defined quite similarly to other deep learning libraries like TensorFlow, Keras, and MXNet."
},
{
"code": null,
"e": 5137,
"s": 4938,
"text": "In Pytorch, all network models and datasets much be explicitly transferred from CPU to GPU. We do this by applying the .to() function to our model below. Later, we’ll do the same for our image data."
},
{
"code": null,
"e": 5228,
"s": 5137,
"text": "Finally, we can write out our training loop. Check out the code below to see how it works!"
},
{
"code": null,
"e": 5665,
"s": 5228,
"text": "All Pytorch training loops will go through each epoch and each batch in the training data loader.On each loop iteration, the image data and labels are transferred to the GPU.Each training loop also explicitly applies the forward pass, backward pass, and optimisation steps.The model is applied to the images in the batch and then the loss for that batch is calculated.The gradients are calculated and back-propagated through the network"
},
{
"code": null,
"e": 5763,
"s": 5665,
"text": "All Pytorch training loops will go through each epoch and each batch in the training data loader."
},
{
"code": null,
"e": 5841,
"s": 5763,
"text": "On each loop iteration, the image data and labels are transferred to the GPU."
},
{
"code": null,
"e": 5941,
"s": 5841,
"text": "Each training loop also explicitly applies the forward pass, backward pass, and optimisation steps."
},
{
"code": null,
"e": 6037,
"s": 5941,
"text": "The model is applied to the images in the batch and then the loss for that batch is calculated."
},
{
"code": null,
"e": 6106,
"s": 6037,
"text": "The gradients are calculated and back-propagated through the network"
},
{
"code": null,
"e": 6404,
"s": 6106,
"text": "Testing a network’s performance in Pytorch sets up a similar loop as in the training phase. The main difference being that we don’t need to do a backward propagation of the gradients. We’ll still do the forward-pass and just get the label with the maximum probability at the output of the network."
},
{
"code": null,
"e": 6489,
"s": 6404,
"text": "In this case, after 10 epochs our network got an accuracy of 99.06% on the test set!"
},
{
"code": null,
"e": 6575,
"s": 6489,
"text": "To save the model to disk to use later, just use the torch.save() function and voila!"
}
] |
Fast inverse square root - GeeksforGeeks | 26 Mar, 2018
Fast inverse square root is an algorithm that estimates , the reciprocal (or multiplicative inverse) of the square root of a 32-bit floating-point number x in IEEE 754 floating-point format. Computing reciprocal square roots is necessary in many applications, such as vector normalization in video games and is mostly used in calculations involved in 3D programming. In 3D graphics, surface normals, 3-coordinate vectors of length 1 is used, to express lighting and reflection. There were a lot of surface normals. And calculating them involves normalizing a lot of vectors. Normalizing is often just a fancy term for division. The Pythagorean theorem computes distance between points, and dividing by distance helps normalize vectors:
This algorithm is best known for its implementation in 1999 in the source code of Quake III Arena Game, a first-person shooter video game that made heavy use of 3D graphics. At that time, it was generally computationally expensive to compute the reciprocal of a floating-point number, especially on a large scale; the fast inverse square root bypassed this step.
Algorithm :Step 1 : It reinterprets the bits of the floating-point input as an integer.
i = * ( long * ) &y;
Step 2 : It takes the resulting value and does integer arithmetic on it which produces an approximation of the value we’re looking for.
i = 0x5f3759df - ( i >> 1 );
Step 3 : The result is not the approximation itself though, it is an integer which happens to be, if you reinterpret the bits as a floating point number, the approximation. So the code does the reverse of the conversion in step 1 to get back to floating point:
y = * ( float * ) &i;
Step 4 : And finally it runs a single iteration of Newton’s method to improve the approximation.
y = y * ( threehalfs - ( x2 * y * y ) ); //threehalfs = 1.5F;
The algorithm accepts a 32-bit floating-point number as the input and stores a halved value for later use. Then, treating the bits representing the floating-point number as a 32-bit integer, a logical shift right by one bit is performed and the result subtracted from the magic number 0x5F3759DF. This is the first approximation of the inverse square root of the input. Treating the bits again as a floating-point number, it runs one iteration of Newton’s approximation method, yielding a more precise approximation.
Let’s say there is a number in exponent form or scientific notation: =100 millionNow, to find the regular square root, we’d just divide the exponent by 2: And if, want to know the inverse square root, divide the exponent by -2 to flip the sign:
So, the code converts the floating-point number into an integer. It then shifts the bits by one, which means the exponent bits are divided by 2 (when we eventually turn the bits back into a float). And lastly, to negate the exponent, we subtract from the magic number 0x5f3759df. This does a few things: it preserves the mantissa (the non-exponent part, aka 5 in: 5 · ), handles odd-even exponents, shifting bits from the exponent into the mantissa, and all sorts of funky stuff.
The following code is the fast inverse square root implementation from Quake III Arena (exact original comment written in Quake III Arena Game).
// CPP program for fast inverse square root.#include<bits/stdc++.h>using namespace std; // function to find the inverse square rootfloat inverse_rsqrt( float number ){ const float threehalfs = 1.5F; float x2 = number * 0.5F; float y = number; // evil floating point bit level hacking long i = * ( long * ) &y; // value is pre-assumed i = 0x5f3759df - ( i >> 1 ); y = * ( float * ) &i; // 1st iteration y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed // y = y * ( threehalfs - ( x2 * y * y ) ); return y;} // driver codeint main(){ int n = 256; float f = inverse_rsqrt(n); cout << f << endl; return 0;}
Output :
0.0623942
Bit Magic
C++ Programs
Mathematical
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Set, Clear and Toggle a given bit of a number in C
Check whether K-th bit is set or not
Write an Efficient Method to Check if a Number is Multiple of 3
Reverse actual bits of the given number
Program to find parity
Header files in C/C++ and its uses
C++ Program for QuickSort
How to return multiple values from a function in C or C++?
Program to print ASCII Value of a character
C++ program for hashing with chaining | [
{
"code": null,
"e": 24621,
"s": 24593,
"text": "\n26 Mar, 2018"
},
{
"code": null,
"e": 25357,
"s": 24621,
"text": "Fast inverse square root is an algorithm that estimates , the reciprocal (or multiplicative inverse) of the square root of a 32-bit floating-point number x in IEEE 754 floating-point format. Computing reciprocal square roots is necessary in many applications, such as vector normalization in video games and is mostly used in calculations involved in 3D programming. In 3D graphics, surface normals, 3-coordinate vectors of length 1 is used, to express lighting and reflection. There were a lot of surface normals. And calculating them involves normalizing a lot of vectors. Normalizing is often just a fancy term for division. The Pythagorean theorem computes distance between points, and dividing by distance helps normalize vectors:"
},
{
"code": null,
"e": 25720,
"s": 25357,
"text": "This algorithm is best known for its implementation in 1999 in the source code of Quake III Arena Game, a first-person shooter video game that made heavy use of 3D graphics. At that time, it was generally computationally expensive to compute the reciprocal of a floating-point number, especially on a large scale; the fast inverse square root bypassed this step."
},
{
"code": null,
"e": 25808,
"s": 25720,
"text": "Algorithm :Step 1 : It reinterprets the bits of the floating-point input as an integer."
},
{
"code": null,
"e": 25832,
"s": 25808,
"text": "i = * ( long * ) &y; \n"
},
{
"code": null,
"e": 25968,
"s": 25832,
"text": "Step 2 : It takes the resulting value and does integer arithmetic on it which produces an approximation of the value we’re looking for."
},
{
"code": null,
"e": 25999,
"s": 25968,
"text": "i = 0x5f3759df - ( i >> 1 );\n"
},
{
"code": null,
"e": 26260,
"s": 25999,
"text": "Step 3 : The result is not the approximation itself though, it is an integer which happens to be, if you reinterpret the bits as a floating point number, the approximation. So the code does the reverse of the conversion in step 1 to get back to floating point:"
},
{
"code": null,
"e": 26284,
"s": 26260,
"text": "y = * ( float * ) &i;\n"
},
{
"code": null,
"e": 26381,
"s": 26284,
"text": "Step 4 : And finally it runs a single iteration of Newton’s method to improve the approximation."
},
{
"code": null,
"e": 26453,
"s": 26381,
"text": "y = y * ( threehalfs - ( x2 * y * y ) ); //threehalfs = 1.5F;\n"
},
{
"code": null,
"e": 26970,
"s": 26453,
"text": "The algorithm accepts a 32-bit floating-point number as the input and stores a halved value for later use. Then, treating the bits representing the floating-point number as a 32-bit integer, a logical shift right by one bit is performed and the result subtracted from the magic number 0x5F3759DF. This is the first approximation of the inverse square root of the input. Treating the bits again as a floating-point number, it runs one iteration of Newton’s approximation method, yielding a more precise approximation."
},
{
"code": null,
"e": 27239,
"s": 26970,
"text": "Let’s say there is a number in exponent form or scientific notation: =100 millionNow, to find the regular square root, we’d just divide the exponent by 2: And if, want to know the inverse square root, divide the exponent by -2 to flip the sign: "
},
{
"code": null,
"e": 27719,
"s": 27239,
"text": "So, the code converts the floating-point number into an integer. It then shifts the bits by one, which means the exponent bits are divided by 2 (when we eventually turn the bits back into a float). And lastly, to negate the exponent, we subtract from the magic number 0x5f3759df. This does a few things: it preserves the mantissa (the non-exponent part, aka 5 in: 5 · ), handles odd-even exponents, shifting bits from the exponent into the mantissa, and all sorts of funky stuff."
},
{
"code": null,
"e": 27864,
"s": 27719,
"text": "The following code is the fast inverse square root implementation from Quake III Arena (exact original comment written in Quake III Arena Game)."
},
{
"code": "// CPP program for fast inverse square root.#include<bits/stdc++.h>using namespace std; // function to find the inverse square rootfloat inverse_rsqrt( float number ){ const float threehalfs = 1.5F; float x2 = number * 0.5F; float y = number; // evil floating point bit level hacking long i = * ( long * ) &y; // value is pre-assumed i = 0x5f3759df - ( i >> 1 ); y = * ( float * ) &i; // 1st iteration y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed // y = y * ( threehalfs - ( x2 * y * y ) ); return y;} // driver codeint main(){ int n = 256; float f = inverse_rsqrt(n); cout << f << endl; return 0;}",
"e": 28590,
"s": 27864,
"text": null
},
{
"code": null,
"e": 28599,
"s": 28590,
"text": "Output :"
},
{
"code": null,
"e": 28610,
"s": 28599,
"text": "0.0623942\n"
},
{
"code": null,
"e": 28620,
"s": 28610,
"text": "Bit Magic"
},
{
"code": null,
"e": 28633,
"s": 28620,
"text": "C++ Programs"
},
{
"code": null,
"e": 28646,
"s": 28633,
"text": "Mathematical"
},
{
"code": null,
"e": 28659,
"s": 28646,
"text": "Mathematical"
},
{
"code": null,
"e": 28669,
"s": 28659,
"text": "Bit Magic"
},
{
"code": null,
"e": 28767,
"s": 28669,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28776,
"s": 28767,
"text": "Comments"
},
{
"code": null,
"e": 28789,
"s": 28776,
"text": "Old Comments"
},
{
"code": null,
"e": 28840,
"s": 28789,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 28877,
"s": 28840,
"text": "Check whether K-th bit is set or not"
},
{
"code": null,
"e": 28941,
"s": 28877,
"text": "Write an Efficient Method to Check if a Number is Multiple of 3"
},
{
"code": null,
"e": 28981,
"s": 28941,
"text": "Reverse actual bits of the given number"
},
{
"code": null,
"e": 29004,
"s": 28981,
"text": "Program to find parity"
},
{
"code": null,
"e": 29039,
"s": 29004,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 29065,
"s": 29039,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 29124,
"s": 29065,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 29168,
"s": 29124,
"text": "Program to print ASCII Value of a character"
}
] |
C++ Program to Implement Heap Sort | A Heap is a complete binary tree which is either Min Heap or Max Heap.
In a Max Heap, the key at root must be maximum among all keys
present in Heap. This property must be recursively true for all nodes in
that Binary Tree. Min Heap is similar to MinHeap.
void BHeap::Insert(int ele): Perform insertion operation to insert element in heap.
void BHeap::DeleteMin(): Perform deleteion operation to delete minimum value from heap.
int BHeap::ExtractMin(): Perfrom operation to extract minimum value from heap.
void BHeap::showHeap(): To show the elements of heap.
void BHeap::heapifyup(int in): maintain heap structure in bottom up manner.
void BHeap::heapifydown(int in): maintain heap structure in top down manner.
#include <iostream>
#include <cstdlib>
#include <vector>
#include <iterator>
using namespace std;
class BHeap {
private:
vector <int> heap;
int l(int parent);
int r(int parent);
int par(int child);
void heapifyup(int in);
void heapifydown(int in);
public:
BHeap()
{}
void Insert(int element);
void DeleteMin();
int ExtractMin();
void showHeap();
int Size();
};
int main() {
BHeap h;
while (1) {
cout<<"1.Insert Element"<<endl;
cout<<"2.Delete Minimum Element"<<endl;
cout<<"3.Extract Minimum Element"<<endl;
cout<<"4.Show Heap"<<endl;
cout<<"5.Exit"<<endl;
int c, e;
cout<<"Enter your choice: ";
cin>>c;
switch(c) {
case 1:
cout<<"Enter the element to be inserted: ";
cin>>e;
h.Insert(e);
break;
case 2:
h.DeleteMin();
break;
case 3:
if (h.ExtractMin() == -1) {
cout<<"Heap is Empty"<<endl;
}
else
cout<<"Minimum Element: "<<h.ExtractMin()<<endl;
break;
case 4:
cout<<"Displaying elements of Hwap: ";
h.showHeap();
break;
case 5:
exit(1);
default:
cout<<"Enter Correct Choice"<<endl;
}
}
return 0;
}
int BHeap::Size() //size of heap {
return heap.size();
}
void BHeap::Insert(int ele) //insert element in heap {
heap.push_back(ele);//push element into the heap
heapifyup(heap.size() -1);//call heapifyup() to maintain heap structure
}
void BHeap::DeleteMin() //delete minimum value from heap {
if (heap.size() == 0) {
cout<<"Heap is Empty"<<endl;
return;
}
heap[0] = heap.at(heap.size() - 1);
heap.pop_back();//pop element
heapifydown(0);
cout<<"Element Deleted"<<endl;
}
int BHeap::ExtractMin() //extract minimum value from heap
{
if (heap.size() == 0) {
return -1;
}
else
return heap.front();
}
void BHeap::showHeap() //show the elements of heap {
vector <int>::iterator pos = heap.begin();
cout<<"Heap --> ";
while (pos != heap.end()) {
cout<<*pos<<" ";
pos++;
}
cout<<endl;
}
int BHeap::l(int parent) // return left child of node.
{
int l = 2 * parent + 1;
if (l < heap.size())
return l;
else
return -1;
}
int BHeap::r(int parent) // return right child of node.
{
int r = 2 * parent + 2;
if (r < heap.size())
return r;
else
return -1;
}
int BHeap::par(int child)// return parent
{
int p = (child - 1)/2;
if (child == 0)
return -1;
else
return p;
}
void BHeap::heapifyup(int in)//maintain heap structure in bottom up manner.
{
if (in >= 0 && par(in) >= 0 && heap[par(in)] > heap[in]) {
int temp = heap[in];
heap[in] = heap[par(in)];
heap[par(in)] = temp;
heapifyup(par(in));
}
}
void BHeap::heapifydown(int in)//maintain heap structure in top down manner.
{
int child = l(in);
int child1 = r(in);
if (child >= 0 && child1 >= 0 && heap[child] > heap[child1]) {
child = child1;
}
if (child > 0 && heap[in] > heap[child]) {
int t = heap[in];
heap[in] = heap[child];
heap[child] = t;
heapifydown(child);
}
}
1.Insert Element
2.Delete Minimum Element
3.Extract Minimum Element
4.Show Heap
5.Exit
Enter your choice: 1
Enter the element to be inserted: 2
1.Insert Element
2.Delete Minimum Element
3.Extract Minimum Element
4.Show Heap
5.Exit
Enter your choice: 1
Enter the element to be inserted: 3
1.Insert Element
2.Delete Minimum Element
3.Extract Minimum Element
4.Show Heap
5.Exit
Enter your choice: 1
Enter the element to be inserted: 7
1.Insert Element
2.Delete Minimum Element
3.Extract Minimum Element
4.Show Heap
5.Exit
Enter your choice: 1
Enter the element to be inserted: 6
1.Insert Element
2.Delete Minimum Element
3.Extract Minimum Element
4.Show Heap
5.Exit
Enter your choice: 4
Displaying elements of Hwap: Heap --> 2 3 7 6
1.Insert Element
2.Delete Minimum Element
3.Extract Minimum Element
4.Show Heap
5.Exit
Enter your choice: 3
Minimum Element: 2
1.Insert Element
2.Delete Minimum Element
3.Extract Minimum Element
4.Show Heap
5.Exit
Enter your choice: 3
Minimum Element: 2
1.Insert Element
2.Delete Minimum Element
3.Extract Minimum Element
4.Show Heap
5.Exit
Enter your choice: 2
Element Deleted
1.Insert Element
2.Delete Minimum Element
3.Extract Minimum Element
4.Show Heap
5.Exit
Enter your choice: 4
Displaying elements of Hwap: Heap --> 3 6 7
1.Insert Element
2.Delete Minimum Element
3.Extract Minimum Element
4.Show Heap
5.Exit
Enter your choice: 5 | [
{
"code": null,
"e": 1318,
"s": 1062,
"text": "A Heap is a complete binary tree which is either Min Heap or Max Heap.\nIn a Max Heap, the key at root must be maximum among all keys\npresent in Heap. This property must be recursively true for all nodes in\nthat Binary Tree. Min Heap is similar to MinHeap."
},
{
"code": null,
"e": 1402,
"s": 1318,
"text": "void BHeap::Insert(int ele): Perform insertion operation to insert element in heap."
},
{
"code": null,
"e": 1490,
"s": 1402,
"text": "void BHeap::DeleteMin(): Perform deleteion operation to delete minimum value from heap."
},
{
"code": null,
"e": 1569,
"s": 1490,
"text": "int BHeap::ExtractMin(): Perfrom operation to extract minimum value from heap."
},
{
"code": null,
"e": 1623,
"s": 1569,
"text": "void BHeap::showHeap(): To show the elements of heap."
},
{
"code": null,
"e": 1699,
"s": 1623,
"text": "void BHeap::heapifyup(int in): maintain heap structure in bottom up manner."
},
{
"code": null,
"e": 1776,
"s": 1699,
"text": "void BHeap::heapifydown(int in): maintain heap structure in top down manner."
},
{
"code": null,
"e": 5135,
"s": 1776,
"text": "#include <iostream>\n#include <cstdlib>\n#include <vector>\n#include <iterator>\nusing namespace std;\nclass BHeap {\n private:\n vector <int> heap;\n int l(int parent);\n int r(int parent);\n int par(int child);\n void heapifyup(int in);\n void heapifydown(int in);\n public:\n BHeap()\n {}\n void Insert(int element);\n void DeleteMin();\n int ExtractMin();\n void showHeap();\n int Size();\n}; \nint main() {\n BHeap h;\n while (1) {\n cout<<\"1.Insert Element\"<<endl;\n cout<<\"2.Delete Minimum Element\"<<endl;\n cout<<\"3.Extract Minimum Element\"<<endl;\n cout<<\"4.Show Heap\"<<endl;\n cout<<\"5.Exit\"<<endl;\n int c, e;\n cout<<\"Enter your choice: \";\n cin>>c;\n switch(c) {\n case 1:\n cout<<\"Enter the element to be inserted: \";\n cin>>e;\n h.Insert(e);\n break;\n case 2:\n h.DeleteMin();\n break;\n case 3:\n if (h.ExtractMin() == -1) {\n cout<<\"Heap is Empty\"<<endl;\n }\n else\n cout<<\"Minimum Element: \"<<h.ExtractMin()<<endl;\n break;\n case 4:\n cout<<\"Displaying elements of Hwap: \";\n h.showHeap();\n break;\n case 5:\n exit(1);\n default:\n cout<<\"Enter Correct Choice\"<<endl;\n } \n }\n return 0;\n}\nint BHeap::Size() //size of heap {\n return heap.size();\n}\nvoid BHeap::Insert(int ele) //insert element in heap {\n heap.push_back(ele);//push element into the heap\n heapifyup(heap.size() -1);//call heapifyup() to maintain heap structure\n}\nvoid BHeap::DeleteMin() //delete minimum value from heap {\n if (heap.size() == 0) {\n cout<<\"Heap is Empty\"<<endl;\n return;\n }\n heap[0] = heap.at(heap.size() - 1);\n heap.pop_back();//pop element\n heapifydown(0);\n cout<<\"Element Deleted\"<<endl;\n}\nint BHeap::ExtractMin() //extract minimum value from heap\n{\n if (heap.size() == 0) {\n return -1;\n }\n else\n return heap.front();\n}\nvoid BHeap::showHeap() //show the elements of heap {\n vector <int>::iterator pos = heap.begin();\n cout<<\"Heap --> \";\n while (pos != heap.end()) {\n cout<<*pos<<\" \";\n pos++;\n }\n cout<<endl;\n}\nint BHeap::l(int parent) // return left child of node.\n{\n int l = 2 * parent + 1;\n if (l < heap.size())\n return l;\n else\n return -1;\n}\nint BHeap::r(int parent) // return right child of node.\n{\n int r = 2 * parent + 2;\n if (r < heap.size())\n return r;\n else\n return -1;\n}\nint BHeap::par(int child)// return parent\n{\n int p = (child - 1)/2;\n if (child == 0)\n return -1;\n else\n return p;\n}\nvoid BHeap::heapifyup(int in)//maintain heap structure in bottom up manner.\n{\n if (in >= 0 && par(in) >= 0 && heap[par(in)] > heap[in]) {\n int temp = heap[in];\n heap[in] = heap[par(in)];\n heap[par(in)] = temp;\n heapifyup(par(in));\n }\n}\nvoid BHeap::heapifydown(int in)//maintain heap structure in top down manner.\n{\n int child = l(in);\n int child1 = r(in);\n if (child >= 0 && child1 >= 0 && heap[child] > heap[child1]) {\n child = child1;\n }\n if (child > 0 && heap[in] > heap[child]) {\n int t = heap[in];\n heap[in] = heap[child];\n heap[child] = t;\n heapifydown(child);\n }\n}"
},
{
"code": null,
"e": 6503,
"s": 5135,
"text": "1.Insert Element\n2.Delete Minimum Element\n3.Extract Minimum Element\n4.Show Heap\n5.Exit\nEnter your choice: 1\nEnter the element to be inserted: 2\n1.Insert Element\n2.Delete Minimum Element\n3.Extract Minimum Element\n4.Show Heap\n5.Exit\nEnter your choice: 1\nEnter the element to be inserted: 3\n1.Insert Element\n2.Delete Minimum Element\n3.Extract Minimum Element\n4.Show Heap\n5.Exit\nEnter your choice: 1\nEnter the element to be inserted: 7\n1.Insert Element\n2.Delete Minimum Element\n3.Extract Minimum Element\n4.Show Heap\n5.Exit\nEnter your choice: 1\nEnter the element to be inserted: 6\n1.Insert Element\n2.Delete Minimum Element\n3.Extract Minimum Element\n4.Show Heap\n5.Exit\nEnter your choice: 4\nDisplaying elements of Hwap: Heap --> 2 3 7 6\n1.Insert Element\n2.Delete Minimum Element\n3.Extract Minimum Element\n4.Show Heap\n5.Exit\nEnter your choice: 3\nMinimum Element: 2\n1.Insert Element\n2.Delete Minimum Element\n3.Extract Minimum Element\n4.Show Heap\n5.Exit\nEnter your choice: 3\nMinimum Element: 2\n1.Insert Element\n2.Delete Minimum Element\n3.Extract Minimum Element\n4.Show Heap\n5.Exit\nEnter your choice: 2\nElement Deleted\n1.Insert Element\n2.Delete Minimum Element\n3.Extract Minimum Element\n4.Show Heap\n5.Exit\nEnter your choice: 4\nDisplaying elements of Hwap: Heap --> 3 6 7\n1.Insert Element\n2.Delete Minimum Element\n3.Extract Minimum Element\n4.Show Heap\n5.Exit\nEnter your choice: 5"
}
] |
Practical Statistics & Visualization With Python & Plotly | by Susan Li | Towards Data Science | One day last week, I was googling “statistics with Python”, the results were somewhat unfruitful. Most literature, tutorials and articles focus on statistics with R, because R is a language dedicated to statistics and has more statistical analysis features than Python.
In two excellent statistics books, “Practical Statistics for Data Scientists” and “An Introduction to Statistical Learning”, the statistical concepts were all implemented in R.
Data science is a fusion of multiple disciplines, including statistics, computer science, information technology, and domain-specific fields. And we use powerful, open-source Python tools daily to manipulate, analyze, and visualize datasets.
And I would certainly recommend anyone interested in becoming a Data Scientist or Machine Learning Engineer to develop a deep understanding and practice constantly on statistical learning theories.
This prompts me to write a post for the subject. And I will use one dataset to review as many statistics concepts as I can and lets get started!
The data is the house prices data set that can be found here.
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsfrom plotly.offline import init_notebook_mode, iplotimport plotly.figure_factory as ffimport cufflinkscufflinks.go_offline()cufflinks.set_config_file(world_readable=True, theme='pearl')import plotly.graph_objs as goimport plotly.plotly as pyimport plotlyfrom plotly import toolsplotly.tools.set_credentials_file(username='XXX', api_key='XXX')init_notebook_mode(connected=True)pd.set_option('display.max_columns', 100)df = pd.read_csv('house_train.csv')df.drop('Id', axis=1, inplace=True)df.head()
Univariate analysis is perhaps the simplest form of statistical analysis, and the key fact is that only one variable is involved.
Statistical summary for numeric data include things like the mean, min, and max of the data, can be useful to get a feel for how large some of the variables are and what variables may be the most important.
df.describe().T
Statistical summary for categorical or string variables will show “count”, “unique”, “top”, and “freq”.
table_cat = ff.create_table(df.describe(include=['O']).T, index=True, index_title='Categorical columns')iplot(table_cat)
Plot a histogram of SalePrice of all the houses in the data.
df['SalePrice'].iplot( kind='hist', bins=100, xTitle='price', linecolor='black', yTitle='count', title='Histogram of Sale Price')
Plot a boxplot of SalePrice of all the houses in the data. Boxplots do not show the shape of the distribution, but they can give us a better idea about the center and spread of the distribution as well as any potential outliers that may exist. Boxplots and Histograms often complement each other and help us understand more about the data.
df['SalePrice'].iplot(kind='box', title='Box plot of SalePrice')
Plotting by groups, we can see how a variable changes in response to another. For example, if there is a difference between house SalePrice with or with no central air conditioning. Or if house SalePrice varies according to the size of the garage, and so on.
df.groupby('CentralAir')['SalePrice'].describe()
It is obviously that the mean and median sale price for houses with no air conditioning are much lower than the houses with air conditioning.
The larger the garage, the higher house median price, this works until we reach 3-cars garage. Apparently, the houses with 3-cars garages have the highest median price, even higher than the houses with 4-cars garage.
df.loc[df['GarageCars'] == 0]['SalePrice'].iplot( kind='hist', bins=50, xTitle='price', linecolor='black', yTitle='count', title='Histogram of Sale Price of houses with no garage')
df.loc[df['GarageCars'] == 1]['SalePrice'].iplot( kind='hist', bins=50, xTitle='price', linecolor='black', yTitle='count', title='Histogram of Sale Price of houses with 1-car garage')
df.loc[df['GarageCars'] == 2]['SalePrice'].iplot( kind='hist', bins=100, xTitle='price', linecolor='black', yTitle='count', title='Histogram of Sale Price of houses with 2-car garage')
df.loc[df['GarageCars'] == 3]['SalePrice'].iplot( kind='hist', bins=50, xTitle='price', linecolor='black', yTitle='count', title='Histogram of Sale Price of houses with 3-car garage')
df.loc[df['GarageCars'] == 4]['SalePrice'].iplot( kind='hist', bins=10, xTitle='price', linecolor='black', yTitle='count', title='Histogram of Sale Price of houses with 4-car garage')
Frequency tells us how often something happened. Frequency tables give us a snapshot of the data to allow us to find patterns.
x = df.OverallQual.value_counts()x/x.sum()
x = df.GarageCars.value_counts()x/x.sum()
x = df.CentralAir.value_counts()x/x.sum()
A quick way to get a set of numerical summaries for a quantitative variable is to use the describe method.
df.SalePrice.describe()
We can also calculate individual summary statistics of SalePrice.
print("The mean of sale price, - Pandas method: ", df.SalePrice.mean())print("The mean of sale price, - Numpy function: ", np.mean(df.SalePrice))print("The median sale price: ", df.SalePrice.median())print("50th percentile, same as the median: ", np.percentile(df.SalePrice, 50))print("75th percentile: ", np.percentile(df.SalePrice, 75))print("Pandas method for quantiles, equivalent to 75th percentile: ", df.SalePrice.quantile(0.75))
Calculate the proportion of the houses with sale price between 25th percentile (129975) and 75th percentile (214000).
print('The proportion of the houses with prices between 25th percentile and 75th percentile: ', np.mean((df.SalePrice >= 129975) & (df.SalePrice <= 214000)))
Calculate the proportion of the houses with total square feet of basement area between 25th percentile (795.75) and 75th percentile (1298.25).
print('The proportion of house with total square feet of basement area between 25th percentile and 75th percentile: ', np.mean((df.TotalBsmtSF >= 795.75) & (df.TotalBsmtSF <= 1298.25)))
Lastly, we calculate the proportion of the houses based on either conditions. Since some houses are under both criteria, the proportion below is less than the sum of the two proportions calculated above.
a = (df.SalePrice >= 129975) & (df.SalePrice <= 214000)b = (df.TotalBsmtSF >= 795.75) & (df.TotalBsmtSF <= 1298.25)print(np.mean(a | b))
Calculate sale price IQR for houses with no air conditioning.
q75, q25 = np.percentile(df.loc[df['CentralAir']=='N']['SalePrice'], [75,25])iqr = q75 - q25print('Sale price IQR for houses with no air conditioning: ', iqr)
Calculate sale price IQR for houses with air conditioning.
q75, q25 = np.percentile(df.loc[df['CentralAir']=='Y']['SalePrice'], [75,25])iqr = q75 - q25print('Sale price IQR for houses with air conditioning: ', iqr)
Another way to get more information out of a dataset is to divide it into smaller, more uniform subsets, and analyze each of these “strata” on its own. We will create a new HouseAge column, then partition the data into HouseAge strata, and construct side-by-side boxplots of the sale price within each stratum.
df['HouseAge'] = 2019 - df['YearBuilt']df["AgeGrp"] = pd.cut(df.HouseAge, [9, 20, 40, 60, 80, 100, 147]) # Create age strata based on these cut pointsplt.figure(figsize=(12, 5)) sns.boxplot(x="AgeGrp", y="SalePrice", data=df);
The older the house, the lower the median price, that is, house price tends to decrease with age, until it reaches 100 years old. The median price of over 100 year old houses is higher than the median price of houses age between 80 and 100 years.
plt.figure(figsize=(12, 5))sns.boxplot(x="AgeGrp", y="SalePrice", hue="CentralAir", data=df)plt.show();
We have learned earlier that house price tends to differ between with and with no air conditioning. From above graph, we also find out that recent houses (9–40 years old) are all equipped with air conditioning.
plt.figure(figsize=(12, 5))sns.boxplot(x="CentralAir", y="SalePrice", hue="AgeGrp", data=df)plt.show();
We now group first by air conditioning, and then within air conditioning group by age bands. Each approach highlights a different aspect of the data.
We can also stratify jointly by House age and air conditioning to explore how building type varies by both of these factors simultaneously.
df1 = df.groupby(["AgeGrp", "CentralAir"])["BldgType"]df1 = df1.value_counts()df1 = df1.unstack()df1 = df1.apply(lambda x: x/x.sum(), axis=1)print(df1.to_string(float_format="%.3f"))
For all house age groups, vast majority type of dwelling in the data is 1Fam. The older the house, the more likely to have no air conditioning. However, for a 1Fam house over 100 years old, it is a little more likely to have air conditioning than not. There were neither very new nor very old duplex house types. For a 40–60 year old duplex house, it is more likely to have no air conditioning.
Multivariate analysis is based on the statistical principle of multivariate statistics, which involves observation and analysis of more than one statistical outcome variable at a time.
A scatter plot is a very common and easily-understood visualization of quantitative bivariate data. Below we make a scatter plot of Sale Price against Above ground living area square feet. it is apparently a linear relationship.
df.iplot( x='GrLivArea', y='SalePrice', xTitle='Above ground living area square feet', yTitle='Sale price', mode='markers', title='Sale Price vs Above ground living area square feet')
The following two plot margins show the densities for the Sale Price and Above ground living area separately, while the plot in the center shows their density jointly.
We continue exploring the relationship between SalePrice and GrLivArea, stratifying by BldgType.
In almost all the building types, SalePrice and GrLivArea shows a positive linear relationship. In the results below, we see that the correlation between SalepPrice and GrLivArea in 1Fam building type is the highest at 0.74, while in Duplex building type the correlation is the lowest at 0.49.
print(df.loc[df.BldgType=="1Fam", ["GrLivArea", "SalePrice"]].corr())print(df.loc[df.BldgType=="TwnhsE", ["GrLivArea", "SalePrice"]].corr())print(df.loc[df.BldgType=='Duplex', ["GrLivArea", "SalePrice"]].corr())print(df.loc[df.BldgType=="Twnhs", ["GrLivArea", "SalePrice"]].corr())print(df.loc[df.BldgType=="2fmCon", ["GrLivArea", "SalePrice"]].corr())
We create a contingency table, counting the number of houses in each cell defined by a combination of building type and the general zoning classification.
x = pd.crosstab(df.MSZoning, df.BldgType)x
Below we normalize within rows. This gives us the proportion of houses in each zoning classification that fall into each building type variable.
x.apply(lambda z: z/z.sum(), axis=1)
We can also normalize within the columns. This gives us the proportion of houses within each building type that fall into each zoning classification.
x.apply(lambda z: z/z.sum(), axis=0)
One step further, we will look at the proportion of houses in each zoning class, for each combination of the air conditioning and building type variables.
df.groupby(["CentralAir", "BldgType", "MSZoning"]).size().unstack().fillna(0).apply(lambda x: x/x.sum(), axis=1)
The highest proportion of houses in the data are the ones with zoning RL, with air conditioning and 1Fam building type. With no air conditioning, the highest proportion of houses are the ones in zoning RL and Duplex building type.
To get fancier, we are going to plot a violin plot to show the distribution of SalePrice for houses that are in each building type category.
We can see that the SalesPrice distribution of 1Fam building type are slightly right-skewed, and for the other building types, the SalePrice distributions are nearly normal.
Jupyter notebook for this post can be found on Github, and there is an nbviewer version as well. | [
{
"code": null,
"e": 442,
"s": 172,
"text": "One day last week, I was googling “statistics with Python”, the results were somewhat unfruitful. Most literature, tutorials and articles focus on statistics with R, because R is a language dedicated to statistics and has more statistical analysis features than Python."
},
{
"code": null,
"e": 619,
"s": 442,
"text": "In two excellent statistics books, “Practical Statistics for Data Scientists” and “An Introduction to Statistical Learning”, the statistical concepts were all implemented in R."
},
{
"code": null,
"e": 861,
"s": 619,
"text": "Data science is a fusion of multiple disciplines, including statistics, computer science, information technology, and domain-specific fields. And we use powerful, open-source Python tools daily to manipulate, analyze, and visualize datasets."
},
{
"code": null,
"e": 1059,
"s": 861,
"text": "And I would certainly recommend anyone interested in becoming a Data Scientist or Machine Learning Engineer to develop a deep understanding and practice constantly on statistical learning theories."
},
{
"code": null,
"e": 1204,
"s": 1059,
"text": "This prompts me to write a post for the subject. And I will use one dataset to review as many statistics concepts as I can and lets get started!"
},
{
"code": null,
"e": 1266,
"s": 1204,
"text": "The data is the house prices data set that can be found here."
},
{
"code": null,
"e": 1852,
"s": 1266,
"text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsfrom plotly.offline import init_notebook_mode, iplotimport plotly.figure_factory as ffimport cufflinkscufflinks.go_offline()cufflinks.set_config_file(world_readable=True, theme='pearl')import plotly.graph_objs as goimport plotly.plotly as pyimport plotlyfrom plotly import toolsplotly.tools.set_credentials_file(username='XXX', api_key='XXX')init_notebook_mode(connected=True)pd.set_option('display.max_columns', 100)df = pd.read_csv('house_train.csv')df.drop('Id', axis=1, inplace=True)df.head()"
},
{
"code": null,
"e": 1982,
"s": 1852,
"text": "Univariate analysis is perhaps the simplest form of statistical analysis, and the key fact is that only one variable is involved."
},
{
"code": null,
"e": 2189,
"s": 1982,
"text": "Statistical summary for numeric data include things like the mean, min, and max of the data, can be useful to get a feel for how large some of the variables are and what variables may be the most important."
},
{
"code": null,
"e": 2205,
"s": 2189,
"text": "df.describe().T"
},
{
"code": null,
"e": 2309,
"s": 2205,
"text": "Statistical summary for categorical or string variables will show “count”, “unique”, “top”, and “freq”."
},
{
"code": null,
"e": 2430,
"s": 2309,
"text": "table_cat = ff.create_table(df.describe(include=['O']).T, index=True, index_title='Categorical columns')iplot(table_cat)"
},
{
"code": null,
"e": 2491,
"s": 2430,
"text": "Plot a histogram of SalePrice of all the houses in the data."
},
{
"code": null,
"e": 2639,
"s": 2491,
"text": "df['SalePrice'].iplot( kind='hist', bins=100, xTitle='price', linecolor='black', yTitle='count', title='Histogram of Sale Price')"
},
{
"code": null,
"e": 2979,
"s": 2639,
"text": "Plot a boxplot of SalePrice of all the houses in the data. Boxplots do not show the shape of the distribution, but they can give us a better idea about the center and spread of the distribution as well as any potential outliers that may exist. Boxplots and Histograms often complement each other and help us understand more about the data."
},
{
"code": null,
"e": 3044,
"s": 2979,
"text": "df['SalePrice'].iplot(kind='box', title='Box plot of SalePrice')"
},
{
"code": null,
"e": 3303,
"s": 3044,
"text": "Plotting by groups, we can see how a variable changes in response to another. For example, if there is a difference between house SalePrice with or with no central air conditioning. Or if house SalePrice varies according to the size of the garage, and so on."
},
{
"code": null,
"e": 3352,
"s": 3303,
"text": "df.groupby('CentralAir')['SalePrice'].describe()"
},
{
"code": null,
"e": 3494,
"s": 3352,
"text": "It is obviously that the mean and median sale price for houses with no air conditioning are much lower than the houses with air conditioning."
},
{
"code": null,
"e": 3711,
"s": 3494,
"text": "The larger the garage, the higher house median price, this works until we reach 3-cars garage. Apparently, the houses with 3-cars garages have the highest median price, even higher than the houses with 4-cars garage."
},
{
"code": null,
"e": 3910,
"s": 3711,
"text": "df.loc[df['GarageCars'] == 0]['SalePrice'].iplot( kind='hist', bins=50, xTitle='price', linecolor='black', yTitle='count', title='Histogram of Sale Price of houses with no garage')"
},
{
"code": null,
"e": 4112,
"s": 3910,
"text": "df.loc[df['GarageCars'] == 1]['SalePrice'].iplot( kind='hist', bins=50, xTitle='price', linecolor='black', yTitle='count', title='Histogram of Sale Price of houses with 1-car garage')"
},
{
"code": null,
"e": 4315,
"s": 4112,
"text": "df.loc[df['GarageCars'] == 2]['SalePrice'].iplot( kind='hist', bins=100, xTitle='price', linecolor='black', yTitle='count', title='Histogram of Sale Price of houses with 2-car garage')"
},
{
"code": null,
"e": 4517,
"s": 4315,
"text": "df.loc[df['GarageCars'] == 3]['SalePrice'].iplot( kind='hist', bins=50, xTitle='price', linecolor='black', yTitle='count', title='Histogram of Sale Price of houses with 3-car garage')"
},
{
"code": null,
"e": 4719,
"s": 4517,
"text": "df.loc[df['GarageCars'] == 4]['SalePrice'].iplot( kind='hist', bins=10, xTitle='price', linecolor='black', yTitle='count', title='Histogram of Sale Price of houses with 4-car garage')"
},
{
"code": null,
"e": 4846,
"s": 4719,
"text": "Frequency tells us how often something happened. Frequency tables give us a snapshot of the data to allow us to find patterns."
},
{
"code": null,
"e": 4889,
"s": 4846,
"text": "x = df.OverallQual.value_counts()x/x.sum()"
},
{
"code": null,
"e": 4931,
"s": 4889,
"text": "x = df.GarageCars.value_counts()x/x.sum()"
},
{
"code": null,
"e": 4973,
"s": 4931,
"text": "x = df.CentralAir.value_counts()x/x.sum()"
},
{
"code": null,
"e": 5080,
"s": 4973,
"text": "A quick way to get a set of numerical summaries for a quantitative variable is to use the describe method."
},
{
"code": null,
"e": 5104,
"s": 5080,
"text": "df.SalePrice.describe()"
},
{
"code": null,
"e": 5170,
"s": 5104,
"text": "We can also calculate individual summary statistics of SalePrice."
},
{
"code": null,
"e": 5607,
"s": 5170,
"text": "print(\"The mean of sale price, - Pandas method: \", df.SalePrice.mean())print(\"The mean of sale price, - Numpy function: \", np.mean(df.SalePrice))print(\"The median sale price: \", df.SalePrice.median())print(\"50th percentile, same as the median: \", np.percentile(df.SalePrice, 50))print(\"75th percentile: \", np.percentile(df.SalePrice, 75))print(\"Pandas method for quantiles, equivalent to 75th percentile: \", df.SalePrice.quantile(0.75))"
},
{
"code": null,
"e": 5725,
"s": 5607,
"text": "Calculate the proportion of the houses with sale price between 25th percentile (129975) and 75th percentile (214000)."
},
{
"code": null,
"e": 5883,
"s": 5725,
"text": "print('The proportion of the houses with prices between 25th percentile and 75th percentile: ', np.mean((df.SalePrice >= 129975) & (df.SalePrice <= 214000)))"
},
{
"code": null,
"e": 6026,
"s": 5883,
"text": "Calculate the proportion of the houses with total square feet of basement area between 25th percentile (795.75) and 75th percentile (1298.25)."
},
{
"code": null,
"e": 6212,
"s": 6026,
"text": "print('The proportion of house with total square feet of basement area between 25th percentile and 75th percentile: ', np.mean((df.TotalBsmtSF >= 795.75) & (df.TotalBsmtSF <= 1298.25)))"
},
{
"code": null,
"e": 6416,
"s": 6212,
"text": "Lastly, we calculate the proportion of the houses based on either conditions. Since some houses are under both criteria, the proportion below is less than the sum of the two proportions calculated above."
},
{
"code": null,
"e": 6553,
"s": 6416,
"text": "a = (df.SalePrice >= 129975) & (df.SalePrice <= 214000)b = (df.TotalBsmtSF >= 795.75) & (df.TotalBsmtSF <= 1298.25)print(np.mean(a | b))"
},
{
"code": null,
"e": 6615,
"s": 6553,
"text": "Calculate sale price IQR for houses with no air conditioning."
},
{
"code": null,
"e": 6774,
"s": 6615,
"text": "q75, q25 = np.percentile(df.loc[df['CentralAir']=='N']['SalePrice'], [75,25])iqr = q75 - q25print('Sale price IQR for houses with no air conditioning: ', iqr)"
},
{
"code": null,
"e": 6833,
"s": 6774,
"text": "Calculate sale price IQR for houses with air conditioning."
},
{
"code": null,
"e": 6989,
"s": 6833,
"text": "q75, q25 = np.percentile(df.loc[df['CentralAir']=='Y']['SalePrice'], [75,25])iqr = q75 - q25print('Sale price IQR for houses with air conditioning: ', iqr)"
},
{
"code": null,
"e": 7300,
"s": 6989,
"text": "Another way to get more information out of a dataset is to divide it into smaller, more uniform subsets, and analyze each of these “strata” on its own. We will create a new HouseAge column, then partition the data into HouseAge strata, and construct side-by-side boxplots of the sale price within each stratum."
},
{
"code": null,
"e": 7527,
"s": 7300,
"text": "df['HouseAge'] = 2019 - df['YearBuilt']df[\"AgeGrp\"] = pd.cut(df.HouseAge, [9, 20, 40, 60, 80, 100, 147]) # Create age strata based on these cut pointsplt.figure(figsize=(12, 5)) sns.boxplot(x=\"AgeGrp\", y=\"SalePrice\", data=df);"
},
{
"code": null,
"e": 7774,
"s": 7527,
"text": "The older the house, the lower the median price, that is, house price tends to decrease with age, until it reaches 100 years old. The median price of over 100 year old houses is higher than the median price of houses age between 80 and 100 years."
},
{
"code": null,
"e": 7878,
"s": 7774,
"text": "plt.figure(figsize=(12, 5))sns.boxplot(x=\"AgeGrp\", y=\"SalePrice\", hue=\"CentralAir\", data=df)plt.show();"
},
{
"code": null,
"e": 8089,
"s": 7878,
"text": "We have learned earlier that house price tends to differ between with and with no air conditioning. From above graph, we also find out that recent houses (9–40 years old) are all equipped with air conditioning."
},
{
"code": null,
"e": 8193,
"s": 8089,
"text": "plt.figure(figsize=(12, 5))sns.boxplot(x=\"CentralAir\", y=\"SalePrice\", hue=\"AgeGrp\", data=df)plt.show();"
},
{
"code": null,
"e": 8343,
"s": 8193,
"text": "We now group first by air conditioning, and then within air conditioning group by age bands. Each approach highlights a different aspect of the data."
},
{
"code": null,
"e": 8483,
"s": 8343,
"text": "We can also stratify jointly by House age and air conditioning to explore how building type varies by both of these factors simultaneously."
},
{
"code": null,
"e": 8666,
"s": 8483,
"text": "df1 = df.groupby([\"AgeGrp\", \"CentralAir\"])[\"BldgType\"]df1 = df1.value_counts()df1 = df1.unstack()df1 = df1.apply(lambda x: x/x.sum(), axis=1)print(df1.to_string(float_format=\"%.3f\"))"
},
{
"code": null,
"e": 9061,
"s": 8666,
"text": "For all house age groups, vast majority type of dwelling in the data is 1Fam. The older the house, the more likely to have no air conditioning. However, for a 1Fam house over 100 years old, it is a little more likely to have air conditioning than not. There were neither very new nor very old duplex house types. For a 40–60 year old duplex house, it is more likely to have no air conditioning."
},
{
"code": null,
"e": 9246,
"s": 9061,
"text": "Multivariate analysis is based on the statistical principle of multivariate statistics, which involves observation and analysis of more than one statistical outcome variable at a time."
},
{
"code": null,
"e": 9475,
"s": 9246,
"text": "A scatter plot is a very common and easily-understood visualization of quantitative bivariate data. Below we make a scatter plot of Sale Price against Above ground living area square feet. it is apparently a linear relationship."
},
{
"code": null,
"e": 9677,
"s": 9475,
"text": "df.iplot( x='GrLivArea', y='SalePrice', xTitle='Above ground living area square feet', yTitle='Sale price', mode='markers', title='Sale Price vs Above ground living area square feet')"
},
{
"code": null,
"e": 9845,
"s": 9677,
"text": "The following two plot margins show the densities for the Sale Price and Above ground living area separately, while the plot in the center shows their density jointly."
},
{
"code": null,
"e": 9942,
"s": 9845,
"text": "We continue exploring the relationship between SalePrice and GrLivArea, stratifying by BldgType."
},
{
"code": null,
"e": 10236,
"s": 9942,
"text": "In almost all the building types, SalePrice and GrLivArea shows a positive linear relationship. In the results below, we see that the correlation between SalepPrice and GrLivArea in 1Fam building type is the highest at 0.74, while in Duplex building type the correlation is the lowest at 0.49."
},
{
"code": null,
"e": 10589,
"s": 10236,
"text": "print(df.loc[df.BldgType==\"1Fam\", [\"GrLivArea\", \"SalePrice\"]].corr())print(df.loc[df.BldgType==\"TwnhsE\", [\"GrLivArea\", \"SalePrice\"]].corr())print(df.loc[df.BldgType=='Duplex', [\"GrLivArea\", \"SalePrice\"]].corr())print(df.loc[df.BldgType==\"Twnhs\", [\"GrLivArea\", \"SalePrice\"]].corr())print(df.loc[df.BldgType==\"2fmCon\", [\"GrLivArea\", \"SalePrice\"]].corr())"
},
{
"code": null,
"e": 10744,
"s": 10589,
"text": "We create a contingency table, counting the number of houses in each cell defined by a combination of building type and the general zoning classification."
},
{
"code": null,
"e": 10787,
"s": 10744,
"text": "x = pd.crosstab(df.MSZoning, df.BldgType)x"
},
{
"code": null,
"e": 10932,
"s": 10787,
"text": "Below we normalize within rows. This gives us the proportion of houses in each zoning classification that fall into each building type variable."
},
{
"code": null,
"e": 10969,
"s": 10932,
"text": "x.apply(lambda z: z/z.sum(), axis=1)"
},
{
"code": null,
"e": 11119,
"s": 10969,
"text": "We can also normalize within the columns. This gives us the proportion of houses within each building type that fall into each zoning classification."
},
{
"code": null,
"e": 11156,
"s": 11119,
"text": "x.apply(lambda z: z/z.sum(), axis=0)"
},
{
"code": null,
"e": 11311,
"s": 11156,
"text": "One step further, we will look at the proportion of houses in each zoning class, for each combination of the air conditioning and building type variables."
},
{
"code": null,
"e": 11424,
"s": 11311,
"text": "df.groupby([\"CentralAir\", \"BldgType\", \"MSZoning\"]).size().unstack().fillna(0).apply(lambda x: x/x.sum(), axis=1)"
},
{
"code": null,
"e": 11655,
"s": 11424,
"text": "The highest proportion of houses in the data are the ones with zoning RL, with air conditioning and 1Fam building type. With no air conditioning, the highest proportion of houses are the ones in zoning RL and Duplex building type."
},
{
"code": null,
"e": 11796,
"s": 11655,
"text": "To get fancier, we are going to plot a violin plot to show the distribution of SalePrice for houses that are in each building type category."
},
{
"code": null,
"e": 11970,
"s": 11796,
"text": "We can see that the SalesPrice distribution of 1Fam building type are slightly right-skewed, and for the other building types, the SalePrice distributions are nearly normal."
}
] |
PHP | similar_text() Function - GeeksforGeeks | 23 Mar, 2018
The similar_text() function is a built-in function in PHP. This function calculates the similarity of two strings and returns the number of matching characters in the two strings. The function operates by finding the longest first common sub-string, and repeating this for the prefixes and the suffixes, recursively. The sum of lengths of all the common sub-strings is returned.
It can also calculate the similarity of the two strings in percent. The function calculates the similarity in percent, by dividing the result by the average of the lengths of the given strings times 100.
Syntax :
similar_text( $string1, $string2, $percent)
Parameters: This function accepts three parameters as shown in the above syntax out of which first two must be supplied and last one is optional. All of these parameters are described below:
$string1, $string2 : These mandatory parameters specify the two strings to be compared
$percent : This parameter is optional. It specifies a variable name for storing the similarity in percent. By passing a reference as third argument, the function will calculate the similarity in percentage.
Return Value : It returns the number of matching characters between the two strings.
Examples:
Input : $string1 = "code", $string2 = "coders"
Output : 4 (80 %)
Input : $string1 = "hackers", $string2 = "hackathons"
Output : 5 (58.823529411765 %)
Below programs illustrate the similar_text() function:
Program 1 :
<?php $sim = similar_text("hackers", "hackathons", $percent); // To display the number of matching charactersecho "Number of similar characters : $sim\n"; // To display the percentage of matching charactersecho "Percentage of similar characters : $percent\n"; ?>
Output
Number of similar characters : 5
Percentage of similar characters : 58.823529411765>
Program 2 : This program will highlight the case-sensitivity of the function.
<?php $output = similar_text("geeks for geeks", "Geeks for Geeks", $percent); // To display the number of matching charactersecho "Number of similar characters : $output\n"; // To display the percentage of matching charactersecho "Percentage of similar characters : $percent\n"; ?>
Output:
Number of similar characters : 13
Percentage of similar characters : 86.666666666667
Program 3: The order of passing the strings is very important. Altering the variables will give a different result.
<?php $output1 = similar_text("with mysql", "php is best"); // To display the number of matching charactersecho "Number of similar characters : $output1\n"; $output2 = similar_text( "php is best", "with mysql"); // To display the number of matching charactersecho "Number of similar characters : $output2\n"; ?>
Output:
Number of similar characters : 2
Number of similar characters : 3
Reference:http://php.net/manual/en/function.similar-text.php
PHP-string
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to fetch data from localserver database and display on HTML table using PHP ?
How to pass form variables from one page to other page in PHP ?
Create a drop-down list that options fetched from a MySQL database in PHP
How to create admin login page using PHP?
Different ways for passing data to view in Laravel
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24581,
"s": 24553,
"text": "\n23 Mar, 2018"
},
{
"code": null,
"e": 24960,
"s": 24581,
"text": "The similar_text() function is a built-in function in PHP. This function calculates the similarity of two strings and returns the number of matching characters in the two strings. The function operates by finding the longest first common sub-string, and repeating this for the prefixes and the suffixes, recursively. The sum of lengths of all the common sub-strings is returned."
},
{
"code": null,
"e": 25164,
"s": 24960,
"text": "It can also calculate the similarity of the two strings in percent. The function calculates the similarity in percent, by dividing the result by the average of the lengths of the given strings times 100."
},
{
"code": null,
"e": 25173,
"s": 25164,
"text": "Syntax :"
},
{
"code": null,
"e": 25217,
"s": 25173,
"text": "similar_text( $string1, $string2, $percent)"
},
{
"code": null,
"e": 25408,
"s": 25217,
"text": "Parameters: This function accepts three parameters as shown in the above syntax out of which first two must be supplied and last one is optional. All of these parameters are described below:"
},
{
"code": null,
"e": 25495,
"s": 25408,
"text": "$string1, $string2 : These mandatory parameters specify the two strings to be compared"
},
{
"code": null,
"e": 25702,
"s": 25495,
"text": "$percent : This parameter is optional. It specifies a variable name for storing the similarity in percent. By passing a reference as third argument, the function will calculate the similarity in percentage."
},
{
"code": null,
"e": 25787,
"s": 25702,
"text": "Return Value : It returns the number of matching characters between the two strings."
},
{
"code": null,
"e": 25797,
"s": 25787,
"text": "Examples:"
},
{
"code": null,
"e": 25949,
"s": 25797,
"text": "Input : $string1 = \"code\", $string2 = \"coders\"\nOutput : 4 (80 %)\n\nInput : $string1 = \"hackers\", $string2 = \"hackathons\"\nOutput : 5 (58.823529411765 %)\n"
},
{
"code": null,
"e": 26004,
"s": 25949,
"text": "Below programs illustrate the similar_text() function:"
},
{
"code": null,
"e": 26016,
"s": 26004,
"text": "Program 1 :"
},
{
"code": "<?php $sim = similar_text(\"hackers\", \"hackathons\", $percent); // To display the number of matching charactersecho \"Number of similar characters : $sim\\n\"; // To display the percentage of matching charactersecho \"Percentage of similar characters : $percent\\n\"; ?>",
"e": 26283,
"s": 26016,
"text": null
},
{
"code": null,
"e": 26290,
"s": 26283,
"text": "Output"
},
{
"code": null,
"e": 26376,
"s": 26290,
"text": "Number of similar characters : 5\nPercentage of similar characters : 58.823529411765>\n"
},
{
"code": null,
"e": 26454,
"s": 26376,
"text": "Program 2 : This program will highlight the case-sensitivity of the function."
},
{
"code": "<?php $output = similar_text(\"geeks for geeks\", \"Geeks for Geeks\", $percent); // To display the number of matching charactersecho \"Number of similar characters : $output\\n\"; // To display the percentage of matching charactersecho \"Percentage of similar characters : $percent\\n\"; ?>",
"e": 26757,
"s": 26454,
"text": null
},
{
"code": null,
"e": 26765,
"s": 26757,
"text": "Output:"
},
{
"code": null,
"e": 26851,
"s": 26765,
"text": "Number of similar characters : 13\nPercentage of similar characters : 86.666666666667\n"
},
{
"code": null,
"e": 26967,
"s": 26851,
"text": "Program 3: The order of passing the strings is very important. Altering the variables will give a different result."
},
{
"code": "<?php $output1 = similar_text(\"with mysql\", \"php is best\"); // To display the number of matching charactersecho \"Number of similar characters : $output1\\n\"; $output2 = similar_text( \"php is best\", \"with mysql\"); // To display the number of matching charactersecho \"Number of similar characters : $output2\\n\"; ?>",
"e": 27284,
"s": 26967,
"text": null
},
{
"code": null,
"e": 27292,
"s": 27284,
"text": "Output:"
},
{
"code": null,
"e": 27359,
"s": 27292,
"text": "Number of similar characters : 2\nNumber of similar characters : 3\n"
},
{
"code": null,
"e": 27420,
"s": 27359,
"text": "Reference:http://php.net/manual/en/function.similar-text.php"
},
{
"code": null,
"e": 27431,
"s": 27420,
"text": "PHP-string"
},
{
"code": null,
"e": 27435,
"s": 27431,
"text": "PHP"
},
{
"code": null,
"e": 27452,
"s": 27435,
"text": "Web Technologies"
},
{
"code": null,
"e": 27456,
"s": 27452,
"text": "PHP"
},
{
"code": null,
"e": 27554,
"s": 27456,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27563,
"s": 27554,
"text": "Comments"
},
{
"code": null,
"e": 27576,
"s": 27563,
"text": "Old Comments"
},
{
"code": null,
"e": 27658,
"s": 27576,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 27722,
"s": 27658,
"text": "How to pass form variables from one page to other page in PHP ?"
},
{
"code": null,
"e": 27796,
"s": 27722,
"text": "Create a drop-down list that options fetched from a MySQL database in PHP"
},
{
"code": null,
"e": 27838,
"s": 27796,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 27889,
"s": 27838,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 27945,
"s": 27889,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 27978,
"s": 27945,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28040,
"s": 27978,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28083,
"s": 28040,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Adding extra axis ticks using Matplotlib | To add extra ticks in matplotlib, we can take the following Steps −
Create x and y points using numpy.
Create x and y points using numpy.
Plot x and y points over the plot, where x ticks could be from 1 to 10 (100 data points) on the curve.
Plot x and y points over the plot, where x ticks could be from 1 to 10 (100 data points) on the curve.
To add extra ticks, use xticks() method and increase the range of ticks to 1 to 20 from 1 to 10.
To add extra ticks, use xticks() method and increase the range of ticks to 1 to 20 from 1 to 10.
To display the figure, use the show() method.
To display the figure, use the show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(1, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.xticks(range(1, 20))
plt.show() | [
{
"code": null,
"e": 1130,
"s": 1062,
"text": "To add extra ticks in matplotlib, we can take the following Steps −"
},
{
"code": null,
"e": 1165,
"s": 1130,
"text": "Create x and y points using numpy."
},
{
"code": null,
"e": 1200,
"s": 1165,
"text": "Create x and y points using numpy."
},
{
"code": null,
"e": 1303,
"s": 1200,
"text": "Plot x and y points over the plot, where x ticks could be from 1 to 10 (100 data points) on the curve."
},
{
"code": null,
"e": 1406,
"s": 1303,
"text": "Plot x and y points over the plot, where x ticks could be from 1 to 10 (100 data points) on the curve."
},
{
"code": null,
"e": 1503,
"s": 1406,
"text": "To add extra ticks, use xticks() method and increase the range of ticks to 1 to 20 from 1 to 10."
},
{
"code": null,
"e": 1600,
"s": 1503,
"text": "To add extra ticks, use xticks() method and increase the range of ticks to 1 to 20 from 1 to 10."
},
{
"code": null,
"e": 1646,
"s": 1600,
"text": "To display the figure, use the show() method."
},
{
"code": null,
"e": 1692,
"s": 1646,
"text": "To display the figure, use the show() method."
},
{
"code": null,
"e": 1928,
"s": 1692,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = np.linspace(1, 10, 100)\ny = np.sin(x)\nplt.plot(x, y)\nplt.xticks(range(1, 20))\nplt.show()"
}
] |
Scala | Tuple | 01 Mar, 2019
Tuple is a collection of elements. Tuples are heterogeneous data structures, i.e., is they can store elements of different data types. A tuple is immutable, unlike an array in scala which is mutable.An example of a tuple storing an integer, a string, and boolean value.
val name = (15, "Chandan", true)
Type of tuple is defined by, the number of the element it contains and datatype of those elements.
For Example:
// this is tuple of type Tuple3[ Int, String, Boolean ]
val name = (15, "Chandan", true)
Let N be the number of elements in a tuple. Scala currently is limited to 22 elements in a tuple, that is N should be, 1<=N<=22 , the tuple can have at most 22 elements, if the number of elements exceeds 22 then this will generate an error. However we can use nested tuples to overcome this limit (Note that a tuple can contain other tuples)
Access element from tuple: Tuple elements can be accessed using an underscore syntax, method tup._i is used to access the ith element of the tuple.Example :// Scala program to access // element using underscore method // Creating objectobject gfg { // Main method def main(args: Array[String]) { var name = (15, "chandan", true) println(name._1) // print 1st element println(name._2) // print 2st element println(name._3) // print 3st element }}Output:15
chandan
true
Pattern matching on tuples : Pattern matching is a mechanism for checking a value against a pattern. A successful match can also deconstruct a value into its constituent parts.Example :// Scala program of pattern matching on tuples // Creating objectobject gfg { // Main method def main(args: Array[String]) { var (a, b, c) = (15, "chandan", true) println(a) println(b) println(c) }}Output:15
chandan
true
Here, in above example var (a, b, c)= (15, “chandan”, true) expression assign a = 15, b = “chandan”, c = true.Iterating over a tuple : To iterate over tuple, tuple.productIterator() method is used.Example :// Scala program to iterate over tuples// using productIterator method // Creating objectobject gfg { // Main method def main(args: Array[String]) { var name = (15, "chandan", true) // The foreach method takes a function // as parameter and applies it to // every element in the collection name.productIterator.foreach{i=>println(i)} }}Output:15
chandan
true
Converting tuple to string: Converting a tuple to a string concatenates all of its elements into a string. We use the tuple.toString() method for this.Example :// Scala program to convert tuple element to String // Creating objectobject gfg{ // Main method def main(args: Array[String]) { val name = (15, "chandan", true) // print converted string println(name.toString() ) } }Output:(15, chandan, true)
Swap the elements of tuple: Swapping the element of a tuple we can use tuple.swap Method.Example :// Scala program to swap tuple element // Creating objectobject gfg { // Main method def main(args: Array[String]) { val name = ("geeksforgeeks","gfg") // print swapped element println(name.swap) }}Output:(Geeksquize,geeksforgeeks)
My Personal Notes
arrow_drop_upSave
Access element from tuple: Tuple elements can be accessed using an underscore syntax, method tup._i is used to access the ith element of the tuple.Example :// Scala program to access // element using underscore method // Creating objectobject gfg { // Main method def main(args: Array[String]) { var name = (15, "chandan", true) println(name._1) // print 1st element println(name._2) // print 2st element println(name._3) // print 3st element }}Output:15
chandan
true
// Scala program to access // element using underscore method // Creating objectobject gfg { // Main method def main(args: Array[String]) { var name = (15, "chandan", true) println(name._1) // print 1st element println(name._2) // print 2st element println(name._3) // print 3st element }}
15
chandan
true
Pattern matching on tuples : Pattern matching is a mechanism for checking a value against a pattern. A successful match can also deconstruct a value into its constituent parts.Example :// Scala program of pattern matching on tuples // Creating objectobject gfg { // Main method def main(args: Array[String]) { var (a, b, c) = (15, "chandan", true) println(a) println(b) println(c) }}Output:15
chandan
true
Here, in above example var (a, b, c)= (15, “chandan”, true) expression assign a = 15, b = “chandan”, c = true.
// Scala program of pattern matching on tuples // Creating objectobject gfg { // Main method def main(args: Array[String]) { var (a, b, c) = (15, "chandan", true) println(a) println(b) println(c) }}
15
chandan
true
Here, in above example var (a, b, c)= (15, “chandan”, true) expression assign a = 15, b = “chandan”, c = true.
Iterating over a tuple : To iterate over tuple, tuple.productIterator() method is used.Example :// Scala program to iterate over tuples// using productIterator method // Creating objectobject gfg { // Main method def main(args: Array[String]) { var name = (15, "chandan", true) // The foreach method takes a function // as parameter and applies it to // every element in the collection name.productIterator.foreach{i=>println(i)} }}Output:15
chandan
true
// Scala program to iterate over tuples// using productIterator method // Creating objectobject gfg { // Main method def main(args: Array[String]) { var name = (15, "chandan", true) // The foreach method takes a function // as parameter and applies it to // every element in the collection name.productIterator.foreach{i=>println(i)} }}
15
chandan
true
Converting tuple to string: Converting a tuple to a string concatenates all of its elements into a string. We use the tuple.toString() method for this.Example :// Scala program to convert tuple element to String // Creating objectobject gfg{ // Main method def main(args: Array[String]) { val name = (15, "chandan", true) // print converted string println(name.toString() ) } }Output:(15, chandan, true)
// Scala program to convert tuple element to String // Creating objectobject gfg{ // Main method def main(args: Array[String]) { val name = (15, "chandan", true) // print converted string println(name.toString() ) } }
(15, chandan, true)
Swap the elements of tuple: Swapping the element of a tuple we can use tuple.swap Method.Example :// Scala program to swap tuple element // Creating objectobject gfg { // Main method def main(args: Array[String]) { val name = ("geeksforgeeks","gfg") // print swapped element println(name.swap) }}Output:(Geeksquize,geeksforgeeks)
// Scala program to swap tuple element // Creating objectobject gfg { // Main method def main(args: Array[String]) { val name = ("geeksforgeeks","gfg") // print swapped element println(name.swap) }}
(Geeksquize,geeksforgeeks)
Scala-Data Type
Scala-Tuple
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Mar, 2019"
},
{
"code": null,
"e": 322,
"s": 52,
"text": "Tuple is a collection of elements. Tuples are heterogeneous data structures, i.e., is they can store elements of different data types. A tuple is immutable, unlike an array in scala which is mutable.An example of a tuple storing an integer, a string, and boolean value."
},
{
"code": null,
"e": 356,
"s": 322,
"text": "val name = (15, \"Chandan\", true)\n"
},
{
"code": null,
"e": 455,
"s": 356,
"text": "Type of tuple is defined by, the number of the element it contains and datatype of those elements."
},
{
"code": null,
"e": 468,
"s": 455,
"text": "For Example:"
},
{
"code": null,
"e": 559,
"s": 468,
"text": "// this is tuple of type Tuple3[ Int, String, Boolean ] \nval name = (15, \"Chandan\", true)\n"
},
{
"code": null,
"e": 901,
"s": 559,
"text": "Let N be the number of elements in a tuple. Scala currently is limited to 22 elements in a tuple, that is N should be, 1<=N<=22 , the tuple can have at most 22 elements, if the number of elements exceeds 22 then this will generate an error. However we can use nested tuples to overcome this limit (Note that a tuple can contain other tuples)"
},
{
"code": null,
"e": 3349,
"s": 901,
"text": "Access element from tuple: Tuple elements can be accessed using an underscore syntax, method tup._i is used to access the ith element of the tuple.Example :// Scala program to access // element using underscore method // Creating objectobject gfg { // Main method def main(args: Array[String]) { var name = (15, \"chandan\", true) println(name._1) // print 1st element println(name._2) // print 2st element println(name._3) // print 3st element }}Output:15\nchandan\ntrue\nPattern matching on tuples : Pattern matching is a mechanism for checking a value against a pattern. A successful match can also deconstruct a value into its constituent parts.Example :// Scala program of pattern matching on tuples // Creating objectobject gfg { // Main method def main(args: Array[String]) { var (a, b, c) = (15, \"chandan\", true) println(a) println(b) println(c) }}Output:15\nchandan\ntrue\nHere, in above example var (a, b, c)= (15, “chandan”, true) expression assign a = 15, b = “chandan”, c = true.Iterating over a tuple : To iterate over tuple, tuple.productIterator() method is used.Example :// Scala program to iterate over tuples// using productIterator method // Creating objectobject gfg { // Main method def main(args: Array[String]) { var name = (15, \"chandan\", true) // The foreach method takes a function // as parameter and applies it to // every element in the collection name.productIterator.foreach{i=>println(i)} }}Output:15\nchandan\ntrue\nConverting tuple to string: Converting a tuple to a string concatenates all of its elements into a string. We use the tuple.toString() method for this.Example :// Scala program to convert tuple element to String // Creating objectobject gfg{ // Main method def main(args: Array[String]) { val name = (15, \"chandan\", true) // print converted string println(name.toString() ) } }Output:(15, chandan, true)\nSwap the elements of tuple: Swapping the element of a tuple we can use tuple.swap Method.Example :// Scala program to swap tuple element // Creating objectobject gfg { // Main method def main(args: Array[String]) { val name = (\"geeksforgeeks\",\"gfg\") // print swapped element println(name.swap) }}Output:(Geeksquize,geeksforgeeks)\nMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 3864,
"s": 3349,
"text": "Access element from tuple: Tuple elements can be accessed using an underscore syntax, method tup._i is used to access the ith element of the tuple.Example :// Scala program to access // element using underscore method // Creating objectobject gfg { // Main method def main(args: Array[String]) { var name = (15, \"chandan\", true) println(name._1) // print 1st element println(name._2) // print 2st element println(name._3) // print 3st element }}Output:15\nchandan\ntrue\n"
},
{
"code": "// Scala program to access // element using underscore method // Creating objectobject gfg { // Main method def main(args: Array[String]) { var name = (15, \"chandan\", true) println(name._1) // print 1st element println(name._2) // print 2st element println(name._3) // print 3st element }}",
"e": 4200,
"s": 3864,
"text": null
},
{
"code": null,
"e": 4217,
"s": 4200,
"text": "15\nchandan\ntrue\n"
},
{
"code": null,
"e": 4776,
"s": 4217,
"text": "Pattern matching on tuples : Pattern matching is a mechanism for checking a value against a pattern. A successful match can also deconstruct a value into its constituent parts.Example :// Scala program of pattern matching on tuples // Creating objectobject gfg { // Main method def main(args: Array[String]) { var (a, b, c) = (15, \"chandan\", true) println(a) println(b) println(c) }}Output:15\nchandan\ntrue\nHere, in above example var (a, b, c)= (15, “chandan”, true) expression assign a = 15, b = “chandan”, c = true."
},
{
"code": "// Scala program of pattern matching on tuples // Creating objectobject gfg { // Main method def main(args: Array[String]) { var (a, b, c) = (15, \"chandan\", true) println(a) println(b) println(c) }}",
"e": 5017,
"s": 4776,
"text": null
},
{
"code": null,
"e": 5034,
"s": 5017,
"text": "15\nchandan\ntrue\n"
},
{
"code": null,
"e": 5145,
"s": 5034,
"text": "Here, in above example var (a, b, c)= (15, “chandan”, true) expression assign a = 15, b = “chandan”, c = true."
},
{
"code": null,
"e": 5661,
"s": 5145,
"text": "Iterating over a tuple : To iterate over tuple, tuple.productIterator() method is used.Example :// Scala program to iterate over tuples// using productIterator method // Creating objectobject gfg { // Main method def main(args: Array[String]) { var name = (15, \"chandan\", true) // The foreach method takes a function // as parameter and applies it to // every element in the collection name.productIterator.foreach{i=>println(i)} }}Output:15\nchandan\ntrue\n"
},
{
"code": "// Scala program to iterate over tuples// using productIterator method // Creating objectobject gfg { // Main method def main(args: Array[String]) { var name = (15, \"chandan\", true) // The foreach method takes a function // as parameter and applies it to // every element in the collection name.productIterator.foreach{i=>println(i)} }}",
"e": 6058,
"s": 5661,
"text": null
},
{
"code": null,
"e": 6075,
"s": 6058,
"text": "15\nchandan\ntrue\n"
},
{
"code": null,
"e": 6526,
"s": 6075,
"text": "Converting tuple to string: Converting a tuple to a string concatenates all of its elements into a string. We use the tuple.toString() method for this.Example :// Scala program to convert tuple element to String // Creating objectobject gfg{ // Main method def main(args: Array[String]) { val name = (15, \"chandan\", true) // print converted string println(name.toString() ) } }Output:(15, chandan, true)\n"
},
{
"code": "// Scala program to convert tuple element to String // Creating objectobject gfg{ // Main method def main(args: Array[String]) { val name = (15, \"chandan\", true) // print converted string println(name.toString() ) } }",
"e": 6790,
"s": 6526,
"text": null
},
{
"code": null,
"e": 6811,
"s": 6790,
"text": "(15, chandan, true)\n"
},
{
"code": null,
"e": 7187,
"s": 6811,
"text": "Swap the elements of tuple: Swapping the element of a tuple we can use tuple.swap Method.Example :// Scala program to swap tuple element // Creating objectobject gfg { // Main method def main(args: Array[String]) { val name = (\"geeksforgeeks\",\"gfg\") // print swapped element println(name.swap) }}Output:(Geeksquize,geeksforgeeks)\n"
},
{
"code": "// Scala program to swap tuple element // Creating objectobject gfg { // Main method def main(args: Array[String]) { val name = (\"geeksforgeeks\",\"gfg\") // print swapped element println(name.swap) }}",
"e": 7431,
"s": 7187,
"text": null
},
{
"code": null,
"e": 7459,
"s": 7431,
"text": "(Geeksquize,geeksforgeeks)\n"
},
{
"code": null,
"e": 7475,
"s": 7459,
"text": "Scala-Data Type"
},
{
"code": null,
"e": 7487,
"s": 7475,
"text": "Scala-Tuple"
},
{
"code": null,
"e": 7493,
"s": 7487,
"text": "Scala"
}
] |
Get column names from CSV using Python | 14 Aug, 2021
CSV stands for Comma Separated Values and CSV files are essentially text files which are used to store data in a tabular fashion using commas (,) as delimiters. CSV is a file format and all the files of this format are stored with a .csv extension. It is a very popular and extensively used format for storing the data in a structured form. CSV files find a lot of applications in Machine Learning and Statistical Models. Python has a library dedicated to deal with operations catering to CSV files such as reading, writing, or modifying them. Following is an example of how a CSV file looks like.
This article deals with the different ways to get column names from CSV files using Python. The following approaches can be used to accomplish the same :
Using Python’s CSV library to read the CSV file line and line and printing the header as the names of the columns
Reading the CSV file as a dictionary using DictReader and then printing out the keys of the dictionary
Converting the CSV file to a data frame using the Pandas library of Python
Method 1:
Using this approach, we first read the CSV file using the CSV library of Python and then output the first row which represents the column names.
Python3
# importing the csv libraryimport csv # opening the csv file by specifying# the location# with the variable name as csv_filewith open('data.csv') as csv_file: # creating an object of csv reader # with the delimiter as , csv_reader = csv.reader(csv_file, delimiter = ',') # list to store the names of columns list_of_column_names = [] # loop to iterate through the rows of csv for row in csv_reader: # adding the first row list_of_column_names.append(row) # breaking the loop after the # first iteration itself break # printing the resultprint("List of column names : ", list_of_column_names[0])
Output:
List of column names : ['Column1', 'Column2', 'Column3']
Method 2:
Under the second approach, we use the DictReader function of the CSV library to read the CSV file as a dictionary. We can simply use keys() method to get the column names.
Steps :
Open the CSV file using DictReader.
Convert this file into a list.
Convert the first row of the list to the dictionary.
Call the keys() method of the dictionary and convert it into a list.
Display the list.
Python3
# importing the csv libraryimport csv # opening the csv filewith open('data.csv') as csv_file: # reading the csv file using DictReader csv_reader = csv.DictReader(csv_file) # converting the file to dictionary # by first converting to list # and then converting the list to dict dict_from_csv = dict(list(csv_reader)[0]) # making a list from the keys of the dict list_of_column_names = list(dict_from_csv.keys()) # displaying the list of column names print("List of column names : ", list_of_column_names)
Output :
List of column names : ['Column1', 'Column2', 'Column3']
Method 3:
Under this approach, we read the CSV file as a data frame using the pandas library of Python. Then, we just call the column’s method of the data frame.
Python3
# importing the pandas libraryimport pandas as pd # reading the csv file using read_csv# storing the data frame in variable called dfdf = pd.read_csv('data.csv') # creating a list of column names by# calling the .columnslist_of_column_names = list(df.columns) # displaying the list of column namesprint('List of column names : ', list_of_column_names)
Output :
List of column names : ['Column1', 'Column2', 'Column3']
The Data Frame looks as follows :
The CSV file as a Data Frame
varshagumber28
python-csv
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Aug, 2021"
},
{
"code": null,
"e": 652,
"s": 54,
"text": "CSV stands for Comma Separated Values and CSV files are essentially text files which are used to store data in a tabular fashion using commas (,) as delimiters. CSV is a file format and all the files of this format are stored with a .csv extension. It is a very popular and extensively used format for storing the data in a structured form. CSV files find a lot of applications in Machine Learning and Statistical Models. Python has a library dedicated to deal with operations catering to CSV files such as reading, writing, or modifying them. Following is an example of how a CSV file looks like."
},
{
"code": null,
"e": 806,
"s": 652,
"text": "This article deals with the different ways to get column names from CSV files using Python. The following approaches can be used to accomplish the same :"
},
{
"code": null,
"e": 920,
"s": 806,
"text": "Using Python’s CSV library to read the CSV file line and line and printing the header as the names of the columns"
},
{
"code": null,
"e": 1023,
"s": 920,
"text": "Reading the CSV file as a dictionary using DictReader and then printing out the keys of the dictionary"
},
{
"code": null,
"e": 1098,
"s": 1023,
"text": "Converting the CSV file to a data frame using the Pandas library of Python"
},
{
"code": null,
"e": 1108,
"s": 1098,
"text": "Method 1:"
},
{
"code": null,
"e": 1253,
"s": 1108,
"text": "Using this approach, we first read the CSV file using the CSV library of Python and then output the first row which represents the column names."
},
{
"code": null,
"e": 1261,
"s": 1253,
"text": "Python3"
},
{
"code": "# importing the csv libraryimport csv # opening the csv file by specifying# the location# with the variable name as csv_filewith open('data.csv') as csv_file: # creating an object of csv reader # with the delimiter as , csv_reader = csv.reader(csv_file, delimiter = ',') # list to store the names of columns list_of_column_names = [] # loop to iterate through the rows of csv for row in csv_reader: # adding the first row list_of_column_names.append(row) # breaking the loop after the # first iteration itself break # printing the resultprint(\"List of column names : \", list_of_column_names[0])",
"e": 1922,
"s": 1261,
"text": null
},
{
"code": null,
"e": 1930,
"s": 1922,
"text": "Output:"
},
{
"code": null,
"e": 1987,
"s": 1930,
"text": "List of column names : ['Column1', 'Column2', 'Column3']"
},
{
"code": null,
"e": 1997,
"s": 1987,
"text": "Method 2:"
},
{
"code": null,
"e": 2169,
"s": 1997,
"text": "Under the second approach, we use the DictReader function of the CSV library to read the CSV file as a dictionary. We can simply use keys() method to get the column names."
},
{
"code": null,
"e": 2177,
"s": 2169,
"text": "Steps :"
},
{
"code": null,
"e": 2213,
"s": 2177,
"text": "Open the CSV file using DictReader."
},
{
"code": null,
"e": 2244,
"s": 2213,
"text": "Convert this file into a list."
},
{
"code": null,
"e": 2297,
"s": 2244,
"text": "Convert the first row of the list to the dictionary."
},
{
"code": null,
"e": 2366,
"s": 2297,
"text": "Call the keys() method of the dictionary and convert it into a list."
},
{
"code": null,
"e": 2384,
"s": 2366,
"text": "Display the list."
},
{
"code": null,
"e": 2392,
"s": 2384,
"text": "Python3"
},
{
"code": "# importing the csv libraryimport csv # opening the csv filewith open('data.csv') as csv_file: # reading the csv file using DictReader csv_reader = csv.DictReader(csv_file) # converting the file to dictionary # by first converting to list # and then converting the list to dict dict_from_csv = dict(list(csv_reader)[0]) # making a list from the keys of the dict list_of_column_names = list(dict_from_csv.keys()) # displaying the list of column names print(\"List of column names : \", list_of_column_names)",
"e": 2944,
"s": 2392,
"text": null
},
{
"code": null,
"e": 2953,
"s": 2944,
"text": "Output :"
},
{
"code": null,
"e": 3010,
"s": 2953,
"text": "List of column names : ['Column1', 'Column2', 'Column3']"
},
{
"code": null,
"e": 3021,
"s": 3010,
"text": "Method 3: "
},
{
"code": null,
"e": 3173,
"s": 3021,
"text": "Under this approach, we read the CSV file as a data frame using the pandas library of Python. Then, we just call the column’s method of the data frame."
},
{
"code": null,
"e": 3181,
"s": 3173,
"text": "Python3"
},
{
"code": "# importing the pandas libraryimport pandas as pd # reading the csv file using read_csv# storing the data frame in variable called dfdf = pd.read_csv('data.csv') # creating a list of column names by# calling the .columnslist_of_column_names = list(df.columns) # displaying the list of column namesprint('List of column names : ', list_of_column_names)",
"e": 3538,
"s": 3181,
"text": null
},
{
"code": null,
"e": 3547,
"s": 3538,
"text": "Output :"
},
{
"code": null,
"e": 3604,
"s": 3547,
"text": "List of column names : ['Column1', 'Column2', 'Column3']"
},
{
"code": null,
"e": 3638,
"s": 3604,
"text": "The Data Frame looks as follows :"
},
{
"code": null,
"e": 3667,
"s": 3638,
"text": "The CSV file as a Data Frame"
},
{
"code": null,
"e": 3682,
"s": 3667,
"text": "varshagumber28"
},
{
"code": null,
"e": 3693,
"s": 3682,
"text": "python-csv"
},
{
"code": null,
"e": 3700,
"s": 3693,
"text": "Python"
}
] |
Tekion Corp Interview Experience for SDE | On-Campus 2021 | 09 Aug, 2021
Tekion arrived for hiring in the last week of July 2021 in our campus for the SDE role (INTERNSHIP + FTE). We had a total of 4 rounds ( 1 Online Coding on HackerEarth + 2 Technical Interviews+ 1 HR Interview).
Here is my interview experience for the same.
Round 1 ( Online Coding Round) :
This round was conducted on the HackerEarth platform, There were 18 MCQs and 2 coding questions of easy/medium difficulty and the time allotted was 75 Mins.
The MCQs predominantly contained output finding questions where the code was in Java. Apart from this, the MCQs had questions from DBMS and algorithm analysis. There was 1 easy aptitude question as well.
Suggestions for MCQs :
Have a sound knowledge of OOPS, OS, DBMS, and Basics of Java.
Practice some Input-Output and OOPs-based, problems on C++ and Java.
Coding Questions :
Function f(x) is defined as the smallest fibonacci number greater than or equal to x. The task is to calculate g(l,r) where g(l,r) is defined as g(l,r) = f(l)+f(l+1)+f(l+2)+.....+f(r). Constraint: 1<=l<=r<=10^9.
Given N coins and an array of costs that represents the cost of each digit (1,2,...9), where costs[i] is the cost of picking the digit i. The task is to find the largest number that can be represented by using the N coins.
Round 2 (Technical Interview 1):
The Interviewer started by asking Theory from OS, DBMS, OOPS, and CN. This went on for around 20 mins.
In DBMS he asked, Normalization and its types, Transactions, etc.
In OS he asked,
Difference between process and thread.
Scheduling Algorithms.
Deadlocks.
Semaphore and Mutex.
Static and Dynamic Binding
Page fault and Demand Paging.
In OOPs, he asked
Important features of OOps.
Diamond Problem in Multiple Inheritance.
Virtual Keyword.
In DBMS, he asked
Normalization and its types.
Transactions.
ACID properties of DBMS.
In CN, he asked :
Difference between TCP and UDP.
OSI Model.
After this he asked 2 Coding Problems,
Given an Array Find Maximum Sum subarray in it.
Given a BST, find the kth smallest Element in O(logn).
I was able to give the proper logic and explain my approach to him and he was satisfied with my Solution.
After this, he asked if I had any questions for him.
This round lasted for about 70 Mins.
Round 3 (Technical Interview 2): The interviewer started off with, 2 Coding Questions :
Given a sorted rotated array and a target, find if the target is present in the array in O(logN).
Given a BST, convert it into a Sorted Doubly Linked List and return the pointer to the head of the Doubly Linked List.
I was able to explain the logic to the Interviewer for both the problems and then I was asked to code the solution for both the problems, which I did as well.
After verifying the code, he asked some questions from the OS, DBMS, OOPS, and CN,
Difference between Unique key and Primary key.
Indexing and its use in DBMS.
Difference between Locks and Semaphore.
Paging and Segmentation.
Deadlock and its conditions.
What are TCP and UDP used for?
Why do we use Object-Oriented Programming?
After this, he asked if I had any questions for him.
This round lasted for about 70 Mins.
The round went well and I was confident that I would get a mail for the next round.
The mail for the final HR round came 4 hours later.
Round 4 (HR Interview):
I had never been given an HR round before, so I was a little nervous.
The interviewer greeted me and asked me how was my day.
It was more like a discussion rather than an Interview.
He started with the standard question, Tell me about yourself.
I had already prepared answers for 2-3 types of HR round introduction and Behavioral questions. So I was able to give him a short, precise, and to-the-point Introduction of mine.
Then he moved on to the Projects I had done in my B.Tech.
I told about 2-3 Projects which I did until now and briefly explained about all of them.
Then he asked me if I had any questions for him.
I asked few questions, and he was happy to answer.
This HR Round went on for around 15-20 Mins.
Next Day, Result was declared and I was selected.
My suggestion for the Interviews :
Practice all the Standard Company problems from GfG.
Have a good understanding of the CS Fundamentals in OS, DBMS, CN, and OOPS.
Prepare some short notes on CS fundamentals and DSA Problems, which will be useful for last-minute revision.
Prepare and notes down answers to some Standard HR round questions :
Tell me about Yourself.
What are your Strengths and Weaknesses?
Tell me about a hard situation for you, and how did you overcome it.
Tell me about a time when you took a risk and failed.
Why should we hire you?
At last, always keep calm while giving the Interviews for positive results.
All the best for your Interviews.
Marketing
On-Campus
Tekion
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Aug, 2021"
},
{
"code": null,
"e": 240,
"s": 28,
"text": "Tekion arrived for hiring in the last week of July 2021 in our campus for the SDE role (INTERNSHIP + FTE). We had a total of 4 rounds ( 1 Online Coding on HackerEarth + 2 Technical Interviews+ 1 HR Interview). "
},
{
"code": null,
"e": 286,
"s": 240,
"text": "Here is my interview experience for the same."
},
{
"code": null,
"e": 319,
"s": 286,
"text": "Round 1 ( Online Coding Round) :"
},
{
"code": null,
"e": 476,
"s": 319,
"text": "This round was conducted on the HackerEarth platform, There were 18 MCQs and 2 coding questions of easy/medium difficulty and the time allotted was 75 Mins."
},
{
"code": null,
"e": 680,
"s": 476,
"text": "The MCQs predominantly contained output finding questions where the code was in Java. Apart from this, the MCQs had questions from DBMS and algorithm analysis. There was 1 easy aptitude question as well."
},
{
"code": null,
"e": 703,
"s": 680,
"text": "Suggestions for MCQs :"
},
{
"code": null,
"e": 765,
"s": 703,
"text": "Have a sound knowledge of OOPS, OS, DBMS, and Basics of Java."
},
{
"code": null,
"e": 834,
"s": 765,
"text": "Practice some Input-Output and OOPs-based, problems on C++ and Java."
},
{
"code": null,
"e": 853,
"s": 834,
"text": "Coding Questions :"
},
{
"code": null,
"e": 1066,
"s": 853,
"text": "Function f(x) is defined as the smallest fibonacci number greater than or equal to x. The task is to calculate g(l,r) where g(l,r) is defined as g(l,r) = f(l)+f(l+1)+f(l+2)+.....+f(r). Constraint: 1<=l<=r<=10^9."
},
{
"code": null,
"e": 1289,
"s": 1066,
"text": "Given N coins and an array of costs that represents the cost of each digit (1,2,...9), where costs[i] is the cost of picking the digit i. The task is to find the largest number that can be represented by using the N coins."
},
{
"code": null,
"e": 1322,
"s": 1289,
"text": "Round 2 (Technical Interview 1):"
},
{
"code": null,
"e": 1426,
"s": 1322,
"text": "The Interviewer started by asking Theory from OS, DBMS, OOPS, and CN. This went on for around 20 mins."
},
{
"code": null,
"e": 1492,
"s": 1426,
"text": "In DBMS he asked, Normalization and its types, Transactions, etc."
},
{
"code": null,
"e": 1508,
"s": 1492,
"text": "In OS he asked,"
},
{
"code": null,
"e": 1547,
"s": 1508,
"text": "Difference between process and thread."
},
{
"code": null,
"e": 1570,
"s": 1547,
"text": "Scheduling Algorithms."
},
{
"code": null,
"e": 1581,
"s": 1570,
"text": "Deadlocks."
},
{
"code": null,
"e": 1602,
"s": 1581,
"text": "Semaphore and Mutex."
},
{
"code": null,
"e": 1629,
"s": 1602,
"text": "Static and Dynamic Binding"
},
{
"code": null,
"e": 1659,
"s": 1629,
"text": "Page fault and Demand Paging."
},
{
"code": null,
"e": 1677,
"s": 1659,
"text": "In OOPs, he asked"
},
{
"code": null,
"e": 1705,
"s": 1677,
"text": "Important features of OOps."
},
{
"code": null,
"e": 1746,
"s": 1705,
"text": "Diamond Problem in Multiple Inheritance."
},
{
"code": null,
"e": 1763,
"s": 1746,
"text": "Virtual Keyword."
},
{
"code": null,
"e": 1781,
"s": 1763,
"text": "In DBMS, he asked"
},
{
"code": null,
"e": 1810,
"s": 1781,
"text": "Normalization and its types."
},
{
"code": null,
"e": 1824,
"s": 1810,
"text": "Transactions."
},
{
"code": null,
"e": 1849,
"s": 1824,
"text": "ACID properties of DBMS."
},
{
"code": null,
"e": 1867,
"s": 1849,
"text": "In CN, he asked :"
},
{
"code": null,
"e": 1899,
"s": 1867,
"text": "Difference between TCP and UDP."
},
{
"code": null,
"e": 1910,
"s": 1899,
"text": "OSI Model."
},
{
"code": null,
"e": 1949,
"s": 1910,
"text": "After this he asked 2 Coding Problems,"
},
{
"code": null,
"e": 1998,
"s": 1949,
"text": " Given an Array Find Maximum Sum subarray in it."
},
{
"code": null,
"e": 2054,
"s": 1998,
"text": " Given a BST, find the kth smallest Element in O(logn)."
},
{
"code": null,
"e": 2160,
"s": 2054,
"text": "I was able to give the proper logic and explain my approach to him and he was satisfied with my Solution."
},
{
"code": null,
"e": 2213,
"s": 2160,
"text": "After this, he asked if I had any questions for him."
},
{
"code": null,
"e": 2250,
"s": 2213,
"text": "This round lasted for about 70 Mins."
},
{
"code": null,
"e": 2338,
"s": 2250,
"text": "Round 3 (Technical Interview 2): The interviewer started off with, 2 Coding Questions :"
},
{
"code": null,
"e": 2437,
"s": 2338,
"text": " Given a sorted rotated array and a target, find if the target is present in the array in O(logN)."
},
{
"code": null,
"e": 2556,
"s": 2437,
"text": "Given a BST, convert it into a Sorted Doubly Linked List and return the pointer to the head of the Doubly Linked List."
},
{
"code": null,
"e": 2715,
"s": 2556,
"text": "I was able to explain the logic to the Interviewer for both the problems and then I was asked to code the solution for both the problems, which I did as well."
},
{
"code": null,
"e": 2798,
"s": 2715,
"text": "After verifying the code, he asked some questions from the OS, DBMS, OOPS, and CN,"
},
{
"code": null,
"e": 2845,
"s": 2798,
"text": "Difference between Unique key and Primary key."
},
{
"code": null,
"e": 2875,
"s": 2845,
"text": "Indexing and its use in DBMS."
},
{
"code": null,
"e": 2915,
"s": 2875,
"text": "Difference between Locks and Semaphore."
},
{
"code": null,
"e": 2940,
"s": 2915,
"text": "Paging and Segmentation."
},
{
"code": null,
"e": 2969,
"s": 2940,
"text": "Deadlock and its conditions."
},
{
"code": null,
"e": 3000,
"s": 2969,
"text": "What are TCP and UDP used for?"
},
{
"code": null,
"e": 3043,
"s": 3000,
"text": "Why do we use Object-Oriented Programming?"
},
{
"code": null,
"e": 3096,
"s": 3043,
"text": "After this, he asked if I had any questions for him."
},
{
"code": null,
"e": 3133,
"s": 3096,
"text": "This round lasted for about 70 Mins."
},
{
"code": null,
"e": 3217,
"s": 3133,
"text": "The round went well and I was confident that I would get a mail for the next round."
},
{
"code": null,
"e": 3269,
"s": 3217,
"text": "The mail for the final HR round came 4 hours later."
},
{
"code": null,
"e": 3293,
"s": 3269,
"text": "Round 4 (HR Interview):"
},
{
"code": null,
"e": 3363,
"s": 3293,
"text": "I had never been given an HR round before, so I was a little nervous."
},
{
"code": null,
"e": 3419,
"s": 3363,
"text": "The interviewer greeted me and asked me how was my day."
},
{
"code": null,
"e": 3475,
"s": 3419,
"text": "It was more like a discussion rather than an Interview."
},
{
"code": null,
"e": 3538,
"s": 3475,
"text": "He started with the standard question, Tell me about yourself."
},
{
"code": null,
"e": 3717,
"s": 3538,
"text": "I had already prepared answers for 2-3 types of HR round introduction and Behavioral questions. So I was able to give him a short, precise, and to-the-point Introduction of mine."
},
{
"code": null,
"e": 3775,
"s": 3717,
"text": "Then he moved on to the Projects I had done in my B.Tech."
},
{
"code": null,
"e": 3864,
"s": 3775,
"text": "I told about 2-3 Projects which I did until now and briefly explained about all of them."
},
{
"code": null,
"e": 3913,
"s": 3864,
"text": "Then he asked me if I had any questions for him."
},
{
"code": null,
"e": 3964,
"s": 3913,
"text": "I asked few questions, and he was happy to answer."
},
{
"code": null,
"e": 4009,
"s": 3964,
"text": "This HR Round went on for around 15-20 Mins."
},
{
"code": null,
"e": 4059,
"s": 4009,
"text": "Next Day, Result was declared and I was selected."
},
{
"code": null,
"e": 4094,
"s": 4059,
"text": "My suggestion for the Interviews :"
},
{
"code": null,
"e": 4147,
"s": 4094,
"text": "Practice all the Standard Company problems from GfG."
},
{
"code": null,
"e": 4223,
"s": 4147,
"text": "Have a good understanding of the CS Fundamentals in OS, DBMS, CN, and OOPS."
},
{
"code": null,
"e": 4332,
"s": 4223,
"text": "Prepare some short notes on CS fundamentals and DSA Problems, which will be useful for last-minute revision."
},
{
"code": null,
"e": 4401,
"s": 4332,
"text": "Prepare and notes down answers to some Standard HR round questions :"
},
{
"code": null,
"e": 4425,
"s": 4401,
"text": "Tell me about Yourself."
},
{
"code": null,
"e": 4465,
"s": 4425,
"text": "What are your Strengths and Weaknesses?"
},
{
"code": null,
"e": 4534,
"s": 4465,
"text": "Tell me about a hard situation for you, and how did you overcome it."
},
{
"code": null,
"e": 4588,
"s": 4534,
"text": "Tell me about a time when you took a risk and failed."
},
{
"code": null,
"e": 4612,
"s": 4588,
"text": "Why should we hire you?"
},
{
"code": null,
"e": 4688,
"s": 4612,
"text": "At last, always keep calm while giving the Interviews for positive results."
},
{
"code": null,
"e": 4722,
"s": 4688,
"text": "All the best for your Interviews."
},
{
"code": null,
"e": 4732,
"s": 4722,
"text": "Marketing"
},
{
"code": null,
"e": 4742,
"s": 4732,
"text": "On-Campus"
},
{
"code": null,
"e": 4749,
"s": 4742,
"text": "Tekion"
},
{
"code": null,
"e": 4771,
"s": 4749,
"text": "Interview Experiences"
}
] |
PostgreSQL – NUMERIC Data Type | 28 Aug, 2020
PostgreSQL supports the NUMERIC type for storing numbers with a very large number of digits. Generally NUMERIC type are used for the monetary or amounts storage where precision is required.
Syntax: NUMERIC(precision, scale)
Where,
Precision: Total number of digits.
Scale: Number of digits in terms of a fraction.
The NUMERIC value can have up to 131, 072 digits before the decimal point of 16, 383 digits after the decimal point.It is allowed to have a zero or positive scale, as the syntax defined below for a NUMERIC column with the scale of zero:
Syntax: NUMERIC(precision)
If you eliminate both precision and scale, there is no limit to the precision or the scale and the syntax will be as below:
Syntax: NUMERIC
The NUMERIC and DECIMAL types are equivalent in PostgreSQL and upto the SQL standard.It is recommended to not use the NUMERIC type, if precision is not required as the calculation on NUMERIC values is slower than integers, floats, and double precision.
Example 1:Create a new table named products with the below commands:
CREATE TABLE IF NOT EXISTS products (
id serial PRIMARY KEY,
name VARCHAR NOT NULL,
price NUMERIC (5, 2)
);
Now insert some products with the prices whose scales exceed the scale declared in the price column:
INSERT INTO products (name, price)
VALUES
('Phone', 100.2157),
('Tablet', 300.2149);
As the scale of the price column is 2, PostgreSQL rounds the value 100.2157 up to 100.22 and rounds the value 300.2149 down to 300.21The below query returns all rows of the products table:
SELECT
*
FROM
products;
Output:
Example 2:Create a new table named products with the below commands:
CREATE TABLE IF NOT EXISTS employee_salary(
id serial PRIMARY KEY,
name VARCHAR NOT NULL,
salary NUMERIC (10, 2)
);
Now insert some products with the prices whose scales exceed the scale declared in the price column:
INSERT INTO employee_salary(name, salary)
VALUES
('Raju', 57896.2277),
('Abhishek', 84561.3657),
('Nikhil', 55100.11957),
('Ravi', 49300.21425849);
As the scale of the price column is 2, PostgreSQL rounds the value 57896.2277 up to 57896.22 for Raju, the value 84561.3657 down to 84561.36 for Abhishek, the value 55100.11957 to 55100.12 for Nikhil and the value 49300.21425849 to 49300.21 for Ravi.The below query returns all rows of the products table:
SELECT
*
FROM
employee_salary;
Output:
postgreSQL-dataTypes
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - For Loops
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - Function Returning A Table
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - DROP INDEX
PostgreSQL - Copy Table
How to use PostgreSQL Database in Django? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 218,
"s": 28,
"text": "PostgreSQL supports the NUMERIC type for storing numbers with a very large number of digits. Generally NUMERIC type are used for the monetary or amounts storage where precision is required."
},
{
"code": null,
"e": 353,
"s": 218,
"text": "Syntax: NUMERIC(precision, scale)\n\nWhere,\n Precision: Total number of digits.\n Scale: Number of digits in terms of a fraction."
},
{
"code": null,
"e": 590,
"s": 353,
"text": "The NUMERIC value can have up to 131, 072 digits before the decimal point of 16, 383 digits after the decimal point.It is allowed to have a zero or positive scale, as the syntax defined below for a NUMERIC column with the scale of zero:"
},
{
"code": null,
"e": 617,
"s": 590,
"text": "Syntax: NUMERIC(precision)"
},
{
"code": null,
"e": 741,
"s": 617,
"text": "If you eliminate both precision and scale, there is no limit to the precision or the scale and the syntax will be as below:"
},
{
"code": null,
"e": 757,
"s": 741,
"text": "Syntax: NUMERIC"
},
{
"code": null,
"e": 1010,
"s": 757,
"text": "The NUMERIC and DECIMAL types are equivalent in PostgreSQL and upto the SQL standard.It is recommended to not use the NUMERIC type, if precision is not required as the calculation on NUMERIC values is slower than integers, floats, and double precision."
},
{
"code": null,
"e": 1079,
"s": 1010,
"text": "Example 1:Create a new table named products with the below commands:"
},
{
"code": null,
"e": 1199,
"s": 1079,
"text": "CREATE TABLE IF NOT EXISTS products (\n id serial PRIMARY KEY,\n name VARCHAR NOT NULL,\n price NUMERIC (5, 2)\n);"
},
{
"code": null,
"e": 1300,
"s": 1199,
"text": "Now insert some products with the prices whose scales exceed the scale declared in the price column:"
},
{
"code": null,
"e": 1394,
"s": 1300,
"text": "INSERT INTO products (name, price)\nVALUES\n ('Phone', 100.2157), \n ('Tablet', 300.2149);"
},
{
"code": null,
"e": 1583,
"s": 1394,
"text": "As the scale of the price column is 2, PostgreSQL rounds the value 100.2157 up to 100.22 and rounds the value 300.2149 down to 300.21The below query returns all rows of the products table:"
},
{
"code": null,
"e": 1615,
"s": 1583,
"text": "SELECT\n *\nFROM\n products;"
},
{
"code": null,
"e": 1623,
"s": 1615,
"text": "Output:"
},
{
"code": null,
"e": 1692,
"s": 1623,
"text": "Example 2:Create a new table named products with the below commands:"
},
{
"code": null,
"e": 1820,
"s": 1692,
"text": "CREATE TABLE IF NOT EXISTS employee_salary(\n id serial PRIMARY KEY,\n name VARCHAR NOT NULL,\n salary NUMERIC (10, 2)\n);"
},
{
"code": null,
"e": 1921,
"s": 1820,
"text": "Now insert some products with the prices whose scales exceed the scale declared in the price column:"
},
{
"code": null,
"e": 2086,
"s": 1921,
"text": "INSERT INTO employee_salary(name, salary)\nVALUES\n ('Raju', 57896.2277),\n ('Abhishek', 84561.3657),\n ('Nikhil', 55100.11957), \n ('Ravi', 49300.21425849);"
},
{
"code": null,
"e": 2392,
"s": 2086,
"text": "As the scale of the price column is 2, PostgreSQL rounds the value 57896.2277 up to 57896.22 for Raju, the value 84561.3657 down to 84561.36 for Abhishek, the value 55100.11957 to 55100.12 for Nikhil and the value 49300.21425849 to 49300.21 for Ravi.The below query returns all rows of the products table:"
},
{
"code": null,
"e": 2431,
"s": 2392,
"text": "SELECT\n *\nFROM\n employee_salary;"
},
{
"code": null,
"e": 2439,
"s": 2431,
"text": "Output:"
},
{
"code": null,
"e": 2460,
"s": 2439,
"text": "postgreSQL-dataTypes"
},
{
"code": null,
"e": 2471,
"s": 2460,
"text": "PostgreSQL"
},
{
"code": null,
"e": 2569,
"s": 2471,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2596,
"s": 2569,
"text": "PostgreSQL - Psql commands"
},
{
"code": null,
"e": 2628,
"s": 2596,
"text": "PostgreSQL - Change Column Type"
},
{
"code": null,
"e": 2651,
"s": 2628,
"text": "PostgreSQL - For Loops"
},
{
"code": null,
"e": 2689,
"s": 2651,
"text": "PostgreSQL - LIMIT with OFFSET clause"
},
{
"code": null,
"e": 2729,
"s": 2689,
"text": "PostgreSQL - Function Returning A Table"
},
{
"code": null,
"e": 2763,
"s": 2729,
"text": "PostgreSQL - ARRAY_AGG() Function"
},
{
"code": null,
"e": 2818,
"s": 2763,
"text": "PostgreSQL - Create Auto-increment Column using SERIAL"
},
{
"code": null,
"e": 2842,
"s": 2818,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 2866,
"s": 2842,
"text": "PostgreSQL - Copy Table"
}
] |
Range and Indices in C# 8.0 | 28 Nov, 2019
As we already know about the Range and Indices. We use them several times in our programs, they provide a short syntax to represent or access a single or a range of elements from the given sequence or collections. In this article, we will learn what’s newly added in the range and indices in C# 8.0. In C# 8.0, the following new things are added in the range and indices:
1. Two New Types:
System.Range: It represents a sub-range of the given sequence or collection.
System.Index: It represents an index into the given sequence or collection.
2. Two New Operators:
^ Operator: It is known as the index from the end operator. It returns an index that is relative to the end of the sequence or collection. It is the most compact and easiest way to find the end elements compare to earlier methods.// Old Method
var lastval = myarr[myarr.Length-1]
// New Method
var lastval = myarr[^1]
Example:// C# program to illustrate the use // of the index from end operator(^)using System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array int[] myarr = new int[] {34, 56, 77, 88, 90, 45}; // Simple getting the index value Console.WriteLine("Values of the specified indexes:"); Console.WriteLine(myarr[0]); Console.WriteLine(myarr[1]); Console.WriteLine(myarr[2]); Console.WriteLine(myarr[3]); Console.WriteLine(myarr[4]); Console.WriteLine(myarr[5]); // Now we use index from end(^) // operator with the given index // This will return the end value // which is related to the specified // index Console.WriteLine("The end values of the specified indexes:"); Console.WriteLine(myarr[^1]); Console.WriteLine(myarr[^2]); Console.WriteLine(myarr[^3]); Console.WriteLine(myarr[^4]); Console.WriteLine(myarr[^5]); Console.WriteLine(myarr[^6]); }}}Output:Values of the specified indexes:
34
56
77
88
90
45
The end values of the specified indexes:
45
90
88
77
56
34
Explanation: In the above example, we have an array of int type named myarr. Here, first we simply get the values of the specified index that is:34, 56, 77, 88, 90, 45
Index : Value
[0] : 34
[1] : 56
[2] : 77
[3] : 88
[4] : 90
[5] : 45
Now we find the last value of the specified index with the help of ^ operator that is:Index : Value
[^1] : 45
[^2] : 90
[^3] : 88
[^4] : 77
[^5] : 56
[^6] : 34
Important Points:The working of this operator is similar to myarr[arr.Length].You are not allowed to use myarr[^0] if you use this, then this will throw an error because the end index starts from ^1, not from ^0 as shown in the below example:Example:// C# program to illustrate the use // of the index from end operator(^)using System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array int[] myarr = new int[] {34, 56, 77, 88, 90, 45}; // Simply getting the index value Console.WriteLine("Values of the specified index:"); Console.WriteLine(myarr[0]); // Now we use index from end(^) // operator with the given index // This will return the end value // which is related to the specified // index Console.WriteLine("The end values of the specified index:"); Console.WriteLine(myarr[^0]); }}}Output:Values of the specified index:34The end values of the specified index:Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.at example.Program.Main(String[] args) in /Users/anki/Projects/example/example/Program.cs:line 22You are allowed to use the index as a variable and this variable place in between brackets[]. As shown in the below example:Example:// C# program to illustrate how// to declare a index as a variableusing System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array int[] number = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}; // Declare an index // as a variable Index i = ^6; var val = number[i]; // Displaying number Console.WriteLine("Number: " + val); }}}Output:Number: 4
// Old Method
var lastval = myarr[myarr.Length-1]
// New Method
var lastval = myarr[^1]
Example:
// C# program to illustrate the use // of the index from end operator(^)using System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array int[] myarr = new int[] {34, 56, 77, 88, 90, 45}; // Simple getting the index value Console.WriteLine("Values of the specified indexes:"); Console.WriteLine(myarr[0]); Console.WriteLine(myarr[1]); Console.WriteLine(myarr[2]); Console.WriteLine(myarr[3]); Console.WriteLine(myarr[4]); Console.WriteLine(myarr[5]); // Now we use index from end(^) // operator with the given index // This will return the end value // which is related to the specified // index Console.WriteLine("The end values of the specified indexes:"); Console.WriteLine(myarr[^1]); Console.WriteLine(myarr[^2]); Console.WriteLine(myarr[^3]); Console.WriteLine(myarr[^4]); Console.WriteLine(myarr[^5]); Console.WriteLine(myarr[^6]); }}}
Output:
Values of the specified indexes:
34
56
77
88
90
45
The end values of the specified indexes:
45
90
88
77
56
34
Explanation: In the above example, we have an array of int type named myarr. Here, first we simply get the values of the specified index that is:
34, 56, 77, 88, 90, 45
Index : Value
[0] : 34
[1] : 56
[2] : 77
[3] : 88
[4] : 90
[5] : 45
Now we find the last value of the specified index with the help of ^ operator that is:
Index : Value
[^1] : 45
[^2] : 90
[^3] : 88
[^4] : 77
[^5] : 56
[^6] : 34
Important Points:
The working of this operator is similar to myarr[arr.Length].
You are not allowed to use myarr[^0] if you use this, then this will throw an error because the end index starts from ^1, not from ^0 as shown in the below example:Example:// C# program to illustrate the use // of the index from end operator(^)using System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array int[] myarr = new int[] {34, 56, 77, 88, 90, 45}; // Simply getting the index value Console.WriteLine("Values of the specified index:"); Console.WriteLine(myarr[0]); // Now we use index from end(^) // operator with the given index // This will return the end value // which is related to the specified // index Console.WriteLine("The end values of the specified index:"); Console.WriteLine(myarr[^0]); }}}Output:Values of the specified index:34The end values of the specified index:Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.at example.Program.Main(String[] args) in /Users/anki/Projects/example/example/Program.cs:line 22
Example:
// C# program to illustrate the use // of the index from end operator(^)using System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array int[] myarr = new int[] {34, 56, 77, 88, 90, 45}; // Simply getting the index value Console.WriteLine("Values of the specified index:"); Console.WriteLine(myarr[0]); // Now we use index from end(^) // operator with the given index // This will return the end value // which is related to the specified // index Console.WriteLine("The end values of the specified index:"); Console.WriteLine(myarr[^0]); }}}
Output:
Values of the specified index:34The end values of the specified index:Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.at example.Program.Main(String[] args) in /Users/anki/Projects/example/example/Program.cs:line 22
You are allowed to use the index as a variable and this variable place in between brackets[]. As shown in the below example:Example:// C# program to illustrate how// to declare a index as a variableusing System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array int[] number = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}; // Declare an index // as a variable Index i = ^6; var val = number[i]; // Displaying number Console.WriteLine("Number: " + val); }}}Output:Number: 4
Example:
// C# program to illustrate how// to declare a index as a variableusing System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array int[] number = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}; // Declare an index // as a variable Index i = ^6; var val = number[i]; // Displaying number Console.WriteLine("Number: " + val); }}}
Output:
Number: 4
.. Operator: It is known as the range operator. And it specifies the start and end as its operands of the given range. It is the most compact and easiest way to find the range of the elements from the specified sequence or collection in comparison to earlier methods.// Old Method
var arr = myemp.GetRange(1, 5);
// New Method
var arr = myemp[2..3]
Example:// C# program to illustrate the // use of the range operator(..)using System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array string[] myemp = new string[] {"Anu", "Priya", "Rohit", "Amit", "Shreya", "Rinu", "Sumit", "Zoya"}; Console.Write("Name of the employees in project A: "); var P_A = myemp[0..3]; foreach(var emp1 in P_A) Console.Write($" [{emp1}]"); Console.Write("\nName of the employees in project B: "); var P_B = myemp[3..5]; foreach(var emp2 in P_B) Console.Write($" [{emp2}]"); Console.Write("\nName of the employees in project C: "); var P_C = myemp[1..^2]; foreach (var emp3 in P_C) Console.Write($" [{emp3}]"); Console.Write("\nName of the employees in project D: "); var P_D = myemp[..]; foreach(var emp4 in P_D) Console.Write($" [{emp4}]"); Console.Write("\nName of the employees in project E: "); var P_E = myemp[..2]; foreach(var emp5 in P_E) Console.Write($" [{emp5}]"); Console.Write("\nName of the employees in project F: "); var P_F = myemp[6..]; foreach(var emp6 in P_F) Console.Write($" [{emp6}]"); Console.Write("\nName of the employees in project G: "); var P_G = myemp[^3.. ^ 1]; foreach(var emp7 in P_G) Console.Write($" [{emp7}]"); }}}Output:Name of the employees in project A: [Anu] [Priya] [Rohit]
Name of the employees in project B: [Amit] [Shreya]
Name of the employees in project C: [Priya] [Rohit] [Amit] [Shreya] [Rinu]
Name of the employees in project D: [Anu] [Priya] [Rohit] [Amit] [Shreya] [Rinu] [Sumit] [Zoya]
Name of the employees in project E: [Anu] [Priya]
Name of the employees in project F: [Sumit] [Zoya]
Name of the employees in project G: [Rinu] [Sumit]
Important Points:When you create a range using range operator, then it will not add the last element. For example, we have an array {1, 2, 3, 4, 5, 6 }, now we want to print range[1..3], then it will print 2, 3. It does not print 2, 3, 4.In Range, if a range contains starting and ending index like Range[start, end], then such types of ranges are known as the bounded range.In Range, if a range contains only starting, ending index or doesn’t contain starting and ending indexes like Range[start..], or Range[..end], or Range[..], then such types of ranges are known as the unbounded range.You are allowed to use range as a variable and this variable place in between brackets[]. As shown in the below example:Example:// C# program to illustrate how to// declare a range as a variableusing System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array int[] number = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}; Console.Write("Number: "); // Declaring a range as a variable Range num = 1..3; int[] val = number[num]; // Displaying number foreach(var n in val) Console.Write($" [{n}]"); }}}Output:Number: [2] [3]
// Old Method
var arr = myemp.GetRange(1, 5);
// New Method
var arr = myemp[2..3]
Example:
// C# program to illustrate the // use of the range operator(..)using System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array string[] myemp = new string[] {"Anu", "Priya", "Rohit", "Amit", "Shreya", "Rinu", "Sumit", "Zoya"}; Console.Write("Name of the employees in project A: "); var P_A = myemp[0..3]; foreach(var emp1 in P_A) Console.Write($" [{emp1}]"); Console.Write("\nName of the employees in project B: "); var P_B = myemp[3..5]; foreach(var emp2 in P_B) Console.Write($" [{emp2}]"); Console.Write("\nName of the employees in project C: "); var P_C = myemp[1..^2]; foreach (var emp3 in P_C) Console.Write($" [{emp3}]"); Console.Write("\nName of the employees in project D: "); var P_D = myemp[..]; foreach(var emp4 in P_D) Console.Write($" [{emp4}]"); Console.Write("\nName of the employees in project E: "); var P_E = myemp[..2]; foreach(var emp5 in P_E) Console.Write($" [{emp5}]"); Console.Write("\nName of the employees in project F: "); var P_F = myemp[6..]; foreach(var emp6 in P_F) Console.Write($" [{emp6}]"); Console.Write("\nName of the employees in project G: "); var P_G = myemp[^3.. ^ 1]; foreach(var emp7 in P_G) Console.Write($" [{emp7}]"); }}}
Output:
Name of the employees in project A: [Anu] [Priya] [Rohit]
Name of the employees in project B: [Amit] [Shreya]
Name of the employees in project C: [Priya] [Rohit] [Amit] [Shreya] [Rinu]
Name of the employees in project D: [Anu] [Priya] [Rohit] [Amit] [Shreya] [Rinu] [Sumit] [Zoya]
Name of the employees in project E: [Anu] [Priya]
Name of the employees in project F: [Sumit] [Zoya]
Name of the employees in project G: [Rinu] [Sumit]
Important Points:
When you create a range using range operator, then it will not add the last element. For example, we have an array {1, 2, 3, 4, 5, 6 }, now we want to print range[1..3], then it will print 2, 3. It does not print 2, 3, 4.
In Range, if a range contains starting and ending index like Range[start, end], then such types of ranges are known as the bounded range.
In Range, if a range contains only starting, ending index or doesn’t contain starting and ending indexes like Range[start..], or Range[..end], or Range[..], then such types of ranges are known as the unbounded range.
You are allowed to use range as a variable and this variable place in between brackets[]. As shown in the below example:Example:// C# program to illustrate how to// declare a range as a variableusing System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array int[] number = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}; Console.Write("Number: "); // Declaring a range as a variable Range num = 1..3; int[] val = number[num]; // Displaying number foreach(var n in val) Console.Write($" [{n}]"); }}}Output:Number: [2] [3]
Example:
// C# program to illustrate how to// declare a range as a variableusing System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array int[] number = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}; Console.Write("Number: "); // Declaring a range as a variable Range num = 1..3; int[] val = number[num]; // Displaying number foreach(var n in val) Console.Write($" [{n}]"); }}}
Output:
Number: [2] [3]
CSharp-8.0
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
Introduction to .NET Framework
C# | Delegates
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
C# | Method Overriding
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
C# | Class and Object
Extension Method in C# | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Nov, 2019"
},
{
"code": null,
"e": 400,
"s": 28,
"text": "As we already know about the Range and Indices. We use them several times in our programs, they provide a short syntax to represent or access a single or a range of elements from the given sequence or collections. In this article, we will learn what’s newly added in the range and indices in C# 8.0. In C# 8.0, the following new things are added in the range and indices:"
},
{
"code": null,
"e": 418,
"s": 400,
"text": "1. Two New Types:"
},
{
"code": null,
"e": 495,
"s": 418,
"text": "System.Range: It represents a sub-range of the given sequence or collection."
},
{
"code": null,
"e": 571,
"s": 495,
"text": "System.Index: It represents an index into the given sequence or collection."
},
{
"code": null,
"e": 593,
"s": 571,
"text": "2. Two New Operators:"
},
{
"code": null,
"e": 4447,
"s": 593,
"text": "^ Operator: It is known as the index from the end operator. It returns an index that is relative to the end of the sequence or collection. It is the most compact and easiest way to find the end elements compare to earlier methods.// Old Method\nvar lastval = myarr[myarr.Length-1]\n\n// New Method\nvar lastval = myarr[^1]\nExample:// C# program to illustrate the use // of the index from end operator(^)using System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array int[] myarr = new int[] {34, 56, 77, 88, 90, 45}; // Simple getting the index value Console.WriteLine(\"Values of the specified indexes:\"); Console.WriteLine(myarr[0]); Console.WriteLine(myarr[1]); Console.WriteLine(myarr[2]); Console.WriteLine(myarr[3]); Console.WriteLine(myarr[4]); Console.WriteLine(myarr[5]); // Now we use index from end(^) // operator with the given index // This will return the end value // which is related to the specified // index Console.WriteLine(\"The end values of the specified indexes:\"); Console.WriteLine(myarr[^1]); Console.WriteLine(myarr[^2]); Console.WriteLine(myarr[^3]); Console.WriteLine(myarr[^4]); Console.WriteLine(myarr[^5]); Console.WriteLine(myarr[^6]); }}}Output:Values of the specified indexes:\n34\n56\n77\n88\n90\n45\nThe end values of the specified indexes:\n45\n90\n88\n77\n56\n34\nExplanation: In the above example, we have an array of int type named myarr. Here, first we simply get the values of the specified index that is:34, 56, 77, 88, 90, 45\nIndex : Value\n [0] : 34\n [1] : 56\n [2] : 77\n [3] : 88\n [4] : 90\n [5] : 45\n\nNow we find the last value of the specified index with the help of ^ operator that is:Index : Value\n [^1] : 45\n [^2] : 90\n [^3] : 88\n [^4] : 77\n [^5] : 56\n [^6] : 34\nImportant Points:The working of this operator is similar to myarr[arr.Length].You are not allowed to use myarr[^0] if you use this, then this will throw an error because the end index starts from ^1, not from ^0 as shown in the below example:Example:// C# program to illustrate the use // of the index from end operator(^)using System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array int[] myarr = new int[] {34, 56, 77, 88, 90, 45}; // Simply getting the index value Console.WriteLine(\"Values of the specified index:\"); Console.WriteLine(myarr[0]); // Now we use index from end(^) // operator with the given index // This will return the end value // which is related to the specified // index Console.WriteLine(\"The end values of the specified index:\"); Console.WriteLine(myarr[^0]); }}}Output:Values of the specified index:34The end values of the specified index:Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.at example.Program.Main(String[] args) in /Users/anki/Projects/example/example/Program.cs:line 22You are allowed to use the index as a variable and this variable place in between brackets[]. As shown in the below example:Example:// C# program to illustrate how// to declare a index as a variableusing System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array int[] number = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}; // Declare an index // as a variable Index i = ^6; var val = number[i]; // Displaying number Console.WriteLine(\"Number: \" + val); }}}Output:Number: 4"
},
{
"code": null,
"e": 4537,
"s": 4447,
"text": "// Old Method\nvar lastval = myarr[myarr.Length-1]\n\n// New Method\nvar lastval = myarr[^1]\n"
},
{
"code": null,
"e": 4546,
"s": 4537,
"text": "Example:"
},
{
"code": "// C# program to illustrate the use // of the index from end operator(^)using System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array int[] myarr = new int[] {34, 56, 77, 88, 90, 45}; // Simple getting the index value Console.WriteLine(\"Values of the specified indexes:\"); Console.WriteLine(myarr[0]); Console.WriteLine(myarr[1]); Console.WriteLine(myarr[2]); Console.WriteLine(myarr[3]); Console.WriteLine(myarr[4]); Console.WriteLine(myarr[5]); // Now we use index from end(^) // operator with the given index // This will return the end value // which is related to the specified // index Console.WriteLine(\"The end values of the specified indexes:\"); Console.WriteLine(myarr[^1]); Console.WriteLine(myarr[^2]); Console.WriteLine(myarr[^3]); Console.WriteLine(myarr[^4]); Console.WriteLine(myarr[^5]); Console.WriteLine(myarr[^6]); }}}",
"e": 5631,
"s": 4546,
"text": null
},
{
"code": null,
"e": 5639,
"s": 5631,
"text": "Output:"
},
{
"code": null,
"e": 5750,
"s": 5639,
"text": "Values of the specified indexes:\n34\n56\n77\n88\n90\n45\nThe end values of the specified indexes:\n45\n90\n88\n77\n56\n34\n"
},
{
"code": null,
"e": 5896,
"s": 5750,
"text": "Explanation: In the above example, we have an array of int type named myarr. Here, first we simply get the values of the specified index that is:"
},
{
"code": null,
"e": 6001,
"s": 5896,
"text": "34, 56, 77, 88, 90, 45\nIndex : Value\n [0] : 34\n [1] : 56\n [2] : 77\n [3] : 88\n [4] : 90\n [5] : 45\n\n"
},
{
"code": null,
"e": 6088,
"s": 6001,
"text": "Now we find the last value of the specified index with the help of ^ operator that is:"
},
{
"code": null,
"e": 6175,
"s": 6088,
"text": "Index : Value\n [^1] : 45\n [^2] : 90\n [^3] : 88\n [^4] : 77\n [^5] : 56\n [^6] : 34\n"
},
{
"code": null,
"e": 6193,
"s": 6175,
"text": "Important Points:"
},
{
"code": null,
"e": 6255,
"s": 6193,
"text": "The working of this operator is similar to myarr[arr.Length]."
},
{
"code": null,
"e": 7435,
"s": 6255,
"text": "You are not allowed to use myarr[^0] if you use this, then this will throw an error because the end index starts from ^1, not from ^0 as shown in the below example:Example:// C# program to illustrate the use // of the index from end operator(^)using System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array int[] myarr = new int[] {34, 56, 77, 88, 90, 45}; // Simply getting the index value Console.WriteLine(\"Values of the specified index:\"); Console.WriteLine(myarr[0]); // Now we use index from end(^) // operator with the given index // This will return the end value // which is related to the specified // index Console.WriteLine(\"The end values of the specified index:\"); Console.WriteLine(myarr[^0]); }}}Output:Values of the specified index:34The end values of the specified index:Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.at example.Program.Main(String[] args) in /Users/anki/Projects/example/example/Program.cs:line 22"
},
{
"code": null,
"e": 7444,
"s": 7435,
"text": "Example:"
},
{
"code": "// C# program to illustrate the use // of the index from end operator(^)using System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array int[] myarr = new int[] {34, 56, 77, 88, 90, 45}; // Simply getting the index value Console.WriteLine(\"Values of the specified index:\"); Console.WriteLine(myarr[0]); // Now we use index from end(^) // operator with the given index // This will return the end value // which is related to the specified // index Console.WriteLine(\"The end values of the specified index:\"); Console.WriteLine(myarr[^0]); }}}",
"e": 8182,
"s": 7444,
"text": null
},
{
"code": null,
"e": 8190,
"s": 8182,
"text": "Output:"
},
{
"code": null,
"e": 8454,
"s": 8190,
"text": "Values of the specified index:34The end values of the specified index:Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.at example.Program.Main(String[] args) in /Users/anki/Projects/example/example/Program.cs:line 22"
},
{
"code": null,
"e": 9102,
"s": 8454,
"text": "You are allowed to use the index as a variable and this variable place in between brackets[]. As shown in the below example:Example:// C# program to illustrate how// to declare a index as a variableusing System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array int[] number = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}; // Declare an index // as a variable Index i = ^6; var val = number[i]; // Displaying number Console.WriteLine(\"Number: \" + val); }}}Output:Number: 4"
},
{
"code": null,
"e": 9111,
"s": 9102,
"text": "Example:"
},
{
"code": "// C# program to illustrate how// to declare a index as a variableusing System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array int[] number = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}; // Declare an index // as a variable Index i = ^6; var val = number[i]; // Displaying number Console.WriteLine(\"Number: \" + val); }}}",
"e": 9611,
"s": 9111,
"text": null
},
{
"code": null,
"e": 9619,
"s": 9611,
"text": "Output:"
},
{
"code": null,
"e": 9629,
"s": 9619,
"text": "Number: 4"
},
{
"code": null,
"e": 13283,
"s": 9629,
"text": ".. Operator: It is known as the range operator. And it specifies the start and end as its operands of the given range. It is the most compact and easiest way to find the range of the elements from the specified sequence or collection in comparison to earlier methods.// Old Method\nvar arr = myemp.GetRange(1, 5);\n\n// New Method\nvar arr = myemp[2..3]\nExample:// C# program to illustrate the // use of the range operator(..)using System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array string[] myemp = new string[] {\"Anu\", \"Priya\", \"Rohit\", \"Amit\", \"Shreya\", \"Rinu\", \"Sumit\", \"Zoya\"}; Console.Write(\"Name of the employees in project A: \"); var P_A = myemp[0..3]; foreach(var emp1 in P_A) Console.Write($\" [{emp1}]\"); Console.Write(\"\\nName of the employees in project B: \"); var P_B = myemp[3..5]; foreach(var emp2 in P_B) Console.Write($\" [{emp2}]\"); Console.Write(\"\\nName of the employees in project C: \"); var P_C = myemp[1..^2]; foreach (var emp3 in P_C) Console.Write($\" [{emp3}]\"); Console.Write(\"\\nName of the employees in project D: \"); var P_D = myemp[..]; foreach(var emp4 in P_D) Console.Write($\" [{emp4}]\"); Console.Write(\"\\nName of the employees in project E: \"); var P_E = myemp[..2]; foreach(var emp5 in P_E) Console.Write($\" [{emp5}]\"); Console.Write(\"\\nName of the employees in project F: \"); var P_F = myemp[6..]; foreach(var emp6 in P_F) Console.Write($\" [{emp6}]\"); Console.Write(\"\\nName of the employees in project G: \"); var P_G = myemp[^3.. ^ 1]; foreach(var emp7 in P_G) Console.Write($\" [{emp7}]\"); }}}Output:Name of the employees in project A: [Anu] [Priya] [Rohit]\nName of the employees in project B: [Amit] [Shreya]\nName of the employees in project C: [Priya] [Rohit] [Amit] [Shreya] [Rinu]\nName of the employees in project D: [Anu] [Priya] [Rohit] [Amit] [Shreya] [Rinu] [Sumit] [Zoya]\nName of the employees in project E: [Anu] [Priya]\nName of the employees in project F: [Sumit] [Zoya]\nName of the employees in project G: [Rinu] [Sumit]\nImportant Points:When you create a range using range operator, then it will not add the last element. For example, we have an array {1, 2, 3, 4, 5, 6 }, now we want to print range[1..3], then it will print 2, 3. It does not print 2, 3, 4.In Range, if a range contains starting and ending index like Range[start, end], then such types of ranges are known as the bounded range.In Range, if a range contains only starting, ending index or doesn’t contain starting and ending indexes like Range[start..], or Range[..end], or Range[..], then such types of ranges are known as the unbounded range.You are allowed to use range as a variable and this variable place in between brackets[]. As shown in the below example:Example:// C# program to illustrate how to// declare a range as a variableusing System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array int[] number = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}; Console.Write(\"Number: \"); // Declaring a range as a variable Range num = 1..3; int[] val = number[num]; // Displaying number foreach(var n in val) Console.Write($\" [{n}]\"); }}}Output:Number: [2] [3]\n"
},
{
"code": null,
"e": 13367,
"s": 13283,
"text": "// Old Method\nvar arr = myemp.GetRange(1, 5);\n\n// New Method\nvar arr = myemp[2..3]\n"
},
{
"code": null,
"e": 13376,
"s": 13367,
"text": "Example:"
},
{
"code": "// C# program to illustrate the // use of the range operator(..)using System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array string[] myemp = new string[] {\"Anu\", \"Priya\", \"Rohit\", \"Amit\", \"Shreya\", \"Rinu\", \"Sumit\", \"Zoya\"}; Console.Write(\"Name of the employees in project A: \"); var P_A = myemp[0..3]; foreach(var emp1 in P_A) Console.Write($\" [{emp1}]\"); Console.Write(\"\\nName of the employees in project B: \"); var P_B = myemp[3..5]; foreach(var emp2 in P_B) Console.Write($\" [{emp2}]\"); Console.Write(\"\\nName of the employees in project C: \"); var P_C = myemp[1..^2]; foreach (var emp3 in P_C) Console.Write($\" [{emp3}]\"); Console.Write(\"\\nName of the employees in project D: \"); var P_D = myemp[..]; foreach(var emp4 in P_D) Console.Write($\" [{emp4}]\"); Console.Write(\"\\nName of the employees in project E: \"); var P_E = myemp[..2]; foreach(var emp5 in P_E) Console.Write($\" [{emp5}]\"); Console.Write(\"\\nName of the employees in project F: \"); var P_F = myemp[6..]; foreach(var emp6 in P_F) Console.Write($\" [{emp6}]\"); Console.Write(\"\\nName of the employees in project G: \"); var P_G = myemp[^3.. ^ 1]; foreach(var emp7 in P_G) Console.Write($\" [{emp7}]\"); }}}",
"e": 14925,
"s": 13376,
"text": null
},
{
"code": null,
"e": 14933,
"s": 14925,
"text": "Output:"
},
{
"code": null,
"e": 15374,
"s": 14933,
"text": "Name of the employees in project A: [Anu] [Priya] [Rohit]\nName of the employees in project B: [Amit] [Shreya]\nName of the employees in project C: [Priya] [Rohit] [Amit] [Shreya] [Rinu]\nName of the employees in project D: [Anu] [Priya] [Rohit] [Amit] [Shreya] [Rinu] [Sumit] [Zoya]\nName of the employees in project E: [Anu] [Priya]\nName of the employees in project F: [Sumit] [Zoya]\nName of the employees in project G: [Rinu] [Sumit]\n"
},
{
"code": null,
"e": 15392,
"s": 15374,
"text": "Important Points:"
},
{
"code": null,
"e": 15614,
"s": 15392,
"text": "When you create a range using range operator, then it will not add the last element. For example, we have an array {1, 2, 3, 4, 5, 6 }, now we want to print range[1..3], then it will print 2, 3. It does not print 2, 3, 4."
},
{
"code": null,
"e": 15752,
"s": 15614,
"text": "In Range, if a range contains starting and ending index like Range[start, end], then such types of ranges are known as the bounded range."
},
{
"code": null,
"e": 15969,
"s": 15752,
"text": "In Range, if a range contains only starting, ending index or doesn’t contain starting and ending indexes like Range[start..], or Range[..end], or Range[..], then such types of ranges are known as the unbounded range."
},
{
"code": null,
"e": 16679,
"s": 15969,
"text": "You are allowed to use range as a variable and this variable place in between brackets[]. As shown in the below example:Example:// C# program to illustrate how to// declare a range as a variableusing System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array int[] number = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}; Console.Write(\"Number: \"); // Declaring a range as a variable Range num = 1..3; int[] val = number[num]; // Displaying number foreach(var n in val) Console.Write($\" [{n}]\"); }}}Output:Number: [2] [3]\n"
},
{
"code": null,
"e": 16688,
"s": 16679,
"text": "Example:"
},
{
"code": "// C# program to illustrate how to// declare a range as a variableusing System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array int[] number = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}; Console.Write(\"Number: \"); // Declaring a range as a variable Range num = 1..3; int[] val = number[num]; // Displaying number foreach(var n in val) Console.Write($\" [{n}]\"); }}}",
"e": 17246,
"s": 16688,
"text": null
},
{
"code": null,
"e": 17254,
"s": 17246,
"text": "Output:"
},
{
"code": null,
"e": 17272,
"s": 17254,
"text": "Number: [2] [3]\n"
},
{
"code": null,
"e": 17283,
"s": 17272,
"text": "CSharp-8.0"
},
{
"code": null,
"e": 17286,
"s": 17283,
"text": "C#"
},
{
"code": null,
"e": 17384,
"s": 17286,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 17412,
"s": 17384,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 17443,
"s": 17412,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 17458,
"s": 17443,
"text": "C# | Delegates"
},
{
"code": null,
"e": 17501,
"s": 17458,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 17550,
"s": 17501,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 17573,
"s": 17550,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 17591,
"s": 17573,
"text": "C# | Constructors"
},
{
"code": null,
"e": 17631,
"s": 17591,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 17653,
"s": 17631,
"text": "C# | Class and Object"
}
] |
Minimum number of Binary strings to represent a Number | 17 Nov, 2021
Given a number N. The task is to find the minimum number of binary strings required to represent the given number as the sum of the binary strings.Examples:
Input : 131 Output : Minimum Number of binary strings needed: 3 111 10 10 Input : 564 Output :Minimum Number of binary strings needed: 6 111 111 111 111 110 10
Approach:
Store all digits of the given number in the array.
Find the maximum digit in the array. This maximum number(maxi) indicates the number of binary strings required to represent the given number.
Now, find maxi numbers by substituting 0’s and 1’s greadily.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find the minimum number of// binary strings to represent a number#include <bits/stdc++.h>using namespace std; // Function to find the minimum number of// binary strings to represent a numbervoid minBinary(int n){ int digit[10], len = 0; while (n > 0) { digit[len++] = n % 10; n /= 10; } // Storing digits in correct order reverse(digit, digit + len); int ans = 0; // Find the maximum digit in the array for (int i = 0; i < len; i++) { ans = max(ans, digit[i]); } cout << "Minimum Number of binary strings needed: " << ans << endl; // Traverse for all the binary strings for (int i = 1; i <= ans; i++) { int num = 0; for (int j = 0; j < len; j++) { // If digit at jth position is greater // than 0 then substitute 1 if (digit[j] > 0) { num = num * 10 + 1; digit[j]--; } else { num *= 10; } } cout << num << " "; } } // Driver codeint main(){ int n = 564; minBinary(n); return 0;}
// Java program to find the minimum number of// binary Strings to represent a numberimport java.util.*; class GFG{ // Function to find the minimum number of // binary Strings to represent a number static void minBinary(int n) { int[] digit = new int[10]; int len = 0; while (n > 0) { digit[len++] = n % 10; n /= 10; } // Storing digits in correct order digit = reverse(digit, 0, len - 1); int ans = 0; // Find the maximum digit in the array for (int i = 0; i < len; i++) { ans = Math.max(ans, digit[i]); } System.out.print("Minimum Number of binary" + " Strings needed: " + ans + "\n"); // Traverse for all the binary Strings for (int i = 1; i <= ans; i++) { int num = 0; for (int j = 0; j < len; j++) { // If digit at jth position is greater // than 0 then substitute 1 if (digit[j] > 0) { num = num * 10 + 1; digit[j]--; } else { num *= 10; } } System.out.print(num + " "); } } static int[] reverse(int str[], int start, int end) { // Temporary variable to store character int temp; while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } return str; } // Driver code public static void main(String[] args) { int n = 564; minBinary(n); }} // This code is contributed by 29AjayKumar
# Python3 program to find the minimum number of# binary strings to represent a number # Function to find the minimum number of# binary strings to represent a numberdef minBinary(n): digit = [0 for i in range(3)] len = 0 while (n > 0): digit[len] = n % 10 len += 1 n //= 10 # Storing digits in correct order digit = digit[::-1] ans = 0 # Find the maximum digit in the array for i in range(len): ans = max(ans, digit[i]) print("Minimum Number of binary strings needed:", ans) # Traverse for all the binary strings for i in range(1, ans + 1, 1): num = 0 for j in range(0, len, 1): # If digit at jth position is greater # than 0 then substitute 1 if (digit[j] > 0): num = num * 10 + 1 digit[j] -= 1 else: num *= 10 print(num, end = " ") # Driver codeif __name__ == '__main__': n = 564 minBinary(n) # This code is contributed by# Surendra_Gangwar
// C# program to find the minimum number of// binary Strings to represent a numberusing System; class GFG{ // Function to find the minimum number of // binary Strings to represent a number static void minBinary(int n) { int[] digit = new int[10]; int len = 0; while (n > 0) { digit[len++] = n % 10; n /= 10; } // Storing digits in correct order digit = reverse(digit, 0, len - 1); int ans = 0; // Find the maximum digit in the array for (int i = 0; i < len; i++) { ans = Math.Max(ans, digit[i]); } Console.Write("Minimum Number of binary" + " Strings needed: " + ans + "\n"); // Traverse for all the binary Strings for (int i = 1; i <= ans; i++) { int num = 0; for (int j = 0; j < len; j++) { // If digit at jth position is greater // than 0 then substitute 1 if (digit[j] > 0) { num = num * 10 + 1; digit[j]--; } else { num *= 10; } } Console.Write(num + " "); } } static int[] reverse(int []str, int start, int end) { // Temporary variable to store character int temp; while (start <= end) { // Swapping the first and // last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } return str; } // Driver code public static void Main(String[] args) { int n = 564; minBinary(n); }} // This code is contributed by 29AjayKumar
<script> // Javascript program to// find the minimum number of// binary Strings to represent// a number // Function to find the minimum number of // binary Strings to represent a number function minBinary(n) { var digit = Array(10).fill(0); var len = 0; while (n > 0) { digit[len++] = n % 10; n = parseInt(n/10); } // Storing digits in correct order digit = reverse(digit, 0, len - 1); var ans = 0; // Find the maximum digit in the array for (i = 0; i < len; i++) { ans = Math.max(ans, digit[i]); } document.write("Minimum Number of binary" + " Strings needed: " + ans + "<br/>"); // Traverse for all the binary Strings for (i = 1; i <= ans; i++) { var num = 0; for (j = 0; j < len; j++) { // If digit at jth position is greater // than 0 then substitute 1 if (digit[j] > 0) { num = num * 10 + 1; digit[j]--; } else { num *= 10; } } document.write(num + " "); } } function reverse(str , start , end) { // Temporary variable to store character var temp; while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } return str; } // Driver code var n = 564; minBinary(n); // This code contributed by umadevi9616 </script>
Output:
Minimum No of binary strings needed: 6
111 111 111 111 110 10
Time Complexity: O(N)
Auxiliary Space: O(1)
SURENDRA_GANGWAR
29AjayKumar
umadevi9616
rohitsingh07052
binary-string
Greedy Algorithms
Arrays
Greedy
Arrays
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Nov, 2021"
},
{
"code": null,
"e": 187,
"s": 28,
"text": "Given a number N. The task is to find the minimum number of binary strings required to represent the given number as the sum of the binary strings.Examples: "
},
{
"code": null,
"e": 349,
"s": 187,
"text": "Input : 131 Output : Minimum Number of binary strings needed: 3 111 10 10 Input : 564 Output :Minimum Number of binary strings needed: 6 111 111 111 111 110 10 "
},
{
"code": null,
"e": 363,
"s": 351,
"text": "Approach: "
},
{
"code": null,
"e": 414,
"s": 363,
"text": "Store all digits of the given number in the array."
},
{
"code": null,
"e": 556,
"s": 414,
"text": "Find the maximum digit in the array. This maximum number(maxi) indicates the number of binary strings required to represent the given number."
},
{
"code": null,
"e": 617,
"s": 556,
"text": "Now, find maxi numbers by substituting 0’s and 1’s greadily."
},
{
"code": null,
"e": 670,
"s": 617,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 674,
"s": 670,
"text": "C++"
},
{
"code": null,
"e": 679,
"s": 674,
"text": "Java"
},
{
"code": null,
"e": 687,
"s": 679,
"text": "Python3"
},
{
"code": null,
"e": 690,
"s": 687,
"text": "C#"
},
{
"code": null,
"e": 701,
"s": 690,
"text": "Javascript"
},
{
"code": "// C++ program to find the minimum number of// binary strings to represent a number#include <bits/stdc++.h>using namespace std; // Function to find the minimum number of// binary strings to represent a numbervoid minBinary(int n){ int digit[10], len = 0; while (n > 0) { digit[len++] = n % 10; n /= 10; } // Storing digits in correct order reverse(digit, digit + len); int ans = 0; // Find the maximum digit in the array for (int i = 0; i < len; i++) { ans = max(ans, digit[i]); } cout << \"Minimum Number of binary strings needed: \" << ans << endl; // Traverse for all the binary strings for (int i = 1; i <= ans; i++) { int num = 0; for (int j = 0; j < len; j++) { // If digit at jth position is greater // than 0 then substitute 1 if (digit[j] > 0) { num = num * 10 + 1; digit[j]--; } else { num *= 10; } } cout << num << \" \"; } } // Driver codeint main(){ int n = 564; minBinary(n); return 0;}",
"e": 1853,
"s": 701,
"text": null
},
{
"code": "// Java program to find the minimum number of// binary Strings to represent a numberimport java.util.*; class GFG{ // Function to find the minimum number of // binary Strings to represent a number static void minBinary(int n) { int[] digit = new int[10]; int len = 0; while (n > 0) { digit[len++] = n % 10; n /= 10; } // Storing digits in correct order digit = reverse(digit, 0, len - 1); int ans = 0; // Find the maximum digit in the array for (int i = 0; i < len; i++) { ans = Math.max(ans, digit[i]); } System.out.print(\"Minimum Number of binary\" + \" Strings needed: \" + ans + \"\\n\"); // Traverse for all the binary Strings for (int i = 1; i <= ans; i++) { int num = 0; for (int j = 0; j < len; j++) { // If digit at jth position is greater // than 0 then substitute 1 if (digit[j] > 0) { num = num * 10 + 1; digit[j]--; } else { num *= 10; } } System.out.print(num + \" \"); } } static int[] reverse(int str[], int start, int end) { // Temporary variable to store character int temp; while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } return str; } // Driver code public static void main(String[] args) { int n = 564; minBinary(n); }} // This code is contributed by 29AjayKumar",
"e": 3717,
"s": 1853,
"text": null
},
{
"code": "# Python3 program to find the minimum number of# binary strings to represent a number # Function to find the minimum number of# binary strings to represent a numberdef minBinary(n): digit = [0 for i in range(3)] len = 0 while (n > 0): digit[len] = n % 10 len += 1 n //= 10 # Storing digits in correct order digit = digit[::-1] ans = 0 # Find the maximum digit in the array for i in range(len): ans = max(ans, digit[i]) print(\"Minimum Number of binary strings needed:\", ans) # Traverse for all the binary strings for i in range(1, ans + 1, 1): num = 0 for j in range(0, len, 1): # If digit at jth position is greater # than 0 then substitute 1 if (digit[j] > 0): num = num * 10 + 1 digit[j] -= 1 else: num *= 10 print(num, end = \" \") # Driver codeif __name__ == '__main__': n = 564 minBinary(n) # This code is contributed by# Surendra_Gangwar",
"e": 4780,
"s": 3717,
"text": null
},
{
"code": "// C# program to find the minimum number of// binary Strings to represent a numberusing System; class GFG{ // Function to find the minimum number of // binary Strings to represent a number static void minBinary(int n) { int[] digit = new int[10]; int len = 0; while (n > 0) { digit[len++] = n % 10; n /= 10; } // Storing digits in correct order digit = reverse(digit, 0, len - 1); int ans = 0; // Find the maximum digit in the array for (int i = 0; i < len; i++) { ans = Math.Max(ans, digit[i]); } Console.Write(\"Minimum Number of binary\" + \" Strings needed: \" + ans + \"\\n\"); // Traverse for all the binary Strings for (int i = 1; i <= ans; i++) { int num = 0; for (int j = 0; j < len; j++) { // If digit at jth position is greater // than 0 then substitute 1 if (digit[j] > 0) { num = num * 10 + 1; digit[j]--; } else { num *= 10; } } Console.Write(num + \" \"); } } static int[] reverse(int []str, int start, int end) { // Temporary variable to store character int temp; while (start <= end) { // Swapping the first and // last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } return str; } // Driver code public static void Main(String[] args) { int n = 564; minBinary(n); }} // This code is contributed by 29AjayKumar",
"e": 6641,
"s": 4780,
"text": null
},
{
"code": "<script> // Javascript program to// find the minimum number of// binary Strings to represent// a number // Function to find the minimum number of // binary Strings to represent a number function minBinary(n) { var digit = Array(10).fill(0); var len = 0; while (n > 0) { digit[len++] = n % 10; n = parseInt(n/10); } // Storing digits in correct order digit = reverse(digit, 0, len - 1); var ans = 0; // Find the maximum digit in the array for (i = 0; i < len; i++) { ans = Math.max(ans, digit[i]); } document.write(\"Minimum Number of binary\" + \" Strings needed: \" + ans + \"<br/>\"); // Traverse for all the binary Strings for (i = 1; i <= ans; i++) { var num = 0; for (j = 0; j < len; j++) { // If digit at jth position is greater // than 0 then substitute 1 if (digit[j] > 0) { num = num * 10 + 1; digit[j]--; } else { num *= 10; } } document.write(num + \" \"); } } function reverse(str , start , end) { // Temporary variable to store character var temp; while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } return str; } // Driver code var n = 564; minBinary(n); // This code contributed by umadevi9616 </script>",
"e": 8328,
"s": 6641,
"text": null
},
{
"code": null,
"e": 8338,
"s": 8328,
"text": "Output: "
},
{
"code": null,
"e": 8401,
"s": 8338,
"text": "Minimum No of binary strings needed: 6\n111 111 111 111 110 10 "
},
{
"code": null,
"e": 8423,
"s": 8401,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 8446,
"s": 8423,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 8463,
"s": 8446,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 8475,
"s": 8463,
"text": "29AjayKumar"
},
{
"code": null,
"e": 8487,
"s": 8475,
"text": "umadevi9616"
},
{
"code": null,
"e": 8503,
"s": 8487,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 8517,
"s": 8503,
"text": "binary-string"
},
{
"code": null,
"e": 8535,
"s": 8517,
"text": "Greedy Algorithms"
},
{
"code": null,
"e": 8542,
"s": 8535,
"text": "Arrays"
},
{
"code": null,
"e": 8549,
"s": 8542,
"text": "Greedy"
},
{
"code": null,
"e": 8556,
"s": 8549,
"text": "Arrays"
},
{
"code": null,
"e": 8563,
"s": 8556,
"text": "Greedy"
}
] |
Python | Tensorflow nn.sigmoid() | 12 Dec, 2021
Tensorflow is an open-source machine learning library developed by Google. One of its applications is to develop deep neural networks. The module tensorflow.nn provides support for many basic neural network operations.One of the many activation functions is the sigmoid function which is defined as .Sigmoid function outputs in the range (0, 1), it makes it ideal for binary classification problems where we need to find the probability of the data belonging to a particular class. The sigmoid function is differentiable at every point and its derivative comes out to be . Since the expression involves the sigmoid function, its value can be reused to make the backward propagation faster.Sigmoid function suffers from the problem of “vanishing gradients” as it flattens out at both ends, resulting in very small changes in the weights during backpropagation. This can make the neural network refuse to learn and get stuck. Due to this reason, usage of the sigmoid function is being replaced by other non-linear functions such as Rectified Linear Unit (ReLU).The function tf.nn.sigmoid() [alias tf.sigmoid] provides support for the sigmoid function in Tensorflow.
Syntax: tf.nn.sigmoid(x, name=None) or tf.sigmoid(x, name=None)Parameters: x: A tensor of any of the following types: float16, float32, float64, complex64, or complex128. name (optional): The name for the operation.Return type: A tensor with the same type as that of x.
Code #1:
Python3
# Importing the Tensorflow libraryimport tensorflow as tf # A constant vector of size 6a = tf.constant([1.0, -0.5, 3.4, -2.1, 0.0, -6.5], dtype = tf.float32) # Applying the sigmoid function and# storing the result in 'b'b = tf.nn.sigmoid(a, name ='sigmoid') # Initiating a Tensorflow sessionwith tf.Session() as sess: print('Input type:', a) print('Input:', sess.run(a)) print('Return type:', b) print('Output:', sess.run(b))
Output:
Input type: Tensor("Const_1:0", shape=(6, ), dtype=float32)
Input: [ 1. -0.5 3.4000001 -2.0999999 0. -6.5 ]
Return type: Tensor("sigmoid:0", shape=(6, ), dtype=float32)
Output: [ 0.7310586 0.37754068 0.96770459 0.10909683 0.5 0.00150118]
Code #2: Visualization
Python3
# Importing the Tensorflow libraryimport tensorflow as tf # Importing the NumPy libraryimport numpy as np # Importing the matplotlib.pyplot functionimport matplotlib.pyplot as plt # A vector of size 15 with values from -5 to 5a = np.linspace(-5, 5, 15) # Applying the sigmoid function and# storing the result in 'b'b = tf.nn.sigmoid(a, name ='sigmoid') # Initiating a Tensorflow sessionwith tf.Session() as sess: print('Input:', a) print('Output:', sess.run(b)) plt.plot(a, sess.run(b), color = 'red', marker = "o") plt.title("tensorflow.nn.sigmoid") plt.xlabel("X") plt.ylabel("Y") plt.show()
Output:
Input: Input: [-5. -4.28571429 -3.57142857 -2.85714286 -2.14285714 -1.42857143
-0.71428571 0. 0.71428571 1.42857143 2.14285714 2.85714286
3.57142857 4.28571429 5. ]
Output: [ 0.00669285 0.01357692 0.02734679 0.05431327 0.10500059 0.19332137
0.32865255 0.5 0.67134745 0.80667863 0.89499941 0.94568673
0.97265321 0.98642308 0.99330715]
sanskar27jain
sweetyty
Tensorflow
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Reinforcement learning
Supervised and Unsupervised learning
Decision Tree Introduction with example
Search Algorithms in AI
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": 28,
"s": 0,
"text": "\n12 Dec, 2021"
},
{
"code": null,
"e": 1193,
"s": 28,
"text": "Tensorflow is an open-source machine learning library developed by Google. One of its applications is to develop deep neural networks. The module tensorflow.nn provides support for many basic neural network operations.One of the many activation functions is the sigmoid function which is defined as .Sigmoid function outputs in the range (0, 1), it makes it ideal for binary classification problems where we need to find the probability of the data belonging to a particular class. The sigmoid function is differentiable at every point and its derivative comes out to be . Since the expression involves the sigmoid function, its value can be reused to make the backward propagation faster.Sigmoid function suffers from the problem of “vanishing gradients” as it flattens out at both ends, resulting in very small changes in the weights during backpropagation. This can make the neural network refuse to learn and get stuck. Due to this reason, usage of the sigmoid function is being replaced by other non-linear functions such as Rectified Linear Unit (ReLU).The function tf.nn.sigmoid() [alias tf.sigmoid] provides support for the sigmoid function in Tensorflow. "
},
{
"code": null,
"e": 1465,
"s": 1193,
"text": "Syntax: tf.nn.sigmoid(x, name=None) or tf.sigmoid(x, name=None)Parameters: x: A tensor of any of the following types: float16, float32, float64, complex64, or complex128. name (optional): The name for the operation.Return type: A tensor with the same type as that of x. "
},
{
"code": null,
"e": 1475,
"s": 1465,
"text": "Code #1: "
},
{
"code": null,
"e": 1483,
"s": 1475,
"text": "Python3"
},
{
"code": "# Importing the Tensorflow libraryimport tensorflow as tf # A constant vector of size 6a = tf.constant([1.0, -0.5, 3.4, -2.1, 0.0, -6.5], dtype = tf.float32) # Applying the sigmoid function and# storing the result in 'b'b = tf.nn.sigmoid(a, name ='sigmoid') # Initiating a Tensorflow sessionwith tf.Session() as sess: print('Input type:', a) print('Input:', sess.run(a)) print('Return type:', b) print('Output:', sess.run(b))",
"e": 1921,
"s": 1483,
"text": null
},
{
"code": null,
"e": 1930,
"s": 1921,
"text": "Output: "
},
{
"code": null,
"e": 2208,
"s": 1930,
"text": "Input type: Tensor(\"Const_1:0\", shape=(6, ), dtype=float32)\nInput: [ 1. -0.5 3.4000001 -2.0999999 0. -6.5 ]\nReturn type: Tensor(\"sigmoid:0\", shape=(6, ), dtype=float32)\nOutput: [ 0.7310586 0.37754068 0.96770459 0.10909683 0.5 0.00150118]"
},
{
"code": null,
"e": 2232,
"s": 2208,
"text": "Code #2: Visualization "
},
{
"code": null,
"e": 2240,
"s": 2232,
"text": "Python3"
},
{
"code": "# Importing the Tensorflow libraryimport tensorflow as tf # Importing the NumPy libraryimport numpy as np # Importing the matplotlib.pyplot functionimport matplotlib.pyplot as plt # A vector of size 15 with values from -5 to 5a = np.linspace(-5, 5, 15) # Applying the sigmoid function and# storing the result in 'b'b = tf.nn.sigmoid(a, name ='sigmoid') # Initiating a Tensorflow sessionwith tf.Session() as sess: print('Input:', a) print('Output:', sess.run(b)) plt.plot(a, sess.run(b), color = 'red', marker = \"o\") plt.title(\"tensorflow.nn.sigmoid\") plt.xlabel(\"X\") plt.ylabel(\"Y\") plt.show()",
"e": 2856,
"s": 2240,
"text": null
},
{
"code": null,
"e": 2866,
"s": 2856,
"text": "Output: "
},
{
"code": null,
"e": 3256,
"s": 2866,
"text": "Input: Input: [-5. -4.28571429 -3.57142857 -2.85714286 -2.14285714 -1.42857143\n -0.71428571 0. 0.71428571 1.42857143 2.14285714 2.85714286\n 3.57142857 4.28571429 5. ]\nOutput: [ 0.00669285 0.01357692 0.02734679 0.05431327 0.10500059 0.19332137\n 0.32865255 0.5 0.67134745 0.80667863 0.89499941 0.94568673\n 0.97265321 0.98642308 0.99330715]"
},
{
"code": null,
"e": 3274,
"s": 3260,
"text": "sanskar27jain"
},
{
"code": null,
"e": 3283,
"s": 3274,
"text": "sweetyty"
},
{
"code": null,
"e": 3294,
"s": 3283,
"text": "Tensorflow"
},
{
"code": null,
"e": 3311,
"s": 3294,
"text": "Machine Learning"
},
{
"code": null,
"e": 3318,
"s": 3311,
"text": "Python"
},
{
"code": null,
"e": 3335,
"s": 3318,
"text": "Machine Learning"
},
{
"code": null,
"e": 3433,
"s": 3335,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3456,
"s": 3433,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 3479,
"s": 3456,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 3516,
"s": 3479,
"text": "Supervised and Unsupervised learning"
},
{
"code": null,
"e": 3556,
"s": 3516,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 3580,
"s": 3556,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 3608,
"s": 3580,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3658,
"s": 3608,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3680,
"s": 3658,
"text": "Python map() function"
}
] |
Stream mapToDouble() in Java with examples | 06 Dec, 2018
Stream mapToDouble (ToDoubleFunction mapper) returns a DoubleStream consisting of the results of applying the given function to the elements of this stream.
Stream mapToDouble (ToDoubleFunction mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance as output.
Syntax :
DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper)
Where, A sequence of primitive double-valued
elements and T is the type of stream elements.
mapper is a stateless function which is applied
to each element and the function returns the new stream.
Example 1 : mapToDouble() with operation of selecting elements satisfying given function.
// Java code for Stream mapToDouble// (ToDoubleFunction mapper) to get a// DoubleStream by applying the given function// to the elements of this stream.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of Strings List<String> list = Arrays.asList("10", "6.548", "9.12", "11", "15"); // Using Stream mapToDouble(ToDoubleFunction mapper) // and displaying the corresponding DoubleStream list.stream().mapToDouble(num -> Double.parseDouble(num)) .filter(num -> (num * num) * 2 == 450) .forEach(System.out::println); }}
Output :
15.0
Example 2 : mapToDouble() with operation of returning a stream with square of string length.
// Java code for Stream mapToDouble// (ToDoubleFunction mapper) to get a// DoubleStream by applying the given function// to the elements of this stream.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of Strings List<String> list = Arrays.asList("CSE", "JAVA", "gfg", "C++", "C"); // Using Stream mapToDouble(ToDoubleFunction mapper) // and displaying the corresponding DoubleStream // which contains square of length of each element in // given Stream list.stream().mapToDouble(str -> str.length() * str.length()) .forEach(System.out::println); }}
Output :
9.0
16.0
9.0
9.0
1.0
Java - util package
Java-Functions
java-stream
Java-Stream interface
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Dec, 2018"
},
{
"code": null,
"e": 185,
"s": 28,
"text": "Stream mapToDouble (ToDoubleFunction mapper) returns a DoubleStream consisting of the results of applying the given function to the elements of this stream."
},
{
"code": null,
"e": 430,
"s": 185,
"text": "Stream mapToDouble (ToDoubleFunction mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance as output."
},
{
"code": null,
"e": 439,
"s": 430,
"text": "Syntax :"
},
{
"code": null,
"e": 700,
"s": 439,
"text": "DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper)\n\nWhere, A sequence of primitive double-valued\nelements and T is the type of stream elements. \nmapper is a stateless function which is applied\nto each element and the function returns the new stream.\n"
},
{
"code": null,
"e": 790,
"s": 700,
"text": "Example 1 : mapToDouble() with operation of selecting elements satisfying given function."
},
{
"code": "// Java code for Stream mapToDouble// (ToDoubleFunction mapper) to get a// DoubleStream by applying the given function// to the elements of this stream.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of Strings List<String> list = Arrays.asList(\"10\", \"6.548\", \"9.12\", \"11\", \"15\"); // Using Stream mapToDouble(ToDoubleFunction mapper) // and displaying the corresponding DoubleStream list.stream().mapToDouble(num -> Double.parseDouble(num)) .filter(num -> (num * num) * 2 == 450) .forEach(System.out::println); }}",
"e": 1506,
"s": 790,
"text": null
},
{
"code": null,
"e": 1515,
"s": 1506,
"text": "Output :"
},
{
"code": null,
"e": 1521,
"s": 1515,
"text": "15.0\n"
},
{
"code": null,
"e": 1614,
"s": 1521,
"text": "Example 2 : mapToDouble() with operation of returning a stream with square of string length."
},
{
"code": "// Java code for Stream mapToDouble// (ToDoubleFunction mapper) to get a// DoubleStream by applying the given function// to the elements of this stream.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of Strings List<String> list = Arrays.asList(\"CSE\", \"JAVA\", \"gfg\", \"C++\", \"C\"); // Using Stream mapToDouble(ToDoubleFunction mapper) // and displaying the corresponding DoubleStream // which contains square of length of each element in // given Stream list.stream().mapToDouble(str -> str.length() * str.length()) .forEach(System.out::println); }}",
"e": 2358,
"s": 1614,
"text": null
},
{
"code": null,
"e": 2367,
"s": 2358,
"text": "Output :"
},
{
"code": null,
"e": 2389,
"s": 2367,
"text": "9.0\n16.0\n9.0\n9.0\n1.0\n"
},
{
"code": null,
"e": 2409,
"s": 2389,
"text": "Java - util package"
},
{
"code": null,
"e": 2424,
"s": 2409,
"text": "Java-Functions"
},
{
"code": null,
"e": 2436,
"s": 2424,
"text": "java-stream"
},
{
"code": null,
"e": 2458,
"s": 2436,
"text": "Java-Stream interface"
},
{
"code": null,
"e": 2463,
"s": 2458,
"text": "Java"
},
{
"code": null,
"e": 2468,
"s": 2463,
"text": "Java"
},
{
"code": null,
"e": 2566,
"s": 2468,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2617,
"s": 2566,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 2648,
"s": 2617,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 2667,
"s": 2648,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 2697,
"s": 2667,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 2712,
"s": 2697,
"text": "Stream In Java"
},
{
"code": null,
"e": 2730,
"s": 2712,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 2750,
"s": 2730,
"text": "Collections in Java"
},
{
"code": null,
"e": 2774,
"s": 2750,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 2806,
"s": 2774,
"text": "Multidimensional Arrays in Java"
}
] |
Elasticsearch - Aggregations | The aggregations framework collects all the data selected by the search query and consists of many building blocks, which help in building complex summaries of the data. The basic structure of an aggregation is shown here −
"aggregations" : {
"" : {
"" : {
}
[,"meta" : { [] } ]?
[,"aggregations" : { []+ } ]?
}
[,"" : { ... } ]*
}
There are different types of aggregations, each with its own purpose. They are discussed in detail in this chapter.
These aggregations help in computing matrices from the field’s values of the aggregated documents and sometime some values can be generated from scripts.
Numeric matrices are either single-valued like average aggregation or multi-valued like stats.
This aggregation is used to get the average of any numeric field present in the aggregated
documents. For example,
POST /schools/_search
{
"aggs":{
"avg_fees":{"avg":{"field":"fees"}}
}
}
On running the above code, we get the following result −
{
"took" : 41,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "schools",
"_type" : "school",
"_id" : "5",
"_score" : 1.0,
"_source" : {
"name" : "Central School",
"description" : "CBSE Affiliation",
"street" : "Nagan",
"city" : "paprola",
"state" : "HP",
"zip" : "176115",
"location" : [
31.8955385,
76.8380405
],
"fees" : 2200,
"tags" : [
"Senior Secondary",
"beautiful campus"
],
"rating" : "3.3"
}
},
{
"_index" : "schools",
"_type" : "school",
"_id" : "4",
"_score" : 1.0,
"_source" : {
"name" : "City Best School",
"description" : "ICSE",
"street" : "West End",
"city" : "Meerut",
"state" : "UP",
"zip" : "250002",
"location" : [
28.9926174,
77.692485
],
"fees" : 3500,
"tags" : [
"fully computerized"
],
"rating" : "4.5"
}
}
]
},
"aggregations" : {
"avg_fees" : {
"value" : 2850.0
}
}
}
This aggregation gives the count of distinct values of a particular field.
POST /schools/_search?size=0
{
"aggs":{
"distinct_name_count":{"cardinality":{"field":"fees"}}
}
}
On running the above code, we get the following result −
{
"took" : 2,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"distinct_name_count" : {
"value" : 2
}
}
}
Note − The value of cardinality is 2 because there are two distinct values in fees.
This aggregation generates all the statistics about a specific numerical field in aggregated documents.
POST /schools/_search?size=0
{
"aggs" : {
"fees_stats" : { "extended_stats" : { "field" : "fees" } }
}
}
On running the above code, we get the following result −
{
"took" : 8,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"fees_stats" : {
"count" : 2,
"min" : 2200.0,
"max" : 3500.0,
"avg" : 2850.0,
"sum" : 5700.0,
"sum_of_squares" : 1.709E7,
"variance" : 422500.0,
"std_deviation" : 650.0,
"std_deviation_bounds" : {
"upper" : 4150.0,
"lower" : 1550.0
}
}
}
}
This aggregation finds the max value of a specific numeric field in aggregated documents.
POST /schools/_search?size=0
{
"aggs" : {
"max_fees" : { "max" : { "field" : "fees" } }
}
}
On running the above code, we get the following result −
{
"took" : 16,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"max_fees" : {
"value" : 3500.0
}
}
}
This aggregation finds the min value of a specific numeric field in aggregated documents.
POST /schools/_search?size=0
{
"aggs" : {
"min_fees" : { "min" : { "field" : "fees" } }
}
}
On running the above code, we get the following result −
{
"took" : 2,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"min_fees" : {
"value" : 2200.0
}
}
}
This aggregation calculates the sum of a specific numeric field in aggregated documents.
POST /schools/_search?size=0
{
"aggs" : {
"total_fees" : { "sum" : { "field" : "fees" } }
}
}
On running the above code, we get the following result −
{
"took" : 8,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"total_fees" : {
"value" : 5700.0
}
}
}
There are some other metrics aggregations which are used in special cases like geo bounds aggregation and geo centroid aggregation for the purpose of geo location.
A multi-value metrics aggregation that computes stats over numeric values extracted from the aggregated documents.
POST /schools/_search?size=0
{
"aggs" : {
"grades_stats" : { "stats" : { "field" : "fees" } }
}
}
On running the above code, we get the following result −
{
"took" : 2,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"grades_stats" : {
"count" : 2,
"min" : 2200.0,
"max" : 3500.0,
"avg" : 2850.0,
"sum" : 5700.0
}
}
}
You can add some data about the aggregation at the time of request by using meta tag and can get that in response.
POST /schools/_search?size=0
{
"aggs" : {
"avg_fees" : { "avg" : { "field" : "fees" } ,
"meta" :{
"dsc" :"Lowest Fees This Year"
}
}
}
}
On running the above code, we get the following result −
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"avg_fees" : {
"meta" : {
"dsc" : "Lowest Fees This Year"
},
"value" : 2850.0 | [
{
"code": null,
"e": 2939,
"s": 2715,
"text": "The aggregations framework collects all the data selected by the search query and consists of many building blocks, which help in building complex summaries of the data. The basic structure of an aggregation is shown here −"
},
{
"code": null,
"e": 3083,
"s": 2939,
"text": "\"aggregations\" : {\n \"\" : {\n \"\" : {\n\n }\n \n [,\"meta\" : { [] } ]?\n [,\"aggregations\" : { []+ } ]?\n }\n [,\"\" : { ... } ]*\n}"
},
{
"code": null,
"e": 3199,
"s": 3083,
"text": "There are different types of aggregations, each with its own purpose. They are discussed in detail in this chapter."
},
{
"code": null,
"e": 3353,
"s": 3199,
"text": "These aggregations help in computing matrices from the field’s values of the aggregated documents and sometime some values can be generated from scripts."
},
{
"code": null,
"e": 3448,
"s": 3353,
"text": "Numeric matrices are either single-valued like average aggregation or multi-valued like stats."
},
{
"code": null,
"e": 3563,
"s": 3448,
"text": "This aggregation is used to get the average of any numeric field present in the aggregated\ndocuments. For example,"
},
{
"code": null,
"e": 3648,
"s": 3563,
"text": "POST /schools/_search\n{\n \"aggs\":{\n \"avg_fees\":{\"avg\":{\"field\":\"fees\"}}\n }\n}"
},
{
"code": null,
"e": 3705,
"s": 3648,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 5334,
"s": 3705,
"text": "{\n \"took\" : 41,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 2,\n \"relation\" : \"eq\"\n },\n \"max_score\" : 1.0,\n \"hits\" : [\n {\n \"_index\" : \"schools\",\n \"_type\" : \"school\",\n \"_id\" : \"5\",\n \"_score\" : 1.0,\n \"_source\" : {\n \"name\" : \"Central School\",\n \"description\" : \"CBSE Affiliation\",\n \"street\" : \"Nagan\",\n \"city\" : \"paprola\",\n \"state\" : \"HP\",\n \"zip\" : \"176115\",\n \"location\" : [\n 31.8955385,\n 76.8380405\n ],\n \"fees\" : 2200,\n \"tags\" : [\n \"Senior Secondary\",\n \"beautiful campus\"\n ],\n \"rating\" : \"3.3\"\n }\n },\n {\n \"_index\" : \"schools\",\n \"_type\" : \"school\",\n \"_id\" : \"4\",\n \"_score\" : 1.0,\n \"_source\" : {\n \"name\" : \"City Best School\",\n \"description\" : \"ICSE\",\n \"street\" : \"West End\",\n \"city\" : \"Meerut\",\n \"state\" : \"UP\",\n \"zip\" : \"250002\",\n \"location\" : [\n 28.9926174,\n 77.692485\n ],\n \"fees\" : 3500,\n \"tags\" : [\n \"fully computerized\"\n ],\n \"rating\" : \"4.5\"\n }\n }\n ]\n },\n \"aggregations\" : {\n \"avg_fees\" : {\n \"value\" : 2850.0\n }\n }\n}\n"
},
{
"code": null,
"e": 5409,
"s": 5334,
"text": "This aggregation gives the count of distinct values of a particular field."
},
{
"code": null,
"e": 5520,
"s": 5409,
"text": "POST /schools/_search?size=0\n{\n \"aggs\":{\n \"distinct_name_count\":{\"cardinality\":{\"field\":\"fees\"}}\n }\n}"
},
{
"code": null,
"e": 5577,
"s": 5520,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 5956,
"s": 5577,
"text": "{\n \"took\" : 2,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 2,\n \"relation\" : \"eq\"\n },\n \"max_score\" : null,\n \"hits\" : [ ]\n },\n \"aggregations\" : {\n \"distinct_name_count\" : {\n \"value\" : 2\n }\n }\n}\n"
},
{
"code": null,
"e": 6040,
"s": 5956,
"text": "Note − The value of cardinality is 2 because there are two distinct values in fees."
},
{
"code": null,
"e": 6144,
"s": 6040,
"text": "This aggregation generates all the statistics about a specific numerical field in aggregated documents."
},
{
"code": null,
"e": 6261,
"s": 6144,
"text": "POST /schools/_search?size=0\n{\n \"aggs\" : {\n \"fees_stats\" : { \"extended_stats\" : { \"field\" : \"fees\" } }\n }\n}"
},
{
"code": null,
"e": 6318,
"s": 6261,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 6998,
"s": 6318,
"text": "{\n \"took\" : 8,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 2,\n \"relation\" : \"eq\"\n },\n \"max_score\" : null,\n \"hits\" : [ ]\n },\n \"aggregations\" : {\n \"fees_stats\" : {\n \"count\" : 2,\n \"min\" : 2200.0,\n \"max\" : 3500.0,\n \"avg\" : 2850.0,\n \"sum\" : 5700.0,\n \"sum_of_squares\" : 1.709E7,\n \"variance\" : 422500.0,\n \"std_deviation\" : 650.0,\n \"std_deviation_bounds\" : {\n \"upper\" : 4150.0,\n \"lower\" : 1550.0\n }\n }\n }\n}\n"
},
{
"code": null,
"e": 7088,
"s": 6998,
"text": "This aggregation finds the max value of a specific numeric field in aggregated documents."
},
{
"code": null,
"e": 7189,
"s": 7088,
"text": "POST /schools/_search?size=0\n{\n \"aggs\" : {\n \"max_fees\" : { \"max\" : { \"field\" : \"fees\" } }\n }\n}"
},
{
"code": null,
"e": 7246,
"s": 7189,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 7619,
"s": 7246,
"text": "{\n \"took\" : 16,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 2,\n \"relation\" : \"eq\"\n },\n \"max_score\" : null,\n \"hits\" : [ ]\n },\n \"aggregations\" : {\n \"max_fees\" : {\n \"value\" : 3500.0\n }\n }\n}\n"
},
{
"code": null,
"e": 7709,
"s": 7619,
"text": "This aggregation finds the min value of a specific numeric field in aggregated documents."
},
{
"code": null,
"e": 7813,
"s": 7709,
"text": "POST /schools/_search?size=0\n{\n \"aggs\" : {\n \"min_fees\" : { \"min\" : { \"field\" : \"fees\" } }\n }\n}"
},
{
"code": null,
"e": 7870,
"s": 7813,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 8242,
"s": 7870,
"text": "{\n \"took\" : 2,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 2,\n \"relation\" : \"eq\"\n },\n \"max_score\" : null,\n \"hits\" : [ ]\n },\n \"aggregations\" : {\n \"min_fees\" : {\n \"value\" : 2200.0\n }\n }\n}\n"
},
{
"code": null,
"e": 8331,
"s": 8242,
"text": "This aggregation calculates the sum of a specific numeric field in aggregated documents."
},
{
"code": null,
"e": 8437,
"s": 8331,
"text": "POST /schools/_search?size=0\n{\n \"aggs\" : {\n \"total_fees\" : { \"sum\" : { \"field\" : \"fees\" } }\n }\n}"
},
{
"code": null,
"e": 8494,
"s": 8437,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 8869,
"s": 8494,
"text": "{\n \"took\" : 8,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 2,\n \"relation\" : \"eq\"\n },\n \"max_score\" : null,\n \"hits\" : [ ]\n },\n \"aggregations\" : {\n \"total_fees\" : {\n \"value\" : 5700.0\n }\n }\n}\n"
},
{
"code": null,
"e": 9033,
"s": 8869,
"text": "There are some other metrics aggregations which are used in special cases like geo bounds aggregation and geo centroid aggregation for the purpose of geo location."
},
{
"code": null,
"e": 9148,
"s": 9033,
"text": "A multi-value metrics aggregation that computes stats over numeric values extracted from the aggregated documents."
},
{
"code": null,
"e": 9258,
"s": 9148,
"text": "POST /schools/_search?size=0\n{\n \"aggs\" : {\n \"grades_stats\" : { \"stats\" : { \"field\" : \"fees\" } }\n }\n}"
},
{
"code": null,
"e": 9315,
"s": 9258,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 9787,
"s": 9315,
"text": "{\n \"took\" : 2,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 2,\n \"relation\" : \"eq\"\n },\n \"max_score\" : null,\n \"hits\" : [ ]\n },\n \"aggregations\" : {\n \"grades_stats\" : {\n \"count\" : 2,\n \"min\" : 2200.0,\n \"max\" : 3500.0,\n \"avg\" : 2850.0,\n \"sum\" : 5700.0\n }\n }\n}\n"
},
{
"code": null,
"e": 9902,
"s": 9787,
"text": "You can add some data about the aggregation at the time of request by using meta tag and can get that in response."
},
{
"code": null,
"e": 10087,
"s": 9902,
"text": "POST /schools/_search?size=0\n{\n \"aggs\" : {\n \"avg_fees\" : { \"avg\" : { \"field\" : \"fees\" } ,\n \"meta\" :{\n \"dsc\" :\"Lowest Fees This Year\"\n }\n }\n }\n}"
},
{
"code": null,
"e": 10144,
"s": 10087,
"text": "On running the above code, we get the following result −"
}
] |
sqrt, sqrtl and sqrtf in C++ | 13 Jun, 2022
There are various functions available in the C++ Library to calculate the square root of a number. Most prominently, sqrt is used. It takes double as an argument. The <cmath> header defines two more inbuilt functions for calculating the square root of a number (apart from sqrt) which has an argument of type float and long double. Therefore, all the functions used for calculating square root in C++ are:
Function
Datatype
sqrt
double
sqrtf
float
sqrtl
long double
The functions have been discussed in detail below:
A) double sqrt(double arg): It returns the square root of a number to type double.
Syntax:
double sqrt(double arg)
CPP
// CPP code to illustrate the use of sqrt function#include <cmath>#include <iomanip>#include <iostream>using namespace std; // Driver Codeint main(){ double val1 = 225.0; double val2 = 300.0; cout << fixed << setprecision(12) << sqrt(val1) << endl; cout << fixed << setprecision(12) << sqrt(val2) << endl; return (0);}
15.000000000000
17.320508075689
Time Complexity: O(√n)Auxiliary Space: O(1)
1. It is mandatory to give the argument otherwise, it will give an error no matching function for call to ‘sqrt()’ as shown below,
CPP
// CPP Program to demonstrate errors in double sqrt()#include <cmath>#include <iostream>using namespace std; // Driver Codeint main(){ double answer; answer = sqrt(); cout << "Square root of " << a << " is " << answer << endl; return 0;}
Output
prog.cpp:9:19: error: no matching function for call to ‘sqrt()’
answer = sqrt();
Time Complexity: O(√n)Auxiliary Space: O(1)
2. If we pass a negative value in the argument domain error occurs and the output will be the Square root of -a, which is -nan.
CPP
// CPP Program to demonstrate errors in double sqrt()#include <cmath>#include <iostream>using namespace std; // Driver Codeint main(){ double a = -2, answer; answer = sqrt(a); cout << "Square root of " << a << " is " << answer << endl; return 0;}
Output:
Square root of -2 is -nan
Time Complexity: O(√n)Auxiliary Space: O(1)B) float sqrtf(float arg): It returns the square root of a number to type float.
Syntax:
float sqrtf(float arg)
CPP
// CPP code to illustrate the use of sqrtf function#include <cmath>#include <iomanip>#include <iostream> using namespace std; int main(){ float val1 = 225.0; float val2 = 300.0; cout << fixed << setprecision(12) << sqrtf(val1) << endl; cout << fixed << setprecision(12) << sqrtf(val2) << endl; return (0);}
15.000000000000
17.320508956909
Time Complexity: O(√n)Auxiliary Space: O(1)C) long double sqrtl(long double arg): It returns the square root of a number to type long double with more precision.
Advantage of sqrtl function: When working with integers of the order 1018, calculating its square root with sqrt function may give an incorrect answer due to precision errors as default functions in programming language works with floats/doubles. But this will always give an accurate answer. Syntax:
long double sqrtl(long double arg)
Following is an illustration given below shows the exact difference when working with long integers with sqrt and sqrtl,1) Using sqrt function:
CPP
// CPP code to illustrate the incorrectness of sqrt// function#include <cmath>#include <iomanip>#include <iostream> using namespace std; int main(){ long long int val1 = 1000000000000000000; long long int val2 = 999999999999999999; cout << fixed << setprecision(12) << sqrt(val1) << endl; cout << fixed << setprecision(12) << sqrt(val2) << endl; return (0);}
1000000000.000000000000
1000000000.000000000000
Time Complexity: O(√n)Auxiliary Space: O(1)
2) Using sqrtl function:
CPP
// CPP code to illustrate the correctness of sqrtl function#include <cmath>#include <iomanip>#include <iostream> using namespace std; int main(){ long long int val1 = 1000000000000000000; long long int val2 = 999999999999999999; cout << fixed << setprecision(12) << sqrtl(val1) << endl; cout << fixed << setprecision(12) << sqrtl(val2) << endl; return (0);}
1000000000.000000000000
999999999.999999999476
Time Complexity: O(√n)Auxiliary Space: O(1)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ManasChhabra2
anshikajain26
susobhanakhuli
CPP-Library
cpp-math
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Set in C++ Standard Template Library (STL)
unordered_map in C++ STL
Inheritance in C++
vector erase() and clear() in C++
The C++ Standard Template Library (STL)
C++ Classes and Objects
Substring in C++
Object Oriented Programming in C++
Priority Queue in C++ Standard Template Library (STL) | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 434,
"s": 28,
"text": "There are various functions available in the C++ Library to calculate the square root of a number. Most prominently, sqrt is used. It takes double as an argument. The <cmath> header defines two more inbuilt functions for calculating the square root of a number (apart from sqrt) which has an argument of type float and long double. Therefore, all the functions used for calculating square root in C++ are:"
},
{
"code": null,
"e": 443,
"s": 434,
"text": "Function"
},
{
"code": null,
"e": 452,
"s": 443,
"text": "Datatype"
},
{
"code": null,
"e": 457,
"s": 452,
"text": "sqrt"
},
{
"code": null,
"e": 464,
"s": 457,
"text": "double"
},
{
"code": null,
"e": 470,
"s": 464,
"text": "sqrtf"
},
{
"code": null,
"e": 476,
"s": 470,
"text": "float"
},
{
"code": null,
"e": 482,
"s": 476,
"text": "sqrtl"
},
{
"code": null,
"e": 494,
"s": 482,
"text": "long double"
},
{
"code": null,
"e": 545,
"s": 494,
"text": "The functions have been discussed in detail below:"
},
{
"code": null,
"e": 629,
"s": 545,
"text": "A) double sqrt(double arg): It returns the square root of a number to type double. "
},
{
"code": null,
"e": 637,
"s": 629,
"text": "Syntax:"
},
{
"code": null,
"e": 661,
"s": 637,
"text": "double sqrt(double arg)"
},
{
"code": null,
"e": 665,
"s": 661,
"text": "CPP"
},
{
"code": "// CPP code to illustrate the use of sqrt function#include <cmath>#include <iomanip>#include <iostream>using namespace std; // Driver Codeint main(){ double val1 = 225.0; double val2 = 300.0; cout << fixed << setprecision(12) << sqrt(val1) << endl; cout << fixed << setprecision(12) << sqrt(val2) << endl; return (0);}",
"e": 1001,
"s": 665,
"text": null
},
{
"code": null,
"e": 1033,
"s": 1001,
"text": "15.000000000000\n17.320508075689"
},
{
"code": null,
"e": 1077,
"s": 1033,
"text": "Time Complexity: O(√n)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1209,
"s": 1077,
"text": "1. It is mandatory to give the argument otherwise, it will give an error no matching function for call to ‘sqrt()’ as shown below, "
},
{
"code": null,
"e": 1213,
"s": 1209,
"text": "CPP"
},
{
"code": "// CPP Program to demonstrate errors in double sqrt()#include <cmath>#include <iostream>using namespace std; // Driver Codeint main(){ double answer; answer = sqrt(); cout << \"Square root of \" << a << \" is \" << answer << endl; return 0;}",
"e": 1473,
"s": 1213,
"text": null
},
{
"code": null,
"e": 1480,
"s": 1473,
"text": "Output"
},
{
"code": null,
"e": 1566,
"s": 1480,
"text": "prog.cpp:9:19: error: no matching function for call to ‘sqrt()’\n answer = sqrt();"
},
{
"code": null,
"e": 1610,
"s": 1566,
"text": "Time Complexity: O(√n)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1738,
"s": 1610,
"text": "2. If we pass a negative value in the argument domain error occurs and the output will be the Square root of -a, which is -nan."
},
{
"code": null,
"e": 1742,
"s": 1738,
"text": "CPP"
},
{
"code": "// CPP Program to demonstrate errors in double sqrt()#include <cmath>#include <iostream>using namespace std; // Driver Codeint main(){ double a = -2, answer; answer = sqrt(a); cout << \"Square root of \" << a << \" is \" << answer << endl; return 0;}",
"e": 2011,
"s": 1742,
"text": null
},
{
"code": null,
"e": 2019,
"s": 2011,
"text": "Output:"
},
{
"code": null,
"e": 2045,
"s": 2019,
"text": "Square root of -2 is -nan"
},
{
"code": null,
"e": 2169,
"s": 2045,
"text": "Time Complexity: O(√n)Auxiliary Space: O(1)B) float sqrtf(float arg): It returns the square root of a number to type float."
},
{
"code": null,
"e": 2177,
"s": 2169,
"text": "Syntax:"
},
{
"code": null,
"e": 2200,
"s": 2177,
"text": "float sqrtf(float arg)"
},
{
"code": null,
"e": 2204,
"s": 2200,
"text": "CPP"
},
{
"code": "// CPP code to illustrate the use of sqrtf function#include <cmath>#include <iomanip>#include <iostream> using namespace std; int main(){ float val1 = 225.0; float val2 = 300.0; cout << fixed << setprecision(12) << sqrtf(val1) << endl; cout << fixed << setprecision(12) << sqrtf(val2) << endl; return (0);}",
"e": 2544,
"s": 2204,
"text": null
},
{
"code": null,
"e": 2576,
"s": 2544,
"text": "15.000000000000\n17.320508956909"
},
{
"code": null,
"e": 2739,
"s": 2576,
"text": "Time Complexity: O(√n)Auxiliary Space: O(1)C) long double sqrtl(long double arg): It returns the square root of a number to type long double with more precision. "
},
{
"code": null,
"e": 3040,
"s": 2739,
"text": "Advantage of sqrtl function: When working with integers of the order 1018, calculating its square root with sqrt function may give an incorrect answer due to precision errors as default functions in programming language works with floats/doubles. But this will always give an accurate answer. Syntax:"
},
{
"code": null,
"e": 3075,
"s": 3040,
"text": "long double sqrtl(long double arg)"
},
{
"code": null,
"e": 3219,
"s": 3075,
"text": "Following is an illustration given below shows the exact difference when working with long integers with sqrt and sqrtl,1) Using sqrt function:"
},
{
"code": null,
"e": 3223,
"s": 3219,
"text": "CPP"
},
{
"code": "// CPP code to illustrate the incorrectness of sqrt// function#include <cmath>#include <iomanip>#include <iostream> using namespace std; int main(){ long long int val1 = 1000000000000000000; long long int val2 = 999999999999999999; cout << fixed << setprecision(12) << sqrt(val1) << endl; cout << fixed << setprecision(12) << sqrt(val2) << endl; return (0);}",
"e": 3599,
"s": 3223,
"text": null
},
{
"code": null,
"e": 3647,
"s": 3599,
"text": "1000000000.000000000000\n1000000000.000000000000"
},
{
"code": null,
"e": 3691,
"s": 3647,
"text": "Time Complexity: O(√n)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 3716,
"s": 3691,
"text": "2) Using sqrtl function:"
},
{
"code": null,
"e": 3720,
"s": 3716,
"text": "CPP"
},
{
"code": "// CPP code to illustrate the correctness of sqrtl function#include <cmath>#include <iomanip>#include <iostream> using namespace std; int main(){ long long int val1 = 1000000000000000000; long long int val2 = 999999999999999999; cout << fixed << setprecision(12) << sqrtl(val1) << endl; cout << fixed << setprecision(12) << sqrtl(val2) << endl; return (0);}",
"e": 4111,
"s": 3720,
"text": null
},
{
"code": null,
"e": 4158,
"s": 4111,
"text": "1000000000.000000000000\n999999999.999999999476"
},
{
"code": null,
"e": 4202,
"s": 4158,
"text": "Time Complexity: O(√n)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 4327,
"s": 4202,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4341,
"s": 4327,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 4355,
"s": 4341,
"text": "anshikajain26"
},
{
"code": null,
"e": 4370,
"s": 4355,
"text": "susobhanakhuli"
},
{
"code": null,
"e": 4382,
"s": 4370,
"text": "CPP-Library"
},
{
"code": null,
"e": 4391,
"s": 4382,
"text": "cpp-math"
},
{
"code": null,
"e": 4395,
"s": 4391,
"text": "C++"
},
{
"code": null,
"e": 4399,
"s": 4395,
"text": "CPP"
},
{
"code": null,
"e": 4497,
"s": 4399,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4524,
"s": 4497,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 4567,
"s": 4524,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4592,
"s": 4567,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 4611,
"s": 4592,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 4645,
"s": 4611,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 4685,
"s": 4645,
"text": "The C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4709,
"s": 4685,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 4726,
"s": 4709,
"text": "Substring in C++"
},
{
"code": null,
"e": 4761,
"s": 4726,
"text": "Object Oriented Programming in C++"
}
] |
What are the differences between props and state ? | 28 Jun, 2021
Have you ever wondered how can we pass the data between the components in ReactJS? We can pass the data between the components using Props and State. So, let us know how we can pass the data using props and state and understand the difference between the two.
We will learn about props and state with the help of an example project in ReactJS.
Steps to Create React Project:
Step 1: Create a React application using the following command:npx create-react-app foldername
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 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure:
Project Structure
Props: Props are known as properties it can be used to pass data from one component to another. Props cannot be modified, read-only, and Immutable.
Example: Modify the default code with the below code.
App.js
import Fruit from './Fruit'function App() { const fruits= { name:"Mango", color:"Yellow" } return ( <div className="App"> <Fruit fruits={fruits} /> </div> );} export default App;
App.css
.App{ text-align: center; }
Create a Component known as Fruit.js and add the below code
Fruit.js
import React from "react" const Fruit =(props) =>{ return( <div className="fruit"> <h1>List of Fruits</h1> <p>Name: {props.fruits.name}</p> <p>Color: {props.fruits.color}</p> </div> )} export default Fruit;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm startOutput:
The following will be the output when we execute the above command. The data will be passed from the Parent component i.e. App.js to the Child component i.e. Fruit.js with the usage of the “Props” feature.
State: The state represents parts of an Application that can change. Each component can have its State. The state is Mutable and It is local to the component only.
Example: Let us create a Class component named Car.js within the same project “fruits”.
Add the following code in the Car.js component.
Car.js
import React, {Component} from "react" class Car extends Component{ constructor() { super() this.state={ car: 'Ferrari' } } changeMessage() { this.setState({ car: 'Jaguar' }) } render() { return ( <div className="App"> <h1>{this.state.car}</h1> <button onClick={() => this.changeMessage()}> Change </button> </div> ) }} export default Car
App.js
import './App.css';import Fruit from './Fruit'import Car from './Car'; function App() { const fruits= { name:"Mango", color:"Yellow" } return ( <div className="App"> <Fruit fruits={fruits} /> <hr></hr> <Car /> </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:
The following will be the output when we execute the above command. The data is local to the component “Car” only and it can be updated using the button change in the screen.
Difference between props and state:
PROPS
STATE
Props are used to pass data from one component to another.The state is a local data storage that is local to the component only and cannot be passed to other components.The this.setState property is used to update the state values in the component.
Props are used to pass data from one component to another.
The state is a local data storage that is local to the component only and cannot be passed to other components.
The this.setState property is used to update the state values in the component.
Picked
React-Questions
Difference Between
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Synchronous and Asynchronous Transmission
Difference Between Method Overloading and Method Overriding in Java
Difference Between Go-Back-N and Selective Repeat Protocol
Time complexities of different data structures
Difference between Compile-time and Run-time Polymorphism in Java
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": 53,
"s": 25,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 313,
"s": 53,
"text": "Have you ever wondered how can we pass the data between the components in ReactJS? We can pass the data between the components using Props and State. So, let us know how we can pass the data using props and state and understand the difference between the two."
},
{
"code": null,
"e": 397,
"s": 313,
"text": "We will learn about props and state with the help of an example project in ReactJS."
},
{
"code": null,
"e": 428,
"s": 397,
"text": "Steps to Create React Project:"
},
{
"code": null,
"e": 523,
"s": 428,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 587,
"s": 523,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 619,
"s": 587,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 734,
"s": 621,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 834,
"s": 734,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 848,
"s": 834,
"text": "cd foldername"
},
{
"code": null,
"e": 867,
"s": 848,
"text": "Project Structure:"
},
{
"code": null,
"e": 885,
"s": 867,
"text": "Project Structure"
},
{
"code": null,
"e": 1033,
"s": 885,
"text": "Props: Props are known as properties it can be used to pass data from one component to another. Props cannot be modified, read-only, and Immutable."
},
{
"code": null,
"e": 1088,
"s": 1033,
"text": "Example: Modify the default code with the below code. "
},
{
"code": null,
"e": 1095,
"s": 1088,
"text": "App.js"
},
{
"code": "import Fruit from './Fruit'function App() { const fruits= { name:\"Mango\", color:\"Yellow\" } return ( <div className=\"App\"> <Fruit fruits={fruits} /> </div> );} export default App;",
"e": 1307,
"s": 1095,
"text": null
},
{
"code": null,
"e": 1315,
"s": 1307,
"text": "App.css"
},
{
"code": ".App{ text-align: center; }",
"e": 1347,
"s": 1315,
"text": null
},
{
"code": null,
"e": 1409,
"s": 1349,
"text": "Create a Component known as Fruit.js and add the below code"
},
{
"code": null,
"e": 1418,
"s": 1409,
"text": "Fruit.js"
},
{
"code": "import React from \"react\" const Fruit =(props) =>{ return( <div className=\"fruit\"> <h1>List of Fruits</h1> <p>Name: {props.fruits.name}</p> <p>Color: {props.fruits.color}</p> </div> )} export default Fruit;",
"e": 1677,
"s": 1418,
"text": null
},
{
"code": null,
"e": 1790,
"s": 1677,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 1807,
"s": 1790,
"text": "npm startOutput:"
},
{
"code": null,
"e": 2014,
"s": 1807,
"text": "The following will be the output when we execute the above command. The data will be passed from the Parent component i.e. App.js to the Child component i.e. Fruit.js with the usage of the “Props” feature. "
},
{
"code": null,
"e": 2178,
"s": 2014,
"text": "State: The state represents parts of an Application that can change. Each component can have its State. The state is Mutable and It is local to the component only."
},
{
"code": null,
"e": 2267,
"s": 2178,
"text": "Example: Let us create a Class component named Car.js within the same project “fruits”."
},
{
"code": null,
"e": 2315,
"s": 2267,
"text": "Add the following code in the Car.js component."
},
{
"code": null,
"e": 2322,
"s": 2315,
"text": "Car.js"
},
{
"code": "import React, {Component} from \"react\" class Car extends Component{ constructor() { super() this.state={ car: 'Ferrari' } } changeMessage() { this.setState({ car: 'Jaguar' }) } render() { return ( <div className=\"App\"> <h1>{this.state.car}</h1> <button onClick={() => this.changeMessage()}> Change </button> </div> ) }} export default Car",
"e": 2862,
"s": 2322,
"text": null
},
{
"code": null,
"e": 2871,
"s": 2864,
"text": "App.js"
},
{
"code": "import './App.css';import Fruit from './Fruit'import Car from './Car'; function App() { const fruits= { name:\"Mango\", color:\"Yellow\" } return ( <div className=\"App\"> <Fruit fruits={fruits} /> <hr></hr> <Car /> </div> );} export default App;",
"e": 3156,
"s": 2871,
"text": null
},
{
"code": null,
"e": 3269,
"s": 3156,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 3279,
"s": 3269,
"text": "npm start"
},
{
"code": null,
"e": 3287,
"s": 3279,
"text": "Output:"
},
{
"code": null,
"e": 3462,
"s": 3287,
"text": "The following will be the output when we execute the above command. The data is local to the component “Car” only and it can be updated using the button change in the screen."
},
{
"code": null,
"e": 3498,
"s": 3462,
"text": "Difference between props and state:"
},
{
"code": null,
"e": 3504,
"s": 3498,
"text": "PROPS"
},
{
"code": null,
"e": 3510,
"s": 3504,
"text": "STATE"
},
{
"code": null,
"e": 3759,
"s": 3510,
"text": "Props are used to pass data from one component to another.The state is a local data storage that is local to the component only and cannot be passed to other components.The this.setState property is used to update the state values in the component."
},
{
"code": null,
"e": 3818,
"s": 3759,
"text": "Props are used to pass data from one component to another."
},
{
"code": null,
"e": 3930,
"s": 3818,
"text": "The state is a local data storage that is local to the component only and cannot be passed to other components."
},
{
"code": null,
"e": 4010,
"s": 3930,
"text": "The this.setState property is used to update the state values in the component."
},
{
"code": null,
"e": 4017,
"s": 4010,
"text": "Picked"
},
{
"code": null,
"e": 4033,
"s": 4017,
"text": "React-Questions"
},
{
"code": null,
"e": 4052,
"s": 4033,
"text": "Difference Between"
},
{
"code": null,
"e": 4060,
"s": 4052,
"text": "ReactJS"
},
{
"code": null,
"e": 4077,
"s": 4060,
"text": "Web Technologies"
},
{
"code": null,
"e": 4175,
"s": 4077,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4236,
"s": 4175,
"text": "Difference between Synchronous and Asynchronous Transmission"
},
{
"code": null,
"e": 4304,
"s": 4236,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 4363,
"s": 4304,
"text": "Difference Between Go-Back-N and Selective Repeat Protocol"
},
{
"code": null,
"e": 4410,
"s": 4363,
"text": "Time complexities of different data structures"
},
{
"code": null,
"e": 4476,
"s": 4410,
"text": "Difference between Compile-time and Run-time Polymorphism in Java"
},
{
"code": null,
"e": 4519,
"s": 4476,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 4564,
"s": 4519,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 4602,
"s": 4564,
"text": "Axios in React: A Guide for Beginners"
}
] |
Extract CSS tag from a given HTML using Python | 24 Oct, 2020
Prerequisite: Implementing Web Scraping in Python with BeautifulSoup
In this article, we are going to see how to extract CSS from an HTML document or URL using python.
Module Needed:
bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal.
pip install bs4
requests: Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not comes built-in with Python. To install this type the below command in the terminal.
pip install requests
Approach:
Import module
Create an HTML document and specify the CSS tag into the code
Pass the HTML document into the Beautifulsoup() function
Now traverse the tag with the select() method.
Implementation:
Python3
# import modulefrom bs4 import BeautifulSoup # Html dochtml_doc = """<html><head><title>Geeks</title></head><body><h2>paragraphs</h2> <p>Welcome geeks.</p> <p>Hello geeks.</p> <a class="example" href="www.geeksforgeeks.com" id="dsx_23">java</a><a class="example" href="www.geeksforgeeks.com/python" id="sdcsdsdf">python</a></body></html>"""soup = BeautifulSoup(html_doc, "lxml") # traverse CSS from soupprint("display by CSS class:")print(soup.select(".example"))
Output:
display by CSS class:
[<a class="example" href="www.geeksforgeeks.com" id="dsx_23">java</a>,
<a class="example" href="www.geeksforgeeks.com/python" id="sdcsdsdf">python</a>]
Now let’s get the CSS tag with URL:
Python3
# import modulefrom bs4 import BeautifulSoupimport requests # link for extract html data# Making a GET request def getdata(url): r=requests.get(url) return r.texthtml_doc = getdata('https://www.geeksforgeeks.org/')soup = BeautifulSoup(html_doc,"lxml") # traverse CSS from soup print("\nTags by CSS class:")print(soup.select(".header-main__wrapper"))
Output:
python-utility
Web-scraping
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 | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Oct, 2020"
},
{
"code": null,
"e": 97,
"s": 28,
"text": "Prerequisite: Implementing Web Scraping in Python with BeautifulSoup"
},
{
"code": null,
"e": 196,
"s": 97,
"text": "In this article, we are going to see how to extract CSS from an HTML document or URL using python."
},
{
"code": null,
"e": 212,
"s": 196,
"text": " Module Needed:"
},
{
"code": null,
"e": 405,
"s": 212,
"text": "bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal."
},
{
"code": null,
"e": 422,
"s": 405,
"text": "pip install bs4\n"
},
{
"code": null,
"e": 606,
"s": 422,
"text": "requests: Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not comes built-in with Python. To install this type the below command in the terminal."
},
{
"code": null,
"e": 628,
"s": 606,
"text": "pip install requests\n"
},
{
"code": null,
"e": 638,
"s": 628,
"text": "Approach:"
},
{
"code": null,
"e": 652,
"s": 638,
"text": "Import module"
},
{
"code": null,
"e": 714,
"s": 652,
"text": "Create an HTML document and specify the CSS tag into the code"
},
{
"code": null,
"e": 771,
"s": 714,
"text": "Pass the HTML document into the Beautifulsoup() function"
},
{
"code": null,
"e": 818,
"s": 771,
"text": "Now traverse the tag with the select() method."
},
{
"code": null,
"e": 834,
"s": 818,
"text": "Implementation:"
},
{
"code": null,
"e": 842,
"s": 834,
"text": "Python3"
},
{
"code": "# import modulefrom bs4 import BeautifulSoup # Html dochtml_doc = \"\"\"<html><head><title>Geeks</title></head><body><h2>paragraphs</h2> <p>Welcome geeks.</p> <p>Hello geeks.</p> <a class=\"example\" href=\"www.geeksforgeeks.com\" id=\"dsx_23\">java</a><a class=\"example\" href=\"www.geeksforgeeks.com/python\" id=\"sdcsdsdf\">python</a></body></html>\"\"\"soup = BeautifulSoup(html_doc, \"lxml\") # traverse CSS from soupprint(\"display by CSS class:\")print(soup.select(\".example\"))",
"e": 1314,
"s": 842,
"text": null
},
{
"code": null,
"e": 1322,
"s": 1314,
"text": "Output:"
},
{
"code": null,
"e": 1498,
"s": 1322,
"text": "display by CSS class:\n[<a class=\"example\" href=\"www.geeksforgeeks.com\" id=\"dsx_23\">java</a>, \n<a class=\"example\" href=\"www.geeksforgeeks.com/python\" id=\"sdcsdsdf\">python</a>]\n"
},
{
"code": null,
"e": 1534,
"s": 1498,
"text": "Now let’s get the CSS tag with URL:"
},
{
"code": null,
"e": 1542,
"s": 1534,
"text": "Python3"
},
{
"code": "# import modulefrom bs4 import BeautifulSoupimport requests # link for extract html data# Making a GET request def getdata(url): r=requests.get(url) return r.texthtml_doc = getdata('https://www.geeksforgeeks.org/')soup = BeautifulSoup(html_doc,\"lxml\") # traverse CSS from soup print(\"\\nTags by CSS class:\")print(soup.select(\".header-main__wrapper\"))",
"e": 1907,
"s": 1542,
"text": null
},
{
"code": null,
"e": 1915,
"s": 1907,
"text": "Output:"
},
{
"code": null,
"e": 1930,
"s": 1915,
"text": "python-utility"
},
{
"code": null,
"e": 1943,
"s": 1930,
"text": "Web-scraping"
},
{
"code": null,
"e": 1950,
"s": 1943,
"text": "Python"
},
{
"code": null,
"e": 2048,
"s": 1950,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2080,
"s": 2048,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2107,
"s": 2080,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2138,
"s": 2107,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2159,
"s": 2138,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2215,
"s": 2159,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2238,
"s": 2215,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2280,
"s": 2238,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2322,
"s": 2280,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2361,
"s": 2322,
"text": "Python | datetime.timedelta() function"
}
] |
How to encrypt passwords in a Spring Boot project using Jasypt | 14 Feb, 2020
Spring boot is a Java-based framework to develop microservices in order to build enterprise-level applications.
You often come across developing projects where you have to connect to databases like MongoDB, etc and store the authentic password of DB connection in the config file of spring boot project (application.yml or application.properties). Even passwords or tokens required for Authorization to make other API call are also stored in the same way.
You can actually refrain from adding the actual password in the config file and use ‘jasypt-spring-boot‘, a java library.
What is Jasypt?Jasypt (Java Simplified Encryption), provides encryption support for property sources in Spring Boot Applications. It will help you to add basic encryption features to your projects with very fewer efforts and without writing any code with the help of a few additions in your project here and there. Springboot is a very powerful framework that will help you to add encryption capability without implementing any cryptography method. Jasypt is highly configurable.
Steps To Add Encryption Using Jasypt:
Add maven dependency of jasypt: In the pom.xml file, add maven dependency which can be found easily at maven repository.Add annotation in the Spring Boot Application main Configuration class: @EnableEncryptableProperties annotation needs to be added to make the application understand the encryptable properties across the entire Spring Environment.Decide a secret key to be used for encryption and decryption The secret key is used to encrypt the password and later can be used to decrypt the encrypted value to get the actual password. You can choose any value as the secret key.Generate Encrypted Key The encrypted key can be generated through either of the following 2 methods:Use the Jasypt Online Tool :This link can be used to generate an encrypted key by passing the chosen secret key.The password to encrypt: abcd1234Select type of encryption: Two-way encryption (PBEWithMD5AndDES by default is used)Secret Key: hello (It can be any value)Encrypted String: kNuS1WAezYE7cph7zXVTiPSQSdHTx7KvYou can actually use the tool to encrypt and check the encrypted key by decrypting it.Use the jasypt Jar: Download the jasypt jar file from the maven repository and run it through the following command:java -cp //jasypt-1.9.3/lib/jasypt-1.9.3.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input=”xyz123′′ password=secretkey algorithm=PBEWithMD5AndDESFollowing is the significance of command-line parameters passed to run the jar:input: abcd1234 (Actual password to be encrypted)password: hello (the secret key chosen by you)algorithm: PBEWithMD5AndDES (default algorithm used)OUTPUT: scEjemHosjc/hjA8saT7Y6uC65bs0swg (Encrypted value of input)Note: Though the encrypted value i.e. Encrypted String & OUTPUT in 3.1 and 3.2 respectively are different, as the secret key is the same, the decryption will result in the same value (abcd1234) in both the cases.Add the encrypted key in the config file (application.yml or application.properties): Now instead of adding the actual password ie. “abcd1234” as per the above eg., you need to add the encrypted value generated by either of the above methods. But how will the jasypt dependency understand that the particular property of the config file needs to be decrypted? Hence to make Jasypt aware of your encrypted values, it uses a convention which you need to add in the following format:ENC(encrypted key): ENC(scEjemHosjc/hjA8saT7Y6uC65bs0swg)In the above image, the encryption of the database password is done. You can use it in any scenario where you have to hide the actual password.Secret key chosen needs to be passed to decrypt at runtime: Make the Jasypt aware of the secret key which you have used to form the encrypted value. Hence following are the different methods to pass the secret key: Pass it as a property in the config file. Run the project as usual and the decryption would happen.Run the project with the following command:$mvn-Djasypt.encryptor.password=secretkey spring-boot:runExport Jasypt Encryptor Password:JASYPT_ENCRYPTOR_PASSWORD=hello
Add maven dependency of jasypt: In the pom.xml file, add maven dependency which can be found easily at maven repository.
Add annotation in the Spring Boot Application main Configuration class: @EnableEncryptableProperties annotation needs to be added to make the application understand the encryptable properties across the entire Spring Environment.
Decide a secret key to be used for encryption and decryption The secret key is used to encrypt the password and later can be used to decrypt the encrypted value to get the actual password. You can choose any value as the secret key.
Generate Encrypted Key The encrypted key can be generated through either of the following 2 methods:Use the Jasypt Online Tool :This link can be used to generate an encrypted key by passing the chosen secret key.The password to encrypt: abcd1234Select type of encryption: Two-way encryption (PBEWithMD5AndDES by default is used)Secret Key: hello (It can be any value)Encrypted String: kNuS1WAezYE7cph7zXVTiPSQSdHTx7KvYou can actually use the tool to encrypt and check the encrypted key by decrypting it.Use the jasypt Jar: Download the jasypt jar file from the maven repository and run it through the following command:java -cp //jasypt-1.9.3/lib/jasypt-1.9.3.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input=”xyz123′′ password=secretkey algorithm=PBEWithMD5AndDESFollowing is the significance of command-line parameters passed to run the jar:input: abcd1234 (Actual password to be encrypted)password: hello (the secret key chosen by you)algorithm: PBEWithMD5AndDES (default algorithm used)OUTPUT: scEjemHosjc/hjA8saT7Y6uC65bs0swg (Encrypted value of input)Note: Though the encrypted value i.e. Encrypted String & OUTPUT in 3.1 and 3.2 respectively are different, as the secret key is the same, the decryption will result in the same value (abcd1234) in both the cases.
Use the Jasypt Online Tool :This link can be used to generate an encrypted key by passing the chosen secret key.The password to encrypt: abcd1234Select type of encryption: Two-way encryption (PBEWithMD5AndDES by default is used)Secret Key: hello (It can be any value)Encrypted String: kNuS1WAezYE7cph7zXVTiPSQSdHTx7KvYou can actually use the tool to encrypt and check the encrypted key by decrypting it.Use the jasypt Jar: Download the jasypt jar file from the maven repository and run it through the following command:java -cp //jasypt-1.9.3/lib/jasypt-1.9.3.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input=”xyz123′′ password=secretkey algorithm=PBEWithMD5AndDESFollowing is the significance of command-line parameters passed to run the jar:input: abcd1234 (Actual password to be encrypted)password: hello (the secret key chosen by you)algorithm: PBEWithMD5AndDES (default algorithm used)OUTPUT: scEjemHosjc/hjA8saT7Y6uC65bs0swg (Encrypted value of input)Note: Though the encrypted value i.e. Encrypted String & OUTPUT in 3.1 and 3.2 respectively are different, as the secret key is the same, the decryption will result in the same value (abcd1234) in both the cases.
Use the Jasypt Online Tool :This link can be used to generate an encrypted key by passing the chosen secret key.The password to encrypt: abcd1234Select type of encryption: Two-way encryption (PBEWithMD5AndDES by default is used)Secret Key: hello (It can be any value)Encrypted String: kNuS1WAezYE7cph7zXVTiPSQSdHTx7KvYou can actually use the tool to encrypt and check the encrypted key by decrypting it.
This link can be used to generate an encrypted key by passing the chosen secret key.
The password to encrypt: abcd1234
Select type of encryption: Two-way encryption (PBEWithMD5AndDES by default is used)
Secret Key: hello (It can be any value)
Encrypted String: kNuS1WAezYE7cph7zXVTiPSQSdHTx7Kv
You can actually use the tool to encrypt and check the encrypted key by decrypting it.
Use the jasypt Jar: Download the jasypt jar file from the maven repository and run it through the following command:java -cp //jasypt-1.9.3/lib/jasypt-1.9.3.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input=”xyz123′′ password=secretkey algorithm=PBEWithMD5AndDESFollowing is the significance of command-line parameters passed to run the jar:input: abcd1234 (Actual password to be encrypted)password: hello (the secret key chosen by you)algorithm: PBEWithMD5AndDES (default algorithm used)OUTPUT: scEjemHosjc/hjA8saT7Y6uC65bs0swg (Encrypted value of input)Note: Though the encrypted value i.e. Encrypted String & OUTPUT in 3.1 and 3.2 respectively are different, as the secret key is the same, the decryption will result in the same value (abcd1234) in both the cases.
java -cp //jasypt-1.9.3/lib/jasypt-1.9.3.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input=”xyz123′′ password=secretkey algorithm=PBEWithMD5AndDES
Following is the significance of command-line parameters passed to run the jar:
input: abcd1234 (Actual password to be encrypted)
password: hello (the secret key chosen by you)
algorithm: PBEWithMD5AndDES (default algorithm used)
OUTPUT: scEjemHosjc/hjA8saT7Y6uC65bs0swg (Encrypted value of input)
Note: Though the encrypted value i.e. Encrypted String & OUTPUT in 3.1 and 3.2 respectively are different, as the secret key is the same, the decryption will result in the same value (abcd1234) in both the cases.
Add the encrypted key in the config file (application.yml or application.properties): Now instead of adding the actual password ie. “abcd1234” as per the above eg., you need to add the encrypted value generated by either of the above methods. But how will the jasypt dependency understand that the particular property of the config file needs to be decrypted? Hence to make Jasypt aware of your encrypted values, it uses a convention which you need to add in the following format:ENC(encrypted key): ENC(scEjemHosjc/hjA8saT7Y6uC65bs0swg)In the above image, the encryption of the database password is done. You can use it in any scenario where you have to hide the actual password.
ENC(encrypted key): ENC(scEjemHosjc/hjA8saT7Y6uC65bs0swg)
In the above image, the encryption of the database password is done. You can use it in any scenario where you have to hide the actual password.
Secret key chosen needs to be passed to decrypt at runtime: Make the Jasypt aware of the secret key which you have used to form the encrypted value. Hence following are the different methods to pass the secret key: Pass it as a property in the config file. Run the project as usual and the decryption would happen.Run the project with the following command:$mvn-Djasypt.encryptor.password=secretkey spring-boot:runExport Jasypt Encryptor Password:JASYPT_ENCRYPTOR_PASSWORD=hello
Pass it as a property in the config file. Run the project as usual and the decryption would happen.Run the project with the following command:$mvn-Djasypt.encryptor.password=secretkey spring-boot:runExport Jasypt Encryptor Password:JASYPT_ENCRYPTOR_PASSWORD=hello
Pass it as a property in the config file. Run the project as usual and the decryption would happen.
Run the project with the following command:$mvn-Djasypt.encryptor.password=secretkey spring-boot:run
$mvn-Djasypt.encryptor.password=secretkey spring-boot:run
Export Jasypt Encryptor Password:JASYPT_ENCRYPTOR_PASSWORD=hello
JASYPT_ENCRYPTOR_PASSWORD=hello
cryptography
Java-Spring
Technical Scripter 2019
Java
Technical Scripter
Java
cryptography
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
Set in Java
Introduction to Java
Constructors in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Feb, 2020"
},
{
"code": null,
"e": 140,
"s": 28,
"text": "Spring boot is a Java-based framework to develop microservices in order to build enterprise-level applications."
},
{
"code": null,
"e": 484,
"s": 140,
"text": "You often come across developing projects where you have to connect to databases like MongoDB, etc and store the authentic password of DB connection in the config file of spring boot project (application.yml or application.properties). Even passwords or tokens required for Authorization to make other API call are also stored in the same way."
},
{
"code": null,
"e": 607,
"s": 484,
"text": "You can actually refrain from adding the actual password in the config file and use ‘jasypt-spring-boot‘, a java library. "
},
{
"code": null,
"e": 1087,
"s": 607,
"text": "What is Jasypt?Jasypt (Java Simplified Encryption), provides encryption support for property sources in Spring Boot Applications. It will help you to add basic encryption features to your projects with very fewer efforts and without writing any code with the help of a few additions in your project here and there. Springboot is a very powerful framework that will help you to add encryption capability without implementing any cryptography method. Jasypt is highly configurable."
},
{
"code": null,
"e": 1126,
"s": 1087,
"text": "Steps To Add Encryption Using Jasypt: "
},
{
"code": null,
"e": 4145,
"s": 1126,
"text": "Add maven dependency of jasypt: In the pom.xml file, add maven dependency which can be found easily at maven repository.Add annotation in the Spring Boot Application main Configuration class: @EnableEncryptableProperties annotation needs to be added to make the application understand the encryptable properties across the entire Spring Environment.Decide a secret key to be used for encryption and decryption The secret key is used to encrypt the password and later can be used to decrypt the encrypted value to get the actual password. You can choose any value as the secret key.Generate Encrypted Key The encrypted key can be generated through either of the following 2 methods:Use the Jasypt Online Tool :This link can be used to generate an encrypted key by passing the chosen secret key.The password to encrypt: abcd1234Select type of encryption: Two-way encryption (PBEWithMD5AndDES by default is used)Secret Key: hello (It can be any value)Encrypted String: kNuS1WAezYE7cph7zXVTiPSQSdHTx7KvYou can actually use the tool to encrypt and check the encrypted key by decrypting it.Use the jasypt Jar: Download the jasypt jar file from the maven repository and run it through the following command:java -cp //jasypt-1.9.3/lib/jasypt-1.9.3.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input=”xyz123′′ password=secretkey algorithm=PBEWithMD5AndDESFollowing is the significance of command-line parameters passed to run the jar:input: abcd1234 (Actual password to be encrypted)password: hello (the secret key chosen by you)algorithm: PBEWithMD5AndDES (default algorithm used)OUTPUT: scEjemHosjc/hjA8saT7Y6uC65bs0swg (Encrypted value of input)Note: Though the encrypted value i.e. Encrypted String & OUTPUT in 3.1 and 3.2 respectively are different, as the secret key is the same, the decryption will result in the same value (abcd1234) in both the cases.Add the encrypted key in the config file (application.yml or application.properties): Now instead of adding the actual password ie. “abcd1234” as per the above eg., you need to add the encrypted value generated by either of the above methods. But how will the jasypt dependency understand that the particular property of the config file needs to be decrypted? Hence to make Jasypt aware of your encrypted values, it uses a convention which you need to add in the following format:ENC(encrypted key): ENC(scEjemHosjc/hjA8saT7Y6uC65bs0swg)In the above image, the encryption of the database password is done. You can use it in any scenario where you have to hide the actual password.Secret key chosen needs to be passed to decrypt at runtime: Make the Jasypt aware of the secret key which you have used to form the encrypted value. Hence following are the different methods to pass the secret key: Pass it as a property in the config file. Run the project as usual and the decryption would happen.Run the project with the following command:$mvn-Djasypt.encryptor.password=secretkey spring-boot:runExport Jasypt Encryptor Password:JASYPT_ENCRYPTOR_PASSWORD=hello"
},
{
"code": null,
"e": 4266,
"s": 4145,
"text": "Add maven dependency of jasypt: In the pom.xml file, add maven dependency which can be found easily at maven repository."
},
{
"code": null,
"e": 4496,
"s": 4266,
"text": "Add annotation in the Spring Boot Application main Configuration class: @EnableEncryptableProperties annotation needs to be added to make the application understand the encryptable properties across the entire Spring Environment."
},
{
"code": null,
"e": 4729,
"s": 4496,
"text": "Decide a secret key to be used for encryption and decryption The secret key is used to encrypt the password and later can be used to decrypt the encrypted value to get the actual password. You can choose any value as the secret key."
},
{
"code": null,
"e": 6009,
"s": 4729,
"text": "Generate Encrypted Key The encrypted key can be generated through either of the following 2 methods:Use the Jasypt Online Tool :This link can be used to generate an encrypted key by passing the chosen secret key.The password to encrypt: abcd1234Select type of encryption: Two-way encryption (PBEWithMD5AndDES by default is used)Secret Key: hello (It can be any value)Encrypted String: kNuS1WAezYE7cph7zXVTiPSQSdHTx7KvYou can actually use the tool to encrypt and check the encrypted key by decrypting it.Use the jasypt Jar: Download the jasypt jar file from the maven repository and run it through the following command:java -cp //jasypt-1.9.3/lib/jasypt-1.9.3.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input=”xyz123′′ password=secretkey algorithm=PBEWithMD5AndDESFollowing is the significance of command-line parameters passed to run the jar:input: abcd1234 (Actual password to be encrypted)password: hello (the secret key chosen by you)algorithm: PBEWithMD5AndDES (default algorithm used)OUTPUT: scEjemHosjc/hjA8saT7Y6uC65bs0swg (Encrypted value of input)Note: Though the encrypted value i.e. Encrypted String & OUTPUT in 3.1 and 3.2 respectively are different, as the secret key is the same, the decryption will result in the same value (abcd1234) in both the cases."
},
{
"code": null,
"e": 7189,
"s": 6009,
"text": "Use the Jasypt Online Tool :This link can be used to generate an encrypted key by passing the chosen secret key.The password to encrypt: abcd1234Select type of encryption: Two-way encryption (PBEWithMD5AndDES by default is used)Secret Key: hello (It can be any value)Encrypted String: kNuS1WAezYE7cph7zXVTiPSQSdHTx7KvYou can actually use the tool to encrypt and check the encrypted key by decrypting it.Use the jasypt Jar: Download the jasypt jar file from the maven repository and run it through the following command:java -cp //jasypt-1.9.3/lib/jasypt-1.9.3.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input=”xyz123′′ password=secretkey algorithm=PBEWithMD5AndDESFollowing is the significance of command-line parameters passed to run the jar:input: abcd1234 (Actual password to be encrypted)password: hello (the secret key chosen by you)algorithm: PBEWithMD5AndDES (default algorithm used)OUTPUT: scEjemHosjc/hjA8saT7Y6uC65bs0swg (Encrypted value of input)Note: Though the encrypted value i.e. Encrypted String & OUTPUT in 3.1 and 3.2 respectively are different, as the secret key is the same, the decryption will result in the same value (abcd1234) in both the cases."
},
{
"code": null,
"e": 7593,
"s": 7189,
"text": "Use the Jasypt Online Tool :This link can be used to generate an encrypted key by passing the chosen secret key.The password to encrypt: abcd1234Select type of encryption: Two-way encryption (PBEWithMD5AndDES by default is used)Secret Key: hello (It can be any value)Encrypted String: kNuS1WAezYE7cph7zXVTiPSQSdHTx7KvYou can actually use the tool to encrypt and check the encrypted key by decrypting it."
},
{
"code": null,
"e": 7678,
"s": 7593,
"text": "This link can be used to generate an encrypted key by passing the chosen secret key."
},
{
"code": null,
"e": 7712,
"s": 7678,
"text": "The password to encrypt: abcd1234"
},
{
"code": null,
"e": 7796,
"s": 7712,
"text": "Select type of encryption: Two-way encryption (PBEWithMD5AndDES by default is used)"
},
{
"code": null,
"e": 7836,
"s": 7796,
"text": "Secret Key: hello (It can be any value)"
},
{
"code": null,
"e": 7887,
"s": 7836,
"text": "Encrypted String: kNuS1WAezYE7cph7zXVTiPSQSdHTx7Kv"
},
{
"code": null,
"e": 7974,
"s": 7887,
"text": "You can actually use the tool to encrypt and check the encrypted key by decrypting it."
},
{
"code": null,
"e": 8751,
"s": 7974,
"text": "Use the jasypt Jar: Download the jasypt jar file from the maven repository and run it through the following command:java -cp //jasypt-1.9.3/lib/jasypt-1.9.3.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input=”xyz123′′ password=secretkey algorithm=PBEWithMD5AndDESFollowing is the significance of command-line parameters passed to run the jar:input: abcd1234 (Actual password to be encrypted)password: hello (the secret key chosen by you)algorithm: PBEWithMD5AndDES (default algorithm used)OUTPUT: scEjemHosjc/hjA8saT7Y6uC65bs0swg (Encrypted value of input)Note: Though the encrypted value i.e. Encrypted String & OUTPUT in 3.1 and 3.2 respectively are different, as the secret key is the same, the decryption will result in the same value (abcd1234) in both the cases."
},
{
"code": null,
"e": 8907,
"s": 8751,
"text": "java -cp //jasypt-1.9.3/lib/jasypt-1.9.3.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input=”xyz123′′ password=secretkey algorithm=PBEWithMD5AndDES"
},
{
"code": null,
"e": 8987,
"s": 8907,
"text": "Following is the significance of command-line parameters passed to run the jar:"
},
{
"code": null,
"e": 9037,
"s": 8987,
"text": "input: abcd1234 (Actual password to be encrypted)"
},
{
"code": null,
"e": 9084,
"s": 9037,
"text": "password: hello (the secret key chosen by you)"
},
{
"code": null,
"e": 9137,
"s": 9084,
"text": "algorithm: PBEWithMD5AndDES (default algorithm used)"
},
{
"code": null,
"e": 9205,
"s": 9137,
"text": "OUTPUT: scEjemHosjc/hjA8saT7Y6uC65bs0swg (Encrypted value of input)"
},
{
"code": null,
"e": 9418,
"s": 9205,
"text": "Note: Though the encrypted value i.e. Encrypted String & OUTPUT in 3.1 and 3.2 respectively are different, as the secret key is the same, the decryption will result in the same value (abcd1234) in both the cases."
},
{
"code": null,
"e": 10099,
"s": 9418,
"text": "Add the encrypted key in the config file (application.yml or application.properties): Now instead of adding the actual password ie. “abcd1234” as per the above eg., you need to add the encrypted value generated by either of the above methods. But how will the jasypt dependency understand that the particular property of the config file needs to be decrypted? Hence to make Jasypt aware of your encrypted values, it uses a convention which you need to add in the following format:ENC(encrypted key): ENC(scEjemHosjc/hjA8saT7Y6uC65bs0swg)In the above image, the encryption of the database password is done. You can use it in any scenario where you have to hide the actual password."
},
{
"code": null,
"e": 10157,
"s": 10099,
"text": "ENC(encrypted key): ENC(scEjemHosjc/hjA8saT7Y6uC65bs0swg)"
},
{
"code": null,
"e": 10301,
"s": 10157,
"text": "In the above image, the encryption of the database password is done. You can use it in any scenario where you have to hide the actual password."
},
{
"code": null,
"e": 10780,
"s": 10301,
"text": "Secret key chosen needs to be passed to decrypt at runtime: Make the Jasypt aware of the secret key which you have used to form the encrypted value. Hence following are the different methods to pass the secret key: Pass it as a property in the config file. Run the project as usual and the decryption would happen.Run the project with the following command:$mvn-Djasypt.encryptor.password=secretkey spring-boot:runExport Jasypt Encryptor Password:JASYPT_ENCRYPTOR_PASSWORD=hello"
},
{
"code": null,
"e": 11044,
"s": 10780,
"text": "Pass it as a property in the config file. Run the project as usual and the decryption would happen.Run the project with the following command:$mvn-Djasypt.encryptor.password=secretkey spring-boot:runExport Jasypt Encryptor Password:JASYPT_ENCRYPTOR_PASSWORD=hello"
},
{
"code": null,
"e": 11144,
"s": 11044,
"text": "Pass it as a property in the config file. Run the project as usual and the decryption would happen."
},
{
"code": null,
"e": 11245,
"s": 11144,
"text": "Run the project with the following command:$mvn-Djasypt.encryptor.password=secretkey spring-boot:run"
},
{
"code": null,
"e": 11303,
"s": 11245,
"text": "$mvn-Djasypt.encryptor.password=secretkey spring-boot:run"
},
{
"code": null,
"e": 11368,
"s": 11303,
"text": "Export Jasypt Encryptor Password:JASYPT_ENCRYPTOR_PASSWORD=hello"
},
{
"code": null,
"e": 11400,
"s": 11368,
"text": "JASYPT_ENCRYPTOR_PASSWORD=hello"
},
{
"code": null,
"e": 11413,
"s": 11400,
"text": "cryptography"
},
{
"code": null,
"e": 11425,
"s": 11413,
"text": "Java-Spring"
},
{
"code": null,
"e": 11449,
"s": 11425,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 11454,
"s": 11449,
"text": "Java"
},
{
"code": null,
"e": 11473,
"s": 11454,
"text": "Technical Scripter"
},
{
"code": null,
"e": 11478,
"s": 11473,
"text": "Java"
},
{
"code": null,
"e": 11491,
"s": 11478,
"text": "cryptography"
},
{
"code": null,
"e": 11589,
"s": 11491,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11608,
"s": 11589,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 11626,
"s": 11608,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 11646,
"s": 11626,
"text": "Collections in Java"
},
{
"code": null,
"e": 11661,
"s": 11646,
"text": "Stream In Java"
},
{
"code": null,
"e": 11693,
"s": 11661,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 11713,
"s": 11693,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 11737,
"s": 11713,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 11749,
"s": 11737,
"text": "Set in Java"
},
{
"code": null,
"e": 11770,
"s": 11749,
"text": "Introduction to Java"
}
] |
How to deallocate memory without using free() in C? | 28 May, 2017
Question: How to deallocate dynamically allocate memory without using “free()” function.
Solution: Standard library function realloc() can be used to deallocate previously allocated memory. Below is function declaration of “realloc()” from “stdlib.h”
void *realloc(void *ptr, size_t size);
If “size” is zero, then call to realloc is equivalent to “free(ptr)”. And if “ptr” is NULL and size is non-zero then call to realloc is equivalent to “malloc(size)”.
Let us check with simple example.
/* code with memory leak */#include <stdio.h>#include <stdlib.h> int main(void){ int *ptr = (int*)malloc(10); return 0;}
Check the leak summary with valgrind tool. It shows memory leak of 10 bytes, which is highlighed in red colour.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
[narendra@ubuntu]$ valgrind –leak-check=full ./free
==1238== LEAK SUMMARY:
==1238== definitely lost: 10 bytes in 1 blocks.
==1238== possibly lost: 0 bytes in 0 blocks.
==1238== still reachable: 0 bytes in 0 blocks.
==1238== suppressed: 0 bytes in 0 blocks.
[narendra@ubuntu]$
Let us modify the above code.
#include <stdio.h>#include <stdlib.h> int main(void){ int *ptr = (int*) malloc(10); /* we are calling realloc with size = 0 */ realloc(ptr, 0); return 0;}
Check the valgrind’s output. It shows no memory leaks are possible, highlighted in red color.
[narendra@ubuntu]$ valgrind –leak-check=full ./a.out
==1435== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 11 from 1)
==1435== malloc/free: in use at exit: 0 bytes in 0 blocks.
==1435== malloc/free: 1 allocs, 1 frees, 10 bytes allocated.
==1435== For counts of detected errors, rerun with: -v
==1435== All heap blocks were freed — no leaks are possible.
[narendra@ubuntu]$
This article is compiled by “Narendra Kangralkar“ and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C-Dynamic Memory Allocation
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
Enumeration (or enum) in C
C Language Introduction
Power Function in C/C++
INT_MAX and INT_MIN in C/C++ and Applications
Operators in C / C++ | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 May, 2017"
},
{
"code": null,
"e": 143,
"s": 54,
"text": "Question: How to deallocate dynamically allocate memory without using “free()” function."
},
{
"code": null,
"e": 305,
"s": 143,
"text": "Solution: Standard library function realloc() can be used to deallocate previously allocated memory. Below is function declaration of “realloc()” from “stdlib.h”"
},
{
"code": "void *realloc(void *ptr, size_t size);",
"e": 344,
"s": 305,
"text": null
},
{
"code": null,
"e": 510,
"s": 344,
"text": "If “size” is zero, then call to realloc is equivalent to “free(ptr)”. And if “ptr” is NULL and size is non-zero then call to realloc is equivalent to “malloc(size)”."
},
{
"code": null,
"e": 544,
"s": 510,
"text": "Let us check with simple example."
},
{
"code": "/* code with memory leak */#include <stdio.h>#include <stdlib.h> int main(void){ int *ptr = (int*)malloc(10); return 0;}",
"e": 674,
"s": 544,
"text": null
},
{
"code": null,
"e": 786,
"s": 674,
"text": "Check the leak summary with valgrind tool. It shows memory leak of 10 bytes, which is highlighed in red colour."
},
{
"code": null,
"e": 795,
"s": 786,
"text": "Chapters"
},
{
"code": null,
"e": 822,
"s": 795,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 872,
"s": 822,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 895,
"s": 872,
"text": "captions off, selected"
},
{
"code": null,
"e": 903,
"s": 895,
"text": "English"
},
{
"code": null,
"e": 927,
"s": 903,
"text": "This is a modal window."
},
{
"code": null,
"e": 996,
"s": 927,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1018,
"s": 996,
"text": "End of dialog window."
},
{
"code": null,
"e": 1326,
"s": 1018,
"text": " [narendra@ubuntu]$ valgrind –leak-check=full ./free\n ==1238== LEAK SUMMARY:\n ==1238== definitely lost: 10 bytes in 1 blocks.\n ==1238== possibly lost: 0 bytes in 0 blocks.\n ==1238== still reachable: 0 bytes in 0 blocks.\n ==1238== suppressed: 0 bytes in 0 blocks.\n[narendra@ubuntu]$\n"
},
{
"code": null,
"e": 1356,
"s": 1326,
"text": "Let us modify the above code."
},
{
"code": "#include <stdio.h>#include <stdlib.h> int main(void){ int *ptr = (int*) malloc(10); /* we are calling realloc with size = 0 */ realloc(ptr, 0); return 0;}",
"e": 1533,
"s": 1356,
"text": null
},
{
"code": null,
"e": 1627,
"s": 1533,
"text": "Check the valgrind’s output. It shows no memory leaks are possible, highlighted in red color."
},
{
"code": null,
"e": 2023,
"s": 1627,
"text": " [narendra@ubuntu]$ valgrind –leak-check=full ./a.out\n ==1435== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 11 from 1)\n ==1435== malloc/free: in use at exit: 0 bytes in 0 blocks.\n ==1435== malloc/free: 1 allocs, 1 frees, 10 bytes allocated.\n ==1435== For counts of detected errors, rerun with: -v\n ==1435== All heap blocks were freed — no leaks are possible.\n [narendra@ubuntu]$\n"
},
{
"code": null,
"e": 2234,
"s": 2023,
"text": "This article is compiled by “Narendra Kangralkar“ and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 2262,
"s": 2234,
"text": "C-Dynamic Memory Allocation"
},
{
"code": null,
"e": 2273,
"s": 2262,
"text": "C Language"
},
{
"code": null,
"e": 2371,
"s": 2273,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2388,
"s": 2371,
"text": "Substring in C++"
},
{
"code": null,
"e": 2410,
"s": 2388,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 2455,
"s": 2410,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 2480,
"s": 2455,
"text": "std::string class in C++"
},
{
"code": null,
"e": 2528,
"s": 2480,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 2555,
"s": 2528,
"text": "Enumeration (or enum) in C"
},
{
"code": null,
"e": 2579,
"s": 2555,
"text": "C Language Introduction"
},
{
"code": null,
"e": 2603,
"s": 2579,
"text": "Power Function in C/C++"
},
{
"code": null,
"e": 2649,
"s": 2603,
"text": "INT_MAX and INT_MIN in C/C++ and Applications"
}
] |
Delete an element from array (Using two traversals and one traversal) | 27 Jun, 2022
Given an array and a number ‘x’, write a function to delete ‘x’ from the given array. We assume that array maintains two things with it, capacity and size. So when we remove an item, capacity does not change, only size changes.
Example:
Input: arr[] = {3, 1, 2, 5, 90}, x = 2, size = 5, capacity = 5
Output: arr[] = {3, 1, 5, 90, _}, size = 4, capacity = 5
Input: arr[] = {3, 1, 2, _, _}, x = 2, size = 3, capacity = 5
Output: arr[] = {3, 1, _, _, _}, size = 2, capacity = 5
Method 1(First Search, then Remove): We first search ‘x’ in array, then elements that are on right side of x to one position back. The following are the implementation of this simple approach.
Implementation:
C++
Java
Python3
C#
Javascript
// C++ program to remove a given element from an array#include<bits/stdc++.h>using namespace std; // This function removes an element x from arr[] and// returns new size after removal (size is reduced only// when x is present in arr[]int deleteElement(int arr[], int n, int x){// Search x in arrayint i;for (i=0; i<n; i++) if (arr[i] == x) break; // If x found in arrayif (i < n){ // reduce size of array and move all // elements on space ahead n = n - 1; for (int j=i; j<n; j++) arr[j] = arr[j+1];} return n;} /* Driver program to test above function */int main(){ int arr[] = {11, 15, 6, 8, 9, 10}; int n = sizeof(arr)/sizeof(arr[0]); int x = 6; // Delete x from arr[] n = deleteElement(arr, n, x); cout << "Modified array is \n"; for (int i=0; i<n; i++) cout << arr[i] << " "; return 0;}
// Java program to remove a given element from an arrayimport java.io.*; class Deletion { // This function removes an element x from arr[] and // returns new size after removal (size is reduced only // when x is present in arr[] static int deleteElement(int arr[], int n, int x) { // Search x in array int i; for (i=0; i<n; i++) if (arr[i] == x) break; // If x found in array if (i < n) { // reduce size of array and move all // elements on space ahead n = n - 1; for (int j=i; j<n; j++) arr[j] = arr[j+1]; } return n; } // Driver program to test above function public static void main(String[] args) { int arr[] = {11, 15, 6, 8, 9, 10}; int n = arr.length; int x = 6; // Delete x from arr[] n = deleteElement(arr, n, x); System.out.println("Modified array is"); for (int i = 0; i < n; i++) System.out.print(arr[i]+" "); }}/*This code is contributed by Devesh Agrawal*/
# Python 3 program to remove a given# element from an array # This function removes an element x# from arr[] and returns new size after# removal (size is reduced only when x# is present in arr[]def deleteElement(arr, n, x): # Search x in array for i in range(n): if (arr[i] == x): break # If x found in array if (i < n): # reduce size of array and move # all elements on space ahead n = n - 1; for j in range(i, n, 1): arr[j] = arr[j + 1] return n # Driver Codeif __name__ == '__main__': arr = [11, 15, 6, 8, 9, 10] n = len(arr) x = 6 # Delete x from arr[] n = deleteElement(arr, n, x) print("Modified array is") for i in range(n): print(arr[i], end = " ") # This code is contributed by# Shashank_Sharma
// C# program to remove a given element from// an arrayusing System; class GFG { // This function removes an element x // from arr[] and returns new size // after removal (size is reduced only // when x is present in arr[] static int deleteElement(int []arr, int n, int x) { // Search x in array int i; for (i = 0; i < n; i++) if (arr[i] == x) break; // If x found in array if (i < n) { // reduce size of array and // move all elements on // space ahead n = n - 1; for (int j = i; j < n; j++) arr[j] = arr[j+1]; } return n; } // Driver program to test above function public static void Main() { int []arr = {11, 15, 6, 8, 9, 10}; int n = arr.Length; int x = 6; // Delete x from arr[] n = deleteElement(arr, n, x); Console.WriteLine("Modified array is"); for (int i = 0; i < n; i++) Console.Write(arr[i]+" "); }} // This code is contributed by nitin mittal.
<script> // Javascript program to remove a// given element from an array // This function removes an// element x from arr[] and// returns new size after removal// (size is reduced only// when x is present in arr[]function deleteElement( arr, n, x){ // Search x in array let i; for (i=0; i<n; i++) if (arr[i] == x) break; // If x found in array if (i < n) { // reduce size of array and move all // elements on space ahead n = n - 1; for (let j=i; j<n; j++) arr[j] = arr[j+1]; } return n;} // driver code let arr = [11, 15, 6, 8, 9, 10]; let n = arr.length; let x = 6; // Delete x from arr[] n = deleteElement(arr, n, x); document.write("Modified array is </br>"); for (let i=0; i<n; i++) document.write(arr[i] + " "); </script>
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Modified array is
11 15 8 9 10
Time Complexity : O(n) Auxiliary Space : O(1)
Method 2 (Move elements while searching): This method assumes that the element is always present in array. The idea is to start from right most element and keep moving elements while searching for ‘x’. Below are C++ and Java implementations of this approach. Note that this approach may give unexpected result when ‘x’ is not present in array.
Implemenation:
C++
Java
Python3
C#
Javascript
// C++ program to remove a given element from an array#include<iostream>using namespace std; // This function removes an element x from arr[] and// returns new size after removal.// Returned size is n-1 when element is present.// Otherwise 0 is returned to indicate failure.int deleteElement(int arr[], int n, int x){ // If x is last element, nothing to do if (arr[n-1] == x) return (n-1); // Start from rightmost element and keep moving // elements one position ahead. int prev = arr[n-1], i; for (i=n-2; i>=0 && arr[i]!=x; i--) { int curr = arr[i]; arr[i] = prev; prev = curr; } // If element was not found if (i < 0) return 0; // Else move the next element in place of x arr[i] = prev; return (n-1);} /* Driver program to test above function */int main(){ int arr[] = {11, 15, 6, 8, 9, 10}; int n = sizeof(arr)/sizeof(arr[0]); int x = 6; // Delete x from arr[] n = deleteElement(arr, n, x); cout << "Modified array is \n"; for (int i=0; i<n; i++) cout << arr[i] << " "; return 0;}
// Java program to remove a given element from an arrayimport java.io.*; class Deletion{ // This function removes an element x from arr[] and // returns new size after removal. // Returned size is n-1 when element is present. // Otherwise 0 is returned to indicate failure. static int deleteElement(int arr[], int n, int x) { // If x is last element, nothing to do if (arr[n-1] == x) return (n-1); // Start from rightmost element and keep moving // elements one position ahead. int prev = arr[n-1], i; for (i=n-2; i>=0 && arr[i]!=x; i--) { int curr = arr[i]; arr[i] = prev; prev = curr; } // If element was not found if (i < 0) return 0; // Else move the next element in place of x arr[i] = prev; return (n-1); } // Driver program to test above function public static void main(String[] args) { int arr[] = {11, 15, 6, 8, 9, 10}; int n = arr.length; int x = 6; // Delete x from arr[] n = deleteElement(arr, n, x); System.out.println("Modified array is"); for (int i = 0; i < n; i++) System.out.print(arr[i]+" "); }}/*This code is contributed by Devesh Agrawal*/
# python program to remove a given element from an array # This function removes an element x from arr[] and# returns new size after removal.# Returned size is n-1 when element is present.# Otherwise 0 is returned to indicate failure.def deleteElement(arr,n,x): # If x is last element, nothing to do if arr[n-1]==x: return n-1 # Start from rightmost element and keep moving # elements one position ahead. prev = arr[n-1] for i in range(n-2,1,-1): if arr[i]!=x: curr = arr[i] arr[i] = prev prev = curr # If element was not found if i<0: return 0 # Else move the next element in place of x arr[i] = prev return n-1 # Driver codearr = [11,15,6,8,9,10]n = len(arr)x = 6n = deleteElement(arr,n,x)print("Modified array is")for i in range(n): print(arr[i],end=" ") # This code is contributed by Shrikant13
// C# program to remove a given// element from an arrayusing System;class GFG { // This function removes an // element x from arr[] and // returns new size after // removal. Returned size is // n-1 when element is present. // Otherwise 0 is returned to // indicate failure. static int deleteElement(int []arr, int n, int x) { // If x is last element, // nothing to do if (arr[n - 1] == x) return (n - 1); // Start from rightmost // element and keep moving // elements one position ahead. int prev = arr[n - 1], i; for (i = n - 2; i >= 0 && arr[i] != x; i--) { int curr = arr[i]; arr[i] = prev; prev = curr; } // If element was // not found if (i < 0) return 0; // Else move the next // element in place of x arr[i] = prev; return (n - 1); } // Driver Code public static void Main() { int []arr = {11, 15, 6, 8, 9, 10}; int n = arr.Length; int x = 6; // Delete x from arr[] n = deleteElement(arr, n, x); Console.WriteLine("Modified array is"); for(int i = 0; i < n; i++) Console.Write(arr[i]+" "); }} // This code is contributed by anuj_67.
<script>// Java Script program to remove a given element from an array // This function removes an element x from arr[] and // returns new size after removal. // Returned size is n-1 when element is present. // Otherwise 0 is returned to indicate failure. function deleteElement(arr,n,x) { // If x is last element, nothing to do if (arr[n-1] == x) return (n-1); // Start from rightmost element and keep moving // elements one position ahead. let prev = arr[n-1], i; for (i=n-2; i>=0 && arr[i]!=x; i--) { let curr = arr[i]; arr[i] = prev; prev = curr; } // If element was not found if (i < 0) return 0; // Else move the next element in place of x arr[i] = prev; return (n-1); } // Driver program to test above function let arr = [11, 15, 6, 8, 9, 10]; let n = arr.length; let x = 6; // Delete x from arr[] n = deleteElement(arr, n, x); document.write("Modified array is<br>"); for (let i = 0; i < n; i++) document.write(arr[i]+" "); // This code is contributed by sravan kumar Gottumukkala</script>
Modified array is
11 15 8 9 10
Time Complexity : O(n) Auxiliary Space : O(1)
Deleting an element from an array takes O(n) time even if we are given index of the element to be deleted. The time complexity remains O(n) for sorted arrays as well. In linked list, if we know the pointer to the previous node of the node to be deleted, we can do deletion in O(1) time.
This article is contributed by Himanshu. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
vt_m
shrikanth13
Shashank_Sharma
jana_sayantan
sravankumar8128
kumarabhay712001
codewithrathi
hardikkoriintern
Arrays
Greedy
Arrays
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Linear Search
Multidimensional Arrays in Java
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Write a program to print all permutations of a given string
Huffman Coding | Greedy Algo-3 | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 Jun, 2022"
},
{
"code": null,
"e": 280,
"s": 52,
"text": "Given an array and a number ‘x’, write a function to delete ‘x’ from the given array. We assume that array maintains two things with it, capacity and size. So when we remove an item, capacity does not change, only size changes."
},
{
"code": null,
"e": 290,
"s": 280,
"text": "Example: "
},
{
"code": null,
"e": 533,
"s": 290,
"text": "Input: arr[] = {3, 1, 2, 5, 90}, x = 2, size = 5, capacity = 5\nOutput: arr[] = {3, 1, 5, 90, _}, size = 4, capacity = 5\n\nInput: arr[] = {3, 1, 2, _, _}, x = 2, size = 3, capacity = 5\nOutput: arr[] = {3, 1, _, _, _}, size = 2, capacity = 5\n "
},
{
"code": null,
"e": 726,
"s": 533,
"text": "Method 1(First Search, then Remove): We first search ‘x’ in array, then elements that are on right side of x to one position back. The following are the implementation of this simple approach."
},
{
"code": null,
"e": 742,
"s": 726,
"text": "Implementation:"
},
{
"code": null,
"e": 746,
"s": 742,
"text": "C++"
},
{
"code": null,
"e": 751,
"s": 746,
"text": "Java"
},
{
"code": null,
"e": 759,
"s": 751,
"text": "Python3"
},
{
"code": null,
"e": 762,
"s": 759,
"text": "C#"
},
{
"code": null,
"e": 773,
"s": 762,
"text": "Javascript"
},
{
"code": "// C++ program to remove a given element from an array#include<bits/stdc++.h>using namespace std; // This function removes an element x from arr[] and// returns new size after removal (size is reduced only// when x is present in arr[]int deleteElement(int arr[], int n, int x){// Search x in arrayint i;for (i=0; i<n; i++) if (arr[i] == x) break; // If x found in arrayif (i < n){ // reduce size of array and move all // elements on space ahead n = n - 1; for (int j=i; j<n; j++) arr[j] = arr[j+1];} return n;} /* Driver program to test above function */int main(){ int arr[] = {11, 15, 6, 8, 9, 10}; int n = sizeof(arr)/sizeof(arr[0]); int x = 6; // Delete x from arr[] n = deleteElement(arr, n, x); cout << \"Modified array is \\n\"; for (int i=0; i<n; i++) cout << arr[i] << \" \"; return 0;}",
"e": 1623,
"s": 773,
"text": null
},
{
"code": "// Java program to remove a given element from an arrayimport java.io.*; class Deletion { // This function removes an element x from arr[] and // returns new size after removal (size is reduced only // when x is present in arr[] static int deleteElement(int arr[], int n, int x) { // Search x in array int i; for (i=0; i<n; i++) if (arr[i] == x) break; // If x found in array if (i < n) { // reduce size of array and move all // elements on space ahead n = n - 1; for (int j=i; j<n; j++) arr[j] = arr[j+1]; } return n; } // Driver program to test above function public static void main(String[] args) { int arr[] = {11, 15, 6, 8, 9, 10}; int n = arr.length; int x = 6; // Delete x from arr[] n = deleteElement(arr, n, x); System.out.println(\"Modified array is\"); for (int i = 0; i < n; i++) System.out.print(arr[i]+\" \"); }}/*This code is contributed by Devesh Agrawal*/",
"e": 2751,
"s": 1623,
"text": null
},
{
"code": "# Python 3 program to remove a given# element from an array # This function removes an element x# from arr[] and returns new size after# removal (size is reduced only when x# is present in arr[]def deleteElement(arr, n, x): # Search x in array for i in range(n): if (arr[i] == x): break # If x found in array if (i < n): # reduce size of array and move # all elements on space ahead n = n - 1; for j in range(i, n, 1): arr[j] = arr[j + 1] return n # Driver Codeif __name__ == '__main__': arr = [11, 15, 6, 8, 9, 10] n = len(arr) x = 6 # Delete x from arr[] n = deleteElement(arr, n, x) print(\"Modified array is\") for i in range(n): print(arr[i], end = \" \") # This code is contributed by# Shashank_Sharma",
"e": 3581,
"s": 2751,
"text": null
},
{
"code": "// C# program to remove a given element from// an arrayusing System; class GFG { // This function removes an element x // from arr[] and returns new size // after removal (size is reduced only // when x is present in arr[] static int deleteElement(int []arr, int n, int x) { // Search x in array int i; for (i = 0; i < n; i++) if (arr[i] == x) break; // If x found in array if (i < n) { // reduce size of array and // move all elements on // space ahead n = n - 1; for (int j = i; j < n; j++) arr[j] = arr[j+1]; } return n; } // Driver program to test above function public static void Main() { int []arr = {11, 15, 6, 8, 9, 10}; int n = arr.Length; int x = 6; // Delete x from arr[] n = deleteElement(arr, n, x); Console.WriteLine(\"Modified array is\"); for (int i = 0; i < n; i++) Console.Write(arr[i]+\" \"); }} // This code is contributed by nitin mittal.",
"e": 4757,
"s": 3581,
"text": null
},
{
"code": "<script> // Javascript program to remove a// given element from an array // This function removes an// element x from arr[] and// returns new size after removal// (size is reduced only// when x is present in arr[]function deleteElement( arr, n, x){ // Search x in array let i; for (i=0; i<n; i++) if (arr[i] == x) break; // If x found in array if (i < n) { // reduce size of array and move all // elements on space ahead n = n - 1; for (let j=i; j<n; j++) arr[j] = arr[j+1]; } return n;} // driver code let arr = [11, 15, 6, 8, 9, 10]; let n = arr.length; let x = 6; // Delete x from arr[] n = deleteElement(arr, n, x); document.write(\"Modified array is </br>\"); for (let i=0; i<n; i++) document.write(arr[i] + \" \"); </script>",
"e": 5581,
"s": 4757,
"text": null
},
{
"code": null,
"e": 5590,
"s": 5581,
"text": "Chapters"
},
{
"code": null,
"e": 5617,
"s": 5590,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 5667,
"s": 5617,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 5690,
"s": 5667,
"text": "captions off, selected"
},
{
"code": null,
"e": 5698,
"s": 5690,
"text": "English"
},
{
"code": null,
"e": 5722,
"s": 5698,
"text": "This is a modal window."
},
{
"code": null,
"e": 5791,
"s": 5722,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 5813,
"s": 5791,
"text": "End of dialog window."
},
{
"code": null,
"e": 5846,
"s": 5813,
"text": "Modified array is \n11 15 8 9 10 "
},
{
"code": null,
"e": 5892,
"s": 5846,
"text": "Time Complexity : O(n) Auxiliary Space : O(1)"
},
{
"code": null,
"e": 6236,
"s": 5892,
"text": "Method 2 (Move elements while searching): This method assumes that the element is always present in array. The idea is to start from right most element and keep moving elements while searching for ‘x’. Below are C++ and Java implementations of this approach. Note that this approach may give unexpected result when ‘x’ is not present in array."
},
{
"code": null,
"e": 6252,
"s": 6236,
"text": "Implemenation: "
},
{
"code": null,
"e": 6256,
"s": 6252,
"text": "C++"
},
{
"code": null,
"e": 6261,
"s": 6256,
"text": "Java"
},
{
"code": null,
"e": 6269,
"s": 6261,
"text": "Python3"
},
{
"code": null,
"e": 6272,
"s": 6269,
"text": "C#"
},
{
"code": null,
"e": 6283,
"s": 6272,
"text": "Javascript"
},
{
"code": "// C++ program to remove a given element from an array#include<iostream>using namespace std; // This function removes an element x from arr[] and// returns new size after removal.// Returned size is n-1 when element is present.// Otherwise 0 is returned to indicate failure.int deleteElement(int arr[], int n, int x){ // If x is last element, nothing to do if (arr[n-1] == x) return (n-1); // Start from rightmost element and keep moving // elements one position ahead. int prev = arr[n-1], i; for (i=n-2; i>=0 && arr[i]!=x; i--) { int curr = arr[i]; arr[i] = prev; prev = curr; } // If element was not found if (i < 0) return 0; // Else move the next element in place of x arr[i] = prev; return (n-1);} /* Driver program to test above function */int main(){ int arr[] = {11, 15, 6, 8, 9, 10}; int n = sizeof(arr)/sizeof(arr[0]); int x = 6; // Delete x from arr[] n = deleteElement(arr, n, x); cout << \"Modified array is \\n\"; for (int i=0; i<n; i++) cout << arr[i] << \" \"; return 0;}",
"e": 7358,
"s": 6283,
"text": null
},
{
"code": "// Java program to remove a given element from an arrayimport java.io.*; class Deletion{ // This function removes an element x from arr[] and // returns new size after removal. // Returned size is n-1 when element is present. // Otherwise 0 is returned to indicate failure. static int deleteElement(int arr[], int n, int x) { // If x is last element, nothing to do if (arr[n-1] == x) return (n-1); // Start from rightmost element and keep moving // elements one position ahead. int prev = arr[n-1], i; for (i=n-2; i>=0 && arr[i]!=x; i--) { int curr = arr[i]; arr[i] = prev; prev = curr; } // If element was not found if (i < 0) return 0; // Else move the next element in place of x arr[i] = prev; return (n-1); } // Driver program to test above function public static void main(String[] args) { int arr[] = {11, 15, 6, 8, 9, 10}; int n = arr.length; int x = 6; // Delete x from arr[] n = deleteElement(arr, n, x); System.out.println(\"Modified array is\"); for (int i = 0; i < n; i++) System.out.print(arr[i]+\" \"); }}/*This code is contributed by Devesh Agrawal*/",
"e": 8667,
"s": 7358,
"text": null
},
{
"code": "# python program to remove a given element from an array # This function removes an element x from arr[] and# returns new size after removal.# Returned size is n-1 when element is present.# Otherwise 0 is returned to indicate failure.def deleteElement(arr,n,x): # If x is last element, nothing to do if arr[n-1]==x: return n-1 # Start from rightmost element and keep moving # elements one position ahead. prev = arr[n-1] for i in range(n-2,1,-1): if arr[i]!=x: curr = arr[i] arr[i] = prev prev = curr # If element was not found if i<0: return 0 # Else move the next element in place of x arr[i] = prev return n-1 # Driver codearr = [11,15,6,8,9,10]n = len(arr)x = 6n = deleteElement(arr,n,x)print(\"Modified array is\")for i in range(n): print(arr[i],end=\" \") # This code is contributed by Shrikant13",
"e": 9562,
"s": 8667,
"text": null
},
{
"code": "// C# program to remove a given// element from an arrayusing System;class GFG { // This function removes an // element x from arr[] and // returns new size after // removal. Returned size is // n-1 when element is present. // Otherwise 0 is returned to // indicate failure. static int deleteElement(int []arr, int n, int x) { // If x is last element, // nothing to do if (arr[n - 1] == x) return (n - 1); // Start from rightmost // element and keep moving // elements one position ahead. int prev = arr[n - 1], i; for (i = n - 2; i >= 0 && arr[i] != x; i--) { int curr = arr[i]; arr[i] = prev; prev = curr; } // If element was // not found if (i < 0) return 0; // Else move the next // element in place of x arr[i] = prev; return (n - 1); } // Driver Code public static void Main() { int []arr = {11, 15, 6, 8, 9, 10}; int n = arr.Length; int x = 6; // Delete x from arr[] n = deleteElement(arr, n, x); Console.WriteLine(\"Modified array is\"); for(int i = 0; i < n; i++) Console.Write(arr[i]+\" \"); }} // This code is contributed by anuj_67.",
"e": 10971,
"s": 9562,
"text": null
},
{
"code": "<script>// Java Script program to remove a given element from an array // This function removes an element x from arr[] and // returns new size after removal. // Returned size is n-1 when element is present. // Otherwise 0 is returned to indicate failure. function deleteElement(arr,n,x) { // If x is last element, nothing to do if (arr[n-1] == x) return (n-1); // Start from rightmost element and keep moving // elements one position ahead. let prev = arr[n-1], i; for (i=n-2; i>=0 && arr[i]!=x; i--) { let curr = arr[i]; arr[i] = prev; prev = curr; } // If element was not found if (i < 0) return 0; // Else move the next element in place of x arr[i] = prev; return (n-1); } // Driver program to test above function let arr = [11, 15, 6, 8, 9, 10]; let n = arr.length; let x = 6; // Delete x from arr[] n = deleteElement(arr, n, x); document.write(\"Modified array is<br>\"); for (let i = 0; i < n; i++) document.write(arr[i]+\" \"); // This code is contributed by sravan kumar Gottumukkala</script>",
"e": 12216,
"s": 10971,
"text": null
},
{
"code": null,
"e": 12249,
"s": 12216,
"text": "Modified array is \n11 15 8 9 10 "
},
{
"code": null,
"e": 12295,
"s": 12249,
"text": "Time Complexity : O(n) Auxiliary Space : O(1)"
},
{
"code": null,
"e": 12583,
"s": 12295,
"text": "Deleting an element from an array takes O(n) time even if we are given index of the element to be deleted. The time complexity remains O(n) for sorted arrays as well. In linked list, if we know the pointer to the previous node of the node to be deleted, we can do deletion in O(1) time. "
},
{
"code": null,
"e": 12749,
"s": 12583,
"text": "This article is contributed by Himanshu. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 12762,
"s": 12749,
"text": "nitin mittal"
},
{
"code": null,
"e": 12767,
"s": 12762,
"text": "vt_m"
},
{
"code": null,
"e": 12779,
"s": 12767,
"text": "shrikanth13"
},
{
"code": null,
"e": 12795,
"s": 12779,
"text": "Shashank_Sharma"
},
{
"code": null,
"e": 12809,
"s": 12795,
"text": "jana_sayantan"
},
{
"code": null,
"e": 12825,
"s": 12809,
"text": "sravankumar8128"
},
{
"code": null,
"e": 12842,
"s": 12825,
"text": "kumarabhay712001"
},
{
"code": null,
"e": 12856,
"s": 12842,
"text": "codewithrathi"
},
{
"code": null,
"e": 12873,
"s": 12856,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 12880,
"s": 12873,
"text": "Arrays"
},
{
"code": null,
"e": 12887,
"s": 12880,
"text": "Greedy"
},
{
"code": null,
"e": 12894,
"s": 12887,
"text": "Arrays"
},
{
"code": null,
"e": 12901,
"s": 12894,
"text": "Greedy"
},
{
"code": null,
"e": 12999,
"s": 12901,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13067,
"s": 12999,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 13111,
"s": 13067,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 13159,
"s": 13111,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 13173,
"s": 13159,
"text": "Linear Search"
},
{
"code": null,
"e": 13205,
"s": 13173,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 13256,
"s": 13205,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 13314,
"s": 13256,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 13365,
"s": 13314,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 13425,
"s": 13365,
"text": "Write a program to print all permutations of a given string"
}
] |
Java Nested Loops with Examples | 01 Oct, 2021
Nested loop means a loop statement inside another loop statement. That is why nested loops are also called as “loop inside loop“.Syntax for Nested For loop:
for ( initialization; condition; increment ) {
for ( initialization; condition; increment ) {
// statement of inside loop
}
// statement of outer loop
}
Syntax for Nested While loop:
while(condition) {
while(condition) {
// statement of inside loop
}
// statement of outer loop
}
Syntax for Nested Do-While loop:
do{
do{
// statement of inside loop
}while(condition);
// statement of outer loop
}while(condition);
Note: There is no rule that a loop must be nested inside its own type. In fact, there can be any type of loop nested inside any type and to any level.
Syntax:
do{
while(condition) {
for ( initialization; condition; increment ) {
// statement of inside for loop
}
// statement of inside while loop
}
// statement of outer do-while loop
}while(condition);
Below are some examples to demonstrate the use of Nested Loops:Example 1: Below program uses a nested for loop to print a 2D matrix.
Java
// Java program to print the elements of// a 2 D array or matrix import java.io.*; class GFG { public static void print2D(int mat[][]) { // Loop through all rows for (int i = 0; i < mat.length; i++) { // Loop through all elements of current row for (int j = 0; j < mat[i].length; j++) System.out.print(mat[i][j] + " "); System.out.println(); } } public static void main(String args[]) throws IOException { int mat[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; print2D(mat); }}
1 2 3 4
5 6 7 8
9 10 11 12
Example 2: Below program uses a nested for loop to print all prime factors of a number.
Java
// Java program to print all prime factors import java.io.*;import java.lang.Math; class GFG { // A function to print all prime factors // of a given number n public static void primeFactors(int n) { // Print the number of 2s that divide n while (n % 2 == 0) { System.out.print(2 + " "); n /= 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i += 2) { // While i divides n, print i and divide n while (n % i == 0) { System.out.print(i + " "); n /= i; } } // This condition is to handle the case when // n is a prime number greater than 2 if (n > 2) System.out.print(n); } public static void main(String[] args) { int n = 315; primeFactors(n); }}
3 3 5 7
adnanirshad158
loop
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
Strings in Java
Java Programming Examples
Abstraction in Java
HashSet in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Oct, 2021"
},
{
"code": null,
"e": 211,
"s": 52,
"text": "Nested loop means a loop statement inside another loop statement. That is why nested loops are also called as “loop inside loop“.Syntax for Nested For loop: "
},
{
"code": null,
"e": 388,
"s": 211,
"text": "for ( initialization; condition; increment ) {\n\n for ( initialization; condition; increment ) {\n \n // statement of inside loop\n }\n\n // statement of outer loop\n}"
},
{
"code": null,
"e": 420,
"s": 388,
"text": "Syntax for Nested While loop: "
},
{
"code": null,
"e": 541,
"s": 420,
"text": "while(condition) {\n\n while(condition) {\n \n // statement of inside loop\n }\n\n // statement of outer loop\n}"
},
{
"code": null,
"e": 576,
"s": 541,
"text": "Syntax for Nested Do-While loop: "
},
{
"code": null,
"e": 701,
"s": 576,
"text": "do{\n\n do{\n \n // statement of inside loop\n }while(condition);\n\n // statement of outer loop\n}while(condition);"
},
{
"code": null,
"e": 854,
"s": 703,
"text": "Note: There is no rule that a loop must be nested inside its own type. In fact, there can be any type of loop nested inside any type and to any level."
},
{
"code": null,
"e": 864,
"s": 854,
"text": "Syntax: "
},
{
"code": null,
"e": 1112,
"s": 864,
"text": "do{\n\n while(condition) {\n \n for ( initialization; condition; increment ) {\n \n // statement of inside for loop\n }\n\n // statement of inside while loop\n }\n\n // statement of outer do-while loop\n}while(condition);"
},
{
"code": null,
"e": 1246,
"s": 1112,
"text": "Below are some examples to demonstrate the use of Nested Loops:Example 1: Below program uses a nested for loop to print a 2D matrix. "
},
{
"code": null,
"e": 1251,
"s": 1246,
"text": "Java"
},
{
"code": "// Java program to print the elements of// a 2 D array or matrix import java.io.*; class GFG { public static void print2D(int mat[][]) { // Loop through all rows for (int i = 0; i < mat.length; i++) { // Loop through all elements of current row for (int j = 0; j < mat[i].length; j++) System.out.print(mat[i][j] + \" \"); System.out.println(); } } public static void main(String args[]) throws IOException { int mat[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; print2D(mat); }}",
"e": 1894,
"s": 1251,
"text": null
},
{
"code": null,
"e": 1923,
"s": 1894,
"text": "1 2 3 4 \n5 6 7 8 \n9 10 11 12"
},
{
"code": null,
"e": 2014,
"s": 1925,
"text": "Example 2: Below program uses a nested for loop to print all prime factors of a number. "
},
{
"code": null,
"e": 2019,
"s": 2014,
"text": "Java"
},
{
"code": "// Java program to print all prime factors import java.io.*;import java.lang.Math; class GFG { // A function to print all prime factors // of a given number n public static void primeFactors(int n) { // Print the number of 2s that divide n while (n % 2 == 0) { System.out.print(2 + \" \"); n /= 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i += 2) { // While i divides n, print i and divide n while (n % i == 0) { System.out.print(i + \" \"); n /= i; } } // This condition is to handle the case when // n is a prime number greater than 2 if (n > 2) System.out.print(n); } public static void main(String[] args) { int n = 315; primeFactors(n); }}",
"e": 2941,
"s": 2019,
"text": null
},
{
"code": null,
"e": 2949,
"s": 2941,
"text": "3 3 5 7"
},
{
"code": null,
"e": 2966,
"s": 2951,
"text": "adnanirshad158"
},
{
"code": null,
"e": 2971,
"s": 2966,
"text": "loop"
},
{
"code": null,
"e": 2976,
"s": 2971,
"text": "Java"
},
{
"code": null,
"e": 2981,
"s": 2976,
"text": "Java"
},
{
"code": null,
"e": 3079,
"s": 2981,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3094,
"s": 3079,
"text": "Stream In Java"
},
{
"code": null,
"e": 3115,
"s": 3094,
"text": "Introduction to Java"
},
{
"code": null,
"e": 3136,
"s": 3115,
"text": "Constructors in Java"
},
{
"code": null,
"e": 3155,
"s": 3136,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 3172,
"s": 3155,
"text": "Generics in Java"
},
{
"code": null,
"e": 3202,
"s": 3172,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 3218,
"s": 3202,
"text": "Strings in Java"
},
{
"code": null,
"e": 3244,
"s": 3218,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 3264,
"s": 3244,
"text": "Abstraction in Java"
}
] |
Python Program to convert Kilometers to Miles | 19 Dec, 2017
Kilometer is a unit of length in the metric system equivalent to 1000 meters.
Miles is also the unit of length equal to 1760 yards.
Example:
Input: 5.5
Output: 3.418
Input: 6.5
Output: 4.039
Formula:
1 kilometer equals 0.62137 miles.
Miles = kilometer * 0.62137
Kilometer = Miles / 0.62137
# Python3 program to convert# kilometers to miles # driver codekilometers = 5.5 # conversion factorconv = 0.621371 # calculate milesmiles = kilometers * convprint('%0.3f kilometers is equal to %0.3f miles' %(kilometers,miles)) kilometers = 6.5 # calculate milesmiles = kilometers * convprint('%0.3f kilometers is equal to %0.3f miles' %(kilometers,miles))
Output:
5.500 kilometers is equal to 3.418 miles
6.500 kilometers is equal to 4.039 miles
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Program to find GCD or HCF of two numbers
Find minimum number of coins that make a given value
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n19 Dec, 2017"
},
{
"code": null,
"e": 132,
"s": 54,
"text": "Kilometer is a unit of length in the metric system equivalent to 1000 meters."
},
{
"code": null,
"e": 186,
"s": 132,
"text": "Miles is also the unit of length equal to 1760 yards."
},
{
"code": null,
"e": 195,
"s": 186,
"text": "Example:"
},
{
"code": null,
"e": 249,
"s": 195,
"text": "Input: 5.5 \nOutput: 3.418 \n\nInput: 6.5\nOutput: 4.039\n"
},
{
"code": null,
"e": 258,
"s": 249,
"text": "Formula:"
},
{
"code": null,
"e": 352,
"s": 258,
"text": "1 kilometer equals 0.62137 miles.\nMiles = kilometer * 0.62137 \nKilometer = Miles / 0.62137\n"
},
{
"code": "# Python3 program to convert# kilometers to miles # driver codekilometers = 5.5 # conversion factorconv = 0.621371 # calculate milesmiles = kilometers * convprint('%0.3f kilometers is equal to %0.3f miles' %(kilometers,miles)) kilometers = 6.5 # calculate milesmiles = kilometers * convprint('%0.3f kilometers is equal to %0.3f miles' %(kilometers,miles))",
"e": 713,
"s": 352,
"text": null
},
{
"code": null,
"e": 721,
"s": 713,
"text": "Output:"
},
{
"code": null,
"e": 804,
"s": 721,
"text": "5.500 kilometers is equal to 3.418 miles\n6.500 kilometers is equal to 4.039 miles\n"
},
{
"code": null,
"e": 817,
"s": 804,
"text": "Mathematical"
},
{
"code": null,
"e": 836,
"s": 817,
"text": "School Programming"
},
{
"code": null,
"e": 849,
"s": 836,
"text": "Mathematical"
},
{
"code": null,
"e": 947,
"s": 849,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 971,
"s": 947,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 992,
"s": 971,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 1006,
"s": 992,
"text": "Prime Numbers"
},
{
"code": null,
"e": 1048,
"s": 1006,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 1101,
"s": 1048,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 1119,
"s": 1101,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1144,
"s": 1119,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 1160,
"s": 1144,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 1183,
"s": 1160,
"text": "Introduction To PYTHON"
}
] |
Packages In Java | 04 Mar, 2022
Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces. Packages are used for:
Preventing naming conflicts. For example there can be two classes with name Employee in two packages, college.staff.cse.Employee and college.staff.ee.Employee
Making searching/locating and usage of classes, interfaces, enumerations and annotations easier
Providing controlled access: protected and default have package level access control. A protected member is accessible by classes in the same package and its subclasses. A default member (without any access specifier) is accessible by classes in the same package only.
Packages can be considered as data encapsulation (or data-hiding).
All we need to do is put related classes into packages. After that, we can simply write an import class from existing packages and use it in our program. A package is a container of a group of related classes where some of the classes are accessible are exposed and others are kept for internal purpose.We can reuse existing classes from the packages as many time as we need it in our program.
How packages work?
Package names and directory structure are closely related. For example if a package name is college.staff.cse, then there are three directories, college, staff and cse such that cse is present in staff and staff is present college. Also, the directory college is accessible through CLASSPATH variable, i.e., path of parent directory of college is present in CLASSPATH. The idea is to make sure that classes are easy to locate.Package naming conventions : Packages are named in reverse order of domain names, i.e., org.geeksforgeeks.practice. For example, in a college, the recommended convention is college.tech.cse, college.tech.ee, college.art.history, etc.
Adding a class to a Package : We can add more classes to a created package by using package name at the top of the program and saving it in the package directory. We need a new java file to define a public class, otherwise we can add the new class to an existing .java file and recompile it.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Subpackages: Packages that are inside another package are the subpackages. These are not imported by default, they have to imported explicitly. Also, members of a subpackage have no access privileges, i.e., they are considered as different package for protected and default access specifiers.Example :
import java.util.*;
util is a subpackage created inside java package.
Accessing classes inside a package
Consider following two statements :
// import the Vector class from util package.
import java.util.vector;
// import all the classes from util package
import java.util.*;
First Statement is used to import Vector class from util package which is contained inside java.
Second statement imports all the classes from util package.
// All the classes and interfaces of this package
// will be accessible but not subpackages.
import package.*;
// Only mentioned class of this package will be accessible.
import package.classname;
// Class name is generally used when two packages have the same
// class name. For example in below code both packages have
// date class so using a fully qualified name to avoid conflict
import java.util.Date;
import my.package.Date;
// Java program to demonstrate accessing of members when// corresponding classes are imported and not imported.import java.util.Vector; public class ImportDemo{ public ImportDemo() { // java.util.Vector is imported, hence we are // able to access directly in our code. Vector newVector = new Vector(); // java.util.ArrayList is not imported, hence // we were referring to it using the complete // package. java.util.ArrayList newList = new java.util.ArrayList(); } public static void main(String arg[]) { new ImportDemo(); }}
Types of packages:
Built-in PackagesThese packages consist of a large number of classes which are a part of Java API.Some of the commonly used built-in packages are:1) java.lang: Contains language support classes(e.g classed which defines primitive data types, math operations). This package is automatically imported.2) java.io: Contains classed for supporting input / output operations.3) java.util: Contains utility classes which implement data structures like Linked List, Dictionary and support ; for Date / Time operations.4) java.applet: Contains classes for creating Applets.5) java.awt: Contain classes for implementing the components for graphical user interfaces (like button , ;menus etc).6) java.net: Contain classes for supporting networking operations.
User-defined packagesThese are the packages that are defined by the user. First we create a directory myPackage (name should be same as the name of the package). Then create the MyClass inside the directory with the first statement being the package names.
// Name of the package must be same as the directory
// under which this file is saved
package myPackage;
public class MyClass
{
public void getNames(String s)
{
System.out.println(s);
}
}
Now we can use the MyClass class in our program.
/* import 'MyClass' class from 'names' myPackage */
import myPackage.MyClass;
public class PrintName
{
public static void main(String args[])
{
// Initializing the String variable
// with a value
String name = "GeeksforGeeks";
// Creating an instance of class MyClass in
// the package.
MyClass obj = new MyClass();
obj.getNames(name);
}
}
Note : MyClass.java must be saved inside the myPackage directory since it is a part of the package.
Using Static Import
Static import is a feature introduced in Java programming language ( versions 5 and above ) that allows members ( fields and methods ) defined in a class as public static to be used in Java code without specifying the class in which the field is defined.Following program demonstrates static import :
// Note static keyword after import.import static java.lang.System.*; class StaticImportDemo{ public static void main(String args[]) { // We don't need to use 'System.out' // as imported using static. out.println("GeeksforGeeks"); }}
Output:
GeeksforGeeks
Handling name conflicts
The only time we need to pay attention to packages is when we have a name conflict . For example both, java.util and java.sql packages have a class named Date. So if we import both packages in program as follows:
import java.util.*;
import java.sql.*;
//And then use Date class, then we will get a compile-time error :
Date today ; //ERROR-- java.util.Date or java.sql.Date?
The compiler will not be able to figure out which Date class do we want. This problem can be solved by using a specific import statement:
import java.util.Date;
import java.sql.*;
If we need both Date classes then, we need to use a full package name every time we declare a new object of that class.For Example:
java.util.Date deadLine = new java.util.Date();
java.sql.Date today = new java.sql.Date();
Directory structure
The package name is closely associated with the directory structure used to store the classes. The classes (and other entities) belonging to a specific package are stored together in the same directory. Furthermore, they are stored in a sub-directory structure specified by its package name. For example, the class Circle of package com.zzz.project1.subproject2 is stored as “$BASE_DIR\com\zzz\project1\subproject2\Circle.class”, where $BASE_DIR denotes the base directory of the package. Clearly, the “dot” in the package name corresponds to a sub-directory of the file system.
The base directory ($BASE_DIR) could be located anywhere in the file system. Hence, the Java compiler and runtime must be informed about the location of the $BASE_DIR so as to locate the classes. This is accomplished by an environment variable called CLASSPATH. CLASSPATH is similar to another environment variable PATH, which is used by the command shell to search for the executable programs.
Setting CLASSPATH:CLASSPATH can be set by any of the following ways:
CLASSPATH can be set permanently in the environment: In Windows, choose control panel ? System ? Advanced ? Environment Variables ? choose “System Variables” (for all the users) or “User Variables” (only the currently login user) ? choose “Edit” (if CLASSPATH already exists) or “New” ? Enter “CLASSPATH” as the variable name ? Enter the required directories and JAR files (separated by semicolons) as the value (e.g., “.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar”). Take note that you need to include the current working directory (denoted by ‘.’) in the CLASSPATH.To check the current setting of the CLASSPATH, issue the following command:> SET CLASSPATH
> SET CLASSPATH
CLASSPATH can be set temporarily for that particular CMD shell session by issuing the following command:> SET CLASSPATH=.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar
> SET CLASSPATH=.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar
Instead of using the CLASSPATH environment variable, you can also use the command-line option -classpath or -cp of the javac and java commands, for example,> java –classpath c:\javaproject\classes com.abc.project1.subproject2.MyClass3
> java –classpath c:\javaproject\classes com.abc.project1.subproject2.MyClass3
Illustration of user-defined packages:Creating our first package:File name – ClassOne.java
package package_name; public class ClassOne { public void methodClassOne() { System.out.println("Hello there its ClassOne"); }}
Creating our second package:File name – ClassTwo.java
package package_one; public class ClassTwo { public void methodClassTwo(){ System.out.println("Hello there i am ClassTwo"); } }
Making use of both the created packages:File name – Testing.java
import package_one.ClassTwo;import package_name.ClassOne; public class Testing { public static void main(String[] args){ ClassTwo a = new ClassTwo(); ClassOne b = new ClassOne(); a.methodClassTwo(); b.methodClassOne(); }}
Output:
Hello there i am ClassTwo
Hello there its ClassOne
Now having a look at the directory structure of both the packages and the testing class file:
Important points:
Every class is part of some package.If no package is specified, the classes in the file goes into a special unnamed package (the same unnamed package for all files).All classes/interfaces in a file are part of the same package. Multiple files can specify the same package name.If package name is specified, the file must be in a subdirectory called name (i.e., the directory name must match the package name).We can access public classes in another (named) package using: package-name.class-name
Every class is part of some package.
If no package is specified, the classes in the file goes into a special unnamed package (the same unnamed package for all files).
All classes/interfaces in a file are part of the same package. Multiple files can specify the same package name.
If package name is specified, the file must be in a subdirectory called name (i.e., the directory name must match the package name).
We can access public classes in another (named) package using: package-name.class-name
Packages (Basics) | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPackages (Basics) | GeeksforGeeksWatch laterShareCopy link16/17InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 12:32•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=fhWCG4G1oHY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Related Article: Quiz on Packages in JavaReference: http://pages.cs.wisc.edu/~hasti/cs368/JavaTutorial/NOTES/Packages.htmlThis article is contributed by Nikhil Meherwal and Prateek Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nidhi_biet
rkbhola5
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
How to iterate any Map in Java
Stream In Java
Singleton Class in Java
Initialize an ArrayList in Java
Initializing a List in Java
Generics in Java
Java Programming Examples | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Mar, 2022"
},
{
"code": null,
"e": 170,
"s": 52,
"text": "Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces. Packages are used for:"
},
{
"code": null,
"e": 329,
"s": 170,
"text": "Preventing naming conflicts. For example there can be two classes with name Employee in two packages, college.staff.cse.Employee and college.staff.ee.Employee"
},
{
"code": null,
"e": 425,
"s": 329,
"text": "Making searching/locating and usage of classes, interfaces, enumerations and annotations easier"
},
{
"code": null,
"e": 694,
"s": 425,
"text": "Providing controlled access: protected and default have package level access control. A protected member is accessible by classes in the same package and its subclasses. A default member (without any access specifier) is accessible by classes in the same package only."
},
{
"code": null,
"e": 761,
"s": 694,
"text": "Packages can be considered as data encapsulation (or data-hiding)."
},
{
"code": null,
"e": 1155,
"s": 761,
"text": "All we need to do is put related classes into packages. After that, we can simply write an import class from existing packages and use it in our program. A package is a container of a group of related classes where some of the classes are accessible are exposed and others are kept for internal purpose.We can reuse existing classes from the packages as many time as we need it in our program."
},
{
"code": null,
"e": 1174,
"s": 1155,
"text": "How packages work?"
},
{
"code": null,
"e": 1834,
"s": 1174,
"text": "Package names and directory structure are closely related. For example if a package name is college.staff.cse, then there are three directories, college, staff and cse such that cse is present in staff and staff is present college. Also, the directory college is accessible through CLASSPATH variable, i.e., path of parent directory of college is present in CLASSPATH. The idea is to make sure that classes are easy to locate.Package naming conventions : Packages are named in reverse order of domain names, i.e., org.geeksforgeeks.practice. For example, in a college, the recommended convention is college.tech.cse, college.tech.ee, college.art.history, etc."
},
{
"code": null,
"e": 2126,
"s": 1834,
"text": "Adding a class to a Package : We can add more classes to a created package by using package name at the top of the program and saving it in the package directory. We need a new java file to define a public class, otherwise we can add the new class to an existing .java file and recompile it."
},
{
"code": null,
"e": 2135,
"s": 2126,
"text": "Chapters"
},
{
"code": null,
"e": 2162,
"s": 2135,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 2212,
"s": 2162,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 2235,
"s": 2212,
"text": "captions off, selected"
},
{
"code": null,
"e": 2243,
"s": 2235,
"text": "English"
},
{
"code": null,
"e": 2267,
"s": 2243,
"text": "This is a modal window."
},
{
"code": null,
"e": 2336,
"s": 2267,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 2358,
"s": 2336,
"text": "End of dialog window."
},
{
"code": null,
"e": 2660,
"s": 2358,
"text": "Subpackages: Packages that are inside another package are the subpackages. These are not imported by default, they have to imported explicitly. Also, members of a subpackage have no access privileges, i.e., they are considered as different package for protected and default access specifiers.Example :"
},
{
"code": null,
"e": 2681,
"s": 2660,
"text": "import java.util.*;\n"
},
{
"code": null,
"e": 2731,
"s": 2681,
"text": "util is a subpackage created inside java package."
},
{
"code": null,
"e": 2768,
"s": 2733,
"text": "Accessing classes inside a package"
},
{
"code": null,
"e": 2804,
"s": 2768,
"text": "Consider following two statements :"
},
{
"code": null,
"e": 2943,
"s": 2804,
"text": "// import the Vector class from util package.\nimport java.util.vector; \n\n// import all the classes from util package\nimport java.util.*; \n"
},
{
"code": null,
"e": 3040,
"s": 2943,
"text": "First Statement is used to import Vector class from util package which is contained inside java."
},
{
"code": null,
"e": 3100,
"s": 3040,
"text": "Second statement imports all the classes from util package."
},
{
"code": null,
"e": 3535,
"s": 3100,
"text": "// All the classes and interfaces of this package\n// will be accessible but not subpackages.\nimport package.*;\n\n// Only mentioned class of this package will be accessible.\nimport package.classname;\n\n// Class name is generally used when two packages have the same\n// class name. For example in below code both packages have\n// date class so using a fully qualified name to avoid conflict\nimport java.util.Date;\nimport my.package.Date;\n"
},
{
"code": "// Java program to demonstrate accessing of members when// corresponding classes are imported and not imported.import java.util.Vector; public class ImportDemo{ public ImportDemo() { // java.util.Vector is imported, hence we are // able to access directly in our code. Vector newVector = new Vector(); // java.util.ArrayList is not imported, hence // we were referring to it using the complete // package. java.util.ArrayList newList = new java.util.ArrayList(); } public static void main(String arg[]) { new ImportDemo(); }}",
"e": 4123,
"s": 3535,
"text": null
},
{
"code": null,
"e": 4143,
"s": 4123,
"text": " Types of packages:"
},
{
"code": null,
"e": 4897,
"s": 4143,
"text": "Built-in PackagesThese packages consist of a large number of classes which are a part of Java API.Some of the commonly used built-in packages are:1) java.lang: Contains language support classes(e.g classed which defines primitive data types, math operations). This package is automatically imported.2) java.io: Contains classed for supporting input / output operations.3) java.util: Contains utility classes which implement data structures like Linked List, Dictionary and support ; for Date / Time operations.4) java.applet: Contains classes for creating Applets.5) java.awt: Contain classes for implementing the components for graphical user interfaces (like button , ;menus etc).6) java.net: Contain classes for supporting networking operations."
},
{
"code": null,
"e": 5154,
"s": 4897,
"text": "User-defined packagesThese are the packages that are defined by the user. First we create a directory myPackage (name should be same as the name of the package). Then create the MyClass inside the directory with the first statement being the package names."
},
{
"code": null,
"e": 5381,
"s": 5154,
"text": "// Name of the package must be same as the directory\n// under which this file is saved\npackage myPackage;\n\npublic class MyClass\n{\n public void getNames(String s)\n { \n System.out.println(s); \n }\n}\n"
},
{
"code": null,
"e": 5430,
"s": 5381,
"text": "Now we can use the MyClass class in our program."
},
{
"code": null,
"e": 5849,
"s": 5430,
"text": "/* import 'MyClass' class from 'names' myPackage */\nimport myPackage.MyClass;\n\npublic class PrintName \n{\n public static void main(String args[]) \n { \n // Initializing the String variable \n // with a value \n String name = \"GeeksforGeeks\";\n \n // Creating an instance of class MyClass in \n // the package.\n MyClass obj = new MyClass();\n \n obj.getNames(name);\n }\n}\n"
},
{
"code": null,
"e": 5949,
"s": 5849,
"text": "Note : MyClass.java must be saved inside the myPackage directory since it is a part of the package."
},
{
"code": null,
"e": 5971,
"s": 5951,
"text": "Using Static Import"
},
{
"code": null,
"e": 6272,
"s": 5971,
"text": "Static import is a feature introduced in Java programming language ( versions 5 and above ) that allows members ( fields and methods ) defined in a class as public static to be used in Java code without specifying the class in which the field is defined.Following program demonstrates static import :"
},
{
"code": "// Note static keyword after import.import static java.lang.System.*; class StaticImportDemo{ public static void main(String args[]) { // We don't need to use 'System.out' // as imported using static. out.println(\"GeeksforGeeks\"); }}",
"e": 6542,
"s": 6272,
"text": null
},
{
"code": null,
"e": 6550,
"s": 6542,
"text": "Output:"
},
{
"code": null,
"e": 6565,
"s": 6550,
"text": " GeeksforGeeks"
},
{
"code": null,
"e": 6589,
"s": 6565,
"text": "Handling name conflicts"
},
{
"code": null,
"e": 6802,
"s": 6589,
"text": "The only time we need to pay attention to packages is when we have a name conflict . For example both, java.util and java.sql packages have a class named Date. So if we import both packages in program as follows:"
},
{
"code": null,
"e": 6967,
"s": 6802,
"text": "import java.util.*;\nimport java.sql.*;\n\n//And then use Date class, then we will get a compile-time error :\n\nDate today ; //ERROR-- java.util.Date or java.sql.Date?\n"
},
{
"code": null,
"e": 7105,
"s": 6967,
"text": "The compiler will not be able to figure out which Date class do we want. This problem can be solved by using a specific import statement:"
},
{
"code": null,
"e": 7148,
"s": 7105,
"text": "import java.util.Date;\nimport java.sql.*;\n"
},
{
"code": null,
"e": 7280,
"s": 7148,
"text": "If we need both Date classes then, we need to use a full package name every time we declare a new object of that class.For Example:"
},
{
"code": null,
"e": 7372,
"s": 7280,
"text": "java.util.Date deadLine = new java.util.Date();\njava.sql.Date today = new java.sql.Date();\n"
},
{
"code": null,
"e": 7392,
"s": 7372,
"text": "Directory structure"
},
{
"code": null,
"e": 7971,
"s": 7392,
"text": "The package name is closely associated with the directory structure used to store the classes. The classes (and other entities) belonging to a specific package are stored together in the same directory. Furthermore, they are stored in a sub-directory structure specified by its package name. For example, the class Circle of package com.zzz.project1.subproject2 is stored as “$BASE_DIR\\com\\zzz\\project1\\subproject2\\Circle.class”, where $BASE_DIR denotes the base directory of the package. Clearly, the “dot” in the package name corresponds to a sub-directory of the file system."
},
{
"code": null,
"e": 8366,
"s": 7971,
"text": "The base directory ($BASE_DIR) could be located anywhere in the file system. Hence, the Java compiler and runtime must be informed about the location of the $BASE_DIR so as to locate the classes. This is accomplished by an environment variable called CLASSPATH. CLASSPATH is similar to another environment variable PATH, which is used by the command shell to search for the executable programs."
},
{
"code": null,
"e": 8435,
"s": 8366,
"text": "Setting CLASSPATH:CLASSPATH can be set by any of the following ways:"
},
{
"code": null,
"e": 9104,
"s": 8435,
"text": "CLASSPATH can be set permanently in the environment: In Windows, choose control panel ? System ? Advanced ? Environment Variables ? choose “System Variables” (for all the users) or “User Variables” (only the currently login user) ? choose “Edit” (if CLASSPATH already exists) or “New” ? Enter “CLASSPATH” as the variable name ? Enter the required directories and JAR files (separated by semicolons) as the value (e.g., “.;c:\\javaproject\\classes;d:\\tomcat\\lib\\servlet-api.jar”). Take note that you need to include the current working directory (denoted by ‘.’) in the CLASSPATH.To check the current setting of the CLASSPATH, issue the following command:> SET CLASSPATH\n"
},
{
"code": null,
"e": 9121,
"s": 9104,
"text": "> SET CLASSPATH\n"
},
{
"code": null,
"e": 9297,
"s": 9121,
"text": "CLASSPATH can be set temporarily for that particular CMD shell session by issuing the following command:> SET CLASSPATH=.;c:\\javaproject\\classes;d:\\tomcat\\lib\\servlet-api.jar\n"
},
{
"code": null,
"e": 9369,
"s": 9297,
"text": "> SET CLASSPATH=.;c:\\javaproject\\classes;d:\\tomcat\\lib\\servlet-api.jar\n"
},
{
"code": null,
"e": 9605,
"s": 9369,
"text": "Instead of using the CLASSPATH environment variable, you can also use the command-line option -classpath or -cp of the javac and java commands, for example,> java –classpath c:\\javaproject\\classes com.abc.project1.subproject2.MyClass3\n"
},
{
"code": null,
"e": 9685,
"s": 9605,
"text": "> java –classpath c:\\javaproject\\classes com.abc.project1.subproject2.MyClass3\n"
},
{
"code": null,
"e": 9776,
"s": 9685,
"text": "Illustration of user-defined packages:Creating our first package:File name – ClassOne.java"
},
{
"code": "package package_name; public class ClassOne { public void methodClassOne() { System.out.println(\"Hello there its ClassOne\"); }}",
"e": 9918,
"s": 9776,
"text": null
},
{
"code": null,
"e": 9972,
"s": 9918,
"text": "Creating our second package:File name – ClassTwo.java"
},
{
"code": "package package_one; public class ClassTwo { public void methodClassTwo(){ System.out.println(\"Hello there i am ClassTwo\"); } }",
"e": 10117,
"s": 9972,
"text": null
},
{
"code": null,
"e": 10182,
"s": 10117,
"text": "Making use of both the created packages:File name – Testing.java"
},
{
"code": "import package_one.ClassTwo;import package_name.ClassOne; public class Testing { public static void main(String[] args){ ClassTwo a = new ClassTwo(); ClassOne b = new ClassOne(); a.methodClassTwo(); b.methodClassOne(); }}",
"e": 10439,
"s": 10182,
"text": null
},
{
"code": null,
"e": 10447,
"s": 10439,
"text": "Output:"
},
{
"code": null,
"e": 10499,
"s": 10447,
"text": "Hello there i am ClassTwo\nHello there its ClassOne\n"
},
{
"code": null,
"e": 10593,
"s": 10499,
"text": "Now having a look at the directory structure of both the packages and the testing class file:"
},
{
"code": null,
"e": 10611,
"s": 10593,
"text": "Important points:"
},
{
"code": null,
"e": 11107,
"s": 10611,
"text": "Every class is part of some package.If no package is specified, the classes in the file goes into a special unnamed package (the same unnamed package for all files).All classes/interfaces in a file are part of the same package. Multiple files can specify the same package name.If package name is specified, the file must be in a subdirectory called name (i.e., the directory name must match the package name).We can access public classes in another (named) package using: package-name.class-name"
},
{
"code": null,
"e": 11144,
"s": 11107,
"text": "Every class is part of some package."
},
{
"code": null,
"e": 11274,
"s": 11144,
"text": "If no package is specified, the classes in the file goes into a special unnamed package (the same unnamed package for all files)."
},
{
"code": null,
"e": 11387,
"s": 11274,
"text": "All classes/interfaces in a file are part of the same package. Multiple files can specify the same package name."
},
{
"code": null,
"e": 11520,
"s": 11387,
"text": "If package name is specified, the file must be in a subdirectory called name (i.e., the directory name must match the package name)."
},
{
"code": null,
"e": 11607,
"s": 11520,
"text": "We can access public classes in another (named) package using: package-name.class-name"
},
{
"code": null,
"e": 12905,
"s": 11607,
"text": "Packages (Basics) | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPackages (Basics) | GeeksforGeeksWatch laterShareCopy link16/17InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 12:32•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=fhWCG4G1oHY\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Related Article: Quiz on Packages in JavaReference: http://pages.cs.wisc.edu/~hasti/cs368/JavaTutorial/NOTES/Packages.htmlThis article is contributed by Nikhil Meherwal and Prateek Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 13030,
"s": 12905,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 13041,
"s": 13030,
"text": "nidhi_biet"
},
{
"code": null,
"e": 13050,
"s": 13041,
"text": "rkbhola5"
},
{
"code": null,
"e": 13055,
"s": 13050,
"text": "Java"
},
{
"code": null,
"e": 13060,
"s": 13055,
"text": "Java"
},
{
"code": null,
"e": 13158,
"s": 13060,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13202,
"s": 13158,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 13238,
"s": 13202,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 13263,
"s": 13238,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 13294,
"s": 13263,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 13309,
"s": 13294,
"text": "Stream In Java"
},
{
"code": null,
"e": 13333,
"s": 13309,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 13365,
"s": 13333,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 13393,
"s": 13365,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 13410,
"s": 13393,
"text": "Generics in Java"
}
] |
How Does Threading Work in Android? | 23 Jul, 2021
When an application is launched in Android, it creates the primary thread of execution, referred to as the “main” thread. Most thread is liable for dispatching events to the acceptable interface widgets also as communicating with components from the Android UI toolkit. To keep your application responsive, it’s essential to avoid using the most thread to perform any operation which will find yourself keeping it blocked.
Network operations and database calls, also as loading of certain components, are common samples of operations that one should avoid within the main thread. Once they are called within the main thread, they’re called synchronously, which suggests that the UI will remain completely unresponsive until the operation completes. Due to this, tasks requiring calls are usually performed in different threads, which in turn avoids blocking the UI and keeps it responsive while the tasks are being performed. (i.e., they’ve performed asynchronously from the UI).
Android provides some ways of making and managing threads, and lots of third-party libraries exist that make thread management tons more pleasant. However, with numerous approaches at hand, choosing the proper one are often quite confusing. In this article, you’ll study some common scenarios in Android development where threading becomes essential and a few simple solutions which will be applied to those scenarios and more.
In Android, you’ll categorize all threading components into two basic categories:
Threads that are attached to an activity/fragment: These threads are tied to the lifecycle of the activity/fragment and are terminated as soon because the activity/fragment is destroyed.Threads that aren’t attached to any activity/fragment: These threads can still run beyond the lifetime of the activity/fragment (if any) from which they were spawned.
Threads that are attached to an activity/fragment: These threads are tied to the lifecycle of the activity/fragment and are terminated as soon because the activity/fragment is destroyed.
Threads that aren’t attached to any activity/fragment: These threads can still run beyond the lifetime of the activity/fragment (if any) from which they were spawned.
1. ASYNCTASK
AsyncTask is the most elementary Android component for threading. It’s super easy and simple to use it’s also good for some basic scenarios
Java
public class GeeksActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Adding Task to the List (Async) new MyTask().execute(url); } private class MyTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { String url = params[0]; return doSomeWork(url); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); // do something with the result } }}
AsyncTask, however, falls short if you would like your deferred task to run beyond the lifetime of the activity/fragment. The fact that even the slightest of screen rotation can cause the activity to be destroyed is simply awful! So We Come to:
2. LOADERS
Loaders are the answer to the awful nightmare mentioned above. Loaders are great at performing in that context and they automatically stop when the activity is destroyed, even more, the sweet fact is that they also restart themselves after the activity is recreated.
Java
public class GeeksActivity extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Getting instance of loader manager getLoaderManager().initLoader(1, null, new MyLoaderCallbacks()); } private class MyGeekyLoaderCallbacks implements LoaderManager.LoaderCallbacks { // Overriding the method @Override public Loader onCreateLoader(int id, Bundle args) { return new MyLoader(GeeksforGeeks.this); } @Override public void onLoadFinished(Loader loader, Object data) { } @Override public void onLoaderReset(Loader loader) { } } private class MyLoader extends AsyncTaskLoader { public MyLoader(Context context) { super(context); } @Override public Object loadInBackground() { return someWorkToDo(); } }}
1. SERVICE
Service could be thought of as a component that’s useful for performing long (or potentially long) operations with no UI. Yes, you heard that right! Service’s don’t have any UI of theirs! Service runs within the main thread of its hosting process; the service doesn’t create its own thread and doesn’t run during a separate process unless you specify otherwise.
Java
public class ExampleServiceGeeks extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId) { doSomeLongProccesingWork(); stopSelf(); // Self stopping the service // by calling stopSelf(); return START_NOT_STICKY; } @Nullable @Override // Binding the service to the Method calls public IBinder onBind(Intent intent) { return null; }}
Look at the code snippet below:
Java
Kotlin
public class GeeksforGeeks extends Activity { // ... public class MyAsyncTask extends AsyncTask<Void, Void, String> { @Override protected void onPostExecute(String result) {...} @Override protected String doInBackground(Void... params) {...} }}
class GeeksforGeeks : Activity() { // ... inner class MyAsyncTask : AsyncTask<Unit, Unit, String>() { override fun onPostExecute(result: String) {...} override fun doInBackground(vararg params: Unit): String {...} }}
What seems wrong?
The mistake which happened during this snippet is that the code declares the threading object MyAsyncTask as a non-static inner class of some activity (or an inner class in Kotlin). This declaration creates implicit regard to the enclosing Activity instance. As a result, the thing contains regard to the activity until the threaded work completes, causing a delay within the destruction of the referenced activity. Hence, we get a delay, which in turn harms the system and puts a heavy burden on the memory. A direct solution to the present problem would be to define your overloaded class instances either as static classes or in their own files, thus removing the implicit reference.
Another solution would be to always cancel and pack up background tasks within the appropriate Activity lifecycle callback, like onDestroy. This approach is often tedious and error-prone, however. As a general rule, you ought to not put complex, non-UI logic directly in activities. Additionally, AsyncTask is now deprecated, and it’s not recommended to be used in new code, however.
As described in Processes and therefore the Application Lifecycle, the priority that your app’s threads receive depends partly on where the app is within the app lifecycle. As you create and manage threads in your application, it’s important to line their priority in order that the proper threads get the proper priorities at the proper times.
If the priority is set too high, then that thread might disrupt the UI Thread and even block it in some adverse cases and even the Render Thread, causing the app performance issues like dropped frames, lag, sluggish app UI, etc.
Every time you create a thread, you ought to call setThreadPriority(). The system’s thread scheduler gives preference to threads with high priorities, balancing those priorities with the necessity to eventually get all the work done. Generally, threads within the foreground group get around 95% of the entire execution time from the device, while the background group gets roughly 5%.
So, if you’re getting to rage on by doing long-running work on the pixels, this might be a far better solution for you. When your app creates a thread using HandlerThread don’t forget to line the thread’s priority supported by the sort of labor it’s doing. Remember, CPUs can only handle a little number of threads in parallel. Setting the priority helps the system know the proper ways to schedule this work when all other threads are fighting for attention.
Message Queue Explaining the Thread Process
A detailed discussion about “Service Binding and Threads” could be found here for reference.
martialcoder
Picked
Android
Java
Kotlin
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android RecyclerView in Kotlin
Android SDK and it's Components
Navigation Drawer in Android
How to Communicate Between Fragments in Android?
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Jul, 2021"
},
{
"code": null,
"e": 451,
"s": 28,
"text": "When an application is launched in Android, it creates the primary thread of execution, referred to as the “main” thread. Most thread is liable for dispatching events to the acceptable interface widgets also as communicating with components from the Android UI toolkit. To keep your application responsive, it’s essential to avoid using the most thread to perform any operation which will find yourself keeping it blocked."
},
{
"code": null,
"e": 1008,
"s": 451,
"text": "Network operations and database calls, also as loading of certain components, are common samples of operations that one should avoid within the main thread. Once they are called within the main thread, they’re called synchronously, which suggests that the UI will remain completely unresponsive until the operation completes. Due to this, tasks requiring calls are usually performed in different threads, which in turn avoids blocking the UI and keeps it responsive while the tasks are being performed. (i.e., they’ve performed asynchronously from the UI)."
},
{
"code": null,
"e": 1436,
"s": 1008,
"text": "Android provides some ways of making and managing threads, and lots of third-party libraries exist that make thread management tons more pleasant. However, with numerous approaches at hand, choosing the proper one are often quite confusing. In this article, you’ll study some common scenarios in Android development where threading becomes essential and a few simple solutions which will be applied to those scenarios and more."
},
{
"code": null,
"e": 1518,
"s": 1436,
"text": "In Android, you’ll categorize all threading components into two basic categories:"
},
{
"code": null,
"e": 1871,
"s": 1518,
"text": "Threads that are attached to an activity/fragment: These threads are tied to the lifecycle of the activity/fragment and are terminated as soon because the activity/fragment is destroyed.Threads that aren’t attached to any activity/fragment: These threads can still run beyond the lifetime of the activity/fragment (if any) from which they were spawned."
},
{
"code": null,
"e": 2058,
"s": 1871,
"text": "Threads that are attached to an activity/fragment: These threads are tied to the lifecycle of the activity/fragment and are terminated as soon because the activity/fragment is destroyed."
},
{
"code": null,
"e": 2225,
"s": 2058,
"text": "Threads that aren’t attached to any activity/fragment: These threads can still run beyond the lifetime of the activity/fragment (if any) from which they were spawned."
},
{
"code": null,
"e": 2238,
"s": 2225,
"text": "1. ASYNCTASK"
},
{
"code": null,
"e": 2379,
"s": 2238,
"text": "AsyncTask is the most elementary Android component for threading. It’s super easy and simple to use it’s also good for some basic scenarios "
},
{
"code": null,
"e": 2384,
"s": 2379,
"text": "Java"
},
{
"code": "public class GeeksActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Adding Task to the List (Async) new MyTask().execute(url); } private class MyTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { String url = params[0]; return doSomeWork(url); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); // do something with the result } }}",
"e": 3040,
"s": 2384,
"text": null
},
{
"code": null,
"e": 3285,
"s": 3040,
"text": "AsyncTask, however, falls short if you would like your deferred task to run beyond the lifetime of the activity/fragment. The fact that even the slightest of screen rotation can cause the activity to be destroyed is simply awful! So We Come to:"
},
{
"code": null,
"e": 3297,
"s": 3285,
"text": "2. LOADERS "
},
{
"code": null,
"e": 3565,
"s": 3297,
"text": "Loaders are the answer to the awful nightmare mentioned above. Loaders are great at performing in that context and they automatically stop when the activity is destroyed, even more, the sweet fact is that they also restart themselves after the activity is recreated. "
},
{
"code": null,
"e": 3570,
"s": 3565,
"text": "Java"
},
{
"code": "public class GeeksActivity extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Getting instance of loader manager getLoaderManager().initLoader(1, null, new MyLoaderCallbacks()); } private class MyGeekyLoaderCallbacks implements LoaderManager.LoaderCallbacks { // Overriding the method @Override public Loader onCreateLoader(int id, Bundle args) { return new MyLoader(GeeksforGeeks.this); } @Override public void onLoadFinished(Loader loader, Object data) { } @Override public void onLoaderReset(Loader loader) { } } private class MyLoader extends AsyncTaskLoader { public MyLoader(Context context) { super(context); } @Override public Object loadInBackground() { return someWorkToDo(); } }}",
"e": 4532,
"s": 3570,
"text": null
},
{
"code": null,
"e": 4543,
"s": 4532,
"text": "1. SERVICE"
},
{
"code": null,
"e": 4906,
"s": 4543,
"text": "Service could be thought of as a component that’s useful for performing long (or potentially long) operations with no UI. Yes, you heard that right! Service’s don’t have any UI of theirs! Service runs within the main thread of its hosting process; the service doesn’t create its own thread and doesn’t run during a separate process unless you specify otherwise. "
},
{
"code": null,
"e": 4911,
"s": 4906,
"text": "Java"
},
{
"code": "public class ExampleServiceGeeks extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId) { doSomeLongProccesingWork(); stopSelf(); // Self stopping the service // by calling stopSelf(); return START_NOT_STICKY; } @Nullable @Override // Binding the service to the Method calls public IBinder onBind(Intent intent) { return null; }}",
"e": 5349,
"s": 4911,
"text": null
},
{
"code": null,
"e": 5381,
"s": 5349,
"text": "Look at the code snippet below:"
},
{
"code": null,
"e": 5386,
"s": 5381,
"text": "Java"
},
{
"code": null,
"e": 5393,
"s": 5386,
"text": "Kotlin"
},
{
"code": "public class GeeksforGeeks extends Activity { // ... public class MyAsyncTask extends AsyncTask<Void, Void, String> { @Override protected void onPostExecute(String result) {...} @Override protected String doInBackground(Void... params) {...} }}",
"e": 5651,
"s": 5393,
"text": null
},
{
"code": "class GeeksforGeeks : Activity() { // ... inner class MyAsyncTask : AsyncTask<Unit, Unit, String>() { override fun onPostExecute(result: String) {...} override fun doInBackground(vararg params: Unit): String {...} }}",
"e": 5893,
"s": 5651,
"text": null
},
{
"code": null,
"e": 5912,
"s": 5893,
"text": "What seems wrong? "
},
{
"code": null,
"e": 6600,
"s": 5912,
"text": "The mistake which happened during this snippet is that the code declares the threading object MyAsyncTask as a non-static inner class of some activity (or an inner class in Kotlin). This declaration creates implicit regard to the enclosing Activity instance. As a result, the thing contains regard to the activity until the threaded work completes, causing a delay within the destruction of the referenced activity. Hence, we get a delay, which in turn harms the system and puts a heavy burden on the memory. A direct solution to the present problem would be to define your overloaded class instances either as static classes or in their own files, thus removing the implicit reference. "
},
{
"code": null,
"e": 6984,
"s": 6600,
"text": "Another solution would be to always cancel and pack up background tasks within the appropriate Activity lifecycle callback, like onDestroy. This approach is often tedious and error-prone, however. As a general rule, you ought to not put complex, non-UI logic directly in activities. Additionally, AsyncTask is now deprecated, and it’s not recommended to be used in new code, however."
},
{
"code": null,
"e": 7330,
"s": 6984,
"text": "As described in Processes and therefore the Application Lifecycle, the priority that your app’s threads receive depends partly on where the app is within the app lifecycle. As you create and manage threads in your application, it’s important to line their priority in order that the proper threads get the proper priorities at the proper times. "
},
{
"code": null,
"e": 7561,
"s": 7330,
"text": "If the priority is set too high, then that thread might disrupt the UI Thread and even block it in some adverse cases and even the Render Thread, causing the app performance issues like dropped frames, lag, sluggish app UI, etc. "
},
{
"code": null,
"e": 7947,
"s": 7561,
"text": "Every time you create a thread, you ought to call setThreadPriority(). The system’s thread scheduler gives preference to threads with high priorities, balancing those priorities with the necessity to eventually get all the work done. Generally, threads within the foreground group get around 95% of the entire execution time from the device, while the background group gets roughly 5%."
},
{
"code": null,
"e": 8408,
"s": 7947,
"text": "So, if you’re getting to rage on by doing long-running work on the pixels, this might be a far better solution for you. When your app creates a thread using HandlerThread don’t forget to line the thread’s priority supported by the sort of labor it’s doing. Remember, CPUs can only handle a little number of threads in parallel. Setting the priority helps the system know the proper ways to schedule this work when all other threads are fighting for attention. "
},
{
"code": null,
"e": 8452,
"s": 8408,
"text": "Message Queue Explaining the Thread Process"
},
{
"code": null,
"e": 8545,
"s": 8452,
"text": "A detailed discussion about “Service Binding and Threads” could be found here for reference."
},
{
"code": null,
"e": 8558,
"s": 8545,
"text": "martialcoder"
},
{
"code": null,
"e": 8565,
"s": 8558,
"text": "Picked"
},
{
"code": null,
"e": 8573,
"s": 8565,
"text": "Android"
},
{
"code": null,
"e": 8578,
"s": 8573,
"text": "Java"
},
{
"code": null,
"e": 8585,
"s": 8578,
"text": "Kotlin"
},
{
"code": null,
"e": 8590,
"s": 8585,
"text": "Java"
},
{
"code": null,
"e": 8598,
"s": 8590,
"text": "Android"
},
{
"code": null,
"e": 8696,
"s": 8598,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8765,
"s": 8696,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 8796,
"s": 8765,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 8828,
"s": 8796,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 8857,
"s": 8828,
"text": "Navigation Drawer in Android"
},
{
"code": null,
"e": 8906,
"s": 8857,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 8921,
"s": 8906,
"text": "Arrays in Java"
},
{
"code": null,
"e": 8965,
"s": 8921,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 9001,
"s": 8965,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 9026,
"s": 9001,
"text": "Reverse a string in Java"
}
] |
HTML | <table> summary Attribute | 29 May, 2019
The HTML <table> summary Attribute is used to specify the summary of the table content.
Syntax:
<table summary="text">
Attribute Values:
text: It holds the summary of the table content.
Note: The <table> summary Attribute is not supported by HTML 5.
Example:
<!DOCTYPE html><html> <head> <title> HTML table summary Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML table summary Attribute</h2> <table border="1" summary="It describes the author details."> <tr> <th>NAME</th> <th>AGE</th> <th>BRANCH</th> </tr> <tr> <td>BITTU</td> <td>22</td> <td>CSE</td> </tr> </table></body> </html>
Output:
Supported Browsers: The browser supported by HTML <table> summary Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
How to Insert Form Data into Database using PHP ?
HTTP headers | Content-Type
How to position a div at the bottom of its container using CSS?
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 May, 2019"
},
{
"code": null,
"e": 116,
"s": 28,
"text": "The HTML <table> summary Attribute is used to specify the summary of the table content."
},
{
"code": null,
"e": 124,
"s": 116,
"text": "Syntax:"
},
{
"code": null,
"e": 147,
"s": 124,
"text": "<table summary=\"text\">"
},
{
"code": null,
"e": 165,
"s": 147,
"text": "Attribute Values:"
},
{
"code": null,
"e": 214,
"s": 165,
"text": "text: It holds the summary of the table content."
},
{
"code": null,
"e": 278,
"s": 214,
"text": "Note: The <table> summary Attribute is not supported by HTML 5."
},
{
"code": null,
"e": 287,
"s": 278,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML table summary Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML table summary Attribute</h2> <table border=\"1\" summary=\"It describes the author details.\"> <tr> <th>NAME</th> <th>AGE</th> <th>BRANCH</th> </tr> <tr> <td>BITTU</td> <td>22</td> <td>CSE</td> </tr> </table></body> </html>",
"e": 765,
"s": 287,
"text": null
},
{
"code": null,
"e": 773,
"s": 765,
"text": "Output:"
},
{
"code": null,
"e": 867,
"s": 773,
"text": "Supported Browsers: The browser supported by HTML <table> summary Attribute are listed below:"
},
{
"code": null,
"e": 881,
"s": 867,
"text": "Google Chrome"
},
{
"code": null,
"e": 899,
"s": 881,
"text": "Internet Explorer"
},
{
"code": null,
"e": 907,
"s": 899,
"text": "Firefox"
},
{
"code": null,
"e": 914,
"s": 907,
"text": "Safari"
},
{
"code": null,
"e": 920,
"s": 914,
"text": "Opera"
},
{
"code": null,
"e": 936,
"s": 920,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 941,
"s": 936,
"text": "HTML"
},
{
"code": null,
"e": 958,
"s": 941,
"text": "Web Technologies"
},
{
"code": null,
"e": 963,
"s": 958,
"text": "HTML"
},
{
"code": null,
"e": 1061,
"s": 963,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1085,
"s": 1061,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1124,
"s": 1085,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 1174,
"s": 1124,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 1202,
"s": 1174,
"text": "HTTP headers | Content-Type"
},
{
"code": null,
"e": 1266,
"s": 1202,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 1299,
"s": 1266,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1360,
"s": 1299,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1403,
"s": 1360,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 1475,
"s": 1403,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Positional-only Parameter in Python3.8 | 03 Jul, 2020
Python introduces the new function syntax in Python3.8.2 Version, Where we can introduce the / forward slash to compare the positional only parameter which comes before the / slash and parameters that comes after * is keyword only arguments. Rest of the arguments that are come between / and * can be either positional or keyword type of argument.That means we can combine positional arguments and regular arguments in such a way all the non-positional argument comes after / slash.
Syntax:
def function(a, b, /, c, d, *, e, f):
# Function Body
pass
Where a and b are positional argument, c and d can be either positional or keyword or e and f are strictly keyword type argument.
In the image given below, we can see that power function is a builtin function in Python’s math library and this function uses / slash to enable the positional only argument and now we can implement the same functionality with the help of this version.
Example #1 :In this example we can see that by using positional only argument we can implement the function with the fixed position as we can say only in built-in functions before this python version. With the help of this, we are able to make our program more robust.
# Positional-Only argument def function(a, b, /, c, d, *, e, f): print (a, b, c, d, e, f) function(1, 2, 3, d = 4, e = 5, f = 6) # It works finefunction(1, 2, 3, d = 4, 5, f = 6) # Error occurred
Output :
Example #2 :
# Positional-Only argument def function(a, b, /, **kwargs): print (a, b, kwargs) function(1, 2, a = 4, b = 5, c = 6) # It works finefunction(a = 1, 2, a = 4, b = 5, c = 6) # Error occurred
Output :
python-basics
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jul, 2020"
},
{
"code": null,
"e": 511,
"s": 28,
"text": "Python introduces the new function syntax in Python3.8.2 Version, Where we can introduce the / forward slash to compare the positional only parameter which comes before the / slash and parameters that comes after * is keyword only arguments. Rest of the arguments that are come between / and * can be either positional or keyword type of argument.That means we can combine positional arguments and regular arguments in such a way all the non-positional argument comes after / slash."
},
{
"code": null,
"e": 519,
"s": 511,
"text": "Syntax:"
},
{
"code": null,
"e": 590,
"s": 519,
"text": "def function(a, b, /, c, d, *, e, f):\n # Function Body\n pass \n"
},
{
"code": null,
"e": 720,
"s": 590,
"text": "Where a and b are positional argument, c and d can be either positional or keyword or e and f are strictly keyword type argument."
},
{
"code": null,
"e": 973,
"s": 720,
"text": "In the image given below, we can see that power function is a builtin function in Python’s math library and this function uses / slash to enable the positional only argument and now we can implement the same functionality with the help of this version."
},
{
"code": null,
"e": 1242,
"s": 973,
"text": "Example #1 :In this example we can see that by using positional only argument we can implement the function with the fixed position as we can say only in built-in functions before this python version. With the help of this, we are able to make our program more robust."
},
{
"code": "# Positional-Only argument def function(a, b, /, c, d, *, e, f): print (a, b, c, d, e, f) function(1, 2, 3, d = 4, e = 5, f = 6) # It works finefunction(1, 2, 3, d = 4, 5, f = 6) # Error occurred",
"e": 1442,
"s": 1242,
"text": null
},
{
"code": null,
"e": 1451,
"s": 1442,
"text": "Output :"
},
{
"code": null,
"e": 1464,
"s": 1451,
"text": "Example #2 :"
},
{
"code": "# Positional-Only argument def function(a, b, /, **kwargs): print (a, b, kwargs) function(1, 2, a = 4, b = 5, c = 6) # It works finefunction(a = 1, 2, a = 4, b = 5, c = 6) # Error occurred",
"e": 1657,
"s": 1464,
"text": null
},
{
"code": null,
"e": 1666,
"s": 1657,
"text": "Output :"
},
{
"code": null,
"e": 1680,
"s": 1666,
"text": "python-basics"
},
{
"code": null,
"e": 1697,
"s": 1680,
"text": "Python-Functions"
},
{
"code": null,
"e": 1704,
"s": 1697,
"text": "Python"
}
] |
Boolean Masking with Pandas. Filtering Pandas Dataframes | by Leah Pope | Towards Data Science | One of the topics in Miki Tebeka’s excellent “Faster Pandas” course was how to use Boolean masks to filter data in Pandas. I wanted to practice what I had learned, so I updated a recent project to use Boolean masks. I think this is a very useful technique, so I wanted to share how I updated my code. I’ll show you how to use Boolean masks in some Before and After code snippets taken directly from my project.
Before we dive into the snippets, I’ll provide some context. I wanted to analyse reviews of a popular cooking app. I downloaded the reviews and focused on the ones posted in 2019 and 2020. Why this time range? I wanted to see if there might be a difference in the app reviews before and during COVID. My household increased our home cooking during 2020 and I was curious if the cooking app reviews might show an increase in app usage and/or user enjoyment.
Now, let’s learn how to use Boolean masks by checking out some Before and After code snippets.
The following code filters the dataset to only use the rows where the year is 2019 or 2020.
Before:
#reviewTimestamp is a datetime objectreviews_df = all_reviews_df[(all_reviews_df[‘reviewTimestamp’].dt.year == 2019) | (all_reviews_df[‘reviewTimestamp’].dt.year == 2020)]
After:
pre_mask = all_reviews_df[‘reviewTimestamp’].dt.year == 2019during_mask = all_reviews_df[‘reviewTimestamp’].dt.year == 2020reviews_df = all_reviews_df[pre_mask | during_mask]
Here’s another example below. This code filters the dataset to find the “high” and “low” reviews for 2019 and 2020.
Before:
top_reviews_2019 = reviews_df[(reviews_df[‘reviewTimestamp’].dt.year == 2019) & (reviews_df[‘score’] == 5)][‘content’].to_list()low_reviews_20191 = reviews_df[(reviews_df[‘reviewTimestamp’].dt.year == 2019) & (reviews_df[‘score’] < 3)][‘content’].to_list()top_reviews_2020 = reviews_df[(reviews_df[‘reviewTimestamp’].dt.year == 2020) & (reviews_df[‘score’] == 5)][‘content’].to_list()low_reviews_2020 = reviews_df[(reviews_df[‘reviewTimestamp’].dt.year == 2020) & (reviews_df[‘score’] < 3)][‘content’].to_list()
After:
pre_mask = reviews_df[‘reviewTimestamp’].dt.year == 2019during_mask = reviews_df[‘reviewTimestamp’].dt.year == 2020high_mask = reviews_df[‘score’] == 5low_mask = reviews_df[‘score’] < 3high_reviews_2019 = reviews_df[pre_mask & high_mask][‘content’].to_list()low_reviews_2019 = reviews_df[pre_mask & low_mask][‘content’].to_list()high_reviews_2020 = reviews_df[during_mask & high_mask][‘content’].to_list()low_reviews_2020 = reviews_df[during_mask & low_mask][‘content’].to_list()
Why did I find it useful to make these changes? The first reason is that it makes the code easier to read and to make changes. For example, I might update the analysis with a pre-COVID timeframe of 2018 and 2019 and the during-COVID timeframe of 2020 and 2021. I would just need to update the criteria in the Boolean mask definition instead of going through the code and replacing the criteria in every place I filtered the dataset.
The second reason is that I’d been told that using Boolean masks improves performance. I did performance testing on my code using the %timeit magic command (in cell mode) in the IPython interactive command shell. My performance check revealed that code using a Boolean mask was faster than the code that used regular conditional filtering. On my computer, the code was 7 times faster.
Now you’ve seen some examples of how to use Boolean masks and are aware of the reasons why you should consider using them in your code. Please feel free to reach out with suggestions and to let me know if this content has helped you. | [
{
"code": null,
"e": 583,
"s": 172,
"text": "One of the topics in Miki Tebeka’s excellent “Faster Pandas” course was how to use Boolean masks to filter data in Pandas. I wanted to practice what I had learned, so I updated a recent project to use Boolean masks. I think this is a very useful technique, so I wanted to share how I updated my code. I’ll show you how to use Boolean masks in some Before and After code snippets taken directly from my project."
},
{
"code": null,
"e": 1040,
"s": 583,
"text": "Before we dive into the snippets, I’ll provide some context. I wanted to analyse reviews of a popular cooking app. I downloaded the reviews and focused on the ones posted in 2019 and 2020. Why this time range? I wanted to see if there might be a difference in the app reviews before and during COVID. My household increased our home cooking during 2020 and I was curious if the cooking app reviews might show an increase in app usage and/or user enjoyment."
},
{
"code": null,
"e": 1135,
"s": 1040,
"text": "Now, let’s learn how to use Boolean masks by checking out some Before and After code snippets."
},
{
"code": null,
"e": 1227,
"s": 1135,
"text": "The following code filters the dataset to only use the rows where the year is 2019 or 2020."
},
{
"code": null,
"e": 1235,
"s": 1227,
"text": "Before:"
},
{
"code": null,
"e": 1407,
"s": 1235,
"text": "#reviewTimestamp is a datetime objectreviews_df = all_reviews_df[(all_reviews_df[‘reviewTimestamp’].dt.year == 2019) | (all_reviews_df[‘reviewTimestamp’].dt.year == 2020)]"
},
{
"code": null,
"e": 1414,
"s": 1407,
"text": "After:"
},
{
"code": null,
"e": 1589,
"s": 1414,
"text": "pre_mask = all_reviews_df[‘reviewTimestamp’].dt.year == 2019during_mask = all_reviews_df[‘reviewTimestamp’].dt.year == 2020reviews_df = all_reviews_df[pre_mask | during_mask]"
},
{
"code": null,
"e": 1705,
"s": 1589,
"text": "Here’s another example below. This code filters the dataset to find the “high” and “low” reviews for 2019 and 2020."
},
{
"code": null,
"e": 1713,
"s": 1705,
"text": "Before:"
},
{
"code": null,
"e": 2225,
"s": 1713,
"text": "top_reviews_2019 = reviews_df[(reviews_df[‘reviewTimestamp’].dt.year == 2019) & (reviews_df[‘score’] == 5)][‘content’].to_list()low_reviews_20191 = reviews_df[(reviews_df[‘reviewTimestamp’].dt.year == 2019) & (reviews_df[‘score’] < 3)][‘content’].to_list()top_reviews_2020 = reviews_df[(reviews_df[‘reviewTimestamp’].dt.year == 2020) & (reviews_df[‘score’] == 5)][‘content’].to_list()low_reviews_2020 = reviews_df[(reviews_df[‘reviewTimestamp’].dt.year == 2020) & (reviews_df[‘score’] < 3)][‘content’].to_list()"
},
{
"code": null,
"e": 2232,
"s": 2225,
"text": "After:"
},
{
"code": null,
"e": 2712,
"s": 2232,
"text": "pre_mask = reviews_df[‘reviewTimestamp’].dt.year == 2019during_mask = reviews_df[‘reviewTimestamp’].dt.year == 2020high_mask = reviews_df[‘score’] == 5low_mask = reviews_df[‘score’] < 3high_reviews_2019 = reviews_df[pre_mask & high_mask][‘content’].to_list()low_reviews_2019 = reviews_df[pre_mask & low_mask][‘content’].to_list()high_reviews_2020 = reviews_df[during_mask & high_mask][‘content’].to_list()low_reviews_2020 = reviews_df[during_mask & low_mask][‘content’].to_list()"
},
{
"code": null,
"e": 3145,
"s": 2712,
"text": "Why did I find it useful to make these changes? The first reason is that it makes the code easier to read and to make changes. For example, I might update the analysis with a pre-COVID timeframe of 2018 and 2019 and the during-COVID timeframe of 2020 and 2021. I would just need to update the criteria in the Boolean mask definition instead of going through the code and replacing the criteria in every place I filtered the dataset."
},
{
"code": null,
"e": 3530,
"s": 3145,
"text": "The second reason is that I’d been told that using Boolean masks improves performance. I did performance testing on my code using the %timeit magic command (in cell mode) in the IPython interactive command shell. My performance check revealed that code using a Boolean mask was faster than the code that used regular conditional filtering. On my computer, the code was 7 times faster."
}
] |
TypeScript - Array unshift() | unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
array.unshift( element1, ..., elementN );
element1, ..., elementN − The elements to add to the front of the array.
Returns the length of the new array. It returns undefined in IE browser.
var arr = new Array("orange", "mango", "banana", "sugar");
var length = arr.unshift("water");
console.log("Returned array is : " + arr );
console.log("Length of the array is : " + length );
On compiling, it will generate the same code in JavaScript.
Its output is as follows −
Returned array is : water,orange,mango,banana,sugar
Length of the array is : 5
45 Lectures
4 hours
Antonio Papa
41 Lectures
7 hours
Haider Malik
60 Lectures
2.5 hours
Skillbakerystudios
77 Lectures
8 hours
Sean Bradley
77 Lectures
3.5 hours
TELCOMA Global
19 Lectures
3 hours
Christopher Frewin
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2161,
"s": 2048,
"text": "unshift() method adds one or more elements to the beginning of an array and returns the new length of the array."
},
{
"code": null,
"e": 2204,
"s": 2161,
"text": "array.unshift( element1, ..., elementN );\n"
},
{
"code": null,
"e": 2277,
"s": 2204,
"text": "element1, ..., elementN − The elements to add to the front of the array."
},
{
"code": null,
"e": 2350,
"s": 2277,
"text": "Returns the length of the new array. It returns undefined in IE browser."
},
{
"code": null,
"e": 2543,
"s": 2350,
"text": "var arr = new Array(\"orange\", \"mango\", \"banana\", \"sugar\"); \nvar length = arr.unshift(\"water\"); \nconsole.log(\"Returned array is : \" + arr );\nconsole.log(\"Length of the array is : \" + length );\n"
},
{
"code": null,
"e": 2603,
"s": 2543,
"text": "On compiling, it will generate the same code in JavaScript."
},
{
"code": null,
"e": 2630,
"s": 2603,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 2711,
"s": 2630,
"text": "Returned array is : water,orange,mango,banana,sugar \nLength of the array is : 5\n"
},
{
"code": null,
"e": 2744,
"s": 2711,
"text": "\n 45 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2758,
"s": 2744,
"text": " Antonio Papa"
},
{
"code": null,
"e": 2791,
"s": 2758,
"text": "\n 41 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 2805,
"s": 2791,
"text": " Haider Malik"
},
{
"code": null,
"e": 2840,
"s": 2805,
"text": "\n 60 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2860,
"s": 2840,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 2893,
"s": 2860,
"text": "\n 77 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2907,
"s": 2893,
"text": " Sean Bradley"
},
{
"code": null,
"e": 2942,
"s": 2907,
"text": "\n 77 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 2958,
"s": 2942,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 2991,
"s": 2958,
"text": "\n 19 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3011,
"s": 2991,
"text": " Christopher Frewin"
},
{
"code": null,
"e": 3018,
"s": 3011,
"text": " Print"
},
{
"code": null,
"e": 3029,
"s": 3018,
"text": " Add Notes"
}
] |
Best Way to Solve Python Coding Questions | by Luay Matalka | Towards Data Science | There is certainly some controversy regarding the benefits of Python coding websites such as codewars or leetcode, and whether or not using them actually makes us better programmers. Despite that, many people still use them to prepare for Python interview questions, keeping their Python programming skills sharp, and/or just for fun. Nevertheless, there’s definitely a place for these resources for any Python programmer or data scientist.
In this tutorial, we’ll look at the best way to extract the most utility out of these python coding problems. We will look at a fairly simple Python coding question and work through the proper steps to solve it. This includes first coming up with a plan or outline using pseudocode, and then solving it in different ways starting with the simplest solution.
We need to write a function that takes a single integer value as input, and returns the sum of the integers from zero up to and including that input. The function should return 0 if a non-integer value is passed in.
So if we pass in the number 5 to the function, then it would return the sum of the integers 0 through 5, or (0+1+2+3+4+5), which equals 15. If we pass in any other data type other than an integer, such as a string, or float, etc... the function should return 0.
towardsdatascience.com
The first thing we should do is solve this problem using pseudocode. Pseudocode is just a way to plan out our steps without worrying about the coding syntax.
We can try something like this:
def add(num): # if num is an integer then # add the integers 0 through num and return sum # if num is not an integer then return 0Sample inputs/outputs:# input: 5, output: 15# input: 'and', output: 0
We defined a function, add, that takes in an input, num. Within the add function, we write an outline of steps using comments. If the value passed to the function is an integer, then we will add the integers 0 through that value, and then return the sum. If the value passed to the function is not an integer, then we simply return 0. After that, we write a few examples of what we want our output to be given a specific input.
Let’s expand on this step in the pseudocode above:
# add the integers 0 through num and return sum
This step can be done in many ways. What would the pseudocode look like if we attempt this step using a for loop?
def add(num): # if num is an integer then# create sum variable and assign it to 0# using a for loop, loop over integers 0 to num# update sum value by adding num to it# return sum# if num is not an integer then return 0
Let’s try solving it based on the blueprint we created above!
We can solve this prompt using a for loop as follows:
def add(num): # if num is an integer then if type(num) == int:# create sum variable and assign it to 0 sum = 0# using a for loop, loop over integers 0 to num for x in range(num+1):# update sum value sum += x# return sum return sum# if num is not an integer then return 0 else: return 0
We first check if the value passed in, num, is an integer using the type function.
if type(num) == int:
If the type is an integer, we create a sum variable and assign it the value 0.
sum = 0
We then loop over the integers starting from 0 through the integer passed in to our function using a for loop and the range function. Remember that the range function creates a range object, which is an iterable object, that starts at 0 (if we don’t specify a start value), and goes to the integer less than the stop value (since the stop value is exclusive). That is why we need to add 1 to the stop value (num+1), since we want to add up all the integers from 0 up to and including that number, num.
range(start, stop[, step])
The range function will create a range object, which is an iterable object, and thus we can use a for loop to loop through it. As we are looping through this iterable object, we are adding each number, or x, to the sum variable.
for x in range(num+1): sum += x
Then after the for loop iterations are complete, the function returns the sum.
return sum
Lastly, if the number passed in is not an integer, we return 0.
else: return 0
This is the code without the comments:
def add(num): if type(num) == int: sum = 0 for x in range(num+1): sum += x return sum else: return 0
If we test our add function, we get the correct outputs:
add(5) # 15add('and')# 0
This is a good way to solve this coding problem and it gets the job done. It is easy to read and works correctly. But, in my opinion, by trying to solve this question in other ways, we can perhaps extract more value from it by utilizing our other python knowledge along with our problem-solving skills. These other ways may or may not be more pythonic, but it can be quite fun and useful to think of different ways to solve the same problem.
Let’s try to solve this coding question in a different way.
For more information on iterable objects:
towardsdatascience.com
We recently learned what the reduce function does in a previous tutorial. The reduce function takes an iterable object and reduces it down to a single cumulative value. The reduce function can take in three arguments, two of which are required. The two required arguments are: a function (that itself takes in two arguments), and an iterable object.
We can use the reduce function to find the sum of an iterable object.
Thus, instead of a for loop, we can use reduce to solve our Python problem:
from functools import reducedef add(num): if type(num) == int: return reduce(lambda x,y: x+y, range(num+1)) else: return 0
And that’s it! We use a lambda function as the function argument and the range object as our iterable object. The reduce function then reduces our range object down to a single value, the sum. And then we return that sum.
For more information about the reduce function:
towardsdatascience.com
We can shorten our code even more by using ternary operators. Using ternary operators, we can shorten our if/else statement above into one line using the following format:
x if C else y
C is our condition, which is evaluated first. If it evaluates to True, then x is evaluated and its value will be returned. Otherwise, y is evaluated and its value is returned.
We can implement this into our code as follows:
def add(num): return reduce(lambda x,y: x+y, range(num+1)) if type(num) == int else 0
And through these changes, we managed to reduce the code within our function down to a single line. It may not be the most readable or pythonic way of solving this problem, but in my opinion, it helps us improve our coding and problem-solving skills by forcing us to figure out different ways to solve the same problem.
Let’s see if we can solve this coding question in another way.
For more information on ternary operators:
towardsdatascience.com
We can solve this coding question a different way using Python’s built-in sum function. The sum() function can take in an iterable object and returns the sum of its elements. We can also pass in a start value if we want it to be added to the elements first.
sum(iterable, start)
Let’s solve the coding question using the sum function:
def add(num): return sum(range(num+1)) if type(num) == int else 0
And that’s it! This is likely the best way to solve this coding question, as it is both the most concise and easy to read solution. In addition, it likely will have the best performance as well.
For more information on code performance:
towardsdatascience.com
In this tutorial, we learned that solving a Python problem using different methods can enhance our coding and problem-solving skills by broadening our knowledge base. We looked at an example python coding question and went through the steps of solving it. We first planned how we were going to solve it using pseudocode. Then we implemented this outline of steps by first solving the prompt through the use of a for loop. Later, we solved the same problem using the reduce function. We also implemented ternary operators to shorten our code even further but still maintained readability. Lastly, we used the Python built-in sum function along with ternary operators to come up with the shortest but still most pythonic solution. | [
{
"code": null,
"e": 613,
"s": 172,
"text": "There is certainly some controversy regarding the benefits of Python coding websites such as codewars or leetcode, and whether or not using them actually makes us better programmers. Despite that, many people still use them to prepare for Python interview questions, keeping their Python programming skills sharp, and/or just for fun. Nevertheless, there’s definitely a place for these resources for any Python programmer or data scientist."
},
{
"code": null,
"e": 971,
"s": 613,
"text": "In this tutorial, we’ll look at the best way to extract the most utility out of these python coding problems. We will look at a fairly simple Python coding question and work through the proper steps to solve it. This includes first coming up with a plan or outline using pseudocode, and then solving it in different ways starting with the simplest solution."
},
{
"code": null,
"e": 1187,
"s": 971,
"text": "We need to write a function that takes a single integer value as input, and returns the sum of the integers from zero up to and including that input. The function should return 0 if a non-integer value is passed in."
},
{
"code": null,
"e": 1449,
"s": 1187,
"text": "So if we pass in the number 5 to the function, then it would return the sum of the integers 0 through 5, or (0+1+2+3+4+5), which equals 15. If we pass in any other data type other than an integer, such as a string, or float, etc... the function should return 0."
},
{
"code": null,
"e": 1472,
"s": 1449,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1630,
"s": 1472,
"text": "The first thing we should do is solve this problem using pseudocode. Pseudocode is just a way to plan out our steps without worrying about the coding syntax."
},
{
"code": null,
"e": 1662,
"s": 1630,
"text": "We can try something like this:"
},
{
"code": null,
"e": 1879,
"s": 1662,
"text": "def add(num): # if num is an integer then # add the integers 0 through num and return sum # if num is not an integer then return 0Sample inputs/outputs:# input: 5, output: 15# input: 'and', output: 0"
},
{
"code": null,
"e": 2307,
"s": 1879,
"text": "We defined a function, add, that takes in an input, num. Within the add function, we write an outline of steps using comments. If the value passed to the function is an integer, then we will add the integers 0 through that value, and then return the sum. If the value passed to the function is not an integer, then we simply return 0. After that, we write a few examples of what we want our output to be given a specific input."
},
{
"code": null,
"e": 2358,
"s": 2307,
"text": "Let’s expand on this step in the pseudocode above:"
},
{
"code": null,
"e": 2406,
"s": 2358,
"text": "# add the integers 0 through num and return sum"
},
{
"code": null,
"e": 2520,
"s": 2406,
"text": "This step can be done in many ways. What would the pseudocode look like if we attempt this step using a for loop?"
},
{
"code": null,
"e": 2742,
"s": 2520,
"text": "def add(num): # if num is an integer then# create sum variable and assign it to 0# using a for loop, loop over integers 0 to num# update sum value by adding num to it# return sum# if num is not an integer then return 0"
},
{
"code": null,
"e": 2804,
"s": 2742,
"text": "Let’s try solving it based on the blueprint we created above!"
},
{
"code": null,
"e": 2858,
"s": 2804,
"text": "We can solve this prompt using a for loop as follows:"
},
{
"code": null,
"e": 3193,
"s": 2858,
"text": "def add(num): # if num is an integer then if type(num) == int:# create sum variable and assign it to 0 sum = 0# using a for loop, loop over integers 0 to num for x in range(num+1):# update sum value sum += x# return sum return sum# if num is not an integer then return 0 else: return 0"
},
{
"code": null,
"e": 3276,
"s": 3193,
"text": "We first check if the value passed in, num, is an integer using the type function."
},
{
"code": null,
"e": 3297,
"s": 3276,
"text": "if type(num) == int:"
},
{
"code": null,
"e": 3376,
"s": 3297,
"text": "If the type is an integer, we create a sum variable and assign it the value 0."
},
{
"code": null,
"e": 3384,
"s": 3376,
"text": "sum = 0"
},
{
"code": null,
"e": 3886,
"s": 3384,
"text": "We then loop over the integers starting from 0 through the integer passed in to our function using a for loop and the range function. Remember that the range function creates a range object, which is an iterable object, that starts at 0 (if we don’t specify a start value), and goes to the integer less than the stop value (since the stop value is exclusive). That is why we need to add 1 to the stop value (num+1), since we want to add up all the integers from 0 up to and including that number, num."
},
{
"code": null,
"e": 3913,
"s": 3886,
"text": "range(start, stop[, step])"
},
{
"code": null,
"e": 4142,
"s": 3913,
"text": "The range function will create a range object, which is an iterable object, and thus we can use a for loop to loop through it. As we are looping through this iterable object, we are adding each number, or x, to the sum variable."
},
{
"code": null,
"e": 4177,
"s": 4142,
"text": "for x in range(num+1): sum += x"
},
{
"code": null,
"e": 4256,
"s": 4177,
"text": "Then after the for loop iterations are complete, the function returns the sum."
},
{
"code": null,
"e": 4267,
"s": 4256,
"text": "return sum"
},
{
"code": null,
"e": 4331,
"s": 4267,
"text": "Lastly, if the number passed in is not an integer, we return 0."
},
{
"code": null,
"e": 4349,
"s": 4331,
"text": "else: return 0"
},
{
"code": null,
"e": 4388,
"s": 4349,
"text": "This is the code without the comments:"
},
{
"code": null,
"e": 4534,
"s": 4388,
"text": "def add(num): if type(num) == int: sum = 0 for x in range(num+1): sum += x return sum else: return 0"
},
{
"code": null,
"e": 4591,
"s": 4534,
"text": "If we test our add function, we get the correct outputs:"
},
{
"code": null,
"e": 4616,
"s": 4591,
"text": "add(5) # 15add('and')# 0"
},
{
"code": null,
"e": 5058,
"s": 4616,
"text": "This is a good way to solve this coding problem and it gets the job done. It is easy to read and works correctly. But, in my opinion, by trying to solve this question in other ways, we can perhaps extract more value from it by utilizing our other python knowledge along with our problem-solving skills. These other ways may or may not be more pythonic, but it can be quite fun and useful to think of different ways to solve the same problem."
},
{
"code": null,
"e": 5118,
"s": 5058,
"text": "Let’s try to solve this coding question in a different way."
},
{
"code": null,
"e": 5160,
"s": 5118,
"text": "For more information on iterable objects:"
},
{
"code": null,
"e": 5183,
"s": 5160,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5533,
"s": 5183,
"text": "We recently learned what the reduce function does in a previous tutorial. The reduce function takes an iterable object and reduces it down to a single cumulative value. The reduce function can take in three arguments, two of which are required. The two required arguments are: a function (that itself takes in two arguments), and an iterable object."
},
{
"code": null,
"e": 5603,
"s": 5533,
"text": "We can use the reduce function to find the sum of an iterable object."
},
{
"code": null,
"e": 5679,
"s": 5603,
"text": "Thus, instead of a for loop, we can use reduce to solve our Python problem:"
},
{
"code": null,
"e": 5822,
"s": 5679,
"text": "from functools import reducedef add(num): if type(num) == int: return reduce(lambda x,y: x+y, range(num+1)) else: return 0"
},
{
"code": null,
"e": 6044,
"s": 5822,
"text": "And that’s it! We use a lambda function as the function argument and the range object as our iterable object. The reduce function then reduces our range object down to a single value, the sum. And then we return that sum."
},
{
"code": null,
"e": 6092,
"s": 6044,
"text": "For more information about the reduce function:"
},
{
"code": null,
"e": 6115,
"s": 6092,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6287,
"s": 6115,
"text": "We can shorten our code even more by using ternary operators. Using ternary operators, we can shorten our if/else statement above into one line using the following format:"
},
{
"code": null,
"e": 6301,
"s": 6287,
"text": "x if C else y"
},
{
"code": null,
"e": 6477,
"s": 6301,
"text": "C is our condition, which is evaluated first. If it evaluates to True, then x is evaluated and its value will be returned. Otherwise, y is evaluated and its value is returned."
},
{
"code": null,
"e": 6525,
"s": 6477,
"text": "We can implement this into our code as follows:"
},
{
"code": null,
"e": 6614,
"s": 6525,
"text": "def add(num): return reduce(lambda x,y: x+y, range(num+1)) if type(num) == int else 0"
},
{
"code": null,
"e": 6934,
"s": 6614,
"text": "And through these changes, we managed to reduce the code within our function down to a single line. It may not be the most readable or pythonic way of solving this problem, but in my opinion, it helps us improve our coding and problem-solving skills by forcing us to figure out different ways to solve the same problem."
},
{
"code": null,
"e": 6997,
"s": 6934,
"text": "Let’s see if we can solve this coding question in another way."
},
{
"code": null,
"e": 7040,
"s": 6997,
"text": "For more information on ternary operators:"
},
{
"code": null,
"e": 7063,
"s": 7040,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 7321,
"s": 7063,
"text": "We can solve this coding question a different way using Python’s built-in sum function. The sum() function can take in an iterable object and returns the sum of its elements. We can also pass in a start value if we want it to be added to the elements first."
},
{
"code": null,
"e": 7342,
"s": 7321,
"text": "sum(iterable, start)"
},
{
"code": null,
"e": 7398,
"s": 7342,
"text": "Let’s solve the coding question using the sum function:"
},
{
"code": null,
"e": 7467,
"s": 7398,
"text": "def add(num): return sum(range(num+1)) if type(num) == int else 0"
},
{
"code": null,
"e": 7662,
"s": 7467,
"text": "And that’s it! This is likely the best way to solve this coding question, as it is both the most concise and easy to read solution. In addition, it likely will have the best performance as well."
},
{
"code": null,
"e": 7704,
"s": 7662,
"text": "For more information on code performance:"
},
{
"code": null,
"e": 7727,
"s": 7704,
"text": "towardsdatascience.com"
}
] |
GATE-CS-2006 - GeeksforGeeks | 02 Dec, 2021
p = a3 X x ------------ (1)
q = (a2 + p) X x ---------(2)
r = (a1 + q) X x ---------(3)
result = a0 + r
S -> S * E
S -> E
E -> F + E
E -> F
F -> id
(i) S -> S * .E
(ii) E -> F. + E
(iii) E -> F + .E
Here, size of instruction = 24/8 = 3 bytes.
Program Counter can shift 3 bytes at a time to jump to next instruction.
So the given options must be divisible by 3. only 600 is satisfied.
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
C Program to read contents of Whole File
How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?
How to Append Pandas DataFrame to Existing CSV File?
How to Replace Values in a List in Python?
Spring - REST Controller
How to Read Text Files with Pandas?
How to Calculate Moving Averages in Python? | [
{
"code": null,
"e": 28965,
"s": 28937,
"text": "\n02 Dec, 2021"
},
{
"code": null,
"e": 29079,
"s": 28965,
"text": "\np = a3 X x ------------ (1)\n\nq = (a2 + p) X x ---------(2)\n\nr = (a1 + q) X x ---------(3)\n\nresult = a0 + r "
},
{
"code": null,
"e": 29123,
"s": 29079,
"text": "S -> S * E\nS -> E\nE -> F + E\nE -> F\nF -> id"
},
{
"code": null,
"e": 29175,
"s": 29123,
"text": "(i) S -> S * .E\n(ii) E -> F. + E\n(iii) E -> F + .E "
},
{
"code": null,
"e": 29364,
"s": 29175,
"text": "Here, size of instruction = 24/8 = 3 bytes.\n\nProgram Counter can shift 3 bytes at a time to jump to next instruction.\n\nSo the given options must be divisible by 3. only 600 is satisfied."
},
{
"code": null,
"e": 29462,
"s": 29364,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 29515,
"s": 29462,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 29577,
"s": 29515,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 29657,
"s": 29577,
"text": "How to Fix: SyntaxError: positional argument follows keyword argument in Python"
},
{
"code": null,
"e": 29698,
"s": 29657,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 29778,
"s": 29698,
"text": "How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?"
},
{
"code": null,
"e": 29831,
"s": 29778,
"text": "How to Append Pandas DataFrame to Existing CSV File?"
},
{
"code": null,
"e": 29874,
"s": 29831,
"text": "How to Replace Values in a List in Python?"
},
{
"code": null,
"e": 29899,
"s": 29874,
"text": "Spring - REST Controller"
},
{
"code": null,
"e": 29935,
"s": 29899,
"text": "How to Read Text Files with Pandas?"
}
] |
Can We Have Multiple Main Methods in Java? - GeeksforGeeks | 03 Aug, 2021
Java is an object-oriented language all processing is carried within classes. Execution of a program means dictates java virtual machine to load the class and then start execution of its main method. Java’s main method is entry point of any Java program. Public access modifier is used before the main method so that JVM can identify the execution point of the program. If other access modifiers are used instead of public, it will not be visible to JVM.
Initially, JVM loads the class but there is no object of the class present to call the main method. That is why the main method has to be static so that JVM can load the class and call the main method without having object of class. Java main method does not return anything that is why its return type is void. If we try to return anything from main method, it will give an unexpected value error because it is predefined signature in JVM. Java’s main method accepts string array as an argument. It is also called a command-line argument and it can pass from the command line in the main method. Now let us implement the same via appending clean java programs.
Implementation:
Example 1
Java
// Java Program Illustrating Can we have Multiple main// methods // Importing input output classesimport java.io.*; // Main classclass GFG { // Method 1 // Method inside main() method void test() { // Print statement whenever this method is called System.out.print("Inside class GFG"); } // Method 2 // Main driver method public static void main(String[] args) { // Creating an object class inside main() method GFG obj = new GFG(); // Calling the class object inside main() method obj.test(); }}
Inside class GFG
In the above program we are simply calling test() method by using class object from main() method. Now let us go onto depicting program having multiple main() methods.
Example 2
Java
// Java Program Illustrating Can we have// Multiple main() Methods // Importing input output classesimport java.io.*; // Main classclass GFG { // Method 1 void test() { // Print statement when this method is called System.out.print("inside test"); } // Method 2 // Main driver method public static void main(int i) { // Creating object later calling of class // inside this main() method GFG obj = new GFG(); obj.test(); } // Method 3 // Main driver method public static void main() { // Creating object later calling of class // inside this main() method GFG obj = new GFG(); obj.test(); }}
Output:
Output explanation:
Above program consist of two main methods but throws out an error that the Main method is not found in class, please define the main method as public static void main(String[] args)”. Only the main() method with a single string array as a parameter is considered as an entry point of the program. JVM only looks for main method with string array as an argument. In order for other main methods to execute, you need to call them from inside public static void main(String[ ] args)
Example 3
Java
// Java Program Illustrating Can we have// Multiple main() Methods // Importing input output classesimport java.io.*; // Main classclass GFG { // Method 1 // Main driver method public static void main(int i) { // Print statement for method 1 System.out.println(i); } // Method 2 // Main driver method public static void main(String s) { // Print statement for method 2 System.out.println(s); } // Method 3 // Main driver method public static void main(String[] args) { // Calling above 2 main methods main(1); main("hi"); }}
1
hi
From the above program, we can say that Java can have multiple main methods but with the concept of overloading. There should be only one main method with parameter as string[ ] arg.
sweetyty
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Constructors in Java
Different ways of Reading a text file in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
PriorityQueue in Java
Introduction to Java
How to remove an element from ArrayList in Java? | [
{
"code": null,
"e": 25788,
"s": 25760,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 26243,
"s": 25788,
"text": "Java is an object-oriented language all processing is carried within classes. Execution of a program means dictates java virtual machine to load the class and then start execution of its main method. Java’s main method is entry point of any Java program. Public access modifier is used before the main method so that JVM can identify the execution point of the program. If other access modifiers are used instead of public, it will not be visible to JVM."
},
{
"code": null,
"e": 26905,
"s": 26243,
"text": "Initially, JVM loads the class but there is no object of the class present to call the main method. That is why the main method has to be static so that JVM can load the class and call the main method without having object of class. Java main method does not return anything that is why its return type is void. If we try to return anything from main method, it will give an unexpected value error because it is predefined signature in JVM. Java’s main method accepts string array as an argument. It is also called a command-line argument and it can pass from the command line in the main method. Now let us implement the same via appending clean java programs."
},
{
"code": null,
"e": 26921,
"s": 26905,
"text": "Implementation:"
},
{
"code": null,
"e": 26931,
"s": 26921,
"text": "Example 1"
},
{
"code": null,
"e": 26936,
"s": 26931,
"text": "Java"
},
{
"code": "// Java Program Illustrating Can we have Multiple main// methods // Importing input output classesimport java.io.*; // Main classclass GFG { // Method 1 // Method inside main() method void test() { // Print statement whenever this method is called System.out.print(\"Inside class GFG\"); } // Method 2 // Main driver method public static void main(String[] args) { // Creating an object class inside main() method GFG obj = new GFG(); // Calling the class object inside main() method obj.test(); }}",
"e": 27509,
"s": 26936,
"text": null
},
{
"code": null,
"e": 27526,
"s": 27509,
"text": "Inside class GFG"
},
{
"code": null,
"e": 27695,
"s": 27526,
"text": "In the above program we are simply calling test() method by using class object from main() method. Now let us go onto depicting program having multiple main() methods. "
},
{
"code": null,
"e": 27706,
"s": 27695,
"text": "Example 2 "
},
{
"code": null,
"e": 27711,
"s": 27706,
"text": "Java"
},
{
"code": "// Java Program Illustrating Can we have// Multiple main() Methods // Importing input output classesimport java.io.*; // Main classclass GFG { // Method 1 void test() { // Print statement when this method is called System.out.print(\"inside test\"); } // Method 2 // Main driver method public static void main(int i) { // Creating object later calling of class // inside this main() method GFG obj = new GFG(); obj.test(); } // Method 3 // Main driver method public static void main() { // Creating object later calling of class // inside this main() method GFG obj = new GFG(); obj.test(); }}",
"e": 28422,
"s": 27711,
"text": null
},
{
"code": null,
"e": 28431,
"s": 28422,
"text": "Output: "
},
{
"code": null,
"e": 28451,
"s": 28431,
"text": "Output explanation:"
},
{
"code": null,
"e": 28932,
"s": 28451,
"text": "Above program consist of two main methods but throws out an error that the Main method is not found in class, please define the main method as public static void main(String[] args)”. Only the main() method with a single string array as a parameter is considered as an entry point of the program. JVM only looks for main method with string array as an argument. In order for other main methods to execute, you need to call them from inside public static void main(String[ ] args)"
},
{
"code": null,
"e": 28944,
"s": 28932,
"text": "Example 3 "
},
{
"code": null,
"e": 28949,
"s": 28944,
"text": "Java"
},
{
"code": "// Java Program Illustrating Can we have// Multiple main() Methods // Importing input output classesimport java.io.*; // Main classclass GFG { // Method 1 // Main driver method public static void main(int i) { // Print statement for method 1 System.out.println(i); } // Method 2 // Main driver method public static void main(String s) { // Print statement for method 2 System.out.println(s); } // Method 3 // Main driver method public static void main(String[] args) { // Calling above 2 main methods main(1); main(\"hi\"); }}",
"e": 29574,
"s": 28949,
"text": null
},
{
"code": null,
"e": 29579,
"s": 29574,
"text": "1\nhi"
},
{
"code": null,
"e": 29763,
"s": 29579,
"text": "From the above program, we can say that Java can have multiple main methods but with the concept of overloading. There should be only one main method with parameter as string[ ] arg. "
},
{
"code": null,
"e": 29774,
"s": 29765,
"text": "sweetyty"
},
{
"code": null,
"e": 29779,
"s": 29774,
"text": "Java"
},
{
"code": null,
"e": 29784,
"s": 29779,
"text": "Java"
},
{
"code": null,
"e": 29882,
"s": 29784,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29897,
"s": 29882,
"text": "Stream In Java"
},
{
"code": null,
"e": 29916,
"s": 29897,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29937,
"s": 29916,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29983,
"s": 29937,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 30013,
"s": 29983,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 30030,
"s": 30013,
"text": "Generics in Java"
},
{
"code": null,
"e": 30073,
"s": 30030,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 30095,
"s": 30073,
"text": "PriorityQueue in Java"
},
{
"code": null,
"e": 30116,
"s": 30095,
"text": "Introduction to Java"
}
] |
C++ Pointers | C++ pointers are easy and fun to learn. Some C++ tasks are performed more easily with pointers, and other C++ tasks, such as dynamic memory allocation, cannot be performed without them.
As you know every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator which denotes an address in memory. Consider the following which will print the address of the variables defined −
#include <iostream>
using namespace std;
int main () {
int var1;
char var2[10];
cout << "Address of var1 variable: ";
cout << &var1 << endl;
cout << "Address of var2 variable: ";
cout << &var2 << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Address of var1 variable: 0xbfebd5c0
Address of var2 variable: 0xbfebd5b6
A pointer is a variable whose value is the address of another variable. Like any variable or constant, you must declare a pointer before you can work with it. The general form of a pointer variable declaration is −
type *var-name;
Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name of the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration −
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to.
There are few important operations, which we will do with the pointers very frequently. (a) We define a pointer variable. (b) Assign the address of a variable to a pointer. (c) Finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. Following example makes use of these operations −
#include <iostream>
using namespace std;
int main () {
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable
cout << "Value of var variable: ";
cout << var << endl;
// print the address stored in ip pointer variable
cout << "Address stored in ip variable: ";
cout << ip << endl;
// access the value at the address available in pointer
cout << "Value of *ip variable: ";
cout << *ip << endl;
return 0;
}
When the above code is compiled and executed, it produces result something as follows −
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20
Pointers have many but easy concepts and they are very important to C++ programming. There are following few important pointer concepts which should be clear to a C++ programmer −
C++ supports null pointer, which is a constant with a value of zero defined in several standard libraries.
There are four arithmetic operators that can be used on pointers: ++, --, +, -
There is a close relationship between pointers and arrays.
You can define arrays to hold a number of pointers.
C++ allows you to have pointer on a pointer and so on.
Passing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function.
C++ allows a function to return a pointer to local variable, static variable and dynamically allocated memory as well.
154 Lectures
11.5 hours
Arnab Chakraborty
14 Lectures
57 mins
Kaushik Roy Chowdhury
30 Lectures
12.5 hours
Frahaan Hussain
54 Lectures
3.5 hours
Frahaan Hussain
77 Lectures
5.5 hours
Frahaan Hussain
12 Lectures
3.5 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2504,
"s": 2318,
"text": "C++ pointers are easy and fun to learn. Some C++ tasks are performed more easily with pointers, and other C++ tasks, such as dynamic memory allocation, cannot be performed without them."
},
{
"code": null,
"e": 2768,
"s": 2504,
"text": "As you know every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator which denotes an address in memory. Consider the following which will print the address of the variables defined −"
},
{
"code": null,
"e": 3008,
"s": 2768,
"text": "#include <iostream>\n\nusing namespace std;\nint main () {\n int var1;\n char var2[10];\n\n cout << \"Address of var1 variable: \";\n cout << &var1 << endl;\n\n cout << \"Address of var2 variable: \";\n cout << &var2 << endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 3089,
"s": 3008,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3164,
"s": 3089,
"text": "Address of var1 variable: 0xbfebd5c0\nAddress of var2 variable: 0xbfebd5b6\n"
},
{
"code": null,
"e": 3379,
"s": 3164,
"text": "A pointer is a variable whose value is the address of another variable. Like any variable or constant, you must declare a pointer before you can work with it. The general form of a pointer variable declaration is −"
},
{
"code": null,
"e": 3396,
"s": 3379,
"text": "type *var-name;\n"
},
{
"code": null,
"e": 3748,
"s": 3396,
"text": "Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name of the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration −"
},
{
"code": null,
"e": 3903,
"s": 3748,
"text": "int *ip; // pointer to an integer\ndouble *dp; // pointer to a double\nfloat *fp; // pointer to a float\nchar *ch // pointer to character\n"
},
{
"code": null,
"e": 4210,
"s": 3903,
"text": "The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to."
},
{
"code": null,
"e": 4639,
"s": 4210,
"text": "There are few important operations, which we will do with the pointers very frequently. (a) We define a pointer variable. (b) Assign the address of a variable to a pointer. (c) Finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. Following example makes use of these operations −"
},
{
"code": null,
"e": 5179,
"s": 4639,
"text": "#include <iostream>\n\nusing namespace std;\n\nint main () {\n int var = 20; // actual variable declaration.\n int *ip; // pointer variable \n\n ip = &var; // store address of var in pointer variable\n\n cout << \"Value of var variable: \";\n cout << var << endl;\n\n // print the address stored in ip pointer variable\n cout << \"Address stored in ip variable: \";\n cout << ip << endl;\n\n // access the value at the address available in pointer\n cout << \"Value of *ip variable: \";\n cout << *ip << endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 5267,
"s": 5179,
"text": "When the above code is compiled and executed, it produces result something as follows −"
},
{
"code": null,
"e": 5362,
"s": 5267,
"text": "Value of var variable: 20\nAddress stored in ip variable: 0xbfc601ac\nValue of *ip variable: 20\n"
},
{
"code": null,
"e": 5542,
"s": 5362,
"text": "Pointers have many but easy concepts and they are very important to C++ programming. There are following few important pointer concepts which should be clear to a C++ programmer −"
},
{
"code": null,
"e": 5649,
"s": 5542,
"text": "C++ supports null pointer, which is a constant with a value of zero defined in several standard libraries."
},
{
"code": null,
"e": 5728,
"s": 5649,
"text": "There are four arithmetic operators that can be used on pointers: ++, --, +, -"
},
{
"code": null,
"e": 5787,
"s": 5728,
"text": "There is a close relationship between pointers and arrays."
},
{
"code": null,
"e": 5839,
"s": 5787,
"text": "You can define arrays to hold a number of pointers."
},
{
"code": null,
"e": 5894,
"s": 5839,
"text": "C++ allows you to have pointer on a pointer and so on."
},
{
"code": null,
"e": 6035,
"s": 5894,
"text": "Passing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function."
},
{
"code": null,
"e": 6154,
"s": 6035,
"text": "C++ allows a function to return a pointer to local variable, static variable and dynamically allocated memory as well."
},
{
"code": null,
"e": 6191,
"s": 6154,
"text": "\n 154 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 6210,
"s": 6191,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6242,
"s": 6210,
"text": "\n 14 Lectures \n 57 mins\n"
},
{
"code": null,
"e": 6265,
"s": 6242,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 6301,
"s": 6265,
"text": "\n 30 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 6318,
"s": 6301,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6353,
"s": 6318,
"text": "\n 54 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6370,
"s": 6353,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6405,
"s": 6370,
"text": "\n 77 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6422,
"s": 6405,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6457,
"s": 6422,
"text": "\n 12 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6474,
"s": 6457,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6481,
"s": 6474,
"text": " Print"
},
{
"code": null,
"e": 6492,
"s": 6481,
"text": " Add Notes"
}
] |
Distribution-based loss functions for deep learning models | by Andrea C. | Towards Data Science | Information is made of data. During training step, an artificial neural network learns to map (predict) a set of inputs to a set of outputs from a labeled dataset. Computing the optimal weights is an optimization problem and it is usually solved by the stochastic gradient descent: weights are updated using the backpropagation of prediction error. The gradient descent algorithm updates weights navigating down the gradient (or slope) of the error, so that it can reduce the error of the next prediction. This is, in their very essence, how neural networks work.
When looking for the optimal weights, learning algorithms need a special object to evaluate the fitness of a candidate set of weights: this is the objective function.
Depending on the context, an objective function can be maximized or minimized. When dealing with deep learning models, experts prefer to reason in terms of error, so their goal is to minimize the objective function. Thus, objective function is called loss function and its values (i.e. the errors) are simply called losses. Loss functions are critical to ensure an adequate mathematical representation of the model response and their choice must be carefully considered as it must properly fit the model domain and its classification goals.
Definition and application of loss functions has started with standard machine learning methods. At the time, these functions were based on the distribution of labels, and it is for this reason that following functions are said to be distribution-based loss functions.
Our discussion begins precisely from here and, specifically, with the concept of cross-entropy.
Note: all code used for the plots and for the case study is available on my personal github: https://github.com/andrea-ci/misc-stuff/tree/master/nn-metrics.
According to the information theory, given a discrete random variable x, the entropy H(x) (also referred to as Shannon entropy, by its creator Claude Shannon) is defined as the expected value of logarithm of the inverse of probability:
Intuitively, entropy measures the uncertainty related to the possible outcomes of a random process: the more “surprising” they are for the observer, the higher the entropy is.
Note that the logarithm is in base 2 because in the context of information theory we are interested to the number of bits needed to encode the information carried by the random process.
Now suppose that we have two probability distributions, p and q, defined on the same random variable x. We want to measure the average number of bits needed to identify an event drawn from the sample space of x if the coding scheme is optimized for q rather than for p (that would be the true distribution).
In case the possible outcomes are only two, as in the previous example with the Bernoulli variable, we have the following definition for the binary cross-entropy loss function:
Having a binary scenario permits to simplify the equation so that we have only one argument, pt, which represents the value of probability assigned by the model to the true class (i.e. class to which the sample actually belongs).
Binary cross-entropy is widely used as loss function as it works well for many classification tasks. As a matter of fact, it is a fundamental baseline for distribution-based loss functions.
In the figure, yt is the class label of a sample in a binary classification task, and yp is the probability assigned by the model to that class. The function heavily penalizes the errors of prediction in which a wrong decision is made with high confidence (i.e. yp approaching 0), while it becomes zero when the prediction approaches true value of 1 (i.e. a correct classification is made).
A note: for sake of simplicity, we are going to keep both discussion and examples related to a binary classification task. However, the considerations made so far and in the following are valid, and naturally apply to, the case of multi-label classification as well.
In practice we must often deal with strongly unbalanced datasets: if, for example, we want to train a model to recognize ships in the middle of the ocean, the number of positive pixels, that is those that belong to the class “ship”, will be a very small percentage with respect to all the pixels.
It would be therefore useful to have loss functions able to handle different class labels in a different way, based on their abundance in the dataset or, in other words, according to their a priori classification probabilities.
Two variants of binary cross-entropy have been developed for this purpose: the Weighted Binary Cross-Entropy and the Balanced Cross-Entropy.
Weighted binary cross-entropy (WBCE) uses a coefficient to weight positive samples and it is usually preferred when data exhibit a significant skewness:
Balanced binary cross-entropy (BBCE) is similar to weighted cross-entropy, but in this case also negative samples are affected by a weight coefficient as in the following:
Finally, also Focal Loss (FL) can be seen as variation of binary cross-entropy. This function works well with highly imbalanced datasets because it weights the contribution of samples correctly classified and allows to better learn the hard samples (i.e. positive samples that are not detected):
Here λ is an hyper-parameter that we can use to calibrate importance of misclassified samples. Intuitively, λ decrease the penalty of easy samples by extending the range in which they receive low values of loss.
Note that when λ=0 we get the standard cross-entropy loss.
In addition, focal loss can take also another parameter, commonly referred to as α parameter, that allows to further balance the error term:
Let’s make an example where the choice of focal loss allows us to solve a problem of binary classification on an extremely unbalanced dataset.
To this purpose we consider the Credit Card Fraud Detection dataset hosted on Kaggle. As stated on their page:
“The dataset contains transactions made by credit cards in September 2013 by European cardholders.This dataset presents transactions that occurred in two days, where we have 492 frauds out of 284,807 transactions. The dataset is highly unbalanced, the positive class (frauds) account for 0.172% of all transactions.”
It goes without saying that the goal here is to detect the (very) small subset of fraudulent operations among all total transactions. In the following we give a brief overview of the followed steps.
First of all, we load the dataset and perform some cleanup in order to prepare data for model training.
## DATA LOADING/CLEANSING## Load data from CSV file.df_raw = pd.read_csv(‘creditcardfraud/creditcard.csv’)n_samples = len(df_raw)print(f’Num. of samples: {n_samples}.’)# Check size of samples.df_pos = df_raw[df_raw[‘Class’] == 1]n_pos_samples = len(df_pos)pos_ratio = 100 * n_pos_samples / n_samplesprint(f’Num. of positive samples: {n_pos_samples} ({pos_ratio:.2f}% of total).’)# Drop useless data and convert amount to log space.df_cleaned = df_raw.copy()df_cleaned.pop(‘Time’)df_cleaned[‘log-amount’] = np.log(df_cleaned.pop(‘Amount’) + 0.001)# Double train/test split for testing and validation data.df_train, df_test = train_test_split(df_cleaned, test_size = 0.2, shuffle = True)df_train, df_valid = train_test_split(df_train, test_size = 0.2, shuffle = True)print(f’Size of training data: {len(df_train)}.’)print(f’Size of validation data: {len(df_valid)}.’)print(f’Size of test data: {len(df_test)}.’)# Extract labels and features from data.labels_train = np.array(df_train.pop(‘Class’))labels_valid = np.array(df_valid.pop(‘Class’))labels_test = np.array(df_test.pop(‘Class’))features_train = np.array(df_train)features_valid = np.array(df_valid)features_test = np.array(df_test)# Normalize data.scaler = StandardScaler()features_train = scaler.fit_transform(features_train)features_valid = scaler.transform(features_valid)features_test = scaler.transform(features_test)# Enforce lower/upper bounds.features_train = np.clip(features_train, -5, 5)features_valid = np.clip(features_valid, -5, 5)features_test = np.clip(features_test, -5, 5)n_features = features_train.shape[-1]
We can see that dataset is actually extremely unbalanced, with positive samples accounting for only 0.17% of the total as anticipated.
With Keras, we setup a simple model and we train it using binary cross-entropy as loss function. This is our baseline model. Then we adopt focal loss function instead and we compare the performances obtained.
As evaluation metrics we consider true positives, false negatives, and recall metrics, because we are interested to measure how well the model predicts frauds.
In fact using accuracy, in this case, would not be a proper choice: a “model” that always predicts false (that is, no fraud) would get more than 99.8% accuracy on this dataset. This is why it’s hard to train a model on such unbalanced data.
## MODEL TRAINING## Model parameters.opt = Adam(learning_rate = 1e-3)metrics = [ TruePositives(name = 'tp'), FalseNegatives(name = 'fn'), Recall(name = 'recall')]losses = [ BinaryCrossentropy(), SigmoidFocalCrossEntropy(gamma = 2, alpha = 4)]loss_names = [ 'binary cross-entropy', 'focal loss']logs_loss = []logs_recall = []for loss in losses: # Setup/compile the model. model = Sequential() model.add(Dense(16, input_dim = n_features, activation = 'relu', kernel_initializer = 'he_uniform')) model.add(Dropout(0.5)) model.add(Dense(1, activation = 'sigmoid')) model.compile(optimizer = opt, loss = loss, metrics = metrics) # Fit the model. logs = model.fit(features_train, labels_train, validation_data = (features_valid, labels_valid), epochs = EPOCHS, verbose = 0) logs_loss.append(logs.history['loss']) logs_recall.append(logs.history['recall']) # Evaluate the model. eval_train = model.evaluate(features_train, labels_train, verbose = 0) eval_test = model.evaluate(features_valid, labels_valid, verbose = 0)table = PrettyTable() table.field_names = ['Data', 'Loss', 'TruePositives', 'FalseNegatives', 'Recall'] for stage, eval_info in zip(('training', 'test'), (eval_train, eval_test)): row = [stage] for ii, lbl in enumerate(model.metrics_names): row.append(f'{eval_info[ii]:.3f}') table.add_row(row) print('\n') print(table)
Having trained and validated both configurations, we can compare the results obtained. From the baseline model we get:
Using focal loss instead, classification performs significantly better and all fraud cases are correctly detected:
Let’s also compare the behavior of the two loss functions.
As expected, values of focal loss are lower than those of cross-entropy. Focal loss down-weights the loss of positive samples (frauds) that are misclassified, thus “encouraging” the model to increase sensitivity to fraud cases.
[1] Tsung-Yi Lin, Priya Goyal et al., Focal Loss for Dense Object Detection
[2] Hichame Yessou et al., A Comparative Study of Deep Learning Loss Functions for Multi-Label Remote Sensing Image Classification
[3] Multi-class classification with focal loss for imbalanced datasets
[4] Classification on imbalanced data
[5] Kaggle dataset on Credit Card Fraud Detection | [
{
"code": null,
"e": 735,
"s": 171,
"text": "Information is made of data. During training step, an artificial neural network learns to map (predict) a set of inputs to a set of outputs from a labeled dataset. Computing the optimal weights is an optimization problem and it is usually solved by the stochastic gradient descent: weights are updated using the backpropagation of prediction error. The gradient descent algorithm updates weights navigating down the gradient (or slope) of the error, so that it can reduce the error of the next prediction. This is, in their very essence, how neural networks work."
},
{
"code": null,
"e": 902,
"s": 735,
"text": "When looking for the optimal weights, learning algorithms need a special object to evaluate the fitness of a candidate set of weights: this is the objective function."
},
{
"code": null,
"e": 1443,
"s": 902,
"text": "Depending on the context, an objective function can be maximized or minimized. When dealing with deep learning models, experts prefer to reason in terms of error, so their goal is to minimize the objective function. Thus, objective function is called loss function and its values (i.e. the errors) are simply called losses. Loss functions are critical to ensure an adequate mathematical representation of the model response and their choice must be carefully considered as it must properly fit the model domain and its classification goals."
},
{
"code": null,
"e": 1712,
"s": 1443,
"text": "Definition and application of loss functions has started with standard machine learning methods. At the time, these functions were based on the distribution of labels, and it is for this reason that following functions are said to be distribution-based loss functions."
},
{
"code": null,
"e": 1808,
"s": 1712,
"text": "Our discussion begins precisely from here and, specifically, with the concept of cross-entropy."
},
{
"code": null,
"e": 1965,
"s": 1808,
"text": "Note: all code used for the plots and for the case study is available on my personal github: https://github.com/andrea-ci/misc-stuff/tree/master/nn-metrics."
},
{
"code": null,
"e": 2201,
"s": 1965,
"text": "According to the information theory, given a discrete random variable x, the entropy H(x) (also referred to as Shannon entropy, by its creator Claude Shannon) is defined as the expected value of logarithm of the inverse of probability:"
},
{
"code": null,
"e": 2377,
"s": 2201,
"text": "Intuitively, entropy measures the uncertainty related to the possible outcomes of a random process: the more “surprising” they are for the observer, the higher the entropy is."
},
{
"code": null,
"e": 2563,
"s": 2377,
"text": "Note that the logarithm is in base 2 because in the context of information theory we are interested to the number of bits needed to encode the information carried by the random process."
},
{
"code": null,
"e": 2871,
"s": 2563,
"text": "Now suppose that we have two probability distributions, p and q, defined on the same random variable x. We want to measure the average number of bits needed to identify an event drawn from the sample space of x if the coding scheme is optimized for q rather than for p (that would be the true distribution)."
},
{
"code": null,
"e": 3048,
"s": 2871,
"text": "In case the possible outcomes are only two, as in the previous example with the Bernoulli variable, we have the following definition for the binary cross-entropy loss function:"
},
{
"code": null,
"e": 3278,
"s": 3048,
"text": "Having a binary scenario permits to simplify the equation so that we have only one argument, pt, which represents the value of probability assigned by the model to the true class (i.e. class to which the sample actually belongs)."
},
{
"code": null,
"e": 3468,
"s": 3278,
"text": "Binary cross-entropy is widely used as loss function as it works well for many classification tasks. As a matter of fact, it is a fundamental baseline for distribution-based loss functions."
},
{
"code": null,
"e": 3859,
"s": 3468,
"text": "In the figure, yt is the class label of a sample in a binary classification task, and yp is the probability assigned by the model to that class. The function heavily penalizes the errors of prediction in which a wrong decision is made with high confidence (i.e. yp approaching 0), while it becomes zero when the prediction approaches true value of 1 (i.e. a correct classification is made)."
},
{
"code": null,
"e": 4126,
"s": 3859,
"text": "A note: for sake of simplicity, we are going to keep both discussion and examples related to a binary classification task. However, the considerations made so far and in the following are valid, and naturally apply to, the case of multi-label classification as well."
},
{
"code": null,
"e": 4423,
"s": 4126,
"text": "In practice we must often deal with strongly unbalanced datasets: if, for example, we want to train a model to recognize ships in the middle of the ocean, the number of positive pixels, that is those that belong to the class “ship”, will be a very small percentage with respect to all the pixels."
},
{
"code": null,
"e": 4651,
"s": 4423,
"text": "It would be therefore useful to have loss functions able to handle different class labels in a different way, based on their abundance in the dataset or, in other words, according to their a priori classification probabilities."
},
{
"code": null,
"e": 4792,
"s": 4651,
"text": "Two variants of binary cross-entropy have been developed for this purpose: the Weighted Binary Cross-Entropy and the Balanced Cross-Entropy."
},
{
"code": null,
"e": 4945,
"s": 4792,
"text": "Weighted binary cross-entropy (WBCE) uses a coefficient to weight positive samples and it is usually preferred when data exhibit a significant skewness:"
},
{
"code": null,
"e": 5117,
"s": 4945,
"text": "Balanced binary cross-entropy (BBCE) is similar to weighted cross-entropy, but in this case also negative samples are affected by a weight coefficient as in the following:"
},
{
"code": null,
"e": 5413,
"s": 5117,
"text": "Finally, also Focal Loss (FL) can be seen as variation of binary cross-entropy. This function works well with highly imbalanced datasets because it weights the contribution of samples correctly classified and allows to better learn the hard samples (i.e. positive samples that are not detected):"
},
{
"code": null,
"e": 5625,
"s": 5413,
"text": "Here λ is an hyper-parameter that we can use to calibrate importance of misclassified samples. Intuitively, λ decrease the penalty of easy samples by extending the range in which they receive low values of loss."
},
{
"code": null,
"e": 5684,
"s": 5625,
"text": "Note that when λ=0 we get the standard cross-entropy loss."
},
{
"code": null,
"e": 5825,
"s": 5684,
"text": "In addition, focal loss can take also another parameter, commonly referred to as α parameter, that allows to further balance the error term:"
},
{
"code": null,
"e": 5968,
"s": 5825,
"text": "Let’s make an example where the choice of focal loss allows us to solve a problem of binary classification on an extremely unbalanced dataset."
},
{
"code": null,
"e": 6079,
"s": 5968,
"text": "To this purpose we consider the Credit Card Fraud Detection dataset hosted on Kaggle. As stated on their page:"
},
{
"code": null,
"e": 6396,
"s": 6079,
"text": "“The dataset contains transactions made by credit cards in September 2013 by European cardholders.This dataset presents transactions that occurred in two days, where we have 492 frauds out of 284,807 transactions. The dataset is highly unbalanced, the positive class (frauds) account for 0.172% of all transactions.”"
},
{
"code": null,
"e": 6595,
"s": 6396,
"text": "It goes without saying that the goal here is to detect the (very) small subset of fraudulent operations among all total transactions. In the following we give a brief overview of the followed steps."
},
{
"code": null,
"e": 6699,
"s": 6595,
"text": "First of all, we load the dataset and perform some cleanup in order to prepare data for model training."
},
{
"code": null,
"e": 8284,
"s": 6699,
"text": "## DATA LOADING/CLEANSING## Load data from CSV file.df_raw = pd.read_csv(‘creditcardfraud/creditcard.csv’)n_samples = len(df_raw)print(f’Num. of samples: {n_samples}.’)# Check size of samples.df_pos = df_raw[df_raw[‘Class’] == 1]n_pos_samples = len(df_pos)pos_ratio = 100 * n_pos_samples / n_samplesprint(f’Num. of positive samples: {n_pos_samples} ({pos_ratio:.2f}% of total).’)# Drop useless data and convert amount to log space.df_cleaned = df_raw.copy()df_cleaned.pop(‘Time’)df_cleaned[‘log-amount’] = np.log(df_cleaned.pop(‘Amount’) + 0.001)# Double train/test split for testing and validation data.df_train, df_test = train_test_split(df_cleaned, test_size = 0.2, shuffle = True)df_train, df_valid = train_test_split(df_train, test_size = 0.2, shuffle = True)print(f’Size of training data: {len(df_train)}.’)print(f’Size of validation data: {len(df_valid)}.’)print(f’Size of test data: {len(df_test)}.’)# Extract labels and features from data.labels_train = np.array(df_train.pop(‘Class’))labels_valid = np.array(df_valid.pop(‘Class’))labels_test = np.array(df_test.pop(‘Class’))features_train = np.array(df_train)features_valid = np.array(df_valid)features_test = np.array(df_test)# Normalize data.scaler = StandardScaler()features_train = scaler.fit_transform(features_train)features_valid = scaler.transform(features_valid)features_test = scaler.transform(features_test)# Enforce lower/upper bounds.features_train = np.clip(features_train, -5, 5)features_valid = np.clip(features_valid, -5, 5)features_test = np.clip(features_test, -5, 5)n_features = features_train.shape[-1]"
},
{
"code": null,
"e": 8419,
"s": 8284,
"text": "We can see that dataset is actually extremely unbalanced, with positive samples accounting for only 0.17% of the total as anticipated."
},
{
"code": null,
"e": 8628,
"s": 8419,
"text": "With Keras, we setup a simple model and we train it using binary cross-entropy as loss function. This is our baseline model. Then we adopt focal loss function instead and we compare the performances obtained."
},
{
"code": null,
"e": 8788,
"s": 8628,
"text": "As evaluation metrics we consider true positives, false negatives, and recall metrics, because we are interested to measure how well the model predicts frauds."
},
{
"code": null,
"e": 9029,
"s": 8788,
"text": "In fact using accuracy, in this case, would not be a proper choice: a “model” that always predicts false (that is, no fraud) would get more than 99.8% accuracy on this dataset. This is why it’s hard to train a model on such unbalanced data."
},
{
"code": null,
"e": 10479,
"s": 9029,
"text": "## MODEL TRAINING## Model parameters.opt = Adam(learning_rate = 1e-3)metrics = [ TruePositives(name = 'tp'), FalseNegatives(name = 'fn'), Recall(name = 'recall')]losses = [ BinaryCrossentropy(), SigmoidFocalCrossEntropy(gamma = 2, alpha = 4)]loss_names = [ 'binary cross-entropy', 'focal loss']logs_loss = []logs_recall = []for loss in losses: # Setup/compile the model. model = Sequential() model.add(Dense(16, input_dim = n_features, activation = 'relu', kernel_initializer = 'he_uniform')) model.add(Dropout(0.5)) model.add(Dense(1, activation = 'sigmoid')) model.compile(optimizer = opt, loss = loss, metrics = metrics) # Fit the model. logs = model.fit(features_train, labels_train, validation_data = (features_valid, labels_valid), epochs = EPOCHS, verbose = 0) logs_loss.append(logs.history['loss']) logs_recall.append(logs.history['recall']) # Evaluate the model. eval_train = model.evaluate(features_train, labels_train, verbose = 0) eval_test = model.evaluate(features_valid, labels_valid, verbose = 0)table = PrettyTable() table.field_names = ['Data', 'Loss', 'TruePositives', 'FalseNegatives', 'Recall'] for stage, eval_info in zip(('training', 'test'), (eval_train, eval_test)): row = [stage] for ii, lbl in enumerate(model.metrics_names): row.append(f'{eval_info[ii]:.3f}') table.add_row(row) print('\\n') print(table)"
},
{
"code": null,
"e": 10598,
"s": 10479,
"text": "Having trained and validated both configurations, we can compare the results obtained. From the baseline model we get:"
},
{
"code": null,
"e": 10713,
"s": 10598,
"text": "Using focal loss instead, classification performs significantly better and all fraud cases are correctly detected:"
},
{
"code": null,
"e": 10772,
"s": 10713,
"text": "Let’s also compare the behavior of the two loss functions."
},
{
"code": null,
"e": 11000,
"s": 10772,
"text": "As expected, values of focal loss are lower than those of cross-entropy. Focal loss down-weights the loss of positive samples (frauds) that are misclassified, thus “encouraging” the model to increase sensitivity to fraud cases."
},
{
"code": null,
"e": 11076,
"s": 11000,
"text": "[1] Tsung-Yi Lin, Priya Goyal et al., Focal Loss for Dense Object Detection"
},
{
"code": null,
"e": 11207,
"s": 11076,
"text": "[2] Hichame Yessou et al., A Comparative Study of Deep Learning Loss Functions for Multi-Label Remote Sensing Image Classification"
},
{
"code": null,
"e": 11278,
"s": 11207,
"text": "[3] Multi-class classification with focal loss for imbalanced datasets"
},
{
"code": null,
"e": 11316,
"s": 11278,
"text": "[4] Classification on imbalanced data"
}
] |
What are Inline List Items in CSS | Use Inline List Items to build a horizontal navigation bar. Set the &lt;li&gt; elements as inline.
You can try to run the following code to create horizontal navigation bar:
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
}
.active {
background-color: #4CAF50;
color: white;
}
li {
border-bottom: 1px solid #555;
display: inline;
}
</style>
</head>
<body>
<ul>
<li><a href = "#home">Home</a></li>
<li><a href = "#company" class="active">Company</a></li>
<li><a href = "#product">Product</a></li>
<li><a href = "#services">Services</a></li>
<li><a href = "#contact">Contact</a></li>
</ul>
</body>
</html> | [
{
"code": null,
"e": 1169,
"s": 1062,
"text": "Use Inline List Items to build a horizontal navigation bar. Set the &lt;li&gt; elements as inline."
},
{
"code": null,
"e": 1244,
"s": 1169,
"text": "You can try to run the following code to create horizontal navigation bar:"
},
{
"code": null,
"e": 1254,
"s": 1244,
"text": "Live Demo"
},
{
"code": null,
"e": 1944,
"s": 1254,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n ul {\n list-style-type: none;\n margin: 0;\n padding: 0;\n }\n .active {\n background-color: #4CAF50;\n color: white;\n }\n li {\n border-bottom: 1px solid #555;\n display: inline;\n }\n </style>\n </head>\n <body>\n <ul>\n <li><a href = \"#home\">Home</a></li>\n <li><a href = \"#company\" class=\"active\">Company</a></li>\n <li><a href = \"#product\">Product</a></li>\n <li><a href = \"#services\">Services</a></li>\n <li><a href = \"#contact\">Contact</a></li>\n </ul>\n </body>\n</html>"
}
] |
Get Enumeration over Java HashSet - GeeksforGeeks | 03 Mar, 2021
The HashSet class implements the Set interface, backed by a hash table which is a HashMap instance. There is no assurance as to the iteration order of the set, which implies that over time, the class does not guarantee the constant order of elements. The null element is allowed by this class. The java.util.Collections class enumeration method is used to return an enumeration of the specified collection.
To return enumeration over HashSet:
Syntax:
public static Enumeration enumeration(Collection c)
Method Used: hasMoreElements() Method.
An object that implements the Enumeration interface creates one at a time, a set of objects. hasMoreElements() method of enumeration used to tests if this enumeration contains more elements. If enumeration contains more elements, then it will return true else false.
Syntax:
boolean hasMoreElements()
Return value: This method returns true if there is at least one additional element to be given in this enumeration object, otherwise return false.
Below is the full implementation of the above approach:
Java
// Getting Enumeration over Java HashSetimport java.util.*;import java.util.Enumeration; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating object of HashSet // String type here- name HashSet<String> name = new HashSet<>(); // Adding element to HashSet // Custom inputs name.add("Nikhil"); name.add("Akshay"); name.add("Bina"); name.add("Chintu"); name.add("Dhruv"); // Creating object of type Enumeration<String> Enumeration e = Collections.enumeration(name); // Condition check using hasMoreElements() method while (e.hasMoreElements()) // print the enumeration System.out.println(e.nextElement()); }}
Dhruv
Akshay
Chintu
Bina
Nikhil
Example 2:
Java
// Getting Enumeration over Java HashSetimport java.util.*;import java.util.Enumeration; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating object of HashSet // String type here- name HashSet<String> gfg = new HashSet<>(); // Adding element to HashSet // Custom inputs gfg.add("Welcome"); gfg.add("On"); gfg.add("GFG"); // Creating object of type Enumeration<String> Enumeration e = Collections.enumeration(gfg); // Condition check using hasMoreElements() method while (e.hasMoreElements()) // print the enumeration System.out.println(e.nextElement()); }}
GFG
Welcome
On
Java-Enumeration
java-hashset
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Exceptions in Java
Generics in Java
Convert a String to Character array in Java
Java Programming Examples
Implementing a Linked List in Java using Class
Convert Double to Integer in Java
How to Iterate HashMap in Java? | [
{
"code": null,
"e": 23892,
"s": 23864,
"text": "\n03 Mar, 2021"
},
{
"code": null,
"e": 24300,
"s": 23892,
"text": "The HashSet class implements the Set interface, backed by a hash table which is a HashMap instance. There is no assurance as to the iteration order of the set, which implies that over time, the class does not guarantee the constant order of elements. The null element is allowed by this class. The java.util.Collections class enumeration method is used to return an enumeration of the specified collection. "
},
{
"code": null,
"e": 24336,
"s": 24300,
"text": "To return enumeration over HashSet:"
},
{
"code": null,
"e": 24344,
"s": 24336,
"text": "Syntax:"
},
{
"code": null,
"e": 24396,
"s": 24344,
"text": "public static Enumeration enumeration(Collection c)"
},
{
"code": null,
"e": 24435,
"s": 24396,
"text": "Method Used: hasMoreElements() Method."
},
{
"code": null,
"e": 24702,
"s": 24435,
"text": "An object that implements the Enumeration interface creates one at a time, a set of objects. hasMoreElements() method of enumeration used to tests if this enumeration contains more elements. If enumeration contains more elements, then it will return true else false."
},
{
"code": null,
"e": 24710,
"s": 24702,
"text": "Syntax:"
},
{
"code": null,
"e": 24736,
"s": 24710,
"text": "boolean hasMoreElements()"
},
{
"code": null,
"e": 24883,
"s": 24736,
"text": "Return value: This method returns true if there is at least one additional element to be given in this enumeration object, otherwise return false."
},
{
"code": null,
"e": 24939,
"s": 24883,
"text": "Below is the full implementation of the above approach:"
},
{
"code": null,
"e": 24944,
"s": 24939,
"text": "Java"
},
{
"code": "// Getting Enumeration over Java HashSetimport java.util.*;import java.util.Enumeration; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating object of HashSet // String type here- name HashSet<String> name = new HashSet<>(); // Adding element to HashSet // Custom inputs name.add(\"Nikhil\"); name.add(\"Akshay\"); name.add(\"Bina\"); name.add(\"Chintu\"); name.add(\"Dhruv\"); // Creating object of type Enumeration<String> Enumeration e = Collections.enumeration(name); // Condition check using hasMoreElements() method while (e.hasMoreElements()) // print the enumeration System.out.println(e.nextElement()); }}",
"e": 25742,
"s": 24944,
"text": null
},
{
"code": null,
"e": 25774,
"s": 25742,
"text": "Dhruv\nAkshay\nChintu\nBina\nNikhil"
},
{
"code": null,
"e": 25786,
"s": 25774,
"text": "Example 2: "
},
{
"code": null,
"e": 25791,
"s": 25786,
"text": "Java"
},
{
"code": "// Getting Enumeration over Java HashSetimport java.util.*;import java.util.Enumeration; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating object of HashSet // String type here- name HashSet<String> gfg = new HashSet<>(); // Adding element to HashSet // Custom inputs gfg.add(\"Welcome\"); gfg.add(\"On\"); gfg.add(\"GFG\"); // Creating object of type Enumeration<String> Enumeration e = Collections.enumeration(gfg); // Condition check using hasMoreElements() method while (e.hasMoreElements()) // print the enumeration System.out.println(e.nextElement()); }}",
"e": 26527,
"s": 25791,
"text": null
},
{
"code": null,
"e": 26542,
"s": 26527,
"text": "GFG\nWelcome\nOn"
},
{
"code": null,
"e": 26559,
"s": 26542,
"text": "Java-Enumeration"
},
{
"code": null,
"e": 26572,
"s": 26559,
"text": "java-hashset"
},
{
"code": null,
"e": 26579,
"s": 26572,
"text": "Picked"
},
{
"code": null,
"e": 26584,
"s": 26579,
"text": "Java"
},
{
"code": null,
"e": 26598,
"s": 26584,
"text": "Java Programs"
},
{
"code": null,
"e": 26603,
"s": 26598,
"text": "Java"
},
{
"code": null,
"e": 26701,
"s": 26603,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26710,
"s": 26701,
"text": "Comments"
},
{
"code": null,
"e": 26723,
"s": 26710,
"text": "Old Comments"
},
{
"code": null,
"e": 26769,
"s": 26723,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26790,
"s": 26769,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26805,
"s": 26790,
"text": "Stream In Java"
},
{
"code": null,
"e": 26824,
"s": 26805,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26841,
"s": 26824,
"text": "Generics in Java"
},
{
"code": null,
"e": 26885,
"s": 26841,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 26911,
"s": 26885,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 26958,
"s": 26911,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 26992,
"s": 26958,
"text": "Convert Double to Integer in Java"
}
] |
C++ Floating Point Manipulation | Numerical implementation of a decimal number is a float point number. In C++ programming language the size of a float is 32 bits. And there are some floating point manipulation functions that work on floating-point numbers. Here we have introduced some of the floating-point manipulation functions.
The fmod() function operating on floats will return the remainder of the division of the passed arguments of the method.
Live Demo
#include <iostream>
#include <cmath>
using namespace std;
int main() {
float a, b, rem;
a = 23.4;
b = 4.1;
rem = fmod(a,b);
cout<<"The value of fmod( "<<a<<" , "<<b<<" ) = "<<rem;
}
The value of fmod( 23.4 , 4.1 ) = 2.9
The remainder() function does the same work as fmod function. And return the remainder of the division between the values. This method returns the minimum possible remainder in terms of numeric values. It may negative also.
Live Demo
#include <iostream>
#include <cmath>
using namespace std;
int main() {
float a, b, rem;
a = 23.4;
b = 4.1;
rem = remainder(a,b);
cout<<"The value of remainder( "<<a<<" , "<<b<<" ) = "<<rem;
}
The value of remainder( 23.4 , 4.1 ) = -1.2
This method returns the quotient and remainder of the two values passed also it needs a reference to a variable that will have the value of the quotient. So, this method will return the remainder the same as by the remainder function and reference of the quotient.
Live Demo
#include <iostream>
#include <cmath>
using namespace std;
int main() {
float a, b, rem;
int quo;
a = 23.4;
b = 4.1;
rem = remquo(a,b,&quo);
cout<<a<<" and "<<b<<" passed to the remquo() function gives the following output\n";
cout<<"The remainder is "<<rem<<endl;
cout<<"The quotient is "<<quo;
}
23.4 and 4.1 pass to the the remque() function gives the following
output
The reminder is -1.2
The quotient is 6
The copysign function of C returns a variable with the sign of other variables. The returned variables have the magnitude of the first variable and sign of the second variable.
Live Demo
#include <iostream>
#include <cmath>
using namespace std;
int main(){
double a, b;
a = 9.6;
b = -3.5;
cout<<"copysign function with inputs "<<a<<" and "<<b<<" is "<<copysign(a,b);
}
Copysign function with inputs 9.6 and -3.5 is -9.6
The fmin function as you can see from its name returns that the minimum value of the two arguments of the function. The return type is a float.
Live Demo
#include <iostream>
#include <cmath>
using namespace std;
int main(){
double a, b;
a = 43.5;
b = 21.2;
cout << "The smallest of "<<a<<" and "<<b<<" is "; cout << fmin(a,b)<<endl;
}
The smallest of 43.5 and 21.2 is 21.2
The fmax function is a C programming function that returns the largest number of the two numbers in the arguments.
Live Demo
#include <iostream>
#include <cmath>
using namespace std;
int main(){
double a, b;
a = 43.5;
b = 21.2;
cout << "The largest of "<<a<<" and "<<b<<" is "; cout << fmax(a,b)<<endl;
}
The largest of 43.5 and 21.2 is 43.5
The fdim() function of the C programming language returns the absolute difference of the two numbers that are sent as the arguments to the function.
Live Demo
#include <iostream>
#include <cmath>
using namespace std;
int main(){
double a, b;
a = 43.5;
b = 21.2;
cout << "The absolute difference of "<<a<<" and "<<b<<" is";
cout << fdim(a,b)<<endl;
}
The absolute difference of 43.5 and 21.2 is 22.3
The fma() function of C, returns the multiplication of the arguments given to it. The function returns a float and accepts three floating arguments.
Live Demo
#include <iostream>
#include <cmath>
using namespace std;
int main(){
double a, b, c;
a = 3.5;
b = 2.4;
c = 7.2;
cout << "The multiplication of "<<a<<" , "<<b<<" and "<<c<<" is ";
cout << fma(a,b,c)<<endl;
}
The multiplication of 3.5 , 2.4 and 7.2 is 15.6
These are all the functions that are operated over floating-point numbers.
These are the functions that are defined in cmath library | [
{
"code": null,
"e": 1361,
"s": 1062,
"text": "Numerical implementation of a decimal number is a float point number. In C++ programming language the size of a float is 32 bits. And there are some floating point manipulation functions that work on floating-point numbers. Here we have introduced some of the floating-point manipulation functions."
},
{
"code": null,
"e": 1482,
"s": 1361,
"text": "The fmod() function operating on floats will return the remainder of the division of the passed arguments of the method."
},
{
"code": null,
"e": 1493,
"s": 1482,
"text": " Live Demo"
},
{
"code": null,
"e": 1690,
"s": 1493,
"text": "#include <iostream>\n#include <cmath>\nusing namespace std;\nint main() {\n float a, b, rem;\n a = 23.4;\n b = 4.1;\n rem = fmod(a,b);\n cout<<\"The value of fmod( \"<<a<<\" , \"<<b<<\" ) = \"<<rem;\n}"
},
{
"code": null,
"e": 1728,
"s": 1690,
"text": "The value of fmod( 23.4 , 4.1 ) = 2.9"
},
{
"code": null,
"e": 1952,
"s": 1728,
"text": "The remainder() function does the same work as fmod function. And return the remainder of the division between the values. This method returns the minimum possible remainder in terms of numeric values. It may negative also."
},
{
"code": null,
"e": 1963,
"s": 1952,
"text": " Live Demo"
},
{
"code": null,
"e": 2170,
"s": 1963,
"text": "#include <iostream>\n#include <cmath>\nusing namespace std;\nint main() {\n float a, b, rem;\n a = 23.4;\n b = 4.1;\n rem = remainder(a,b);\n cout<<\"The value of remainder( \"<<a<<\" , \"<<b<<\" ) = \"<<rem;\n}"
},
{
"code": null,
"e": 2214,
"s": 2170,
"text": "The value of remainder( 23.4 , 4.1 ) = -1.2"
},
{
"code": null,
"e": 2479,
"s": 2214,
"text": "This method returns the quotient and remainder of the two values passed also it needs a reference to a variable that will have the value of the quotient. So, this method will return the remainder the same as by the remainder function and reference of the quotient."
},
{
"code": null,
"e": 2490,
"s": 2479,
"text": " Live Demo"
},
{
"code": null,
"e": 2811,
"s": 2490,
"text": "#include <iostream>\n#include <cmath>\nusing namespace std;\nint main() {\n float a, b, rem;\n int quo;\n a = 23.4;\n b = 4.1;\n rem = remquo(a,b,&quo);\n cout<<a<<\" and \"<<b<<\" passed to the remquo() function gives the following output\\n\";\n cout<<\"The remainder is \"<<rem<<endl;\n cout<<\"The quotient is \"<<quo;\n}"
},
{
"code": null,
"e": 2924,
"s": 2811,
"text": "23.4 and 4.1 pass to the the remque() function gives the following\noutput\nThe reminder is -1.2\nThe quotient is 6"
},
{
"code": null,
"e": 3101,
"s": 2924,
"text": "The copysign function of C returns a variable with the sign of other variables. The returned variables have the magnitude of the first variable and sign of the second variable."
},
{
"code": null,
"e": 3112,
"s": 3101,
"text": " Live Demo"
},
{
"code": null,
"e": 3306,
"s": 3112,
"text": "#include <iostream>\n#include <cmath>\nusing namespace std;\nint main(){\n double a, b;\n a = 9.6;\n b = -3.5;\n cout<<\"copysign function with inputs \"<<a<<\" and \"<<b<<\" is \"<<copysign(a,b);\n}"
},
{
"code": null,
"e": 3357,
"s": 3306,
"text": "Copysign function with inputs 9.6 and -3.5 is -9.6"
},
{
"code": null,
"e": 3501,
"s": 3357,
"text": "The fmin function as you can see from its name returns that the minimum value of the two arguments of the function. The return type is a float."
},
{
"code": null,
"e": 3512,
"s": 3501,
"text": " Live Demo"
},
{
"code": null,
"e": 3706,
"s": 3512,
"text": "#include <iostream>\n#include <cmath>\nusing namespace std;\nint main(){\n double a, b;\n a = 43.5;\n b = 21.2;\n cout << \"The smallest of \"<<a<<\" and \"<<b<<\" is \"; cout << fmin(a,b)<<endl;\n}\n"
},
{
"code": null,
"e": 3744,
"s": 3706,
"text": "The smallest of 43.5 and 21.2 is 21.2"
},
{
"code": null,
"e": 3859,
"s": 3744,
"text": "The fmax function is a C programming function that returns the largest number of the two numbers in the arguments."
},
{
"code": null,
"e": 3870,
"s": 3859,
"text": " Live Demo"
},
{
"code": null,
"e": 4062,
"s": 3870,
"text": "#include <iostream>\n#include <cmath>\nusing namespace std;\nint main(){\n double a, b;\n a = 43.5;\n b = 21.2;\n cout << \"The largest of \"<<a<<\" and \"<<b<<\" is \"; cout << fmax(a,b)<<endl;\n}"
},
{
"code": null,
"e": 4099,
"s": 4062,
"text": "The largest of 43.5 and 21.2 is 43.5"
},
{
"code": null,
"e": 4248,
"s": 4099,
"text": "The fdim() function of the C programming language returns the absolute difference of the two numbers that are sent as the arguments to the function."
},
{
"code": null,
"e": 4259,
"s": 4248,
"text": " Live Demo"
},
{
"code": null,
"e": 4465,
"s": 4259,
"text": "#include <iostream>\n#include <cmath>\nusing namespace std;\nint main(){\n double a, b;\n a = 43.5;\n b = 21.2;\n cout << \"The absolute difference of \"<<a<<\" and \"<<b<<\" is\";\n cout << fdim(a,b)<<endl;\n}"
},
{
"code": null,
"e": 4514,
"s": 4465,
"text": "The absolute difference of 43.5 and 21.2 is 22.3"
},
{
"code": null,
"e": 4663,
"s": 4514,
"text": "The fma() function of C, returns the multiplication of the arguments given to it. The function returns a float and accepts three floating arguments."
},
{
"code": null,
"e": 4674,
"s": 4663,
"text": " Live Demo"
},
{
"code": null,
"e": 4900,
"s": 4674,
"text": "#include <iostream>\n#include <cmath>\nusing namespace std;\nint main(){\n double a, b, c;\n a = 3.5;\n b = 2.4;\n c = 7.2;\n cout << \"The multiplication of \"<<a<<\" , \"<<b<<\" and \"<<c<<\" is \";\n cout << fma(a,b,c)<<endl;\n}"
},
{
"code": null,
"e": 4948,
"s": 4900,
"text": "The multiplication of 3.5 , 2.4 and 7.2 is 15.6"
},
{
"code": null,
"e": 5081,
"s": 4948,
"text": "These are all the functions that are operated over floating-point numbers.\nThese are the functions that are defined in cmath library"
}
] |
Updating Nested Embedded Documents in MongoDB? | To update bested documents in MongDB, use UPDATE() and positional($) operator. Let us create a collection with documents −
> db.demo643.insertOne({
... details : [
... {
... "CountryName":"US",
... StudentDetails:[{Name:"Chris"},{SubjectName:"MySQL"}]
... },
...
... {
... "CountryName":"UK",
... StudentDetails:[{Name:"Bob"},{SubjectName:"Java"}]
... }
... ]
... }
... )
{
"acknowledged" : true,
"insertedId" : ObjectId("5e9c737f6c954c74be91e6e3")
}
Display all documents from a collection with the help of find() method −
> db.demo643.find();
This will produce the following output −
{ "_id" : ObjectId("5e9c737f6c954c74be91e6e3"), "details" : [ { "CountryName" : "US", "StudentDetails" : [ { "Name" : "Chris" }, { "SubjectName" : "MySQL" } ] }, { "CountryName" : "UK", "StudentDetails" : [ { "Name" : "Bob" }, { "SubjectName" : "Java" } ] } ] }
Following is the query to update nested embedded documents in MongoDB −
> db.demo643.update({"details.CountryName": "UK"}, {"$push": {"details.$.StudentDetails": {Marks:78}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo643.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5e9c737f6c954c74be91e6e3"),
"details" : [
{
"CountryName" : "US",
"StudentDetails" : [
{
"Name" : "Chris"
},
{
"SubjectName" : "MySQL"
}
]
},
{
"CountryName" : "UK",
"StudentDetails" : [
{
"Name" : "Bob"
},
{
"SubjectName" : "Java"
},
{
"Marks" : 78
}
]
}
]
} | [
{
"code": null,
"e": 1185,
"s": 1062,
"text": "To update bested documents in MongDB, use UPDATE() and positional($) operator. Let us create a collection with documents −"
},
{
"code": null,
"e": 1585,
"s": 1185,
"text": "> db.demo643.insertOne({\n... details : [\n... {\n... \"CountryName\":\"US\",\n... StudentDetails:[{Name:\"Chris\"},{SubjectName:\"MySQL\"}]\n... },\n...\n... {\n... \"CountryName\":\"UK\",\n... StudentDetails:[{Name:\"Bob\"},{SubjectName:\"Java\"}]\n... }\n... ]\n... }\n... )\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e9c737f6c954c74be91e6e3\")\n}"
},
{
"code": null,
"e": 1658,
"s": 1585,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1679,
"s": 1658,
"text": "> db.demo643.find();"
},
{
"code": null,
"e": 1720,
"s": 1679,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1982,
"s": 1720,
"text": "{ \"_id\" : ObjectId(\"5e9c737f6c954c74be91e6e3\"), \"details\" : [ { \"CountryName\" : \"US\", \"StudentDetails\" : [ { \"Name\" : \"Chris\" }, { \"SubjectName\" : \"MySQL\" } ] }, { \"CountryName\" : \"UK\", \"StudentDetails\" : [ { \"Name\" : \"Bob\" }, { \"SubjectName\" : \"Java\" } ] } ] }"
},
{
"code": null,
"e": 2054,
"s": 1982,
"text": "Following is the query to update nested embedded documents in MongoDB −"
},
{
"code": null,
"e": 2224,
"s": 2054,
"text": "> db.demo643.update({\"details.CountryName\": \"UK\"}, {\"$push\": {\"details.$.StudentDetails\": {Marks:78}}})\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })"
},
{
"code": null,
"e": 2297,
"s": 2224,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 2327,
"s": 2297,
"text": "> db.demo643.find().pretty();"
},
{
"code": null,
"e": 2368,
"s": 2327,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2930,
"s": 2368,
"text": "{\n \"_id\" : ObjectId(\"5e9c737f6c954c74be91e6e3\"),\n \"details\" : [\n {\n \"CountryName\" : \"US\",\n \"StudentDetails\" : [\n {\n \"Name\" : \"Chris\"\n },\n {\n \"SubjectName\" : \"MySQL\"\n }\n ]\n },\n {\n \"CountryName\" : \"UK\",\n \"StudentDetails\" : [\n {\n \"Name\" : \"Bob\"\n },\n {\n \"SubjectName\" : \"Java\"\n },\n {\n \"Marks\" : 78\n }\n ]\n }\n ]\n}"
}
] |
Java - Thread Synchronization | When we start two or more threads within a program, there may be a situation when multiple threads try to access the same resource and finally they can produce unforeseen result due to concurrency issues. For example, if multiple threads try to write within a same file then they may corrupt the data because one of the threads can override data or while one thread is opening the same file at the same time another thread might be closing the same file.
So there is a need to synchronize the action of multiple threads and make sure that only one thread can access the resource at a given point in time. This is implemented using a concept called monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor.
Java programming language provides a very handy way of creating threads and synchronizing their task by using synchronized blocks. You keep shared resources within this block. Following is the general form of the synchronized statement −
synchronized(objectidentifier) {
// Access shared variables and other shared resources
}
Here, the objectidentifier is a reference to an object whose lock associates with the monitor that the synchronized statement represents. Now we are going to see two examples, where we will print a counter using two different threads. When threads are not synchronized, they print counter value which is not in sequence, but when we print counter by putting inside synchronized() block, then it prints counter very much in sequence for both the threads.
Here is a simple example which may or may not print counter value in sequence and every time we run it, it produces a different result based on CPU availability to a thread.
class PrintDemo {
public void printCount() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i );
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
PrintDemo PD;
ThreadDemo( String name, PrintDemo pd) {
threadName = name;
PD = pd;
}
public void run() {
PD.printCount();
System.out.println("Thread " + threadName + " exiting.");
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
PrintDemo PD = new PrintDemo();
ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );
ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );
T1.start();
T2.start();
// wait for threads to end
try {
T1.join();
T2.join();
} catch ( Exception e) {
System.out.println("Interrupted");
}
}
}
This produces a different result every time you run this program −
Starting Thread - 1
Starting Thread - 2
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 5
Counter --- 2
Counter --- 1
Counter --- 4
Thread Thread - 1 exiting.
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 2 exiting.
Here is the same example which prints counter value in sequence and every time we run it, it produces the same result.
class PrintDemo {
public void printCount() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i );
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
PrintDemo PD;
ThreadDemo( String name, PrintDemo pd) {
threadName = name;
PD = pd;
}
public void run() {
synchronized(PD) {
PD.printCount();
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
PrintDemo PD = new PrintDemo();
ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );
ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );
T1.start();
T2.start();
// wait for threads to end
try {
T1.join();
T2.join();
} catch ( Exception e) {
System.out.println("Interrupted");
}
}
}
This produces the same result every time you run this program −
Starting Thread - 1
Starting Thread - 2
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 1 exiting.
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 2 exiting.
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": 2832,
"s": 2377,
"text": "When we start two or more threads within a program, there may be a situation when multiple threads try to access the same resource and finally they can produce unforeseen result due to concurrency issues. For example, if multiple threads try to write within a same file then they may corrupt the data because one of the threads can override data or while one thread is opening the same file at the same time another thread might be closing the same file."
},
{
"code": null,
"e": 3176,
"s": 2832,
"text": "So there is a need to synchronize the action of multiple threads and make sure that only one thread can access the resource at a given point in time. This is implemented using a concept called monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor."
},
{
"code": null,
"e": 3414,
"s": 3176,
"text": "Java programming language provides a very handy way of creating threads and synchronizing their task by using synchronized blocks. You keep shared resources within this block. Following is the general form of the synchronized statement −"
},
{
"code": null,
"e": 3507,
"s": 3414,
"text": "synchronized(objectidentifier) {\n // Access shared variables and other shared resources\n}\n"
},
{
"code": null,
"e": 3961,
"s": 3507,
"text": "Here, the objectidentifier is a reference to an object whose lock associates with the monitor that the synchronized statement represents. Now we are going to see two examples, where we will print a counter using two different threads. When threads are not synchronized, they print counter value which is not in sequence, but when we print counter by putting inside synchronized() block, then it prints counter very much in sequence for both the threads."
},
{
"code": null,
"e": 4135,
"s": 3961,
"text": "Here is a simple example which may or may not print counter value in sequence and every time we run it, it produces a different result based on CPU availability to a thread."
},
{
"code": null,
"e": 5344,
"s": 4135,
"text": "class PrintDemo {\n public void printCount() {\n try {\n for(int i = 5; i > 0; i--) {\n System.out.println(\"Counter --- \" + i );\n }\n } catch (Exception e) {\n System.out.println(\"Thread interrupted.\");\n }\n }\n}\n\nclass ThreadDemo extends Thread {\n private Thread t;\n private String threadName;\n PrintDemo PD;\n\n ThreadDemo( String name, PrintDemo pd) {\n threadName = name;\n PD = pd;\n }\n \n public void run() {\n PD.printCount();\n System.out.println(\"Thread \" + threadName + \" exiting.\");\n }\n\n public void start () {\n System.out.println(\"Starting \" + threadName );\n if (t == null) {\n t = new Thread (this, threadName);\n t.start ();\n }\n }\n}\n\npublic class TestThread {\n public static void main(String args[]) {\n\n PrintDemo PD = new PrintDemo();\n\n ThreadDemo T1 = new ThreadDemo( \"Thread - 1 \", PD );\n ThreadDemo T2 = new ThreadDemo( \"Thread - 2 \", PD );\n\n T1.start();\n T2.start();\n\n // wait for threads to end\n try {\n T1.join();\n T2.join();\n } catch ( Exception e) {\n System.out.println(\"Interrupted\");\n }\n }\n}"
},
{
"code": null,
"e": 5411,
"s": 5344,
"text": "This produces a different result every time you run this program −"
},
{
"code": null,
"e": 5688,
"s": 5411,
"text": "Starting Thread - 1\nStarting Thread - 2\nCounter --- 5\nCounter --- 4\nCounter --- 3\nCounter --- 5\nCounter --- 2\nCounter --- 1\nCounter --- 4\nThread Thread - 1 exiting.\nCounter --- 3\nCounter --- 2\nCounter --- 1\nThread Thread - 2 exiting.\n"
},
{
"code": null,
"e": 5807,
"s": 5688,
"text": "Here is the same example which prints counter value in sequence and every time we run it, it produces the same result."
},
{
"code": null,
"e": 7049,
"s": 5807,
"text": "class PrintDemo {\n public void printCount() {\n try {\n for(int i = 5; i > 0; i--) {\n System.out.println(\"Counter --- \" + i );\n }\n } catch (Exception e) {\n System.out.println(\"Thread interrupted.\");\n }\n }\n}\n\nclass ThreadDemo extends Thread {\n private Thread t;\n private String threadName;\n PrintDemo PD;\n\n ThreadDemo( String name, PrintDemo pd) {\n threadName = name;\n PD = pd;\n }\n \n public void run() {\n synchronized(PD) {\n PD.printCount();\n }\n System.out.println(\"Thread \" + threadName + \" exiting.\");\n }\n\n public void start () {\n System.out.println(\"Starting \" + threadName );\n if (t == null) {\n t = new Thread (this, threadName);\n t.start ();\n }\n }\n}\n\npublic class TestThread {\n\n public static void main(String args[]) {\n PrintDemo PD = new PrintDemo();\n\n ThreadDemo T1 = new ThreadDemo( \"Thread - 1 \", PD );\n ThreadDemo T2 = new ThreadDemo( \"Thread - 2 \", PD );\n\n T1.start();\n T2.start();\n\n // wait for threads to end\n try {\n T1.join();\n T2.join();\n } catch ( Exception e) {\n System.out.println(\"Interrupted\");\n }\n }\n}"
},
{
"code": null,
"e": 7113,
"s": 7049,
"text": "This produces the same result every time you run this program −"
},
{
"code": null,
"e": 7390,
"s": 7113,
"text": "Starting Thread - 1\nStarting Thread - 2\nCounter --- 5\nCounter --- 4\nCounter --- 3\nCounter --- 2\nCounter --- 1\nThread Thread - 1 exiting.\nCounter --- 5\nCounter --- 4\nCounter --- 3\nCounter --- 2\nCounter --- 1\nThread Thread - 2 exiting.\n"
},
{
"code": null,
"e": 7423,
"s": 7390,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7439,
"s": 7423,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7472,
"s": 7439,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 7488,
"s": 7472,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7523,
"s": 7488,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7537,
"s": 7523,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7571,
"s": 7537,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 7585,
"s": 7571,
"text": " Tushar Kale"
},
{
"code": null,
"e": 7622,
"s": 7585,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 7637,
"s": 7622,
"text": " Monica Mittal"
},
{
"code": null,
"e": 7670,
"s": 7637,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 7689,
"s": 7670,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7696,
"s": 7689,
"text": " Print"
},
{
"code": null,
"e": 7707,
"s": 7696,
"text": " Add Notes"
}
] |
Laravel - Error Handling | Most web applications have specific mechanisms for error handling. Using these, they track errors and exceptions, and log them to analyze the performance. In this chapter, you will read about error handling in Laravel applications.
Before proceeding further to learn in detail about error handling in Laravel, please note the following important points −
For any new project, Laravel logs errors and exceptions in the App\Exceptions\Handler class, by default. They are then submitted back to the user for analysis.
For any new project, Laravel logs errors and exceptions in the App\Exceptions\Handler class, by default. They are then submitted back to the user for analysis.
When your Laravel application is set in debug mode, detailed error messages with stack traces will be shown on every error that occurs within your web application.
When your Laravel application is set in debug mode, detailed error messages with stack traces will be shown on every error that occurs within your web application.
By default, debug mode is set to false and you can change it to true. This enables the user to track all errors with stack traces.
By default, debug mode is set to false and you can change it to true. This enables the user to track all errors with stack traces.
The configuration of Laravel project includes the debug option which determines how much information about an error is to be displayed to the user. By default in a web application, the option is set to the value defined in the environment variables of the .env file.
The value is set to true in a local development environment and is set to false in a production environment.
If the value is set to true in a production environment, the risk of sharing sensitive information with the end users is higher.
The configuration of Laravel project includes the debug option which determines how much information about an error is to be displayed to the user. By default in a web application, the option is set to the value defined in the environment variables of the .env file.
The value is set to true in a local development environment and is set to false in a production environment.
The value is set to true in a local development environment and is set to false in a production environment.
If the value is set to true in a production environment, the risk of sharing sensitive information with the end users is higher.
If the value is set to true in a production environment, the risk of sharing sensitive information with the end users is higher.
Logging the errors in a web application helps to track them and in planning a strategy for removing them. The log information can be configured in the web application in config/app.php file. Please note the following points while dealing with Error Log in Laravel −
Laravel uses monolog PHP logging library.
Laravel uses monolog PHP logging library.
The logging parameters used for error tracking are single, daily, syslog and errorlog.
The logging parameters used for error tracking are single, daily, syslog and errorlog.
For example, if you wish to log the error messages in log files, you should set the log value in your app configuration to daily as shown in the command below −
For example, if you wish to log the error messages in log files, you should set the log value in your app configuration to daily as shown in the command below −
'log' => env('APP_LOG',’daily’),
If the daily log mode is taken as the parameter, Laravel takes error log for a period of 5 days, by default. If you wish to change the maximum number of log files, you have to set the parameter of log_max_files in the configuration file to a desired value.
If the daily log mode is taken as the parameter, Laravel takes error log for a period of 5 days, by default. If you wish to change the maximum number of log files, you have to set the parameter of log_max_files in the configuration file to a desired value.
‘log_max_files’ => 25;
As Laravel uses monolog PHP logging library, there are various parameters used for analyzing severity levels. Various severity levels that are available are error, critical, alert and emergency messages. You can set the severity level as shown in the command below −
'log_level' => env('APP_LOG_LEVEL', 'error')
13 Lectures
3 hours
Sebastian Sulinski
35 Lectures
3.5 hours
Antonio Papa
7 Lectures
1.5 hours
Sebastian Sulinski
42 Lectures
1 hours
Skillbakerystudios
165 Lectures
13 hours
Paul Carlo Tordecilla
116 Lectures
13 hours
Hafizullah Masoudi
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2704,
"s": 2472,
"text": "Most web applications have specific mechanisms for error handling. Using these, they track errors and exceptions, and log them to analyze the performance. In this chapter, you will read about error handling in Laravel applications."
},
{
"code": null,
"e": 2827,
"s": 2704,
"text": "Before proceeding further to learn in detail about error handling in Laravel, please note the following important points −"
},
{
"code": null,
"e": 2987,
"s": 2827,
"text": "For any new project, Laravel logs errors and exceptions in the App\\Exceptions\\Handler class, by default. They are then submitted back to the user for analysis."
},
{
"code": null,
"e": 3147,
"s": 2987,
"text": "For any new project, Laravel logs errors and exceptions in the App\\Exceptions\\Handler class, by default. They are then submitted back to the user for analysis."
},
{
"code": null,
"e": 3311,
"s": 3147,
"text": "When your Laravel application is set in debug mode, detailed error messages with stack traces will be shown on every error that occurs within your web application."
},
{
"code": null,
"e": 3475,
"s": 3311,
"text": "When your Laravel application is set in debug mode, detailed error messages with stack traces will be shown on every error that occurs within your web application."
},
{
"code": null,
"e": 3606,
"s": 3475,
"text": "By default, debug mode is set to false and you can change it to true. This enables the user to track all errors with stack traces."
},
{
"code": null,
"e": 3737,
"s": 3606,
"text": "By default, debug mode is set to false and you can change it to true. This enables the user to track all errors with stack traces."
},
{
"code": null,
"e": 4245,
"s": 3737,
"text": "The configuration of Laravel project includes the debug option which determines how much information about an error is to be displayed to the user. By default in a web application, the option is set to the value defined in the environment variables of the .env file.\n\nThe value is set to true in a local development environment and is set to false in a production environment.\nIf the value is set to true in a production environment, the risk of sharing sensitive information with the end users is higher.\n\n"
},
{
"code": null,
"e": 4512,
"s": 4245,
"text": "The configuration of Laravel project includes the debug option which determines how much information about an error is to be displayed to the user. By default in a web application, the option is set to the value defined in the environment variables of the .env file."
},
{
"code": null,
"e": 4621,
"s": 4512,
"text": "The value is set to true in a local development environment and is set to false in a production environment."
},
{
"code": null,
"e": 4730,
"s": 4621,
"text": "The value is set to true in a local development environment and is set to false in a production environment."
},
{
"code": null,
"e": 4859,
"s": 4730,
"text": "If the value is set to true in a production environment, the risk of sharing sensitive information with the end users is higher."
},
{
"code": null,
"e": 4988,
"s": 4859,
"text": "If the value is set to true in a production environment, the risk of sharing sensitive information with the end users is higher."
},
{
"code": null,
"e": 5254,
"s": 4988,
"text": "Logging the errors in a web application helps to track them and in planning a strategy for removing them. The log information can be configured in the web application in config/app.php file. Please note the following points while dealing with Error Log in Laravel −"
},
{
"code": null,
"e": 5296,
"s": 5254,
"text": "Laravel uses monolog PHP logging library."
},
{
"code": null,
"e": 5338,
"s": 5296,
"text": "Laravel uses monolog PHP logging library."
},
{
"code": null,
"e": 5425,
"s": 5338,
"text": "The logging parameters used for error tracking are single, daily, syslog and errorlog."
},
{
"code": null,
"e": 5512,
"s": 5425,
"text": "The logging parameters used for error tracking are single, daily, syslog and errorlog."
},
{
"code": null,
"e": 5673,
"s": 5512,
"text": "For example, if you wish to log the error messages in log files, you should set the log value in your app configuration to daily as shown in the command below −"
},
{
"code": null,
"e": 5834,
"s": 5673,
"text": "For example, if you wish to log the error messages in log files, you should set the log value in your app configuration to daily as shown in the command below −"
},
{
"code": null,
"e": 5868,
"s": 5834,
"text": "'log' => env('APP_LOG',’daily’),\n"
},
{
"code": null,
"e": 6125,
"s": 5868,
"text": "If the daily log mode is taken as the parameter, Laravel takes error log for a period of 5 days, by default. If you wish to change the maximum number of log files, you have to set the parameter of log_max_files in the configuration file to a desired value."
},
{
"code": null,
"e": 6382,
"s": 6125,
"text": "If the daily log mode is taken as the parameter, Laravel takes error log for a period of 5 days, by default. If you wish to change the maximum number of log files, you have to set the parameter of log_max_files in the configuration file to a desired value."
},
{
"code": null,
"e": 6406,
"s": 6382,
"text": "‘log_max_files’ => 25;\n"
},
{
"code": null,
"e": 6673,
"s": 6406,
"text": "As Laravel uses monolog PHP logging library, there are various parameters used for analyzing severity levels. Various severity levels that are available are error, critical, alert and emergency messages. You can set the severity level as shown in the command below −"
},
{
"code": null,
"e": 6719,
"s": 6673,
"text": "'log_level' => env('APP_LOG_LEVEL', 'error')\n"
},
{
"code": null,
"e": 6752,
"s": 6719,
"text": "\n 13 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6772,
"s": 6752,
"text": " Sebastian Sulinski"
},
{
"code": null,
"e": 6807,
"s": 6772,
"text": "\n 35 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6821,
"s": 6807,
"text": " Antonio Papa"
},
{
"code": null,
"e": 6855,
"s": 6821,
"text": "\n 7 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6875,
"s": 6855,
"text": " Sebastian Sulinski"
},
{
"code": null,
"e": 6908,
"s": 6875,
"text": "\n 42 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6928,
"s": 6908,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 6963,
"s": 6928,
"text": "\n 165 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 6986,
"s": 6963,
"text": " Paul Carlo Tordecilla"
},
{
"code": null,
"e": 7021,
"s": 6986,
"text": "\n 116 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 7041,
"s": 7021,
"text": " Hafizullah Masoudi"
},
{
"code": null,
"e": 7048,
"s": 7041,
"text": " Print"
},
{
"code": null,
"e": 7059,
"s": 7048,
"text": " Add Notes"
}
] |
Minimum Swaps to Group All 1's Together in Python | Suppose we have a binary array data, we have to find the minimum number of swaps required to group all 1’s stored in the array together in any place in the array. So if the array is like [1,0,1,0,1,0,0,1,1,0,1], then the output will be 3, as possible solution is [0,0,0,0,0,1,1,1,1,1,1]
To solve this, we will follow these steps −
set one := 0, n:= length of data array
make an array summ of size n, and fill this with 0, set summ[0] := data[0]
one := one + data[0]
for i in range 1 to n – 1summ[i] := summ[i - 1] + data[i]one := one + data[i]
summ[i] := summ[i - 1] + data[i]
one := one + data[i]
ans := one
left := 0, right := one – 1
while right < nif left is 0, then temp := summ[right], otherwise temp := summ[right] – summ[left - 1]ans := minimum of ans, one – tempincrease right and left by 1
if left is 0, then temp := summ[right], otherwise temp := summ[right] – summ[left - 1]
ans := minimum of ans, one – temp
increase right and left by 1
return ans
Let us see the following implementation to get better understanding −
Live Demo
class Solution(object):
def minSwaps(self, data):
one = 0
n = len(data)
summ=[0 for i in range(n)]
summ[0] = data[0]
one += data[0]
for i in range(1,n):
summ[i] += summ[i-1]+data[i]
one += data[i]
ans = one
left = 0
right = one-1
while right <n:
if left == 0:
temp = summ[right]
else:
temp = summ[right] - summ[left-1]
ans = min(ans,one-temp)
right+=1
left+=1
return ans
ob = Solution()
print(ob.minSwaps([1,0,1,0,1,0,0,1,1,0,1]))
[1,0,1,0,1,0,0,1,1,0,1]
3 | [
{
"code": null,
"e": 1349,
"s": 1062,
"text": "Suppose we have a binary array data, we have to find the minimum number of swaps required to group all 1’s stored in the array together in any place in the array. So if the array is like [1,0,1,0,1,0,0,1,1,0,1], then the output will be 3, as possible solution is [0,0,0,0,0,1,1,1,1,1,1]"
},
{
"code": null,
"e": 1393,
"s": 1349,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1432,
"s": 1393,
"text": "set one := 0, n:= length of data array"
},
{
"code": null,
"e": 1507,
"s": 1432,
"text": "make an array summ of size n, and fill this with 0, set summ[0] := data[0]"
},
{
"code": null,
"e": 1528,
"s": 1507,
"text": "one := one + data[0]"
},
{
"code": null,
"e": 1606,
"s": 1528,
"text": "for i in range 1 to n – 1summ[i] := summ[i - 1] + data[i]one := one + data[i]"
},
{
"code": null,
"e": 1639,
"s": 1606,
"text": "summ[i] := summ[i - 1] + data[i]"
},
{
"code": null,
"e": 1660,
"s": 1639,
"text": "one := one + data[i]"
},
{
"code": null,
"e": 1671,
"s": 1660,
"text": "ans := one"
},
{
"code": null,
"e": 1699,
"s": 1671,
"text": "left := 0, right := one – 1"
},
{
"code": null,
"e": 1862,
"s": 1699,
"text": "while right < nif left is 0, then temp := summ[right], otherwise temp := summ[right] – summ[left - 1]ans := minimum of ans, one – tempincrease right and left by 1"
},
{
"code": null,
"e": 1949,
"s": 1862,
"text": "if left is 0, then temp := summ[right], otherwise temp := summ[right] – summ[left - 1]"
},
{
"code": null,
"e": 1983,
"s": 1949,
"text": "ans := minimum of ans, one – temp"
},
{
"code": null,
"e": 2012,
"s": 1983,
"text": "increase right and left by 1"
},
{
"code": null,
"e": 2023,
"s": 2012,
"text": "return ans"
},
{
"code": null,
"e": 2093,
"s": 2023,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2104,
"s": 2093,
"text": " Live Demo"
},
{
"code": null,
"e": 2691,
"s": 2104,
"text": "class Solution(object):\n def minSwaps(self, data):\n one = 0\n n = len(data)\n summ=[0 for i in range(n)]\n summ[0] = data[0]\n one += data[0]\n for i in range(1,n):\n summ[i] += summ[i-1]+data[i]\n one += data[i]\n ans = one\n left = 0\n right = one-1\n while right <n:\n if left == 0:\n temp = summ[right]\n else:\n temp = summ[right] - summ[left-1]\n ans = min(ans,one-temp)\n right+=1\n left+=1\n return ans\nob = Solution()\nprint(ob.minSwaps([1,0,1,0,1,0,0,1,1,0,1]))"
},
{
"code": null,
"e": 2715,
"s": 2691,
"text": "[1,0,1,0,1,0,0,1,1,0,1]"
},
{
"code": null,
"e": 2717,
"s": 2715,
"text": "3"
}
] |
RESTful APIs in Python. What are RESTful APIs and implementing... | by Shivangi Sareen | Towards Data Science | API is a hypothetical contract between two softwares. Web APIs have made it easy for cross-language applications to work well.
Application Programming Interfaces are commonly used to retrieve data from remote websites. To make a request to a remote web server and retrieve data, we make use of the URL endpoint from where the API is being served. Each URL is called a request and the data that is sent back is called a response.
A RESTful API is an application program interface that uses HTTP requests to GET, PUT, POST and DELETE data. REST based interactions use constraints that are familiar to anyone well known with HTTP. And the interactions communicate their status using standard HTTP status codes.
Data is constantly changingYou want a small piece of a much larger pool of data
Data is constantly changing
You want a small piece of a much larger pool of data
APIs are hosted on web servers.
When we type www.google.com in the browser’s address bar, the computer is actually asking the www.google.com server for a webpage, which it then returns to the browser.
APIs work in much the same way except instead of the web browser asking for a webpage, the program asks for data.
This data is returned in JSON format.
In order to get the data, we make a request to a web server. The server then replies with the data. In Python, we make use of the requests library to do this.
Most commonly used request is the GET request which is used to retrieve data. GET requests will be the focus of this article.
The root endpoint is the starting point of the API we are requesting from. It completes the path which determines the resource that is being requested. E.g.- https://www.google.com/maps. /maps is the endpoint, https://www.google.com is the starting URL.
GET — Get a resource from a server.
POST — Create a new resource on the server.
PUT, PATCH — Update a request on the server.
DELETE — Delete a resource from the server.
1xx: Informational: Communicates transfer protocol-level information.
2xx: Success: Client’s request was accepted successfully.
3xx: Redirection: Client must take some additional action in order to complete their request.
4xx: Client Error: Client side error.
5xx: Server Error: Server side error.
JSON is the primary format in which data is passed back and forth to APIs and most API servers will send their responses in JSON format — a single string containing a JSON object.
JSON is a way to encode data structures like lists and dictionaries to strings that ensure that they are easily readable by machines.
So, lists and dictionaries can be converted to JSON and strings can be converted to lists and dictionaries.
JSON looks much like a dictionary in Python, with key-value pairs stored.
We’ll be implementing a single case scenario which makes up for most scenarios of GET requests.
import jsonimport requestsimport urllib.parse
Some GET requests are made up of endpoints that have path parameters which aren’t optional and very much a part of the endpoint, e.g.- /volunteer/{volunteerID}/badge/{badgeID}
volunteerID and badgeID need to be passed into the complete URL so as to complete the GET request.
This is where we make use of urllib.parse.
Suppose we have a list of volunteerIDs and badgeIDs in a JSON file that we want to input into the endpoint, call the API and get the resulting information.
#reading in the JSON filewith open(‘volunteer_data.json’, ‘r’) as text_file_input: data=text_file_input.read()#loading that file as a JSON objectobj = json.loads(data)
Next step is to set the URL.
API_ENDPOINT = ‘https://registeredvolunteers.xyz.com/volunteer/{}/badge/{}'
Now, let’s get a for loop running to call the API.
#we pass on the arguments volunteerID and badgeID for i in obj: r=requests.get(API_ENDPOINT.format(urllib.parse.quote(i[‘volunteerID’]),i[‘badgeID’])) print(r.text)#outside for looptext_file_input.close()
Note that if you’re expecting a JSON output, r.text will give you a single string consisting of a JSON object. To extract the JSON object from it, we:
output_json = json.loads(r.text)#or directly user.json()
To get the status code and the reason of that status code of the request,
r.status_coder.reason
The above scenario covers the different cases of GET requests — whether you need to pass URL parameters or not, and if those parameters, that are passed in, are stored in a file (or not); and the different properties of GET requests that you can explore to understand the data received.
GET a head start in REST APIs! | [
{
"code": null,
"e": 299,
"s": 172,
"text": "API is a hypothetical contract between two softwares. Web APIs have made it easy for cross-language applications to work well."
},
{
"code": null,
"e": 601,
"s": 299,
"text": "Application Programming Interfaces are commonly used to retrieve data from remote websites. To make a request to a remote web server and retrieve data, we make use of the URL endpoint from where the API is being served. Each URL is called a request and the data that is sent back is called a response."
},
{
"code": null,
"e": 880,
"s": 601,
"text": "A RESTful API is an application program interface that uses HTTP requests to GET, PUT, POST and DELETE data. REST based interactions use constraints that are familiar to anyone well known with HTTP. And the interactions communicate their status using standard HTTP status codes."
},
{
"code": null,
"e": 960,
"s": 880,
"text": "Data is constantly changingYou want a small piece of a much larger pool of data"
},
{
"code": null,
"e": 988,
"s": 960,
"text": "Data is constantly changing"
},
{
"code": null,
"e": 1041,
"s": 988,
"text": "You want a small piece of a much larger pool of data"
},
{
"code": null,
"e": 1073,
"s": 1041,
"text": "APIs are hosted on web servers."
},
{
"code": null,
"e": 1242,
"s": 1073,
"text": "When we type www.google.com in the browser’s address bar, the computer is actually asking the www.google.com server for a webpage, which it then returns to the browser."
},
{
"code": null,
"e": 1356,
"s": 1242,
"text": "APIs work in much the same way except instead of the web browser asking for a webpage, the program asks for data."
},
{
"code": null,
"e": 1394,
"s": 1356,
"text": "This data is returned in JSON format."
},
{
"code": null,
"e": 1553,
"s": 1394,
"text": "In order to get the data, we make a request to a web server. The server then replies with the data. In Python, we make use of the requests library to do this."
},
{
"code": null,
"e": 1679,
"s": 1553,
"text": "Most commonly used request is the GET request which is used to retrieve data. GET requests will be the focus of this article."
},
{
"code": null,
"e": 1933,
"s": 1679,
"text": "The root endpoint is the starting point of the API we are requesting from. It completes the path which determines the resource that is being requested. E.g.- https://www.google.com/maps. /maps is the endpoint, https://www.google.com is the starting URL."
},
{
"code": null,
"e": 1969,
"s": 1933,
"text": "GET — Get a resource from a server."
},
{
"code": null,
"e": 2013,
"s": 1969,
"text": "POST — Create a new resource on the server."
},
{
"code": null,
"e": 2058,
"s": 2013,
"text": "PUT, PATCH — Update a request on the server."
},
{
"code": null,
"e": 2102,
"s": 2058,
"text": "DELETE — Delete a resource from the server."
},
{
"code": null,
"e": 2172,
"s": 2102,
"text": "1xx: Informational: Communicates transfer protocol-level information."
},
{
"code": null,
"e": 2230,
"s": 2172,
"text": "2xx: Success: Client’s request was accepted successfully."
},
{
"code": null,
"e": 2324,
"s": 2230,
"text": "3xx: Redirection: Client must take some additional action in order to complete their request."
},
{
"code": null,
"e": 2362,
"s": 2324,
"text": "4xx: Client Error: Client side error."
},
{
"code": null,
"e": 2400,
"s": 2362,
"text": "5xx: Server Error: Server side error."
},
{
"code": null,
"e": 2580,
"s": 2400,
"text": "JSON is the primary format in which data is passed back and forth to APIs and most API servers will send their responses in JSON format — a single string containing a JSON object."
},
{
"code": null,
"e": 2714,
"s": 2580,
"text": "JSON is a way to encode data structures like lists and dictionaries to strings that ensure that they are easily readable by machines."
},
{
"code": null,
"e": 2822,
"s": 2714,
"text": "So, lists and dictionaries can be converted to JSON and strings can be converted to lists and dictionaries."
},
{
"code": null,
"e": 2896,
"s": 2822,
"text": "JSON looks much like a dictionary in Python, with key-value pairs stored."
},
{
"code": null,
"e": 2992,
"s": 2896,
"text": "We’ll be implementing a single case scenario which makes up for most scenarios of GET requests."
},
{
"code": null,
"e": 3038,
"s": 2992,
"text": "import jsonimport requestsimport urllib.parse"
},
{
"code": null,
"e": 3214,
"s": 3038,
"text": "Some GET requests are made up of endpoints that have path parameters which aren’t optional and very much a part of the endpoint, e.g.- /volunteer/{volunteerID}/badge/{badgeID}"
},
{
"code": null,
"e": 3313,
"s": 3214,
"text": "volunteerID and badgeID need to be passed into the complete URL so as to complete the GET request."
},
{
"code": null,
"e": 3356,
"s": 3313,
"text": "This is where we make use of urllib.parse."
},
{
"code": null,
"e": 3512,
"s": 3356,
"text": "Suppose we have a list of volunteerIDs and badgeIDs in a JSON file that we want to input into the endpoint, call the API and get the resulting information."
},
{
"code": null,
"e": 3683,
"s": 3512,
"text": "#reading in the JSON filewith open(‘volunteer_data.json’, ‘r’) as text_file_input: data=text_file_input.read()#loading that file as a JSON objectobj = json.loads(data)"
},
{
"code": null,
"e": 3712,
"s": 3683,
"text": "Next step is to set the URL."
},
{
"code": null,
"e": 3788,
"s": 3712,
"text": "API_ENDPOINT = ‘https://registeredvolunteers.xyz.com/volunteer/{}/badge/{}'"
},
{
"code": null,
"e": 3839,
"s": 3788,
"text": "Now, let’s get a for loop running to call the API."
},
{
"code": null,
"e": 4052,
"s": 3839,
"text": "#we pass on the arguments volunteerID and badgeID for i in obj: r=requests.get(API_ENDPOINT.format(urllib.parse.quote(i[‘volunteerID’]),i[‘badgeID’])) print(r.text)#outside for looptext_file_input.close()"
},
{
"code": null,
"e": 4203,
"s": 4052,
"text": "Note that if you’re expecting a JSON output, r.text will give you a single string consisting of a JSON object. To extract the JSON object from it, we:"
},
{
"code": null,
"e": 4260,
"s": 4203,
"text": "output_json = json.loads(r.text)#or directly user.json()"
},
{
"code": null,
"e": 4334,
"s": 4260,
"text": "To get the status code and the reason of that status code of the request,"
},
{
"code": null,
"e": 4356,
"s": 4334,
"text": "r.status_coder.reason"
},
{
"code": null,
"e": 4643,
"s": 4356,
"text": "The above scenario covers the different cases of GET requests — whether you need to pass URL parameters or not, and if those parameters, that are passed in, are stored in a file (or not); and the different properties of GET requests that you can explore to understand the data received."
}
] |
Perl - DBI(Database Independent) Module | Set - 2 - GeeksforGeeks | 10 Jul, 2020
Perl allows the handling of Databases with the help of Perl Scripts. These scripts run with the help of a module known as DBI(Database Independent Interface) module. DBI module provides an API to interact with many databases such as MySQL, Oracle, etc. This module provides a set of variables and methods that provide interaction with a database interface and need not access the original database.
To create a table in Perl, first we have to create a database in SQL. To do so, we will execute the following statement in SQL prompt:
CREATE DATABASE EMP_DB;
Now, a database by the name EMP_DB will web created. We will use this database to store record of employees in our database.
Now, we will connect to this database by using the following command –
my $dbh = DBI->connect("dbi:$driver:$dsn", $username, $passwd, { AutoCommit => 1 })
Now, our connection to the database will be established and we will use the following statement to create a table, EMP_DEATAILS, to hold the record of employee’s details.
my $sth = $dbh->prepare(“CREATE TABLE EMP_DETAILS ( ID INT PRIMARY KEY, EMP_NAME VARCHAR(50), AGE INT, SALARY INT)”);$sth->execute();
The full program for reference is given below :
#!/usr/bin/perl -wuse strict;use DBI;my $driver = "mysql";my $dsn = "database=EMP_DB";my $username = "root";my $passwd = "";my $dbh = DBI->connect("dbi:$driver:$dsn", $username, $passwd, { AutoCommit => 1 }) or die "Failed to connect to database : $DBI::errstr";my $sth = $dbh->prepare("CREATE TABLE EMP_DETAILS ( ID INT PRIMARY KEY, EMP_NAME VARCHAR(50), AGE INT, SALARY INT)"); $sth->execute();
Output:
Now that we have created EMP_DETAILS table in EMP_DB database, lets insert some values into the table by using the following statements :
#$dbh->do("INSERT INTO EMP_DETAILS (ID, EMP_NAME, AGE, SALARY) VALUES (71, 'CHINMAY', 23, 10000)") or die "Failed to insert : $DBI::errstr"; #$dbh->do("INSERT INTO EMP_DETAILS (ID, EMP_NAME, AGE, SALARY) VALUES (73, 'SANSKRUTI', 23, 15000)") or die "Failed to insert : $DBI::errstr"; $dbh->do("INSERT INTO EMP_DETAILS (ID, EMP_NAME, AGE, SALARY) VALUES (150, 'DEREK', 37, 20000)") or die "Failed to insert : $DBI::errstr"; $dbh->do("INSERT INTO EMP_DETAILS (ID, EMP_NAME, AGE, SALARY) VALUES (200, 'ROSS', 30, 24250)") or die "Failed to insert : $DBI::errstr";
Output:
Consider the below given program. In the program, we have used question marks(?) at some places. These question marks are known as placeholders. By using placeholders, the database driver can pre-process the query before executing it to the SQL prompt. This process is known as binding of data. Binding helps us in increasing the code security, which helps to prevent SQL injection attacks.
#!/usr/bin/perl -wuse strict;use DBI;my $driver = "mysql";my $dsn = "database=EMP_DB";my $username = "root";my $passwd = "";my $dbh = DBI->connect("dbi:$driver:$dsn", $username, $passwd, { AutoCommit => 1 }) or die "Failed to connect to database : $DBI::errstr"; # Inserting Bind Valuesprint "Enter Employee ID - ";my $id = <>;chomp($id); print "Enter Employee Name - ";my $name = <>;chomp($name); print "Enter Employee Age - ";my $age = <>;chomp($age); print "Enter Employee Salary - ";my $salary = <>;chomp($salary); my $sth = $dbh->prepare("INSERT INTO EMP_DETAILS ( ID, EMP_NAME, AGE, SALARY) VALUES (?, ?, ?, ?)"); $sth->execute($id, $name, $age, $salary) or die "Failed to insert : $DBI::errstr";
Output:
Our database is now populated with some values. Now we need to read them back to the user. To do so we will use while loop to read back data to the user.
#!/usr/bin/perl -wuse strict;use DBI;my $driver = "mysql";my $dsn = "database=EMP_DB";my $username = "root";my $passwd = "";my $dbh = DBI->connect("dbi:$driver:$dsn", $username, $passwd, { AutoCommit => 1 }) or die "Failed to connect to database : $DBI::errstr"; my $sth = $dbh->prepare("SELECT EMP_NAME, ID FROM EMP_DETAILS WHERE ID<100"); $sth->execute() or die "Failed to select rows : $DBI::errstr"; my $rows = $sth->rows;print "Number of rows updated : $rows \n"; while (my @emp_data = $sth->fetchrow_array()) { my ($name, $id ) = @emp_data; print "Employee Name = $name, Employee ID = $id \n";}$sth->finish();
Output:
To update any value of the table, we can use SQL UPDATE command in the following way :
#!/usr/bin/perl -wuse strict;use DBI;my $driver = "mysql";my $dsn = "database=EMP_DB";my $username = "root";my $passwd = "";my $dbh = DBI->connect("dbi:$driver:$dsn", $username, $passwd, { AutoCommit => 1 }) or die "Failed to connect to database : $DBI::errstr"; $dbh->do("UPDATE EMP_DETAILS SET ID=250 WHERE ID=150") or die "Failed to update : $DBI::errstr";
Output:
Original Table:
Table after Data Updation:
To delete a particular row from the table, we can use SQL DELETE statement in the following way :
#!/usr/bin/perl -wuse strict;use DBI;my $driver = "mysql";my $dsn = "database=EMP_DB";my $username = "root";my $passwd = "";my $dbh = DBI->connect("dbi:$driver:$dsn", $username, $passwd, { AutoCommit => 1 }) or die "Failed to connect to database : $DBI::errstr"; $dbh->do("DELETE FROM EMP_DETAILS WHERE ID=250") or die "Failed to delete : $DBI::errstr"; $dbh->do("DELETE FROM EMP_DETAILS WHERE EMP_NAME='ROSS'") or die "Failed to delete : $DBI::errstr";
Output:
Picked
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | Polymorphism in OOPs
Perl Tutorial - Learn Perl With Examples
Perl | length() Function
Perl | sleep() Function
Perl | Regex Cheat Sheet
Hello World Program in Perl
Introduction to Perl
Perl | Boolean Values
Perl | substitution Operator
Perl | Automatic String to Number Conversion or Casting | [
{
"code": null,
"e": 24034,
"s": 24006,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 24433,
"s": 24034,
"text": "Perl allows the handling of Databases with the help of Perl Scripts. These scripts run with the help of a module known as DBI(Database Independent Interface) module. DBI module provides an API to interact with many databases such as MySQL, Oracle, etc. This module provides a set of variables and methods that provide interaction with a database interface and need not access the original database."
},
{
"code": null,
"e": 24568,
"s": 24433,
"text": "To create a table in Perl, first we have to create a database in SQL. To do so, we will execute the following statement in SQL prompt:"
},
{
"code": null,
"e": 24592,
"s": 24568,
"text": "CREATE DATABASE EMP_DB;"
},
{
"code": null,
"e": 24717,
"s": 24592,
"text": "Now, a database by the name EMP_DB will web created. We will use this database to store record of employees in our database."
},
{
"code": null,
"e": 24788,
"s": 24717,
"text": "Now, we will connect to this database by using the following command –"
},
{
"code": null,
"e": 24872,
"s": 24788,
"text": "my $dbh = DBI->connect(\"dbi:$driver:$dsn\", $username, $passwd, { AutoCommit => 1 })"
},
{
"code": null,
"e": 25045,
"s": 24872,
"text": "Now, our connection to the database will be established and we will use the following statement to create a table, EMP_DEATAILS, to hold the record of employee’s details. "
},
{
"code": null,
"e": 25179,
"s": 25045,
"text": "my $sth = $dbh->prepare(“CREATE TABLE EMP_DETAILS ( ID INT PRIMARY KEY, EMP_NAME VARCHAR(50), AGE INT, SALARY INT)”);$sth->execute();"
},
{
"code": null,
"e": 25227,
"s": 25179,
"text": "The full program for reference is given below :"
},
{
"code": "#!/usr/bin/perl -wuse strict;use DBI;my $driver = \"mysql\";my $dsn = \"database=EMP_DB\";my $username = \"root\";my $passwd = \"\";my $dbh = DBI->connect(\"dbi:$driver:$dsn\", $username, $passwd, { AutoCommit => 1 }) or die \"Failed to connect to database : $DBI::errstr\";my $sth = $dbh->prepare(\"CREATE TABLE EMP_DETAILS ( ID INT PRIMARY KEY, EMP_NAME VARCHAR(50), AGE INT, SALARY INT)\"); $sth->execute();",
"e": 25749,
"s": 25227,
"text": null
},
{
"code": null,
"e": 25757,
"s": 25749,
"text": "Output:"
},
{
"code": null,
"e": 25895,
"s": 25757,
"text": "Now that we have created EMP_DETAILS table in EMP_DB database, lets insert some values into the table by using the following statements :"
},
{
"code": "#$dbh->do(\"INSERT INTO EMP_DETAILS (ID, EMP_NAME, AGE, SALARY) VALUES (71, 'CHINMAY', 23, 10000)\") or die \"Failed to insert : $DBI::errstr\"; #$dbh->do(\"INSERT INTO EMP_DETAILS (ID, EMP_NAME, AGE, SALARY) VALUES (73, 'SANSKRUTI', 23, 15000)\") or die \"Failed to insert : $DBI::errstr\"; $dbh->do(\"INSERT INTO EMP_DETAILS (ID, EMP_NAME, AGE, SALARY) VALUES (150, 'DEREK', 37, 20000)\") or die \"Failed to insert : $DBI::errstr\"; $dbh->do(\"INSERT INTO EMP_DETAILS (ID, EMP_NAME, AGE, SALARY) VALUES (200, 'ROSS', 30, 24250)\") or die \"Failed to insert : $DBI::errstr\";",
"e": 26471,
"s": 25895,
"text": null
},
{
"code": null,
"e": 26479,
"s": 26471,
"text": "Output:"
},
{
"code": null,
"e": 26871,
"s": 26479,
"text": "Consider the below given program. In the program, we have used question marks(?) at some places. These question marks are known as placeholders. By using placeholders, the database driver can pre-process the query before executing it to the SQL prompt. This process is known as binding of data. Binding helps us in increasing the code security, which helps to prevent SQL injection attacks. "
},
{
"code": "#!/usr/bin/perl -wuse strict;use DBI;my $driver = \"mysql\";my $dsn = \"database=EMP_DB\";my $username = \"root\";my $passwd = \"\";my $dbh = DBI->connect(\"dbi:$driver:$dsn\", $username, $passwd, { AutoCommit => 1 }) or die \"Failed to connect to database : $DBI::errstr\"; # Inserting Bind Valuesprint \"Enter Employee ID - \";my $id = <>;chomp($id); print \"Enter Employee Name - \";my $name = <>;chomp($name); print \"Enter Employee Age - \";my $age = <>;chomp($age); print \"Enter Employee Salary - \";my $salary = <>;chomp($salary); my $sth = $dbh->prepare(\"INSERT INTO EMP_DETAILS ( ID, EMP_NAME, AGE, SALARY) VALUES (?, ?, ?, ?)\"); $sth->execute($id, $name, $age, $salary) or die \"Failed to insert : $DBI::errstr\";",
"e": 27718,
"s": 26871,
"text": null
},
{
"code": null,
"e": 27726,
"s": 27718,
"text": "Output:"
},
{
"code": null,
"e": 27880,
"s": 27726,
"text": "Our database is now populated with some values. Now we need to read them back to the user. To do so we will use while loop to read back data to the user."
},
{
"code": "#!/usr/bin/perl -wuse strict;use DBI;my $driver = \"mysql\";my $dsn = \"database=EMP_DB\";my $username = \"root\";my $passwd = \"\";my $dbh = DBI->connect(\"dbi:$driver:$dsn\", $username, $passwd, { AutoCommit => 1 }) or die \"Failed to connect to database : $DBI::errstr\"; my $sth = $dbh->prepare(\"SELECT EMP_NAME, ID FROM EMP_DETAILS WHERE ID<100\"); $sth->execute() or die \"Failed to select rows : $DBI::errstr\"; my $rows = $sth->rows;print \"Number of rows updated : $rows \\n\"; while (my @emp_data = $sth->fetchrow_array()) { my ($name, $id ) = @emp_data; print \"Employee Name = $name, Employee ID = $id \\n\";}$sth->finish();",
"e": 28555,
"s": 27880,
"text": null
},
{
"code": null,
"e": 28563,
"s": 28555,
"text": "Output:"
},
{
"code": null,
"e": 28650,
"s": 28563,
"text": "To update any value of the table, we can use SQL UPDATE command in the following way :"
},
{
"code": "#!/usr/bin/perl -wuse strict;use DBI;my $driver = \"mysql\";my $dsn = \"database=EMP_DB\";my $username = \"root\";my $passwd = \"\";my $dbh = DBI->connect(\"dbi:$driver:$dsn\", $username, $passwd, { AutoCommit => 1 }) or die \"Failed to connect to database : $DBI::errstr\"; $dbh->do(\"UPDATE EMP_DETAILS SET ID=250 WHERE ID=150\") or die \"Failed to update : $DBI::errstr\";",
"e": 29062,
"s": 28650,
"text": null
},
{
"code": null,
"e": 29070,
"s": 29062,
"text": "Output:"
},
{
"code": null,
"e": 29086,
"s": 29070,
"text": "Original Table:"
},
{
"code": null,
"e": 29113,
"s": 29086,
"text": "Table after Data Updation:"
},
{
"code": null,
"e": 29211,
"s": 29113,
"text": "To delete a particular row from the table, we can use SQL DELETE statement in the following way :"
},
{
"code": "#!/usr/bin/perl -wuse strict;use DBI;my $driver = \"mysql\";my $dsn = \"database=EMP_DB\";my $username = \"root\";my $passwd = \"\";my $dbh = DBI->connect(\"dbi:$driver:$dsn\", $username, $passwd, { AutoCommit => 1 }) or die \"Failed to connect to database : $DBI::errstr\"; $dbh->do(\"DELETE FROM EMP_DETAILS WHERE ID=250\") or die \"Failed to delete : $DBI::errstr\"; $dbh->do(\"DELETE FROM EMP_DETAILS WHERE EMP_NAME='ROSS'\") or die \"Failed to delete : $DBI::errstr\";",
"e": 29702,
"s": 29211,
"text": null
},
{
"code": null,
"e": 29710,
"s": 29702,
"text": "Output:"
},
{
"code": null,
"e": 29717,
"s": 29710,
"text": "Picked"
},
{
"code": null,
"e": 29722,
"s": 29717,
"text": "Perl"
},
{
"code": null,
"e": 29727,
"s": 29722,
"text": "Perl"
},
{
"code": null,
"e": 29825,
"s": 29727,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29853,
"s": 29825,
"text": "Perl | Polymorphism in OOPs"
},
{
"code": null,
"e": 29894,
"s": 29853,
"text": "Perl Tutorial - Learn Perl With Examples"
},
{
"code": null,
"e": 29919,
"s": 29894,
"text": "Perl | length() Function"
},
{
"code": null,
"e": 29943,
"s": 29919,
"text": "Perl | sleep() Function"
},
{
"code": null,
"e": 29968,
"s": 29943,
"text": "Perl | Regex Cheat Sheet"
},
{
"code": null,
"e": 29996,
"s": 29968,
"text": "Hello World Program in Perl"
},
{
"code": null,
"e": 30017,
"s": 29996,
"text": "Introduction to Perl"
},
{
"code": null,
"e": 30039,
"s": 30017,
"text": "Perl | Boolean Values"
},
{
"code": null,
"e": 30068,
"s": 30039,
"text": "Perl | substitution Operator"
}
] |
MATLAB - Concatenating Matrices | You can concatenate two matrices to create a larger matrix. The pair of square brackets '[]' is the concatenation operator.
MATLAB allows two types of concatenations −
Horizontal concatenation
Vertical concatenation
When you concatenate two matrices by separating those using commas, they are just appended horizontally. It is called horizontal concatenation.
Alternatively, if you concatenate two matrices by separating those using semicolons, they are appended vertically. It is called vertical concatenation.
Create a script file with the following code −
a = [ 10 12 23 ; 14 8 6; 27 8 9]
b = [ 12 31 45 ; 8 0 -9; 45 2 11]
c = [a, b]
d = [a; b]
When you run the file, it displays the following result −
a =
10 12 23
14 8 6
27 8 9
b =
12 31 45
8 0 -9
45 2 11
c =
10 12 23 12 31 45
14 8 6 8 0 -9
27 8 9 45 2 11
d =
10 12 23
14 8 6
27 8 9
12 31 45
8 0 -9
45 2 11
30 Lectures
4 hours
Nouman Azam
127 Lectures
12 hours
Nouman Azam
17 Lectures
3 hours
Sanjeev
37 Lectures
5 hours
TELCOMA Global
22 Lectures
4 hours
TELCOMA Global
18 Lectures
3 hours
Phinite Academy
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2265,
"s": 2141,
"text": "You can concatenate two matrices to create a larger matrix. The pair of square brackets '[]' is the concatenation operator."
},
{
"code": null,
"e": 2309,
"s": 2265,
"text": "MATLAB allows two types of concatenations −"
},
{
"code": null,
"e": 2334,
"s": 2309,
"text": "Horizontal concatenation"
},
{
"code": null,
"e": 2357,
"s": 2334,
"text": "Vertical concatenation"
},
{
"code": null,
"e": 2501,
"s": 2357,
"text": "When you concatenate two matrices by separating those using commas, they are just appended horizontally. It is called horizontal concatenation."
},
{
"code": null,
"e": 2653,
"s": 2501,
"text": "Alternatively, if you concatenate two matrices by separating those using semicolons, they are appended vertically. It is called vertical concatenation."
},
{
"code": null,
"e": 2700,
"s": 2653,
"text": "Create a script file with the following code −"
},
{
"code": null,
"e": 2789,
"s": 2700,
"text": "a = [ 10 12 23 ; 14 8 6; 27 8 9]\nb = [ 12 31 45 ; 8 0 -9; 45 2 11]\nc = [a, b]\nd = [a; b]"
},
{
"code": null,
"e": 2847,
"s": 2789,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 3231,
"s": 2847,
"text": "a =\n 10 12 23\n 14 8 6\n 27 8 9\nb =\n 12 31 45\n 8 0 -9\n 45 2 11\nc =\n 10 12 23 12 31 45\n 14 8 6 8 0 -9\n 27 8 9 45 2 11\nd =\n 10 12 23\n 14 8 6\n 27 8 9\n 12 31 45\n 8 0 -9\n 45 2 11\n"
},
{
"code": null,
"e": 3264,
"s": 3231,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3277,
"s": 3264,
"text": " Nouman Azam"
},
{
"code": null,
"e": 3312,
"s": 3277,
"text": "\n 127 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 3325,
"s": 3312,
"text": " Nouman Azam"
},
{
"code": null,
"e": 3358,
"s": 3325,
"text": "\n 17 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3367,
"s": 3358,
"text": " Sanjeev"
},
{
"code": null,
"e": 3400,
"s": 3367,
"text": "\n 37 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3416,
"s": 3400,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3449,
"s": 3416,
"text": "\n 22 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3465,
"s": 3449,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3498,
"s": 3465,
"text": "\n 18 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3515,
"s": 3498,
"text": " Phinite Academy"
},
{
"code": null,
"e": 3522,
"s": 3515,
"text": " Print"
},
{
"code": null,
"e": 3533,
"s": 3522,
"text": " Add Notes"
}
] |
How to Plot a Confidence Interval in Python? | 03 Jan, 2021
Confidence Interval is a type of estimate computed from the statistics of the observed data which gives a range of values that’s likely to contain a population parameter with a particular level of confidence.
A confidence interval for the mean is a range of values between which the population mean possibly lies. If I’d make a weather prediction for tomorrow of somewhere between -100 degrees and +100 degrees, I can be 100% sure that this will be correct. However, if I make the prediction to be between 20.4 and 20.5 degrees Celsius, I’m less confident. Note how the confidence decreases, as the interval decreases. The same applies to statistical confidence intervals, but they also rely on other factors.
A 95% confidence interval, will tell me that if we take an infinite number of samples from my population, calculate the interval each time, then in 95% of those intervals, the interval will contain the true population mean. So, with one sample we can calculate the sample mean, and from there get an interval around it, that most likely will contain the true population mean.
Area under the two black lines shows the 95% confidence interval
Confidence Interval as a concept was put forth by Jerzy Neyman in a paper published in 1937. There are various types of the confidence interval, some of the most commonly used ones are: CI for mean, CI for the median, CI for the difference between means, CI for a proportion and CI for the difference in proportions.
Let’s have a look at how this goes with Python.
The lineplot() function which is available in Seaborn, a data visualization library for Python is best to show trends over a period of time however it also helps in plotting the confidence interval.
Syntax:
sns.lineplot(x=None, y=None, hue=None, size=None, style=None, data=None, palette=None, hue_order=None, hue_norm=None, sizes=None, size_order=None, size_norm=None, dashes=True, markers=None, style_order=None, units=None, estimator=’mean’, ci=95, n_boot=1000, sort=True, err_style=’band’, err_kws=None, legend=’brief’, ax=None, **kwargs,)
Parameters:
x, y: Input data variables; must be numeric. Can pass data directly or reference columns in data.
hue: Grouping variable that will produce lines with different colors. Can be either categorical or numeric, although color mapping will behave differently in latter case.
style: Grouping variable that will produce lines with different dashes and/or markers. Can have a numeric dtype but will always be treated as categorical.
data: Tidy (“long-form”) dataframe where each column is a variable and each row is an observation.
markers: Object determining how to draw the markers for different levels of the style variable.
legend: How to draw the legend. If “brief”, numeric “hue“ and “size“ variables will be represented with a sample of evenly spaced values.
Return: The Axes object containing the plot.
By default, the plot aggregates over multiple y values at each value of x and shows an estimate of the central tendency and a confidence interval for that estimate.
Example:
Python3
# import librariesimport numpy as npimport seaborn as snsimport matplotlib.pyplot as plt # generate random datanp.random.seed(0)x = np.random.randint(0, 30, 100)y = x+np.random.normal(0, 1, 100) # create lineplotax = sns.lineplot(x, y)
In the above code, variable x will store 100 random integers from 0 (inclusive) to 30 (exclusive) and variable y will store 100 samples from the Gaussian (Normal) distribution which is centred at 0 with spread/standard deviation 1. NumPy operations are usually done on pairs of arrays on an element-by-element basis. In the simplest case, the two arrays must have exactly the same shape, as in the above example. Finally, a lineplot is created with the help of seaborn library with 95% confidence interval by default. The confidence interval can easily be changed by changing the value of the parameter ‘ci’ which lies within the range of [0, 100], here I have not passed this parameter hence it considers the default value 95.
The light blue shade indicates the confidence level around that point if it has higher confidence the shaded line will be thicker.
The seaborn.regplot() helps to plot data and a linear regression model fit. This function also allows plotting the confidence interval.
Syntax:
seaborn.regplot( x, y, data=None, x_estimator=None, x_bins=None, x_ci=’ci’, scatter=True, fit_reg=True, ci=95, n_boot=1000, units=None, order=1, logistic=False, lowess=False, robust=False, logx=False, x_partial=None, y_partial=None, truncate=False, dropna=True, x_jitter=None, y_jitter=None, label=None, color=None, marker=’o’, scatter_kws=None, line_kws=None, ax=None)
Parameters: The description of some main parameters are given below:
x, y: These are Input variables. If strings, these should correspond with column names in “data”. When pandas objects are used, axes will be labeled with the series name.
data: This is dataframe where each column is a variable and each row is an observation.
lowess: (optional) This parameter take boolean value. If “True”, use “statsmodels” to estimate a nonparametric lowess model (locally weighted linear regression).
color: (optional) Color to apply to all plot elements.
marker: (optional) Marker to use for the scatterplot glyphs.
Return: The Axes object containing the plot.
Basically, it includes a regression line in the scatterplot and helps in seeing any linear relationship between two variables. Below example will show how it can be used to plot confidence interval as well.
Example:
Python3
# import librariesimport numpy as npimport seaborn as snsimport matplotlib.pyplot as plt # create random datanp.random.seed(0)x = np.random.randint(0, 10, 10)y = x+np.random.normal(0, 1, 10) # create regression plotax = sns.regplot(x, y, ci=80)
The regplot() function works in the same manner as the lineplot() with a 95% confidence interval by default. Confidence interval can easily be changed by changing the value of the parameter ‘ci’ which lies in the range of [0, 100]. Here I have passed ci=80 which means instead of the default 95% confidence interval, an 80% confidence interval is plotted.
The width of light blue color shade indicates the confidence level around the regression line.
Bootstrapping is a test/metric that uses random sampling with replacement. It gives the measure of accuracy (bias, variance, confidence intervals, prediction error, etc.) to sample estimates. It allows the estimation of the sampling distribution for most of the statistics using random sampling methods. It may also be used for constructing hypothesis tests.
Example:
Python3
# import librariesimport pandasimport numpyfrom sklearn.utils import resamplefrom sklearn.metrics import accuracy_scorefrom matplotlib import pyplot as plt # load datasetx = numpy.array([180,162,158,172,168,150,171,183,165,176]) # configure bootstrapn_iterations = 1000 # here k=no. of bootstrapped samplesn_size = int(len(x)) # run bootstrapmedians = list()for i in range(n_iterations): s = resample(x, n_samples=n_size); m = numpy.median(s); medians.append(m) # plot scoresplt.hist(medians)plt.show() # confidence intervalsalpha = 0.95p = ((1.0-alpha)/2.0) * 100lower = numpy.percentile(medians, p)p = (alpha+((1.0-alpha)/2.0)) * 100upper = numpy.percentile(medians, p) print(f"\n{alpha*100} confidence interval {lower} and {upper}")
After importing all the necessary libraries create a sample S with size n=10 and store it in a variable x. Using a simple loop generate 1000 artificial samples (=k) with each sample size m=10 (since m<=n). These samples are called the bootstrapped sample. Their medians are computed and stored in a list ‘medians’. Histogram of Medians from 1000 bootstrapped samples is plotted with the help of matplotlib library and using the formula confidence interval of a sample statistic calculates an upper and lower bound for the population value of the statistic at a specified level of confidence based on sample data is calculated.
95.0 confidence interval lies between 161.5 and 176.0
Data Visualization
Picked
Python-matplotlib
Python-Seaborn
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jan, 2021"
},
{
"code": null,
"e": 237,
"s": 28,
"text": "Confidence Interval is a type of estimate computed from the statistics of the observed data which gives a range of values that’s likely to contain a population parameter with a particular level of confidence."
},
{
"code": null,
"e": 738,
"s": 237,
"text": "A confidence interval for the mean is a range of values between which the population mean possibly lies. If I’d make a weather prediction for tomorrow of somewhere between -100 degrees and +100 degrees, I can be 100% sure that this will be correct. However, if I make the prediction to be between 20.4 and 20.5 degrees Celsius, I’m less confident. Note how the confidence decreases, as the interval decreases. The same applies to statistical confidence intervals, but they also rely on other factors."
},
{
"code": null,
"e": 1114,
"s": 738,
"text": "A 95% confidence interval, will tell me that if we take an infinite number of samples from my population, calculate the interval each time, then in 95% of those intervals, the interval will contain the true population mean. So, with one sample we can calculate the sample mean, and from there get an interval around it, that most likely will contain the true population mean."
},
{
"code": null,
"e": 1179,
"s": 1114,
"text": "Area under the two black lines shows the 95% confidence interval"
},
{
"code": null,
"e": 1496,
"s": 1179,
"text": "Confidence Interval as a concept was put forth by Jerzy Neyman in a paper published in 1937. There are various types of the confidence interval, some of the most commonly used ones are: CI for mean, CI for the median, CI for the difference between means, CI for a proportion and CI for the difference in proportions."
},
{
"code": null,
"e": 1544,
"s": 1496,
"text": "Let’s have a look at how this goes with Python."
},
{
"code": null,
"e": 1743,
"s": 1544,
"text": "The lineplot() function which is available in Seaborn, a data visualization library for Python is best to show trends over a period of time however it also helps in plotting the confidence interval."
},
{
"code": null,
"e": 1751,
"s": 1743,
"text": "Syntax:"
},
{
"code": null,
"e": 2088,
"s": 1751,
"text": "sns.lineplot(x=None, y=None, hue=None, size=None, style=None, data=None, palette=None, hue_order=None, hue_norm=None, sizes=None, size_order=None, size_norm=None, dashes=True, markers=None, style_order=None, units=None, estimator=’mean’, ci=95, n_boot=1000, sort=True, err_style=’band’, err_kws=None, legend=’brief’, ax=None, **kwargs,)"
},
{
"code": null,
"e": 2100,
"s": 2088,
"text": "Parameters:"
},
{
"code": null,
"e": 2198,
"s": 2100,
"text": "x, y: Input data variables; must be numeric. Can pass data directly or reference columns in data."
},
{
"code": null,
"e": 2369,
"s": 2198,
"text": "hue: Grouping variable that will produce lines with different colors. Can be either categorical or numeric, although color mapping will behave differently in latter case."
},
{
"code": null,
"e": 2524,
"s": 2369,
"text": "style: Grouping variable that will produce lines with different dashes and/or markers. Can have a numeric dtype but will always be treated as categorical."
},
{
"code": null,
"e": 2623,
"s": 2524,
"text": "data: Tidy (“long-form”) dataframe where each column is a variable and each row is an observation."
},
{
"code": null,
"e": 2719,
"s": 2623,
"text": "markers: Object determining how to draw the markers for different levels of the style variable."
},
{
"code": null,
"e": 2857,
"s": 2719,
"text": "legend: How to draw the legend. If “brief”, numeric “hue“ and “size“ variables will be represented with a sample of evenly spaced values."
},
{
"code": null,
"e": 2902,
"s": 2857,
"text": "Return: The Axes object containing the plot."
},
{
"code": null,
"e": 3067,
"s": 2902,
"text": "By default, the plot aggregates over multiple y values at each value of x and shows an estimate of the central tendency and a confidence interval for that estimate."
},
{
"code": null,
"e": 3076,
"s": 3067,
"text": "Example:"
},
{
"code": null,
"e": 3084,
"s": 3076,
"text": "Python3"
},
{
"code": "# import librariesimport numpy as npimport seaborn as snsimport matplotlib.pyplot as plt # generate random datanp.random.seed(0)x = np.random.randint(0, 30, 100)y = x+np.random.normal(0, 1, 100) # create lineplotax = sns.lineplot(x, y)",
"e": 3322,
"s": 3084,
"text": null
},
{
"code": null,
"e": 4050,
"s": 3322,
"text": "In the above code, variable x will store 100 random integers from 0 (inclusive) to 30 (exclusive) and variable y will store 100 samples from the Gaussian (Normal) distribution which is centred at 0 with spread/standard deviation 1. NumPy operations are usually done on pairs of arrays on an element-by-element basis. In the simplest case, the two arrays must have exactly the same shape, as in the above example. Finally, a lineplot is created with the help of seaborn library with 95% confidence interval by default. The confidence interval can easily be changed by changing the value of the parameter ‘ci’ which lies within the range of [0, 100], here I have not passed this parameter hence it considers the default value 95."
},
{
"code": null,
"e": 4181,
"s": 4050,
"text": "The light blue shade indicates the confidence level around that point if it has higher confidence the shaded line will be thicker."
},
{
"code": null,
"e": 4317,
"s": 4181,
"text": "The seaborn.regplot() helps to plot data and a linear regression model fit. This function also allows plotting the confidence interval."
},
{
"code": null,
"e": 4325,
"s": 4317,
"text": "Syntax:"
},
{
"code": null,
"e": 4701,
"s": 4325,
"text": "seaborn.regplot( x, y, data=None, x_estimator=None, x_bins=None, x_ci=’ci’, scatter=True, fit_reg=True, ci=95, n_boot=1000, units=None, order=1, logistic=False, lowess=False, robust=False, logx=False, x_partial=None, y_partial=None, truncate=False, dropna=True, x_jitter=None, y_jitter=None, label=None, color=None, marker=’o’, scatter_kws=None, line_kws=None, ax=None)"
},
{
"code": null,
"e": 4770,
"s": 4701,
"text": "Parameters: The description of some main parameters are given below:"
},
{
"code": null,
"e": 4941,
"s": 4770,
"text": "x, y: These are Input variables. If strings, these should correspond with column names in “data”. When pandas objects are used, axes will be labeled with the series name."
},
{
"code": null,
"e": 5030,
"s": 4941,
"text": "data: This is dataframe where each column is a variable and each row is an observation."
},
{
"code": null,
"e": 5192,
"s": 5030,
"text": "lowess: (optional) This parameter take boolean value. If “True”, use “statsmodels” to estimate a nonparametric lowess model (locally weighted linear regression)."
},
{
"code": null,
"e": 5247,
"s": 5192,
"text": "color: (optional) Color to apply to all plot elements."
},
{
"code": null,
"e": 5308,
"s": 5247,
"text": "marker: (optional) Marker to use for the scatterplot glyphs."
},
{
"code": null,
"e": 5353,
"s": 5308,
"text": "Return: The Axes object containing the plot."
},
{
"code": null,
"e": 5560,
"s": 5353,
"text": "Basically, it includes a regression line in the scatterplot and helps in seeing any linear relationship between two variables. Below example will show how it can be used to plot confidence interval as well."
},
{
"code": null,
"e": 5569,
"s": 5560,
"text": "Example:"
},
{
"code": null,
"e": 5577,
"s": 5569,
"text": "Python3"
},
{
"code": "# import librariesimport numpy as npimport seaborn as snsimport matplotlib.pyplot as plt # create random datanp.random.seed(0)x = np.random.randint(0, 10, 10)y = x+np.random.normal(0, 1, 10) # create regression plotax = sns.regplot(x, y, ci=80)",
"e": 5824,
"s": 5577,
"text": null
},
{
"code": null,
"e": 6180,
"s": 5824,
"text": "The regplot() function works in the same manner as the lineplot() with a 95% confidence interval by default. Confidence interval can easily be changed by changing the value of the parameter ‘ci’ which lies in the range of [0, 100]. Here I have passed ci=80 which means instead of the default 95% confidence interval, an 80% confidence interval is plotted."
},
{
"code": null,
"e": 6275,
"s": 6180,
"text": "The width of light blue color shade indicates the confidence level around the regression line."
},
{
"code": null,
"e": 6635,
"s": 6275,
"text": "Bootstrapping is a test/metric that uses random sampling with replacement. It gives the measure of accuracy (bias, variance, confidence intervals, prediction error, etc.) to sample estimates. It allows the estimation of the sampling distribution for most of the statistics using random sampling methods. It may also be used for constructing hypothesis tests. "
},
{
"code": null,
"e": 6644,
"s": 6635,
"text": "Example:"
},
{
"code": null,
"e": 6652,
"s": 6644,
"text": "Python3"
},
{
"code": "# import librariesimport pandasimport numpyfrom sklearn.utils import resamplefrom sklearn.metrics import accuracy_scorefrom matplotlib import pyplot as plt # load datasetx = numpy.array([180,162,158,172,168,150,171,183,165,176]) # configure bootstrapn_iterations = 1000 # here k=no. of bootstrapped samplesn_size = int(len(x)) # run bootstrapmedians = list()for i in range(n_iterations): s = resample(x, n_samples=n_size); m = numpy.median(s); medians.append(m) # plot scoresplt.hist(medians)plt.show() # confidence intervalsalpha = 0.95p = ((1.0-alpha)/2.0) * 100lower = numpy.percentile(medians, p)p = (alpha+((1.0-alpha)/2.0)) * 100upper = numpy.percentile(medians, p) print(f\"\\n{alpha*100} confidence interval {lower} and {upper}\")",
"e": 7402,
"s": 6652,
"text": null
},
{
"code": null,
"e": 8029,
"s": 7402,
"text": "After importing all the necessary libraries create a sample S with size n=10 and store it in a variable x. Using a simple loop generate 1000 artificial samples (=k) with each sample size m=10 (since m<=n). These samples are called the bootstrapped sample. Their medians are computed and stored in a list ‘medians’. Histogram of Medians from 1000 bootstrapped samples is plotted with the help of matplotlib library and using the formula confidence interval of a sample statistic calculates an upper and lower bound for the population value of the statistic at a specified level of confidence based on sample data is calculated."
},
{
"code": null,
"e": 8083,
"s": 8029,
"text": "95.0 confidence interval lies between 161.5 and 176.0"
},
{
"code": null,
"e": 8102,
"s": 8083,
"text": "Data Visualization"
},
{
"code": null,
"e": 8109,
"s": 8102,
"text": "Picked"
},
{
"code": null,
"e": 8127,
"s": 8109,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 8142,
"s": 8127,
"text": "Python-Seaborn"
},
{
"code": null,
"e": 8166,
"s": 8142,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 8173,
"s": 8166,
"text": "Python"
},
{
"code": null,
"e": 8192,
"s": 8173,
"text": "Technical Scripter"
}
] |
XAML - Menu | A Menu is a control that enables you to hierarchically organize the elements associated with the commands and event handlers. Menu is an ItemsControl, so it can contain a collection of any object type such as string, image, or panel. The hierarchical inheritance of Menu class is as follows −
Background
Gets or sets a brush that describes the background of a control. (Inherited from Control.)
BindingGroup
Gets or sets the BindingGroup that is used for the element. (Inherited from FrameworkElement.)
BitmapEffect
Obsolete. Gets or sets a bitmap effect that applies directly to the rendered content for this element. This is a dependency property. (Inherited from UIElement.)
BorderThickness
Gets or sets the border thickness of a control. (Inherited from Control.)
ContextMenu
Gets or sets the context menu element that should appear whenever the context menu is requested through user interface (UI) from within this element. (Inherited from FrameworkElement.)
Effect
Gets or sets the bitmap effect to apply to the UIElement. This is a dependency property. (Inherited from UIElement.)
Height
Gets or sets the suggested height of the element. (Inherited from FrameworkElement.)
IsMainMenu
Gets or sets a value that indicates whether this Menu receives a main menu activation notification.
Items
Gets the collection used to generate the content of the ItemsControl. (Inherited from ItemsControl.)
ItemsPanel
Gets or sets the template that defines the panel that controls the layout of items. (Inherited from ItemsControl.)
ItemsSource
Gets or sets a collection used to generate the content of the ItemsControl. (Inherited from ItemsControl.)
ItemStringFormat
Gets or sets a composite string that specifies how to format the items in the ItemsControl if they are displayed as strings. (Inherited from ItemsControl.)
ItemTemplate
Gets or sets the DataTemplate used to display each item. (Inherited from ItemsControl.)
ToolTip
Gets or sets the tool-tip object that is displayed for this element in the user interface (UI). (Inherited from FrameworkElement.)
VerticalContentAlignment
Gets or sets the vertical alignment of the control's content. (Inherited from Control.)
Width
Gets or sets the width of the element. (Inherited from FrameworkElement.)
ContextMenuClosing
Occurs just before any context menu on the element is closed. (Inherited from FrameworkElement.)
ContextMenuOpening
Occurs when any context menu on the element is opened. (Inherited from FrameworkElement.)
KeyDown
Occurs when a key is pressed while focus is on this element. (Inherited from UIElement.)
KeyUp
Occurs when a key is released while focus is on this element. (Inherited from UIElement.)
ToolTipClosing
Occurs just before any tooltip on the element is closed. (Inherited from FrameworkElement.)
ToolTipOpening
Occurs when any tooltip on the element is opened. (Inherited from FrameworkElement.)
TouchDown
Occurs when a finger touches the screen while the finger is over this element. (Inherited from UIElement.)
TouchEnter
Occurs when a touch moves from outside to inside the bounds of this element. (Inherited from UIElement.)
TouchLeave
Occurs when a touch moves from inside to outside the bounds of this element. (Inherited from UIElement.)
TouchMove
Occurs when a finger moves on the screen while the finger is over this element. (Inherited from UIElement.)
TouchUp
Occurs when a finger is raised off of the screen while the finger is over this element. (Inherited from UIElement.)
The following example contains two menu options with some menu item. When a user clicks an item from the menu, the program updates the title. Here is the XAML code.
<Window x:Class = "XAMLMenu.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
Title = "MainWindow" Height = "350" Width = "525">
<Grid>
<Menu HorizontalAlignment = "Left" VerticalAlignment = "Top" Width = "517">
<MenuItem Header = "File">
<MenuItem Header = "Item 1" HorizontalAlignment = "Left"
Width = "140" Click = "MenuItem_Click"/>
<MenuItem Header = "Item 2" HorizontalAlignment = "Left"
Width = "140" Click = "MenuItem_Click"/>
<Separator HorizontalAlignment = "Left" Width = "140"/>
<MenuItem Header = "Item 3" HorizontalAlignment = "Left"
Width = "140" Click = "MenuItem_Click"/>
</MenuItem>
</Menu>
<Menu VerticalAlignment = "Top" Width = "517" Margin = "41,0,-41,0">
<MenuItem Header = "Edit">
<MenuItem Header = "Item 1" HorizontalAlignment = "Left" Width = "140" Click = "MenuItem_Click1"/>
<MenuItem Header = "Item 2" HorizontalAlignment="Left" Width = "140" Click = "MenuItem_Click1"/>
<Separator HorizontalAlignment = "Left" Width = "140"/>
<MenuItem Header = "Item 3" HorizontalAlignment = "Left" Width = "140" Click = "MenuItem_Click1"/>
</MenuItem>
</Menu>
</Grid>
</Window>
Here is the events implementation in C# −
using System.Linq;
using System.Windows;
using System.Windows.Controls;
namespace XAMLMenu {
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
}
private void MenuItem_Click(object sender, RoutedEventArgs e) {
MenuItem item = sender as MenuItem;
this.Title = "File: " + item.Header;
}
private void MenuItem_Click1(object sender, RoutedEventArgs e) {
MenuItem item = sender as MenuItem;
this.Title = "Edit: " + item.Header;
}
}
}
When you compile and execute the above code, it will produce the following output −
We recommend you to execute the above example code and experiment with some other properties and events. | [
{
"code": null,
"e": 2350,
"s": 2057,
"text": "A Menu is a control that enables you to hierarchically organize the elements associated with the commands and event handlers. Menu is an ItemsControl, so it can contain a collection of any object type such as string, image, or panel. The hierarchical inheritance of Menu class is as follows −"
},
{
"code": null,
"e": 2361,
"s": 2350,
"text": "Background"
},
{
"code": null,
"e": 2452,
"s": 2361,
"text": "Gets or sets a brush that describes the background of a control. (Inherited from Control.)"
},
{
"code": null,
"e": 2465,
"s": 2452,
"text": "BindingGroup"
},
{
"code": null,
"e": 2560,
"s": 2465,
"text": "Gets or sets the BindingGroup that is used for the element. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 2573,
"s": 2560,
"text": "BitmapEffect"
},
{
"code": null,
"e": 2735,
"s": 2573,
"text": "Obsolete. Gets or sets a bitmap effect that applies directly to the rendered content for this element. This is a dependency property. (Inherited from UIElement.)"
},
{
"code": null,
"e": 2751,
"s": 2735,
"text": "BorderThickness"
},
{
"code": null,
"e": 2825,
"s": 2751,
"text": "Gets or sets the border thickness of a control. (Inherited from Control.)"
},
{
"code": null,
"e": 2837,
"s": 2825,
"text": "ContextMenu"
},
{
"code": null,
"e": 3022,
"s": 2837,
"text": "Gets or sets the context menu element that should appear whenever the context menu is requested through user interface (UI) from within this element. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 3029,
"s": 3022,
"text": "Effect"
},
{
"code": null,
"e": 3146,
"s": 3029,
"text": "Gets or sets the bitmap effect to apply to the UIElement. This is a dependency property. (Inherited from UIElement.)"
},
{
"code": null,
"e": 3153,
"s": 3146,
"text": "Height"
},
{
"code": null,
"e": 3238,
"s": 3153,
"text": "Gets or sets the suggested height of the element. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 3249,
"s": 3238,
"text": "IsMainMenu"
},
{
"code": null,
"e": 3349,
"s": 3249,
"text": "Gets or sets a value that indicates whether this Menu receives a main menu activation notification."
},
{
"code": null,
"e": 3355,
"s": 3349,
"text": "Items"
},
{
"code": null,
"e": 3456,
"s": 3355,
"text": "Gets the collection used to generate the content of the ItemsControl. (Inherited from ItemsControl.)"
},
{
"code": null,
"e": 3467,
"s": 3456,
"text": "ItemsPanel"
},
{
"code": null,
"e": 3582,
"s": 3467,
"text": "Gets or sets the template that defines the panel that controls the layout of items. (Inherited from ItemsControl.)"
},
{
"code": null,
"e": 3594,
"s": 3582,
"text": "ItemsSource"
},
{
"code": null,
"e": 3701,
"s": 3594,
"text": "Gets or sets a collection used to generate the content of the ItemsControl. (Inherited from ItemsControl.)"
},
{
"code": null,
"e": 3718,
"s": 3701,
"text": "ItemStringFormat"
},
{
"code": null,
"e": 3874,
"s": 3718,
"text": "Gets or sets a composite string that specifies how to format the items in the ItemsControl if they are displayed as strings. (Inherited from ItemsControl.)"
},
{
"code": null,
"e": 3887,
"s": 3874,
"text": "ItemTemplate"
},
{
"code": null,
"e": 3975,
"s": 3887,
"text": "Gets or sets the DataTemplate used to display each item. (Inherited from ItemsControl.)"
},
{
"code": null,
"e": 3983,
"s": 3975,
"text": "ToolTip"
},
{
"code": null,
"e": 4114,
"s": 3983,
"text": "Gets or sets the tool-tip object that is displayed for this element in the user interface (UI). (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 4139,
"s": 4114,
"text": "VerticalContentAlignment"
},
{
"code": null,
"e": 4227,
"s": 4139,
"text": "Gets or sets the vertical alignment of the control's content. (Inherited from Control.)"
},
{
"code": null,
"e": 4233,
"s": 4227,
"text": "Width"
},
{
"code": null,
"e": 4307,
"s": 4233,
"text": "Gets or sets the width of the element. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 4326,
"s": 4307,
"text": "ContextMenuClosing"
},
{
"code": null,
"e": 4423,
"s": 4326,
"text": "Occurs just before any context menu on the element is closed. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 4442,
"s": 4423,
"text": "ContextMenuOpening"
},
{
"code": null,
"e": 4532,
"s": 4442,
"text": "Occurs when any context menu on the element is opened. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 4540,
"s": 4532,
"text": "KeyDown"
},
{
"code": null,
"e": 4629,
"s": 4540,
"text": "Occurs when a key is pressed while focus is on this element. (Inherited from UIElement.)"
},
{
"code": null,
"e": 4635,
"s": 4629,
"text": "KeyUp"
},
{
"code": null,
"e": 4725,
"s": 4635,
"text": "Occurs when a key is released while focus is on this element. (Inherited from UIElement.)"
},
{
"code": null,
"e": 4740,
"s": 4725,
"text": "ToolTipClosing"
},
{
"code": null,
"e": 4832,
"s": 4740,
"text": "Occurs just before any tooltip on the element is closed. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 4847,
"s": 4832,
"text": "ToolTipOpening"
},
{
"code": null,
"e": 4932,
"s": 4847,
"text": "Occurs when any tooltip on the element is opened. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 4942,
"s": 4932,
"text": "TouchDown"
},
{
"code": null,
"e": 5049,
"s": 4942,
"text": "Occurs when a finger touches the screen while the finger is over this element. (Inherited from UIElement.)"
},
{
"code": null,
"e": 5060,
"s": 5049,
"text": "TouchEnter"
},
{
"code": null,
"e": 5165,
"s": 5060,
"text": "Occurs when a touch moves from outside to inside the bounds of this element. (Inherited from UIElement.)"
},
{
"code": null,
"e": 5176,
"s": 5165,
"text": "TouchLeave"
},
{
"code": null,
"e": 5281,
"s": 5176,
"text": "Occurs when a touch moves from inside to outside the bounds of this element. (Inherited from UIElement.)"
},
{
"code": null,
"e": 5291,
"s": 5281,
"text": "TouchMove"
},
{
"code": null,
"e": 5399,
"s": 5291,
"text": "Occurs when a finger moves on the screen while the finger is over this element. (Inherited from UIElement.)"
},
{
"code": null,
"e": 5407,
"s": 5399,
"text": "TouchUp"
},
{
"code": null,
"e": 5523,
"s": 5407,
"text": "Occurs when a finger is raised off of the screen while the finger is over this element. (Inherited from UIElement.)"
},
{
"code": null,
"e": 5688,
"s": 5523,
"text": "The following example contains two menu options with some menu item. When a user clicks an item from the menu, the program updates the title. Here is the XAML code."
},
{
"code": null,
"e": 7123,
"s": 5688,
"text": "<Window x:Class = \"XAMLMenu.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\"\n Title = \"MainWindow\" Height = \"350\" Width = \"525\"> \n\t\n <Grid> \n <Menu HorizontalAlignment = \"Left\" VerticalAlignment = \"Top\" Width = \"517\"> \n <MenuItem Header = \"File\"> \n <MenuItem Header = \"Item 1\" HorizontalAlignment = \"Left\" \n Width = \"140\" Click = \"MenuItem_Click\"/> \n \n <MenuItem Header = \"Item 2\" HorizontalAlignment = \"Left\" \n Width = \"140\" Click = \"MenuItem_Click\"/>\n \n <Separator HorizontalAlignment = \"Left\" Width = \"140\"/> \n\t\t\t\n <MenuItem Header = \"Item 3\" HorizontalAlignment = \"Left\" \n Width = \"140\" Click = \"MenuItem_Click\"/>\n \n </MenuItem>\n </Menu> \n \n <Menu VerticalAlignment = \"Top\" Width = \"517\" Margin = \"41,0,-41,0\">\n <MenuItem Header = \"Edit\">\n <MenuItem Header = \"Item 1\" HorizontalAlignment = \"Left\" Width = \"140\" Click = \"MenuItem_Click1\"/> \n <MenuItem Header = \"Item 2\" HorizontalAlignment=\"Left\" Width = \"140\" Click = \"MenuItem_Click1\"/>\n <Separator HorizontalAlignment = \"Left\" Width = \"140\"/> \n <MenuItem Header = \"Item 3\" HorizontalAlignment = \"Left\" Width = \"140\" Click = \"MenuItem_Click1\"/> \n </MenuItem>\n </Menu> \n </Grid>\n \n</Window>"
},
{
"code": null,
"e": 7165,
"s": 7123,
"text": "Here is the events implementation in C# −"
},
{
"code": null,
"e": 7732,
"s": 7165,
"text": "using System.Linq; \nusing System.Windows; \nusing System.Windows.Controls;\n\nnamespace XAMLMenu {\n public partial class MainWindow : Window {\n public MainWindow() {\n InitializeComponent(); \n } \n private void MenuItem_Click(object sender, RoutedEventArgs e) { \n MenuItem item = sender as MenuItem; \n this.Title = \"File: \" + item.Header; \n } \n private void MenuItem_Click1(object sender, RoutedEventArgs e) { \n MenuItem item = sender as MenuItem; \n this.Title = \"Edit: \" + item.Header; \n } \n } \n}"
},
{
"code": null,
"e": 7816,
"s": 7732,
"text": "When you compile and execute the above code, it will produce the following output −"
}
] |
Optional stream() method in Java with examples | 30 Jul, 2019
The stream() method of java.util.Optional class in Java is used to get the sequential stream of the only value present in this Optional instance. If there is no value present in this Optional instance, then this method returns returns an empty Stream.
Syntax:
public Stream<T> stream()
Parameters: This method do not accept any parameter.
Return value: This method returns the sequential stream of the only value present in this Optional instance. If there is no value present in this Optional instance, then this method returns an empty Stream.
Below programs illustrate stream() method:
Note: Below programs require JDK 9 and above to execute.
Program 1:
// Java program to demonstrate// Optional.stream() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.of(9455); // print value System.out.println("Optional: " + op); // get the Stream System.out.println("Getting the Stream:"); op.stream().forEach(System.out::println); }}
Output:
Optional: Optional[9455]
Getting the Stream:
9455
Program 2:
// Java program to demonstrate// Optional.stream() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.empty(); // print value System.out.println("Optional: " + op); try { // get the Stream System.out.println("Getting the Stream:"); op.stream().forEach(System.out::println); } catch (Exception e) { System.out.println(e); } }}
Output:
Optional: Optional.empty
Getting the Stream:
Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#stream–
Java - util package
Java-Functions
Java-Optional
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": "\n30 Jul, 2019"
},
{
"code": null,
"e": 280,
"s": 28,
"text": "The stream() method of java.util.Optional class in Java is used to get the sequential stream of the only value present in this Optional instance. If there is no value present in this Optional instance, then this method returns returns an empty Stream."
},
{
"code": null,
"e": 288,
"s": 280,
"text": "Syntax:"
},
{
"code": null,
"e": 315,
"s": 288,
"text": "public Stream<T> stream()\n"
},
{
"code": null,
"e": 368,
"s": 315,
"text": "Parameters: This method do not accept any parameter."
},
{
"code": null,
"e": 575,
"s": 368,
"text": "Return value: This method returns the sequential stream of the only value present in this Optional instance. If there is no value present in this Optional instance, then this method returns an empty Stream."
},
{
"code": null,
"e": 618,
"s": 575,
"text": "Below programs illustrate stream() method:"
},
{
"code": null,
"e": 675,
"s": 618,
"text": "Note: Below programs require JDK 9 and above to execute."
},
{
"code": null,
"e": 686,
"s": 675,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// Optional.stream() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.of(9455); // print value System.out.println(\"Optional: \" + op); // get the Stream System.out.println(\"Getting the Stream:\"); op.stream().forEach(System.out::println); }}",
"e": 1152,
"s": 686,
"text": null
},
{
"code": null,
"e": 1160,
"s": 1152,
"text": "Output:"
},
{
"code": null,
"e": 1211,
"s": 1160,
"text": "Optional: Optional[9455]\nGetting the Stream:\n9455\n"
},
{
"code": null,
"e": 1222,
"s": 1211,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// Optional.stream() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.empty(); // print value System.out.println(\"Optional: \" + op); try { // get the Stream System.out.println(\"Getting the Stream:\"); op.stream().forEach(System.out::println); } catch (Exception e) { System.out.println(e); } }}",
"e": 1795,
"s": 1222,
"text": null
},
{
"code": null,
"e": 1803,
"s": 1795,
"text": "Output:"
},
{
"code": null,
"e": 1850,
"s": 1803,
"text": "Optional: Optional.empty\nGetting the Stream:\n\n"
},
{
"code": null,
"e": 1935,
"s": 1850,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#stream–"
},
{
"code": null,
"e": 1955,
"s": 1935,
"text": "Java - util package"
},
{
"code": null,
"e": 1970,
"s": 1955,
"text": "Java-Functions"
},
{
"code": null,
"e": 1984,
"s": 1970,
"text": "Java-Optional"
},
{
"code": null,
"e": 1989,
"s": 1984,
"text": "Java"
},
{
"code": null,
"e": 1994,
"s": 1989,
"text": "Java"
},
{
"code": null,
"e": 2092,
"s": 1994,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2107,
"s": 2092,
"text": "Stream In Java"
},
{
"code": null,
"e": 2128,
"s": 2107,
"text": "Introduction to Java"
},
{
"code": null,
"e": 2149,
"s": 2128,
"text": "Constructors in Java"
},
{
"code": null,
"e": 2168,
"s": 2149,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 2185,
"s": 2168,
"text": "Generics in Java"
},
{
"code": null,
"e": 2215,
"s": 2185,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 2241,
"s": 2215,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 2257,
"s": 2241,
"text": "Strings in Java"
},
{
"code": null,
"e": 2294,
"s": 2257,
"text": "Differences between JDK, JRE and JVM"
}
] |
Sum of subsets of all the subsets of an array | O(2^N) | 21 Apr, 2021
Given an array arr[] of length N, the task is to find the overall sum of subsets of all the subsets of the array.Examples:
Input: arr[] = {1, 1} Output: 6 All possible subsets: a) {} : 0 All the possible subsets of this subset will be {}, Sum = 0 b) {1} : 1 All the possible subsets of this subset will be {} and {1}, Sum = 0 + 1 = 1 c) {1} : 1 All the possible subsets of this subset will be {} and {1}, Sum = 0 + 1 = 1 d) {1, 1} : 4 All the possible subsets of this subset will be {}, {1}, {1} and {1, 1}, Sum = 0 + 1 + 1 + 2 = 4 Thus, ans = 0 + 1 + 1 + 4 = 6Input: arr[] = {1, 4, 2, 12} Output: 513
Approach: In this article, an approach with O(N * 2N) time complexity to solve the given problem will be discussed. First, generate all the possible subsets of the array. There will be 2N subsets in total. Then for each subset, find the sum of all of its subsets.For, that it can be observed that in an array of length L, every element will come exactly 2(L – 1) times in the sum of subsets. So, the contribution of each element will be 2(L – 1) times its values.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to sum of all subsets of a// given arrayvoid subsetSum(vector<int>& c, int& ans){ int L = c.size(); int mul = (int)pow(2, L - 1); for (int i = 0; i < c.size(); i++) ans += c[i] * mul;} // Function to generate the subsetsvoid subsetGen(int* arr, int i, int n, int& ans, vector<int>& c){ // Base-case if (i == n) { // Finding the sum of all the subsets // of the generated subset subsetSum(c, ans); return; } // Recursively accepting and rejecting // the current number subsetGen(arr, i + 1, n, ans, c); c.push_back(arr[i]); subsetGen(arr, i + 1, n, ans, c); c.pop_back();} // Driver codeint main(){ int arr[] = { 1, 1 }; int n = sizeof(arr) / sizeof(int); // To store the final ans int ans = 0; vector<int> c; subsetGen(arr, 0, n, ans, c); cout << ans; return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ // To store the final ansstatic int ans; // Function to sum of all subsets of a// given arraystatic void subsetSum(Vector<Integer> c){ int L = c.size(); int mul = (int)Math.pow(2, L - 1); for (int i = 0; i < c.size(); i++) ans += c.get(i) * mul;} // Function to generate the subsetsstatic void subsetGen(int []arr, int i, int n, Vector<Integer> c){ // Base-case if (i == n) { // Finding the sum of all the subsets // of the generated subset subsetSum(c); return; } // Recursively accepting and rejecting // the current number subsetGen(arr, i + 1, n, c); c.add(arr[i]); subsetGen(arr, i + 1, n, c); c.remove(0);} // Driver codepublic static void main(String []args){ int arr[] = { 1, 1 }; int n = arr.length; Vector<Integer> c = new Vector<Integer>(); subsetGen(arr, 0, n, c); System.out.println(ans);}} // This code is contributed by 29AjayKumar
# Python3 implementation of the approach # store the answerc = []ans = 0 # Function to sum of all subsets of a# given arraydef subsetSum(): global ans L = len(c) mul = pow(2, L - 1) i = 0 while ( i < len(c)): ans += c[i] * mul i += 1 # Function to generate the subsetsdef subsetGen(arr, i, n): # Base-case if (i == n) : # Finding the sum of all the subsets # of the generated subset subsetSum() return # Recursively accepting and rejecting # the current number subsetGen(arr, i + 1, n) c.append(arr[i]) subsetGen(arr, i + 1, n) c.pop() # Driver codeif __name__ == "__main__" : arr = [ 1, 1 ] n = len(arr) subsetGen(arr, 0, n) print (ans) # This code is contributed by Arnab Kundu
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // To store the final ansstatic int ans; // Function to sum of all subsets of a// given arraystatic void subsetSum(List<int> c){ int L = c.Count; int mul = (int)Math.Pow(2, L - 1); for (int i = 0; i < c.Count; i++) ans += c[i] * mul;} // Function to generate the subsetsstatic void subsetGen(int []arr, int i, int n, List<int> c){ // Base-case if (i == n) { // Finding the sum of all the subsets // of the generated subset subsetSum(c); return; } // Recursively accepting and rejecting // the current number subsetGen(arr, i + 1, n, c); c.Add(arr[i]); subsetGen(arr, i + 1, n, c); c.RemoveAt(0);} // Driver codepublic static void Main(String []args){ int []arr = { 1, 1 }; int n = arr.Length; List<int> c = new List<int>(); subsetGen(arr, 0, n, c); Console.WriteLine(ans);}} // This code is contributed by Rajput-Ji
<script>// javascript implementation of the approach // To store the final ans var ans = 0; // Function to sum of all subsets of a // given array function subsetSum( c) { var L = c.length; var mul = parseInt( Math.pow(2, L - 1)); for (i = 0; i < c.length; i++) ans += c[i] * mul; } // Function to generate the subsets function subsetGen(arr , i , n, c) { // Base-case if (i == n) { // Finding the sum of all the subsets // of the generated subset subsetSum(c); return; } // Recursively accepting and rejecting // the current number subsetGen(arr, i + 1, n, c); c.push(arr[i]); subsetGen(arr, i + 1, n, c); c.pop(0); } // Driver code var arr = [ 1, 1 ]; var n = arr.length; var c = []; subsetGen(arr, 0, n, c); document.write(ans); // This code is contributed by todaysgaurav</script>
6
29AjayKumar
Rajput-Ji
andrew1234
todaysgaurav
subset
Arrays
Backtracking
Greedy
Arrays
Greedy
subset
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
N Queen Problem | Backtracking-3
The Knight's tour problem | Backtracking-1
Rat in a Maze | Backtracking-2
Backtracking | Introduction | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 179,
"s": 54,
"text": "Given an array arr[] of length N, the task is to find the overall sum of subsets of all the subsets of the array.Examples: "
},
{
"code": null,
"e": 660,
"s": 179,
"text": "Input: arr[] = {1, 1} Output: 6 All possible subsets: a) {} : 0 All the possible subsets of this subset will be {}, Sum = 0 b) {1} : 1 All the possible subsets of this subset will be {} and {1}, Sum = 0 + 1 = 1 c) {1} : 1 All the possible subsets of this subset will be {} and {1}, Sum = 0 + 1 = 1 d) {1, 1} : 4 All the possible subsets of this subset will be {}, {1}, {1} and {1, 1}, Sum = 0 + 1 + 1 + 2 = 4 Thus, ans = 0 + 1 + 1 + 4 = 6Input: arr[] = {1, 4, 2, 12} Output: 513 "
},
{
"code": null,
"e": 1178,
"s": 662,
"text": "Approach: In this article, an approach with O(N * 2N) time complexity to solve the given problem will be discussed. First, generate all the possible subsets of the array. There will be 2N subsets in total. Then for each subset, find the sum of all of its subsets.For, that it can be observed that in an array of length L, every element will come exactly 2(L – 1) times in the sum of subsets. So, the contribution of each element will be 2(L – 1) times its values.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1182,
"s": 1178,
"text": "C++"
},
{
"code": null,
"e": 1187,
"s": 1182,
"text": "Java"
},
{
"code": null,
"e": 1195,
"s": 1187,
"text": "Python3"
},
{
"code": null,
"e": 1198,
"s": 1195,
"text": "C#"
},
{
"code": null,
"e": 1209,
"s": 1198,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to sum of all subsets of a// given arrayvoid subsetSum(vector<int>& c, int& ans){ int L = c.size(); int mul = (int)pow(2, L - 1); for (int i = 0; i < c.size(); i++) ans += c[i] * mul;} // Function to generate the subsetsvoid subsetGen(int* arr, int i, int n, int& ans, vector<int>& c){ // Base-case if (i == n) { // Finding the sum of all the subsets // of the generated subset subsetSum(c, ans); return; } // Recursively accepting and rejecting // the current number subsetGen(arr, i + 1, n, ans, c); c.push_back(arr[i]); subsetGen(arr, i + 1, n, ans, c); c.pop_back();} // Driver codeint main(){ int arr[] = { 1, 1 }; int n = sizeof(arr) / sizeof(int); // To store the final ans int ans = 0; vector<int> c; subsetGen(arr, 0, n, ans, c); cout << ans; return 0;}",
"e": 2180,
"s": 1209,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ // To store the final ansstatic int ans; // Function to sum of all subsets of a// given arraystatic void subsetSum(Vector<Integer> c){ int L = c.size(); int mul = (int)Math.pow(2, L - 1); for (int i = 0; i < c.size(); i++) ans += c.get(i) * mul;} // Function to generate the subsetsstatic void subsetGen(int []arr, int i, int n, Vector<Integer> c){ // Base-case if (i == n) { // Finding the sum of all the subsets // of the generated subset subsetSum(c); return; } // Recursively accepting and rejecting // the current number subsetGen(arr, i + 1, n, c); c.add(arr[i]); subsetGen(arr, i + 1, n, c); c.remove(0);} // Driver codepublic static void main(String []args){ int arr[] = { 1, 1 }; int n = arr.length; Vector<Integer> c = new Vector<Integer>(); subsetGen(arr, 0, n, c); System.out.println(ans);}} // This code is contributed by 29AjayKumar",
"e": 3210,
"s": 2180,
"text": null
},
{
"code": "# Python3 implementation of the approach # store the answerc = []ans = 0 # Function to sum of all subsets of a# given arraydef subsetSum(): global ans L = len(c) mul = pow(2, L - 1) i = 0 while ( i < len(c)): ans += c[i] * mul i += 1 # Function to generate the subsetsdef subsetGen(arr, i, n): # Base-case if (i == n) : # Finding the sum of all the subsets # of the generated subset subsetSum() return # Recursively accepting and rejecting # the current number subsetGen(arr, i + 1, n) c.append(arr[i]) subsetGen(arr, i + 1, n) c.pop() # Driver codeif __name__ == \"__main__\" : arr = [ 1, 1 ] n = len(arr) subsetGen(arr, 0, n) print (ans) # This code is contributed by Arnab Kundu",
"e": 4004,
"s": 3210,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // To store the final ansstatic int ans; // Function to sum of all subsets of a// given arraystatic void subsetSum(List<int> c){ int L = c.Count; int mul = (int)Math.Pow(2, L - 1); for (int i = 0; i < c.Count; i++) ans += c[i] * mul;} // Function to generate the subsetsstatic void subsetGen(int []arr, int i, int n, List<int> c){ // Base-case if (i == n) { // Finding the sum of all the subsets // of the generated subset subsetSum(c); return; } // Recursively accepting and rejecting // the current number subsetGen(arr, i + 1, n, c); c.Add(arr[i]); subsetGen(arr, i + 1, n, c); c.RemoveAt(0);} // Driver codepublic static void Main(String []args){ int []arr = { 1, 1 }; int n = arr.Length; List<int> c = new List<int>(); subsetGen(arr, 0, n, c); Console.WriteLine(ans);}} // This code is contributed by Rajput-Ji",
"e": 5028,
"s": 4004,
"text": null
},
{
"code": "<script>// javascript implementation of the approach // To store the final ans var ans = 0; // Function to sum of all subsets of a // given array function subsetSum( c) { var L = c.length; var mul = parseInt( Math.pow(2, L - 1)); for (i = 0; i < c.length; i++) ans += c[i] * mul; } // Function to generate the subsets function subsetGen(arr , i , n, c) { // Base-case if (i == n) { // Finding the sum of all the subsets // of the generated subset subsetSum(c); return; } // Recursively accepting and rejecting // the current number subsetGen(arr, i + 1, n, c); c.push(arr[i]); subsetGen(arr, i + 1, n, c); c.pop(0); } // Driver code var arr = [ 1, 1 ]; var n = arr.length; var c = []; subsetGen(arr, 0, n, c); document.write(ans); // This code is contributed by todaysgaurav</script>",
"e": 6029,
"s": 5028,
"text": null
},
{
"code": null,
"e": 6031,
"s": 6029,
"text": "6"
},
{
"code": null,
"e": 6045,
"s": 6033,
"text": "29AjayKumar"
},
{
"code": null,
"e": 6055,
"s": 6045,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 6066,
"s": 6055,
"text": "andrew1234"
},
{
"code": null,
"e": 6079,
"s": 6066,
"text": "todaysgaurav"
},
{
"code": null,
"e": 6086,
"s": 6079,
"text": "subset"
},
{
"code": null,
"e": 6093,
"s": 6086,
"text": "Arrays"
},
{
"code": null,
"e": 6106,
"s": 6093,
"text": "Backtracking"
},
{
"code": null,
"e": 6113,
"s": 6106,
"text": "Greedy"
},
{
"code": null,
"e": 6120,
"s": 6113,
"text": "Arrays"
},
{
"code": null,
"e": 6127,
"s": 6120,
"text": "Greedy"
},
{
"code": null,
"e": 6134,
"s": 6127,
"text": "subset"
},
{
"code": null,
"e": 6147,
"s": 6134,
"text": "Backtracking"
},
{
"code": null,
"e": 6245,
"s": 6147,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6313,
"s": 6245,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 6357,
"s": 6313,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 6389,
"s": 6357,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 6437,
"s": 6389,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 6451,
"s": 6437,
"text": "Linear Search"
},
{
"code": null,
"e": 6536,
"s": 6451,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 6569,
"s": 6536,
"text": "N Queen Problem | Backtracking-3"
},
{
"code": null,
"e": 6612,
"s": 6569,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 6643,
"s": 6612,
"text": "Rat in a Maze | Backtracking-2"
}
] |
Python program to find sum of elements in list | 14 Jun, 2022
Given a list of numbers, write a Python program to find the sum of all the elements in the list.Example:
Input: [12, 15, 3, 10]
Output: 40
Input: [17, 5, 3, 5]
Output: 30
Example #1:
Python3
# Python program to find sum of elements in listtotal = 0 # creating a listlist1 = [11, 5, 17, 18, 23] # Iterate each element in list# and add them in variable totalfor ele in range(0, len(list1)): total = total + list1[ele] # printing total valueprint("Sum of all elements in given list: ", total)
Output:
Sum of all elements in given list: 74
Example #2 : Using while() loop
Python3
# Python program to find sum of elements in listtotal = 0ele = 0 # creating a listlist1 = [11, 5, 17, 18, 23] # Iterate each element in list# and add them in variable totalwhile(ele < len(list1)): total = total + list1[ele] ele += 1 # printing total valueprint("Sum of all elements in given list: ", total)
Output:
Sum of all elements in given list: 74
Example #3: Recursive way
Python3
# Python program to find sum of all# elements in list using recursion # creating a listlist1 = [11, 5, 17, 18, 23] # creating sum_list functiondef sumOfList(list, size): if (size == 0): return 0 else: return list[size - 1] + sumOfList(list, size - 1) # Driver code total = sumOfList(list1, len(list1)) print("Sum of all elements in given list: ", total)
Output:
Sum of all elements in given list: 74
Example #4: Using sum() method
Python3
# Python program to find sum of elements in list # creating a listlist1 = [11, 5, 17, 18, 23] # using sum() functiontotal = sum(list1) # printing total valueprint("Sum of all elements in given list: ", total)
Output:
Sum of all elements in given list: 74
Example 5: Using add() function of operator module.
First we have to import the operator module then using the add() function of operator module adding the all values in the list.
Python3
# Python 3 program to find the sum of all elements in the# list using add function of operator module from operator import*list1 = [12, 15, 3, 10]result = 0for i in list1: # Adding elements in the list using # add function of operator module result = add(i, 0)+result# printing the resultprint(result)
40
sasankgandla
surindertarika1234
laxmigangarajula03
Python list-programs
python-list
Python
Python Programs
School Programming
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Jun, 2022"
},
{
"code": null,
"e": 159,
"s": 52,
"text": "Given a list of numbers, write a Python program to find the sum of all the elements in the list.Example: "
},
{
"code": null,
"e": 226,
"s": 159,
"text": "Input: [12, 15, 3, 10]\nOutput: 40\n\nInput: [17, 5, 3, 5]\nOutput: 30"
},
{
"code": null,
"e": 240,
"s": 226,
"text": "Example #1: "
},
{
"code": null,
"e": 248,
"s": 240,
"text": "Python3"
},
{
"code": "# Python program to find sum of elements in listtotal = 0 # creating a listlist1 = [11, 5, 17, 18, 23] # Iterate each element in list# and add them in variable totalfor ele in range(0, len(list1)): total = total + list1[ele] # printing total valueprint(\"Sum of all elements in given list: \", total)",
"e": 550,
"s": 248,
"text": null
},
{
"code": null,
"e": 560,
"s": 550,
"text": "Output: "
},
{
"code": null,
"e": 599,
"s": 560,
"text": "Sum of all elements in given list: 74"
},
{
"code": null,
"e": 635,
"s": 599,
"text": " Example #2 : Using while() loop "
},
{
"code": null,
"e": 643,
"s": 635,
"text": "Python3"
},
{
"code": "# Python program to find sum of elements in listtotal = 0ele = 0 # creating a listlist1 = [11, 5, 17, 18, 23] # Iterate each element in list# and add them in variable totalwhile(ele < len(list1)): total = total + list1[ele] ele += 1 # printing total valueprint(\"Sum of all elements in given list: \", total)",
"e": 960,
"s": 643,
"text": null
},
{
"code": null,
"e": 970,
"s": 960,
"text": "Output: "
},
{
"code": null,
"e": 1009,
"s": 970,
"text": "Sum of all elements in given list: 74"
},
{
"code": null,
"e": 1039,
"s": 1009,
"text": " Example #3: Recursive way "
},
{
"code": null,
"e": 1047,
"s": 1039,
"text": "Python3"
},
{
"code": "# Python program to find sum of all# elements in list using recursion # creating a listlist1 = [11, 5, 17, 18, 23] # creating sum_list functiondef sumOfList(list, size): if (size == 0): return 0 else: return list[size - 1] + sumOfList(list, size - 1) # Driver code total = sumOfList(list1, len(list1)) print(\"Sum of all elements in given list: \", total)",
"e": 1417,
"s": 1047,
"text": null
},
{
"code": null,
"e": 1427,
"s": 1417,
"text": "Output: "
},
{
"code": null,
"e": 1466,
"s": 1427,
"text": "Sum of all elements in given list: 74"
},
{
"code": null,
"e": 1500,
"s": 1466,
"text": " Example #4: Using sum() method "
},
{
"code": null,
"e": 1508,
"s": 1500,
"text": "Python3"
},
{
"code": "# Python program to find sum of elements in list # creating a listlist1 = [11, 5, 17, 18, 23] # using sum() functiontotal = sum(list1) # printing total valueprint(\"Sum of all elements in given list: \", total)",
"e": 1717,
"s": 1508,
"text": null
},
{
"code": null,
"e": 1727,
"s": 1717,
"text": "Output: "
},
{
"code": null,
"e": 1766,
"s": 1727,
"text": "Sum of all elements in given list: 74"
},
{
"code": null,
"e": 1820,
"s": 1766,
"text": "Example 5: Using add() function of operator module. "
},
{
"code": null,
"e": 1949,
"s": 1820,
"text": "First we have to import the operator module then using the add() function of operator module adding the all values in the list. "
},
{
"code": null,
"e": 1957,
"s": 1949,
"text": "Python3"
},
{
"code": "# Python 3 program to find the sum of all elements in the# list using add function of operator module from operator import*list1 = [12, 15, 3, 10]result = 0for i in list1: # Adding elements in the list using # add function of operator module result = add(i, 0)+result# printing the resultprint(result)",
"e": 2264,
"s": 1957,
"text": null
},
{
"code": null,
"e": 2267,
"s": 2264,
"text": "40"
},
{
"code": null,
"e": 2282,
"s": 2269,
"text": "sasankgandla"
},
{
"code": null,
"e": 2301,
"s": 2282,
"text": "surindertarika1234"
},
{
"code": null,
"e": 2320,
"s": 2301,
"text": "laxmigangarajula03"
},
{
"code": null,
"e": 2341,
"s": 2320,
"text": "Python list-programs"
},
{
"code": null,
"e": 2353,
"s": 2341,
"text": "python-list"
},
{
"code": null,
"e": 2360,
"s": 2353,
"text": "Python"
},
{
"code": null,
"e": 2376,
"s": 2360,
"text": "Python Programs"
},
{
"code": null,
"e": 2395,
"s": 2376,
"text": "School Programming"
},
{
"code": null,
"e": 2407,
"s": 2395,
"text": "python-list"
}
] |
Primality Test | Set 2 (Fermat Method) | 15 Jun, 2021
Given a number n, check if it is prime or not. We have introduced and discussed the School method for primality testing in Set 1.Primality Test | Set 1 (Introduction and School Method)In this post, Fermat’s method is discussed. This method is a probabilistic method and is based on Fermat’s Little Theorem.
Fermat's Little Theorem:
If n is a prime number, then for every a, 1 < a < n-1,
an-1 ≡ 1 (mod n)
OR
an-1 % n = 1
Example: Since 5 is prime, 24 ≡ 1 (mod 5) [or 24%5 = 1],
34 ≡ 1 (mod 5) and 44 ≡ 1 (mod 5)
Since 7 is prime, 26 ≡ 1 (mod 7),
36 ≡ 1 (mod 7), 46 ≡ 1 (mod 7)
56 ≡ 1 (mod 7) and 66 ≡ 1 (mod 7)
Refer this for different proofs.
If a given number is prime, then this method always returns true. If the given number is composite (or non-prime), then it may return true or false, but the probability of producing incorrect results for composite is low and can be reduced by doing more iterations.
Below is algorithm:
// Higher value of k indicates probability of correct
// results for composite inputs become higher. For prime
// inputs, result is always correct
1) Repeat following k times:
a) Pick a randomly in the range [2, n - 2]
b) If gcd(a, n) ≠ 1, then return false
c) If an-1 ≢ 1 (mod n), then return false
2) Return true [probably prime].
Below is the implementation of the above algorithm. The code uses power function from Modular Exponentiation
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find the smallest twin in given range#include <bits/stdc++.h>using namespace std; /* Iterative Function to calculate (a^n)%p in O(logy) */int power(int a, unsigned int n, int p){ int res = 1; // Initialize result a = a % p; // Update 'a' if 'a' >= p while (n > 0) { // If n is odd, multiply 'a' with result if (n & 1) res = (res*a) % p; // n must be even now n = n>>1; // n = n/2 a = (a*a) % p; } return res;} /*Recursive function to calculate gcd of 2 numbers*/int gcd(int a, int b){ if(a < b) return gcd(b, a); else if(a%b == 0) return b; else return gcd(b, a%b); } // If n is prime, then always returns true, If n is// composite than returns false with high probability// Higher value of k increases probability of correct// result.bool isPrime(unsigned int n, int k){ // Corner cases if (n <= 1 || n == 4) return false; if (n <= 3) return true; // Try k times while (k>0) { // Pick a random number in [2..n-2] // Above corner cases make sure that n > 4 int a = 2 + rand()%(n-4); // Checking if a and n are co-prime if (gcd(n, a) != 1) return false; // Fermat's little theorem if (power(a, n-1, n) != 1) return false; k--; } return true;} // Driver Program to test above functionint main(){ int k = 3; isPrime(11, k)? cout << " true\n": cout << " false\n"; isPrime(15, k)? cout << " true\n": cout << " false\n"; return 0;}
// Java program to find the// smallest twin in given range import java.io.*;import java.math.*; class GFG { /* Iterative Function to calculate // (a^n)%p in O(logy) */ static int power(int a,int n, int p) { // Initialize result int res = 1; // Update 'a' if 'a' >= p a = a % p; while (n > 0) { // If n is odd, multiply 'a' with result if ((n & 1) == 1) res = (res * a) % p; // n must be even now n = n >> 1; // n = n/2 a = (a * a) % p; } return res; } // If n is prime, then always returns true, // If n is composite than returns false with // high probability Higher value of k increases // probability of correct result. static boolean isPrime(int n, int k) { // Corner cases if (n <= 1 || n == 4) return false; if (n <= 3) return true; // Try k times while (k > 0) { // Pick a random number in [2..n-2] // Above corner cases make sure that n > 4 int a = 2 + (int)(Math.random() % (n - 4)); // Fermat's little theorem if (power(a, n - 1, n) != 1) return false; k--; } return true; } // Driver Program public static void main(String args[]) { int k = 3; if(isPrime(11, k)) System.out.println(" true"); else System.out.println(" false"); if(isPrime(15, k)) System.out.println(" true"); else System.out.println(" false"); }} // This code is contributed by Nikita Tiwari.
# Python3 program to find the smallest# twin in given rangeimport random # Iterative Function to calculate# (a^n)%p in O(logy)def power(a, n, p): # Initialize result res = 1 # Update 'a' if 'a' >= p a = a % p while n > 0: # If n is odd, multiply # 'a' with result if n % 2: res = (res * a) % p n = n - 1 else: a = (a ** 2) % p # n must be even now n = n // 2 return res % p # If n is prime, then always returns true,# If n is composite than returns false with# high probability Higher value of k increases# probability of correct resultdef isPrime(n, k): # Corner cases if n == 1 or n == 4: return False elif n == 2 or n == 3: return True # Try k times else: for i in range(k): # Pick a random number # in [2..n-2] # Above corner cases make # sure that n > 4 a = random.randint(2, n - 2) # Fermat's little theorem if power(a, n - 1, n) != 1: return False return True # Driver codek = 3if isPrime(11, k): print("true")else: print("false") if isPrime(15, k): print("true")else: print("false") # This code is contributed by Aanchal Tiwari
// C# program to find the// smallest twin in given rangeusing System;class GFG { /* Iterative Function to calculate // (a^n)%p in O(logy) */ static int power(int a,int n, int p) { // Initialize result int res = 1; // Update 'a' if 'a' >= p a = a % p; while (n > 0) { // If n is odd, multiply 'a' with result if ((n & 1) == 1) res = (res * a) % p; // n must be even now n = n >> 1; // n = n/2 a = (a * a) % p; } return res; } // If n is prime, then always returns true, // If n is composite than returns false with // high probability Higher value of k increases // probability of correct result. static bool isPrime(int n, int k) { // Corner cases if (n <= 1 || n == 4) return false; if (n <= 3) return true; // Try k times while (k > 0) { // Pick a random number in [2..n-2] // Above corner cases make sure that n > 4 Random rand = new Random(); int a = 2 + (int)(rand.Next() % (n - 4)); // Fermat's little theorem if (power(a, n - 1, n) != 1) return false; k--; } return true; } static void Main() { int k = 3; if(isPrime(11, k)) Console.WriteLine(" true"); else Console.WriteLine(" false"); if(isPrime(15, k)) Console.WriteLine(" true"); else Console.WriteLine(" false"); }} // This code is contributed by divyesh072019
<?php// PHP program to find the// smallest twin in given range // Iterative Function to calculate// (a^n)%p in O(logy)function power($a, $n, $p){ // Initialize result $res = 1; // Update 'a' if 'a' >= p $a = $a % $p; while ($n > 0) { // If n is odd, multiply // 'a' with result if ($n & 1) $res = ($res * $a) % $p; // n must be even now $n = $n >> 1; // n = n/2 $a = ($a * $a) % $p; } return $res;} // If n is prime, then always// returns true, If n is// composite than returns// false with high probability// Higher value of k increases// probability of correct// result.function isPrime($n, $k){ // Corner cases if ($n <= 1 || $n == 4) return false; if ($n <= 3) return true; // Try k times while ($k > 0) { // Pick a random number // in [2..n-2] // Above corner cases // make sure that n > 4 $a = 2 + rand() % ($n - 4); // Fermat's little theorem if (power($a, $n-1, $n) != 1) return false; $k--; } return true;} // Driver Code$k = 3;$res = isPrime(11, $k) ? " true\n": " false\n";echo($res); $res = isPrime(15, $k) ? " true\n": " false\n";echo($res); // This code is contributed by Ajit.?>
<script> // Javascript program to find the// smallest twin in given range /* Iterative Function to calculate// (a^n)%p in O(logy) */function power( a, n, p){ // Initialize result let res = 1; // Update 'a' if 'a' >= p a = a % p; while (n > 0) { // If n is odd, multiply 'a' with result if ((n & 1) == 1) res = (res * a) % p; // n must be even now n = n >> 1; // n = n/2 a = (a * a) % p; } return res;} // If n is prime, then always returns true,// If n is composite than returns false with// high probability Higher value of k increases// probability of correct result.function isPrime( n, k){// Corner casesif (n <= 1 || n == 4) return false;if (n <= 3) return true; // Try k timeswhile (k > 0){ // Pick a random number in [2..n-2] // Above corner cases make sure that n > 4 let a = Math.floor(Math.random()* (n-1 - 2) + 2); // Fermat's little theorem if (power(a, n - 1, n) != 1) return false; k--; } return true;} // Driver Code let k = 3;if(isPrime(11, k)) document.write(" true" + "</br>");else document.write(" false"+ "</br>");if(isPrime(15, k)) document.write(" true"+ "</br>");else document.write(" false"+ "</br>"); </script>
Output:
true
false
Time complexity of this solution is O(k Log n). Note that the power function takes O(Log n) time. Note that the above method may fail even if we increase the number of iterations (higher k). There exist some composite numbers with the property that for every a < n, gcd(a, n) = 1 and an-1 ≡ 1 (mod n). Such numbers are called Carmichael numbers. Fermat’s primality test is often used if a rapid method is needed for filtering, for example in the key generation phase of the RSA public key cryptographic algorithm.
We will soon be discussing more methods for Primality Testing.
References: https://en.wikipedia.org/wiki/Fermat_primality_test https://en.wikipedia.org/wiki/Prime_number http://www.cse.iitk.ac.in/users/manindra/presentations/FLTBasedTests.pdf https://en.wikipedia.org/wiki/Primality_testThis article is contributed by Ajay. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
jit_t
DevarshiSingh
SamanvayaPanda
aanchaltiwari
divyesh072019
jana_sayantan
nishantjawla12225
Modular Arithmetic
number-theory
Prime Number
Mathematical
Randomized
number-theory
Mathematical
Prime Number
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)
Shuffle a given array using Fisher–Yates shuffle Algorithm
Shuffle or Randomize a list in Java
Generating Random String Using PHP
Estimating the value of Pi using Monte Carlo | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Jun, 2021"
},
{
"code": null,
"e": 359,
"s": 52,
"text": "Given a number n, check if it is prime or not. We have introduced and discussed the School method for primality testing in Set 1.Primality Test | Set 1 (Introduction and School Method)In this post, Fermat’s method is discussed. This method is a probabilistic method and is based on Fermat’s Little Theorem."
},
{
"code": null,
"e": 743,
"s": 359,
"text": "Fermat's Little Theorem:\nIf n is a prime number, then for every a, 1 < a < n-1,\n\nan-1 ≡ 1 (mod n)\n OR \nan-1 % n = 1 \n \n\nExample: Since 5 is prime, 24 ≡ 1 (mod 5) [or 24%5 = 1],\n 34 ≡ 1 (mod 5) and 44 ≡ 1 (mod 5) \n\n Since 7 is prime, 26 ≡ 1 (mod 7),\n 36 ≡ 1 (mod 7), 46 ≡ 1 (mod 7) \n 56 ≡ 1 (mod 7) and 66 ≡ 1 (mod 7) \n\nRefer this for different proofs."
},
{
"code": null,
"e": 1009,
"s": 743,
"text": "If a given number is prime, then this method always returns true. If the given number is composite (or non-prime), then it may return true or false, but the probability of producing incorrect results for composite is low and can be reduced by doing more iterations."
},
{
"code": null,
"e": 1030,
"s": 1009,
"text": "Below is algorithm: "
},
{
"code": null,
"e": 1390,
"s": 1030,
"text": "// Higher value of k indicates probability of correct\n// results for composite inputs become higher. For prime\n// inputs, result is always correct\n1) Repeat following k times:\n a) Pick a randomly in the range [2, n - 2]\n b) If gcd(a, n) ≠ 1, then return false\n c) If an-1 ≢ 1 (mod n), then return false\n2) Return true [probably prime]."
},
{
"code": null,
"e": 1500,
"s": 1390,
"text": "Below is the implementation of the above algorithm. The code uses power function from Modular Exponentiation "
},
{
"code": null,
"e": 1504,
"s": 1500,
"text": "C++"
},
{
"code": null,
"e": 1509,
"s": 1504,
"text": "Java"
},
{
"code": null,
"e": 1517,
"s": 1509,
"text": "Python3"
},
{
"code": null,
"e": 1520,
"s": 1517,
"text": "C#"
},
{
"code": null,
"e": 1524,
"s": 1520,
"text": "PHP"
},
{
"code": null,
"e": 1535,
"s": 1524,
"text": "Javascript"
},
{
"code": "// C++ program to find the smallest twin in given range#include <bits/stdc++.h>using namespace std; /* Iterative Function to calculate (a^n)%p in O(logy) */int power(int a, unsigned int n, int p){ int res = 1; // Initialize result a = a % p; // Update 'a' if 'a' >= p while (n > 0) { // If n is odd, multiply 'a' with result if (n & 1) res = (res*a) % p; // n must be even now n = n>>1; // n = n/2 a = (a*a) % p; } return res;} /*Recursive function to calculate gcd of 2 numbers*/int gcd(int a, int b){ if(a < b) return gcd(b, a); else if(a%b == 0) return b; else return gcd(b, a%b); } // If n is prime, then always returns true, If n is// composite than returns false with high probability// Higher value of k increases probability of correct// result.bool isPrime(unsigned int n, int k){ // Corner cases if (n <= 1 || n == 4) return false; if (n <= 3) return true; // Try k times while (k>0) { // Pick a random number in [2..n-2] // Above corner cases make sure that n > 4 int a = 2 + rand()%(n-4); // Checking if a and n are co-prime if (gcd(n, a) != 1) return false; // Fermat's little theorem if (power(a, n-1, n) != 1) return false; k--; } return true;} // Driver Program to test above functionint main(){ int k = 3; isPrime(11, k)? cout << \" true\\n\": cout << \" false\\n\"; isPrime(15, k)? cout << \" true\\n\": cout << \" false\\n\"; return 0;}",
"e": 3087,
"s": 1535,
"text": null
},
{
"code": "// Java program to find the// smallest twin in given range import java.io.*;import java.math.*; class GFG { /* Iterative Function to calculate // (a^n)%p in O(logy) */ static int power(int a,int n, int p) { // Initialize result int res = 1; // Update 'a' if 'a' >= p a = a % p; while (n > 0) { // If n is odd, multiply 'a' with result if ((n & 1) == 1) res = (res * a) % p; // n must be even now n = n >> 1; // n = n/2 a = (a * a) % p; } return res; } // If n is prime, then always returns true, // If n is composite than returns false with // high probability Higher value of k increases // probability of correct result. static boolean isPrime(int n, int k) { // Corner cases if (n <= 1 || n == 4) return false; if (n <= 3) return true; // Try k times while (k > 0) { // Pick a random number in [2..n-2] // Above corner cases make sure that n > 4 int a = 2 + (int)(Math.random() % (n - 4)); // Fermat's little theorem if (power(a, n - 1, n) != 1) return false; k--; } return true; } // Driver Program public static void main(String args[]) { int k = 3; if(isPrime(11, k)) System.out.println(\" true\"); else System.out.println(\" false\"); if(isPrime(15, k)) System.out.println(\" true\"); else System.out.println(\" false\"); }} // This code is contributed by Nikita Tiwari.",
"e": 4767,
"s": 3087,
"text": null
},
{
"code": "# Python3 program to find the smallest# twin in given rangeimport random # Iterative Function to calculate# (a^n)%p in O(logy)def power(a, n, p): # Initialize result res = 1 # Update 'a' if 'a' >= p a = a % p while n > 0: # If n is odd, multiply # 'a' with result if n % 2: res = (res * a) % p n = n - 1 else: a = (a ** 2) % p # n must be even now n = n // 2 return res % p # If n is prime, then always returns true,# If n is composite than returns false with# high probability Higher value of k increases# probability of correct resultdef isPrime(n, k): # Corner cases if n == 1 or n == 4: return False elif n == 2 or n == 3: return True # Try k times else: for i in range(k): # Pick a random number # in [2..n-2] # Above corner cases make # sure that n > 4 a = random.randint(2, n - 2) # Fermat's little theorem if power(a, n - 1, n) != 1: return False return True # Driver codek = 3if isPrime(11, k): print(\"true\")else: print(\"false\") if isPrime(15, k): print(\"true\")else: print(\"false\") # This code is contributed by Aanchal Tiwari",
"e": 6166,
"s": 4767,
"text": null
},
{
"code": "// C# program to find the// smallest twin in given rangeusing System;class GFG { /* Iterative Function to calculate // (a^n)%p in O(logy) */ static int power(int a,int n, int p) { // Initialize result int res = 1; // Update 'a' if 'a' >= p a = a % p; while (n > 0) { // If n is odd, multiply 'a' with result if ((n & 1) == 1) res = (res * a) % p; // n must be even now n = n >> 1; // n = n/2 a = (a * a) % p; } return res; } // If n is prime, then always returns true, // If n is composite than returns false with // high probability Higher value of k increases // probability of correct result. static bool isPrime(int n, int k) { // Corner cases if (n <= 1 || n == 4) return false; if (n <= 3) return true; // Try k times while (k > 0) { // Pick a random number in [2..n-2] // Above corner cases make sure that n > 4 Random rand = new Random(); int a = 2 + (int)(rand.Next() % (n - 4)); // Fermat's little theorem if (power(a, n - 1, n) != 1) return false; k--; } return true; } static void Main() { int k = 3; if(isPrime(11, k)) Console.WriteLine(\" true\"); else Console.WriteLine(\" false\"); if(isPrime(15, k)) Console.WriteLine(\" true\"); else Console.WriteLine(\" false\"); }} // This code is contributed by divyesh072019",
"e": 7859,
"s": 6166,
"text": null
},
{
"code": "<?php// PHP program to find the// smallest twin in given range // Iterative Function to calculate// (a^n)%p in O(logy)function power($a, $n, $p){ // Initialize result $res = 1; // Update 'a' if 'a' >= p $a = $a % $p; while ($n > 0) { // If n is odd, multiply // 'a' with result if ($n & 1) $res = ($res * $a) % $p; // n must be even now $n = $n >> 1; // n = n/2 $a = ($a * $a) % $p; } return $res;} // If n is prime, then always// returns true, If n is// composite than returns// false with high probability// Higher value of k increases// probability of correct// result.function isPrime($n, $k){ // Corner cases if ($n <= 1 || $n == 4) return false; if ($n <= 3) return true; // Try k times while ($k > 0) { // Pick a random number // in [2..n-2] // Above corner cases // make sure that n > 4 $a = 2 + rand() % ($n - 4); // Fermat's little theorem if (power($a, $n-1, $n) != 1) return false; $k--; } return true;} // Driver Code$k = 3;$res = isPrime(11, $k) ? \" true\\n\": \" false\\n\";echo($res); $res = isPrime(15, $k) ? \" true\\n\": \" false\\n\";echo($res); // This code is contributed by Ajit.?>",
"e": 9178,
"s": 7859,
"text": null
},
{
"code": "<script> // Javascript program to find the// smallest twin in given range /* Iterative Function to calculate// (a^n)%p in O(logy) */function power( a, n, p){ // Initialize result let res = 1; // Update 'a' if 'a' >= p a = a % p; while (n > 0) { // If n is odd, multiply 'a' with result if ((n & 1) == 1) res = (res * a) % p; // n must be even now n = n >> 1; // n = n/2 a = (a * a) % p; } return res;} // If n is prime, then always returns true,// If n is composite than returns false with// high probability Higher value of k increases// probability of correct result.function isPrime( n, k){// Corner casesif (n <= 1 || n == 4) return false;if (n <= 3) return true; // Try k timeswhile (k > 0){ // Pick a random number in [2..n-2] // Above corner cases make sure that n > 4 let a = Math.floor(Math.random()* (n-1 - 2) + 2); // Fermat's little theorem if (power(a, n - 1, n) != 1) return false; k--; } return true;} // Driver Code let k = 3;if(isPrime(11, k)) document.write(\" true\" + \"</br>\");else document.write(\" false\"+ \"</br>\");if(isPrime(15, k)) document.write(\" true\"+ \"</br>\");else document.write(\" false\"+ \"</br>\"); </script>",
"e": 10478,
"s": 9178,
"text": null
},
{
"code": null,
"e": 10487,
"s": 10478,
"text": "Output: "
},
{
"code": null,
"e": 10498,
"s": 10487,
"text": "true\nfalse"
},
{
"code": null,
"e": 11012,
"s": 10498,
"text": "Time complexity of this solution is O(k Log n). Note that the power function takes O(Log n) time. Note that the above method may fail even if we increase the number of iterations (higher k). There exist some composite numbers with the property that for every a < n, gcd(a, n) = 1 and an-1 ≡ 1 (mod n). Such numbers are called Carmichael numbers. Fermat’s primality test is often used if a rapid method is needed for filtering, for example in the key generation phase of the RSA public key cryptographic algorithm."
},
{
"code": null,
"e": 11075,
"s": 11012,
"text": "We will soon be discussing more methods for Primality Testing."
},
{
"code": null,
"e": 11461,
"s": 11075,
"text": "References: https://en.wikipedia.org/wiki/Fermat_primality_test https://en.wikipedia.org/wiki/Prime_number http://www.cse.iitk.ac.in/users/manindra/presentations/FLTBasedTests.pdf https://en.wikipedia.org/wiki/Primality_testThis article is contributed by Ajay. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 11467,
"s": 11461,
"text": "jit_t"
},
{
"code": null,
"e": 11481,
"s": 11467,
"text": "DevarshiSingh"
},
{
"code": null,
"e": 11496,
"s": 11481,
"text": "SamanvayaPanda"
},
{
"code": null,
"e": 11510,
"s": 11496,
"text": "aanchaltiwari"
},
{
"code": null,
"e": 11524,
"s": 11510,
"text": "divyesh072019"
},
{
"code": null,
"e": 11538,
"s": 11524,
"text": "jana_sayantan"
},
{
"code": null,
"e": 11556,
"s": 11538,
"text": "nishantjawla12225"
},
{
"code": null,
"e": 11575,
"s": 11556,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 11589,
"s": 11575,
"text": "number-theory"
},
{
"code": null,
"e": 11602,
"s": 11589,
"text": "Prime Number"
},
{
"code": null,
"e": 11615,
"s": 11602,
"text": "Mathematical"
},
{
"code": null,
"e": 11626,
"s": 11615,
"text": "Randomized"
},
{
"code": null,
"e": 11640,
"s": 11626,
"text": "number-theory"
},
{
"code": null,
"e": 11653,
"s": 11640,
"text": "Mathematical"
},
{
"code": null,
"e": 11666,
"s": 11653,
"text": "Prime Number"
},
{
"code": null,
"e": 11685,
"s": 11666,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 11783,
"s": 11685,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11813,
"s": 11783,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 11856,
"s": 11813,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 11916,
"s": 11856,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 11931,
"s": 11916,
"text": "C++ Data Types"
},
{
"code": null,
"e": 11955,
"s": 11931,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 12034,
"s": 11955,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)"
},
{
"code": null,
"e": 12093,
"s": 12034,
"text": "Shuffle a given array using Fisher–Yates shuffle Algorithm"
},
{
"code": null,
"e": 12129,
"s": 12093,
"text": "Shuffle or Randomize a list in Java"
},
{
"code": null,
"e": 12164,
"s": 12129,
"text": "Generating Random String Using PHP"
}
] |
Twitter Interview | Set 1 | 22 Oct, 2021
Phone screen – I
1. Fibonacci series without using an array – this is a typical favorite question w.r.t. Dynamic Programming where you will ask not to use Memoization or any extra storage to store the values of the previous iterations. (More complicated version of the same problem: Generate Nth row of pascal’s triangle w/o using a 2D array of dimensions N x N)
2. N-ary tree: find if a node exists in the tree with value = x. If yes, return true, else, return false.
Phone screen – II 1. Find the lowest common ancestor of Binary Tree Answer: Done it 10 times Explained how to do it!
2. Clone a graph and analyze the time and space complexity (since DFS based approaches leverage smaller time at the cost of higher memory)
public class Node {
public int data;
List neighbhors;
public Node (int data) {...}
setNeighbors(List neighbhors) {...}
}
// HashMap created = new HashMap();
public Node clone(Node oldGraph) {
if (created.get(oldGraph))
return created.get(oldGraph);
Node newGr = new Node(oldGraph.data);
List nbors = new ArrayList();
created.put(oldGraph, newGr);
List adj = oldGraph.getNeighbhors();
for (Node n : adj) {
nbors.add(clone(n));
}
newGr.setNeighbors(nbors);
return newGr;
}
Phone Screen III
Design a bloom filter to remove the duplicates from an unsorted array!
On-site
1. (Boggle–like a question) In a 2D array (M x N, in the given ex. 3×3) of numbers, find the strictly increasing path from the specified origin cell (1,0) to the specified destination cell (0, 2). The array may contain duplicates, and the solution should work with the dups.
2.a. Design a unique hash function for every tweet on Twitter which will be used as part of a service. 2.b. Find if a directed graph has cycles or not. Write a function with boolean return type for the same.
3. Casual Lunch interview.
4. Pattern matching using patterns containing chars (a to z) and ‘*’, ‘?’ and ‘.’
5.a. Describe how would you do external sort -> come to a map-reduce kind of solution. Each machine has 10M numbers (total 100M), 10 total machines. Each m/c has 20MB RAM and 50GB memory. 5.b. N-Queens problem: find and print all possible non-conflicting positions for the Queen.
6.a. Given an input binary tree and reference to a Node in the tree, find the next in-order successor for the input node. Output null if none. 6.b. What is the best way to sort a k-sorted array? Optimize for time complexity. (My hint: use a priority queue of size k)
7.a. Hiring manager: Design service for a. Durability b. Consistency 7.b. Explain C++’s problem with multiple inheritances.
If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Twitter
Interview Experiences
Twitter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE 1
Amazon Interview Experience SDE-2 (3 Years Experienced)
Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022
Google SWE Interview Experience (Google Online Coding Challenge) 2022
Write It Up: Share Your Interview Experiences
Nagarro Interview Experience | On-Campus 2021
Amazon Interview Experience for SDE-1
Nagarro Interview Experience
Tiger Analytics Interview Experience for Data Analyst (On-Campus)
Samsung Software Competency Test (SWC) for Working professionals | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Oct, 2021"
},
{
"code": null,
"e": 72,
"s": 54,
"text": "Phone screen – I "
},
{
"code": null,
"e": 419,
"s": 72,
"text": "1. Fibonacci series without using an array – this is a typical favorite question w.r.t. Dynamic Programming where you will ask not to use Memoization or any extra storage to store the values of the previous iterations. (More complicated version of the same problem: Generate Nth row of pascal’s triangle w/o using a 2D array of dimensions N x N) "
},
{
"code": null,
"e": 526,
"s": 419,
"text": "2. N-ary tree: find if a node exists in the tree with value = x. If yes, return true, else, return false. "
},
{
"code": null,
"e": 645,
"s": 526,
"text": "Phone screen – II 1. Find the lowest common ancestor of Binary Tree Answer: Done it 10 times Explained how to do it! "
},
{
"code": null,
"e": 786,
"s": 645,
"text": "2. Clone a graph and analyze the time and space complexity (since DFS based approaches leverage smaller time at the cost of higher memory) "
},
{
"code": null,
"e": 1304,
"s": 786,
"text": "public class Node {\n public int data;\n List neighbhors;\n\n public Node (int data) {...}\n setNeighbors(List neighbhors) {...}\n}\n\n// HashMap created = new HashMap();\n\npublic Node clone(Node oldGraph) {\n\n if (created.get(oldGraph))\n return created.get(oldGraph);\n\n Node newGr = new Node(oldGraph.data);\n List nbors = new ArrayList();\n\n created.put(oldGraph, newGr);\n\n List adj = oldGraph.getNeighbhors();\n for (Node n : adj) {\n nbors.add(clone(n));\n }\n\n newGr.setNeighbors(nbors);\n return newGr;\n}"
},
{
"code": null,
"e": 1322,
"s": 1304,
"text": "Phone Screen III "
},
{
"code": null,
"e": 1394,
"s": 1322,
"text": "Design a bloom filter to remove the duplicates from an unsorted array! "
},
{
"code": null,
"e": 1403,
"s": 1394,
"text": "On-site "
},
{
"code": null,
"e": 1679,
"s": 1403,
"text": "1. (Boggle–like a question) In a 2D array (M x N, in the given ex. 3×3) of numbers, find the strictly increasing path from the specified origin cell (1,0) to the specified destination cell (0, 2). The array may contain duplicates, and the solution should work with the dups. "
},
{
"code": null,
"e": 1888,
"s": 1679,
"text": "2.a. Design a unique hash function for every tweet on Twitter which will be used as part of a service. 2.b. Find if a directed graph has cycles or not. Write a function with boolean return type for the same. "
},
{
"code": null,
"e": 1916,
"s": 1888,
"text": "3. Casual Lunch interview. "
},
{
"code": null,
"e": 1999,
"s": 1916,
"text": "4. Pattern matching using patterns containing chars (a to z) and ‘*’, ‘?’ and ‘.’ "
},
{
"code": null,
"e": 2280,
"s": 1999,
"text": "5.a. Describe how would you do external sort -> come to a map-reduce kind of solution. Each machine has 10M numbers (total 100M), 10 total machines. Each m/c has 20MB RAM and 50GB memory. 5.b. N-Queens problem: find and print all possible non-conflicting positions for the Queen. "
},
{
"code": null,
"e": 2548,
"s": 2280,
"text": "6.a. Given an input binary tree and reference to a Node in the tree, find the next in-order successor for the input node. Output null if none. 6.b. What is the best way to sort a k-sorted array? Optimize for time complexity. (My hint: use a priority queue of size k) "
},
{
"code": null,
"e": 2673,
"s": 2548,
"text": "7.a. Hiring manager: Design service for a. Durability b. Consistency 7.b. Explain C++’s problem with multiple inheritances. "
},
{
"code": null,
"e": 2896,
"s": 2673,
"text": "If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 2904,
"s": 2896,
"text": "Twitter"
},
{
"code": null,
"e": 2926,
"s": 2904,
"text": "Interview Experiences"
},
{
"code": null,
"e": 2934,
"s": 2926,
"text": "Twitter"
},
{
"code": null,
"e": 3032,
"s": 2934,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3070,
"s": 3032,
"text": "Amazon Interview Experience for SDE 1"
},
{
"code": null,
"e": 3126,
"s": 3070,
"text": "Amazon Interview Experience SDE-2 (3 Years Experienced)"
},
{
"code": null,
"e": 3199,
"s": 3126,
"text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022"
},
{
"code": null,
"e": 3269,
"s": 3199,
"text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022"
},
{
"code": null,
"e": 3315,
"s": 3269,
"text": "Write It Up: Share Your Interview Experiences"
},
{
"code": null,
"e": 3361,
"s": 3315,
"text": "Nagarro Interview Experience | On-Campus 2021"
},
{
"code": null,
"e": 3399,
"s": 3361,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 3428,
"s": 3399,
"text": "Nagarro Interview Experience"
},
{
"code": null,
"e": 3494,
"s": 3428,
"text": "Tiger Analytics Interview Experience for Data Analyst (On-Campus)"
}
] |
Visualization of a correlation matrix using ggplot2 in R | 21 Jul, 2021
In this article, we will discuss how to visualize a correlation matrix using ggplot2 package in R programming language.
In order to do this, we will install a package called ggcorrplot package. With the help of this package, we can easily visualize a correlation matrix. We can also compute a matrix of correlation p-values by using a function that is present in this package. The corr_pmat() is used for computing the correlation matrix of p-values and the ggcorrplot() is used for displaying the correlation matrix using ggplot.
Syntax :
corr_pmat(x,..)
Where x is the dataframe or the matrix
Syntax:
ggcorrplot(corr, method = c(“circle”, “square”), type = c(“full”, “lower”, “upper”), title = “”, ggtheme=ggplot2::theme_minimal, show.legend = TRUE, legend.title = “corr”, show.diag = FALSE, colors = c(“blue”, “white”, “red”), outline.color = “gray”, hc.order = FALSE, hc.method = “complete”, lab = FALSE, lab_col =”black”, p.mat = NULL,.. )
We will first install and load the ggcorrplot and ggplot2 package using the install.packages() to install and library() to load the package. We need a dataset to construct our correlation matrix and then visualize it. We will create our correlation matrix with the help of cor() function, which computes the correlation coefficient. After computing the correlation matrix, we will compute the matrix of correlation p-values using the corr_pmat() function. Next, we will visualize the correlation matrix with the help of ggcorrplot() function using ggplot2.
We will take a sample dataset for explaining our approach better. We will take the inbuilt USArrests dataset, and we will visualize its correlation matrix following the above approach. We will read the data using the data() function, and we will create the correlation matrix with the help of cor() function to compute the correlation coefficient. The round() function is used to round off the values to a specific decimal value. We will use cor_pmat() function to compute the correlation matrix with p-values.
Syntax :
correlation_matrix <- round(cor(data),1)
Parameters :
correlation_matrix : Variable for correlation matrix used to visualize.
data : data is our dataset which we have taken for visualization.
Syntax:
corrp.mat <- cor_pmat(data)
Parameters :
corrp.mat : Variable for correlation matrix with p-values.
data : It is our dataset taken for creating correlation matrix with p-values.
Example: Creating a correlation matrix
R
# Installing and loading the ggcorrplot packageinstall.packages("ggcorrplot")library(ggcorrplot) # Reading the datadata(USArrests) # Computing correlation matrixcorrelation_matrix <- round(cor(USArrests),1) head(correlation_matrix[, 1:4]) # Computing correlation matrix with p-valuescorrp.mat <- cor_pmat(USArrests) head(corrp.mat[, 1:4])
Output :
Now since we have a correlation matrix and the correlation matrix with p-values, we will now try to visualize this correlation matrix. The first visualization is to use the ggcorrplot() function and plot our correlation matrix in the form of the square and circle method.
Syntax :
ggcorrplot(correlation_matrix, method= c(“circle”,”square”))
Parameters :
correlation_matrix : The correlation matrix for visualization.
method : It is a character value used for visualization methods.
Example: Visualizing the correlation matrix using different methods
R
library(ggplot2)library(ggcorrplot) # Reading the datadata(USArrests) # Computing correlation matrixcorrelation_matrix <- round(cor(USArrests),1) # Computing correlation matrix with p-valuescorrp.mat <- cor_pmat(USArrests) # Visualizing the correlation matrix using # square and circle methodsggcorrplot(correlation_matrix, method ="square")ggcorrplot(correlation_matrix, method ="circle")
Output :
Correlation matrix with circular method
Correlation matrix with square method
Next, we will visualize correlogram layout types in our correlation matrix and providing hc.order and type as lower for lower triangle layout and upper for upper triangle layout as parameters in ggcorrplot() function.
Syntax : ggcorrplot(correlation_matrix, hc.order = TRUE, type = c(“upper”, “lower”), outline.color = “white”)
Parameters :
correlation_matrix : The correlation matrix used for visualization.
hc.order : If it is true, then the correlation matrix will be ordered.
type : It is the arrangement of the character to display.
outline.color : It is the outline color of the square or circle.
Example: Visualizing correlation matrix using different layouts
R
library(ggplot2)library(ggcorrplot) # Reading the datadata(USArrests) # Computing correlation matrixcorrelation_matrix <- round(cor(USArrests),1) # Computing correlation matrix with p-valuescorrp.mat <- cor_pmat(USArrests) # Visualizing upper and lower triangle layoutsggcorrplot(correlation_matrix, hc.order =TRUE, type ="lower", outline.color ="white") ggcorrplot(correlation_matrix, hc.order =TRUE, type ="upper", outline.color ="white")
Output :
Correlation matrix with upper layout
Correlation matrix with lower layout
We will now visualize our correlation matrix by reordering the matrix using hierarchical clustering. We will do this using the ggcorrplot function with correlation matrix, hc.order, outline.color as arguments.
Syntax :
ggcorrplot(correlation_matrix, hc.order = TRUE, outline.color = “white”)
Parameters :
correlation_matrix : The correlation matrix used for visualization.
hc.order : If it is true, then the correlation matrix will be ordered.
outline.color : It is the outline color of the square or circle.
Example: Reordering of the correlation matrix
R
library(ggplot2)library(ggcorrplot) # Reading the datadata(USArrests) # Computing correlation matrixcorrelation_matrix <- round(cor(USArrests),1) # Computing correlation matrix with # p-valuescorrp.mat <- cor_pmat(USArrests) # Visualizing and reordering correlation# matrixggcorrplot(correlation_matrix, hc.order =TRUE, outline.color ="white")
Output :
We will now visualize our correlation matrix by adding the correlation coefficient using the ggcorrplot function and providing correlation matrix, hc.order, type, and lower variables as arguments.
Syntax :
ggcorrplot(correlation_matrix, hc.order = TRUE, type = “lower”, lab = TRUE)
Parameters :
correlation_matrix : The correlation matrix used for visualization.
hc.order : If it is true, then the correlation matrix will be ordered.
type : It is the arrangement of the character to display.
lab : It is a logical value. If it is true, then we add the correlation coefficient to our matrix.
Example: Introducing correlation coefficient
R
library(ggplot2)library(ggcorrplot) # Reading the datadata(USArrests) # Computing correlation matrixcorrelation_matrix <- round(cor(USArrests),1) # Computing correlation matrix with p-valuescorrp.mat <- cor_pmat(USArrests) # Adding the correlation coefficientggcorrplot(correlation_matrix, hc.order =TRUE, type ="lower", lab =TRUE)
Output :
Basically, the significance level is denoted by alpha. We compare the significance level to p-values to check whether the correlation between variables is significant or not. If p-value is less than equal to alpha, then the correlation is significant else, non-significant.
We will visualize our correlation matrix by adding significance level not taking any significant coefficient. We will do this using the ggcorrplot function and taking arguments as our correlation matrix, hc.order, type, and our correlation matrix with p-values.
Syntax :
ggcorrplot(correlation_matrix, hc.order=TRUE, type=”lower”, p.mat=corrp.mat)
Parameters :
correlation_matrix : Our correlation matrix to visualize.
hc.order : If its value is true, then the correlation matrix will be ordered.
type : It is the arrangement of the character to display.
p.mat : Correlation matrix with p-values.
Example: Adding coefficient significance level
R
library(ggplot2)library(ggcorrplot) # Reading the datadata(USArrests) # Computing correlation matrixcorrelation_matrix <- round(cor(USArrests),1) # Computing correlation matrix with p-valuescorrp.mat <- cor_pmat(USArrests) # Adding correlation significance levelggcorrplot(correlation_matrix, hc.order =TRUE, type ="lower", p.mat = corrp.mat)
Output :
We will now visualize our correlation matrix by leaving a blank where there is no significance level. In the previous example, we added a significance level to our correlation matrix. Here, we will remove those parts of the correlation matrix where we did not find any significance level.
We will do this using the ggcorrplot function and take arguments like our correlation matrix, correlation matrix with p-values, hc.order, type and insig.
Syntax :
ggcorrplot(correlation_matrix, hc.order=TRUE, p.mat=corrp.mat, type=”lower”, insig=”blank”)
Parameters:
correlation_matrix : Our correlation matrix to visualize.
hc.order : If it is true, then the correlation matrix will be ordered.
p.mat : Correlation matrix with p-values.
type : It is the arrangement of the character to display.
insig : It is a character mostly containing insignificant correlation coefficients. The value is “pch” by default. If it is provided blank, then it wipes away the corresponding glyphs.
Example: Leaving blank on no significance level
R
library(ggplot2)library(ggcorrplot) # Reading the datadata(USArrests) # Computing correlation matrixcorrelation_matrix <- round(cor(USArrests),1) # Computing correlation matrix with p-valuescorrp.mat <- cor_pmat(USArrests) # Leaving blank on no significance levelggcorrplot(correlation_matrix, hc.order =TRUE, type ="lower", p.mat = corrp.mat, insig="blank")
Output :
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Jul, 2021"
},
{
"code": null,
"e": 148,
"s": 28,
"text": "In this article, we will discuss how to visualize a correlation matrix using ggplot2 package in R programming language."
},
{
"code": null,
"e": 559,
"s": 148,
"text": "In order to do this, we will install a package called ggcorrplot package. With the help of this package, we can easily visualize a correlation matrix. We can also compute a matrix of correlation p-values by using a function that is present in this package. The corr_pmat() is used for computing the correlation matrix of p-values and the ggcorrplot() is used for displaying the correlation matrix using ggplot."
},
{
"code": null,
"e": 569,
"s": 559,
"text": "Syntax : "
},
{
"code": null,
"e": 585,
"s": 569,
"text": "corr_pmat(x,..)"
},
{
"code": null,
"e": 624,
"s": 585,
"text": "Where x is the dataframe or the matrix"
},
{
"code": null,
"e": 632,
"s": 624,
"text": "Syntax:"
},
{
"code": null,
"e": 974,
"s": 632,
"text": "ggcorrplot(corr, method = c(“circle”, “square”), type = c(“full”, “lower”, “upper”), title = “”, ggtheme=ggplot2::theme_minimal, show.legend = TRUE, legend.title = “corr”, show.diag = FALSE, colors = c(“blue”, “white”, “red”), outline.color = “gray”, hc.order = FALSE, hc.method = “complete”, lab = FALSE, lab_col =”black”, p.mat = NULL,.. )"
},
{
"code": null,
"e": 1531,
"s": 974,
"text": "We will first install and load the ggcorrplot and ggplot2 package using the install.packages() to install and library() to load the package. We need a dataset to construct our correlation matrix and then visualize it. We will create our correlation matrix with the help of cor() function, which computes the correlation coefficient. After computing the correlation matrix, we will compute the matrix of correlation p-values using the corr_pmat() function. Next, we will visualize the correlation matrix with the help of ggcorrplot() function using ggplot2."
},
{
"code": null,
"e": 2042,
"s": 1531,
"text": "We will take a sample dataset for explaining our approach better. We will take the inbuilt USArrests dataset, and we will visualize its correlation matrix following the above approach. We will read the data using the data() function, and we will create the correlation matrix with the help of cor() function to compute the correlation coefficient. The round() function is used to round off the values to a specific decimal value. We will use cor_pmat() function to compute the correlation matrix with p-values."
},
{
"code": null,
"e": 2052,
"s": 2042,
"text": "Syntax : "
},
{
"code": null,
"e": 2093,
"s": 2052,
"text": "correlation_matrix <- round(cor(data),1)"
},
{
"code": null,
"e": 2107,
"s": 2093,
"text": "Parameters : "
},
{
"code": null,
"e": 2179,
"s": 2107,
"text": "correlation_matrix : Variable for correlation matrix used to visualize."
},
{
"code": null,
"e": 2246,
"s": 2179,
"text": "data : data is our dataset which we have taken for visualization. "
},
{
"code": null,
"e": 2254,
"s": 2246,
"text": "Syntax:"
},
{
"code": null,
"e": 2282,
"s": 2254,
"text": "corrp.mat <- cor_pmat(data)"
},
{
"code": null,
"e": 2295,
"s": 2282,
"text": "Parameters :"
},
{
"code": null,
"e": 2354,
"s": 2295,
"text": "corrp.mat : Variable for correlation matrix with p-values."
},
{
"code": null,
"e": 2432,
"s": 2354,
"text": "data : It is our dataset taken for creating correlation matrix with p-values."
},
{
"code": null,
"e": 2471,
"s": 2432,
"text": "Example: Creating a correlation matrix"
},
{
"code": null,
"e": 2473,
"s": 2471,
"text": "R"
},
{
"code": "# Installing and loading the ggcorrplot packageinstall.packages(\"ggcorrplot\")library(ggcorrplot) # Reading the datadata(USArrests) # Computing correlation matrixcorrelation_matrix <- round(cor(USArrests),1) head(correlation_matrix[, 1:4]) # Computing correlation matrix with p-valuescorrp.mat <- cor_pmat(USArrests) head(corrp.mat[, 1:4])",
"e": 2817,
"s": 2473,
"text": null
},
{
"code": null,
"e": 2826,
"s": 2817,
"text": "Output :"
},
{
"code": null,
"e": 3098,
"s": 2826,
"text": "Now since we have a correlation matrix and the correlation matrix with p-values, we will now try to visualize this correlation matrix. The first visualization is to use the ggcorrplot() function and plot our correlation matrix in the form of the square and circle method."
},
{
"code": null,
"e": 3107,
"s": 3098,
"text": "Syntax :"
},
{
"code": null,
"e": 3168,
"s": 3107,
"text": "ggcorrplot(correlation_matrix, method= c(“circle”,”square”))"
},
{
"code": null,
"e": 3182,
"s": 3168,
"text": "Parameters : "
},
{
"code": null,
"e": 3245,
"s": 3182,
"text": "correlation_matrix : The correlation matrix for visualization."
},
{
"code": null,
"e": 3310,
"s": 3245,
"text": "method : It is a character value used for visualization methods."
},
{
"code": null,
"e": 3379,
"s": 3310,
"text": "Example: Visualizing the correlation matrix using different methods "
},
{
"code": null,
"e": 3381,
"s": 3379,
"text": "R"
},
{
"code": "library(ggplot2)library(ggcorrplot) # Reading the datadata(USArrests) # Computing correlation matrixcorrelation_matrix <- round(cor(USArrests),1) # Computing correlation matrix with p-valuescorrp.mat <- cor_pmat(USArrests) # Visualizing the correlation matrix using # square and circle methodsggcorrplot(correlation_matrix, method =\"square\")ggcorrplot(correlation_matrix, method =\"circle\")",
"e": 3775,
"s": 3381,
"text": null
},
{
"code": null,
"e": 3784,
"s": 3775,
"text": "Output :"
},
{
"code": null,
"e": 3824,
"s": 3784,
"text": "Correlation matrix with circular method"
},
{
"code": null,
"e": 3862,
"s": 3824,
"text": "Correlation matrix with square method"
},
{
"code": null,
"e": 4080,
"s": 3862,
"text": "Next, we will visualize correlogram layout types in our correlation matrix and providing hc.order and type as lower for lower triangle layout and upper for upper triangle layout as parameters in ggcorrplot() function."
},
{
"code": null,
"e": 4190,
"s": 4080,
"text": "Syntax : ggcorrplot(correlation_matrix, hc.order = TRUE, type = c(“upper”, “lower”), outline.color = “white”)"
},
{
"code": null,
"e": 4203,
"s": 4190,
"text": "Parameters :"
},
{
"code": null,
"e": 4271,
"s": 4203,
"text": "correlation_matrix : The correlation matrix used for visualization."
},
{
"code": null,
"e": 4342,
"s": 4271,
"text": "hc.order : If it is true, then the correlation matrix will be ordered."
},
{
"code": null,
"e": 4400,
"s": 4342,
"text": "type : It is the arrangement of the character to display."
},
{
"code": null,
"e": 4465,
"s": 4400,
"text": "outline.color : It is the outline color of the square or circle."
},
{
"code": null,
"e": 4529,
"s": 4465,
"text": "Example: Visualizing correlation matrix using different layouts"
},
{
"code": null,
"e": 4531,
"s": 4529,
"text": "R"
},
{
"code": "library(ggplot2)library(ggcorrplot) # Reading the datadata(USArrests) # Computing correlation matrixcorrelation_matrix <- round(cor(USArrests),1) # Computing correlation matrix with p-valuescorrp.mat <- cor_pmat(USArrests) # Visualizing upper and lower triangle layoutsggcorrplot(correlation_matrix, hc.order =TRUE, type =\"lower\", outline.color =\"white\") ggcorrplot(correlation_matrix, hc.order =TRUE, type =\"upper\", outline.color =\"white\")",
"e": 4999,
"s": 4531,
"text": null
},
{
"code": null,
"e": 5008,
"s": 4999,
"text": "Output :"
},
{
"code": null,
"e": 5045,
"s": 5008,
"text": "Correlation matrix with upper layout"
},
{
"code": null,
"e": 5082,
"s": 5045,
"text": "Correlation matrix with lower layout"
},
{
"code": null,
"e": 5292,
"s": 5082,
"text": "We will now visualize our correlation matrix by reordering the matrix using hierarchical clustering. We will do this using the ggcorrplot function with correlation matrix, hc.order, outline.color as arguments."
},
{
"code": null,
"e": 5302,
"s": 5292,
"text": "Syntax : "
},
{
"code": null,
"e": 5375,
"s": 5302,
"text": "ggcorrplot(correlation_matrix, hc.order = TRUE, outline.color = “white”)"
},
{
"code": null,
"e": 5388,
"s": 5375,
"text": "Parameters :"
},
{
"code": null,
"e": 5456,
"s": 5388,
"text": "correlation_matrix : The correlation matrix used for visualization."
},
{
"code": null,
"e": 5527,
"s": 5456,
"text": "hc.order : If it is true, then the correlation matrix will be ordered."
},
{
"code": null,
"e": 5592,
"s": 5527,
"text": "outline.color : It is the outline color of the square or circle."
},
{
"code": null,
"e": 5639,
"s": 5592,
"text": "Example: Reordering of the correlation matrix "
},
{
"code": null,
"e": 5641,
"s": 5639,
"text": "R"
},
{
"code": "library(ggplot2)library(ggcorrplot) # Reading the datadata(USArrests) # Computing correlation matrixcorrelation_matrix <- round(cor(USArrests),1) # Computing correlation matrix with # p-valuescorrp.mat <- cor_pmat(USArrests) # Visualizing and reordering correlation# matrixggcorrplot(correlation_matrix, hc.order =TRUE, outline.color =\"white\")",
"e": 5999,
"s": 5641,
"text": null
},
{
"code": null,
"e": 6008,
"s": 5999,
"text": "Output :"
},
{
"code": null,
"e": 6205,
"s": 6008,
"text": "We will now visualize our correlation matrix by adding the correlation coefficient using the ggcorrplot function and providing correlation matrix, hc.order, type, and lower variables as arguments."
},
{
"code": null,
"e": 6215,
"s": 6205,
"text": "Syntax : "
},
{
"code": null,
"e": 6291,
"s": 6215,
"text": "ggcorrplot(correlation_matrix, hc.order = TRUE, type = “lower”, lab = TRUE)"
},
{
"code": null,
"e": 6304,
"s": 6291,
"text": "Parameters :"
},
{
"code": null,
"e": 6372,
"s": 6304,
"text": "correlation_matrix : The correlation matrix used for visualization."
},
{
"code": null,
"e": 6443,
"s": 6372,
"text": "hc.order : If it is true, then the correlation matrix will be ordered."
},
{
"code": null,
"e": 6501,
"s": 6443,
"text": "type : It is the arrangement of the character to display."
},
{
"code": null,
"e": 6600,
"s": 6501,
"text": "lab : It is a logical value. If it is true, then we add the correlation coefficient to our matrix."
},
{
"code": null,
"e": 6645,
"s": 6600,
"text": "Example: Introducing correlation coefficient"
},
{
"code": null,
"e": 6647,
"s": 6645,
"text": "R"
},
{
"code": "library(ggplot2)library(ggcorrplot) # Reading the datadata(USArrests) # Computing correlation matrixcorrelation_matrix <- round(cor(USArrests),1) # Computing correlation matrix with p-valuescorrp.mat <- cor_pmat(USArrests) # Adding the correlation coefficientggcorrplot(correlation_matrix, hc.order =TRUE, type =\"lower\", lab =TRUE)",
"e": 6994,
"s": 6647,
"text": null
},
{
"code": null,
"e": 7003,
"s": 6994,
"text": "Output :"
},
{
"code": null,
"e": 7277,
"s": 7003,
"text": "Basically, the significance level is denoted by alpha. We compare the significance level to p-values to check whether the correlation between variables is significant or not. If p-value is less than equal to alpha, then the correlation is significant else, non-significant."
},
{
"code": null,
"e": 7539,
"s": 7277,
"text": "We will visualize our correlation matrix by adding significance level not taking any significant coefficient. We will do this using the ggcorrplot function and taking arguments as our correlation matrix, hc.order, type, and our correlation matrix with p-values."
},
{
"code": null,
"e": 7549,
"s": 7539,
"text": "Syntax : "
},
{
"code": null,
"e": 7626,
"s": 7549,
"text": "ggcorrplot(correlation_matrix, hc.order=TRUE, type=”lower”, p.mat=corrp.mat)"
},
{
"code": null,
"e": 7639,
"s": 7626,
"text": "Parameters :"
},
{
"code": null,
"e": 7697,
"s": 7639,
"text": "correlation_matrix : Our correlation matrix to visualize."
},
{
"code": null,
"e": 7775,
"s": 7697,
"text": "hc.order : If its value is true, then the correlation matrix will be ordered."
},
{
"code": null,
"e": 7833,
"s": 7775,
"text": "type : It is the arrangement of the character to display."
},
{
"code": null,
"e": 7875,
"s": 7833,
"text": "p.mat : Correlation matrix with p-values."
},
{
"code": null,
"e": 7923,
"s": 7875,
"text": "Example: Adding coefficient significance level "
},
{
"code": null,
"e": 7925,
"s": 7923,
"text": "R"
},
{
"code": "library(ggplot2)library(ggcorrplot) # Reading the datadata(USArrests) # Computing correlation matrixcorrelation_matrix <- round(cor(USArrests),1) # Computing correlation matrix with p-valuescorrp.mat <- cor_pmat(USArrests) # Adding correlation significance levelggcorrplot(correlation_matrix, hc.order =TRUE, type =\"lower\", p.mat = corrp.mat)",
"e": 8283,
"s": 7925,
"text": null
},
{
"code": null,
"e": 8292,
"s": 8283,
"text": "Output :"
},
{
"code": null,
"e": 8581,
"s": 8292,
"text": "We will now visualize our correlation matrix by leaving a blank where there is no significance level. In the previous example, we added a significance level to our correlation matrix. Here, we will remove those parts of the correlation matrix where we did not find any significance level."
},
{
"code": null,
"e": 8735,
"s": 8581,
"text": "We will do this using the ggcorrplot function and take arguments like our correlation matrix, correlation matrix with p-values, hc.order, type and insig."
},
{
"code": null,
"e": 8745,
"s": 8735,
"text": "Syntax : "
},
{
"code": null,
"e": 8837,
"s": 8745,
"text": "ggcorrplot(correlation_matrix, hc.order=TRUE, p.mat=corrp.mat, type=”lower”, insig=”blank”)"
},
{
"code": null,
"e": 8849,
"s": 8837,
"text": "Parameters:"
},
{
"code": null,
"e": 8907,
"s": 8849,
"text": "correlation_matrix : Our correlation matrix to visualize."
},
{
"code": null,
"e": 8980,
"s": 8907,
"text": "hc.order : If it is true, then the correlation matrix will be ordered. "
},
{
"code": null,
"e": 9022,
"s": 8980,
"text": "p.mat : Correlation matrix with p-values."
},
{
"code": null,
"e": 9080,
"s": 9022,
"text": "type : It is the arrangement of the character to display."
},
{
"code": null,
"e": 9265,
"s": 9080,
"text": "insig : It is a character mostly containing insignificant correlation coefficients. The value is “pch” by default. If it is provided blank, then it wipes away the corresponding glyphs."
},
{
"code": null,
"e": 9313,
"s": 9265,
"text": "Example: Leaving blank on no significance level"
},
{
"code": null,
"e": 9315,
"s": 9313,
"text": "R"
},
{
"code": "library(ggplot2)library(ggcorrplot) # Reading the datadata(USArrests) # Computing correlation matrixcorrelation_matrix <- round(cor(USArrests),1) # Computing correlation matrix with p-valuescorrp.mat <- cor_pmat(USArrests) # Leaving blank on no significance levelggcorrplot(correlation_matrix, hc.order =TRUE, type =\"lower\", p.mat = corrp.mat, insig=\"blank\")",
"e": 9689,
"s": 9315,
"text": null
},
{
"code": null,
"e": 9698,
"s": 9689,
"text": "Output :"
},
{
"code": null,
"e": 9705,
"s": 9698,
"text": "Picked"
},
{
"code": null,
"e": 9714,
"s": 9705,
"text": "R-ggplot"
},
{
"code": null,
"e": 9725,
"s": 9714,
"text": "R Language"
},
{
"code": null,
"e": 9823,
"s": 9725,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9875,
"s": 9823,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 9933,
"s": 9875,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 9968,
"s": 9933,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 10006,
"s": 9968,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 10055,
"s": 10006,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 10072,
"s": 10055,
"text": "R - if statement"
},
{
"code": null,
"e": 10109,
"s": 10072,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 10152,
"s": 10109,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 10189,
"s": 10152,
"text": "How to import an Excel File into R ?"
}
] |
Structures in C++ | 25 May, 2021
We often come around situations where we need to store a group of data whether of similar data types or non-similar data types. We have seen Arrays in C++ which are used to store set of data of similar data types at contiguous memory locations.Unlike Arrays, Structures in C++ are user defined data types which are used to store group of items of non-similar data types.
What is a structure?
A structure is a user-defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type.
Structures in C++
How to create a structure?
The ‘struct’ keyword is used to create a structure. The general syntax to create a structure is as shown below:
struct structureName{
member1;
member2;
member3;
.
.
.
memberN;
};
Structures in C++ can contain two types of members:
Data Member: These members are normal C++ variables. We can create a structure with variables of different data types in C++.
Member Functions: These members are normal C++ functions. Along with variables, we can also include functions inside a structure declaration.
Example:
C++
// Data Membersint roll;int age;int marks; // Member Functionsvoid printDetails(){ cout<<"Roll = "<<roll<<"\n"; cout<<"Age = "<<age<<"\n"; cout<<"Marks = "<<marks;}
In the above structure, the data members are three integer variables to store roll number, age and marks of any student and the member function is printDetails() which is printing all of the above details of any student.
How to declare structure variables?
A structure variable can either be declared with structure declaration or as a separate declaration like basic types.
C++
// A variable declaration with structure declaration.struct Point{ int x, y;} p1; // The variable p1 is declared with 'Point' // A variable declaration like basic data typesstruct Point{ int x, y;}; int main(){ struct Point p1; // The variable p1 is declared like a normal variable}
Note: In C++, the struct keyword is optional before in declaration of a variable. In C, it is mandatory.
How to initialize structure members? Structure members cannot be initialized with declaration. For example the following C program fails in compilation. But is considered correct in C++11 and above.
C++
struct Point{ int x = 0; // COMPILER ERROR: cannot initialize members here int y = 0; // COMPILER ERROR: cannot initialize members here};
The reason for above error is simple, when a datatype is declared, no memory is allocated for it. Memory is allocated only when variables are created.
Structure members can be initialized with declaration in C++. For Example the following C++ program Executes Successfully without throwing any Error.
C++
// In C++ We can Initialize the Variables with Declaration in Structure. #include <iostream>using namespace std; struct Point { int x = 0; // It is Considered as Default Arguments and no Error is Raised int y = 1;}; int main(){ struct Point p1; // Accessing members of point p1 // No value is Initialized then the default value is considered. ie x=0 and y=1; cout << "x = " << p1.x << ", y = " << p1.y<<endl; // Initializing the value of y = 20; p1.y = 20; cout << "x = " << p1.x << ", y = " << p1.y; return 0;}// This code is contributed by Samyak Jain
x=0, y=1
x=0, y=20
Structure members can be initialized using curly braces ‘{}’. For example, following is a valid initialization.
C++
struct Point { int x, y;}; int main(){ // A valid initialization. member x gets value 0 and y // gets value 1. The order of declaration is followed. struct Point p1 = { 0, 1 };}
How to access structure elements? Structure members are accessed using dot (.) operator.
C++
#include <iostream>using namespace std; struct Point { int x, y;}; int main(){ struct Point p1 = { 0, 1 }; // Accessing members of point p1 p1.x = 20; cout << "x = " << p1.x << ", y = " << p1.y; return 0;}
x = 20, y = 1
What is an array of structures?
Like other primitive data types, we can create an array of structures.
C++
#include <iostream>using namespace std; struct Point { int x, y;}; int main(){ // Create an array of structures struct Point arr[10]; // Access array members arr[0].x = 10; arr[0].y = 20; cout << arr[0].x << " " << arr[0].y; return 0;}
10 20
What is a structure pointer? Like primitive types, we can have pointer to a structure. If we have a pointer to structure, members are accessed using arrow ( -> ) operator instead of the dot (.) operator.
C++
#include <iostream>using namespace std; struct Point { int x, y;}; int main(){ struct Point p1 = { 1, 2 }; // p2 is a pointer to structure p1 struct Point* p2 = &p1; // Accessing structure members using // structure pointer cout << p2->x << " " << p2->y; return 0;}
1 2
What is structure member alignment? See https://www.geeksforgeeks.org/structure-member-alignment-padding-and-data-packing/In C++, a structure is the same as a class except for a few differences. The most important of them is security. A Structure is not secure and cannot hide its implementation details from the end user while a class is secure and can hide its programming and designing details. Learn more about the differences between Structures and Class in C++.
nabhaninajm
shubham_singh
iamsamyak
Akanksha_Rai
C Basics
cpp-struct
C++
Programming Language
cpp-struct
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set in C++ Standard Template Library (STL)
unordered_map in C++ STL
vector erase() and clear() in C++
C++ Classes and Objects
Substring in C++
Differences between Procedural and Object Oriented Programming
Arrow operator -> in C/C++ with Examples
Modulo Operator (%) in C/C++ with Examples
Decorators with parameters in Python
C# | Data Types | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 May, 2021"
},
{
"code": null,
"e": 424,
"s": 52,
"text": "We often come around situations where we need to store a group of data whether of similar data types or non-similar data types. We have seen Arrays in C++ which are used to store set of data of similar data types at contiguous memory locations.Unlike Arrays, Structures in C++ are user defined data types which are used to store group of items of non-similar data types. "
},
{
"code": null,
"e": 445,
"s": 424,
"text": "What is a structure?"
},
{
"code": null,
"e": 608,
"s": 445,
"text": "A structure is a user-defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type. "
},
{
"code": null,
"e": 626,
"s": 608,
"text": "Structures in C++"
},
{
"code": null,
"e": 653,
"s": 626,
"text": "How to create a structure?"
},
{
"code": null,
"e": 767,
"s": 653,
"text": "The ‘struct’ keyword is used to create a structure. The general syntax to create a structure is as shown below: "
},
{
"code": null,
"e": 862,
"s": 767,
"text": "struct structureName{\n member1;\n member2;\n member3;\n .\n .\n .\n memberN;\n};"
},
{
"code": null,
"e": 916,
"s": 862,
"text": "Structures in C++ can contain two types of members: "
},
{
"code": null,
"e": 1042,
"s": 916,
"text": "Data Member: These members are normal C++ variables. We can create a structure with variables of different data types in C++."
},
{
"code": null,
"e": 1184,
"s": 1042,
"text": "Member Functions: These members are normal C++ functions. Along with variables, we can also include functions inside a structure declaration."
},
{
"code": null,
"e": 1195,
"s": 1184,
"text": "Example: "
},
{
"code": null,
"e": 1199,
"s": 1195,
"text": "C++"
},
{
"code": "// Data Membersint roll;int age;int marks; // Member Functionsvoid printDetails(){ cout<<\"Roll = \"<<roll<<\"\\n\"; cout<<\"Age = \"<<age<<\"\\n\"; cout<<\"Marks = \"<<marks;}",
"e": 1377,
"s": 1199,
"text": null
},
{
"code": null,
"e": 1598,
"s": 1377,
"text": "In the above structure, the data members are three integer variables to store roll number, age and marks of any student and the member function is printDetails() which is printing all of the above details of any student."
},
{
"code": null,
"e": 1634,
"s": 1598,
"text": "How to declare structure variables?"
},
{
"code": null,
"e": 1754,
"s": 1634,
"text": "A structure variable can either be declared with structure declaration or as a separate declaration like basic types. "
},
{
"code": null,
"e": 1758,
"s": 1754,
"text": "C++"
},
{
"code": "// A variable declaration with structure declaration.struct Point{ int x, y;} p1; // The variable p1 is declared with 'Point' // A variable declaration like basic data typesstruct Point{ int x, y;}; int main(){ struct Point p1; // The variable p1 is declared like a normal variable}",
"e": 2050,
"s": 1758,
"text": null
},
{
"code": null,
"e": 2156,
"s": 2050,
"text": "Note: In C++, the struct keyword is optional before in declaration of a variable. In C, it is mandatory. "
},
{
"code": null,
"e": 2356,
"s": 2156,
"text": "How to initialize structure members? Structure members cannot be initialized with declaration. For example the following C program fails in compilation. But is considered correct in C++11 and above. "
},
{
"code": null,
"e": 2360,
"s": 2356,
"text": "C++"
},
{
"code": "struct Point{ int x = 0; // COMPILER ERROR: cannot initialize members here int y = 0; // COMPILER ERROR: cannot initialize members here};",
"e": 2506,
"s": 2360,
"text": null
},
{
"code": null,
"e": 2657,
"s": 2506,
"text": "The reason for above error is simple, when a datatype is declared, no memory is allocated for it. Memory is allocated only when variables are created."
},
{
"code": null,
"e": 2808,
"s": 2657,
"text": "Structure members can be initialized with declaration in C++. For Example the following C++ program Executes Successfully without throwing any Error."
},
{
"code": null,
"e": 2812,
"s": 2808,
"text": "C++"
},
{
"code": "// In C++ We can Initialize the Variables with Declaration in Structure. #include <iostream>using namespace std; struct Point { int x = 0; // It is Considered as Default Arguments and no Error is Raised int y = 1;}; int main(){ struct Point p1; // Accessing members of point p1 // No value is Initialized then the default value is considered. ie x=0 and y=1; cout << \"x = \" << p1.x << \", y = \" << p1.y<<endl; // Initializing the value of y = 20; p1.y = 20; cout << \"x = \" << p1.x << \", y = \" << p1.y; return 0;}// This code is contributed by Samyak Jain",
"e": 3400,
"s": 2812,
"text": null
},
{
"code": null,
"e": 3421,
"s": 3400,
"text": " x=0, y=1\n x=0, y=20"
},
{
"code": null,
"e": 3533,
"s": 3421,
"text": "Structure members can be initialized using curly braces ‘{}’. For example, following is a valid initialization."
},
{
"code": null,
"e": 3537,
"s": 3533,
"text": "C++"
},
{
"code": "struct Point { int x, y;}; int main(){ // A valid initialization. member x gets value 0 and y // gets value 1. The order of declaration is followed. struct Point p1 = { 0, 1 };}",
"e": 3728,
"s": 3537,
"text": null
},
{
"code": null,
"e": 3820,
"s": 3728,
"text": " How to access structure elements? Structure members are accessed using dot (.) operator. "
},
{
"code": null,
"e": 3824,
"s": 3820,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; struct Point { int x, y;}; int main(){ struct Point p1 = { 0, 1 }; // Accessing members of point p1 p1.x = 20; cout << \"x = \" << p1.x << \", y = \" << p1.y; return 0;}",
"e": 4050,
"s": 3824,
"text": null
},
{
"code": null,
"e": 4064,
"s": 4050,
"text": "x = 20, y = 1"
},
{
"code": null,
"e": 4096,
"s": 4064,
"text": "What is an array of structures?"
},
{
"code": null,
"e": 4168,
"s": 4096,
"text": "Like other primitive data types, we can create an array of structures. "
},
{
"code": null,
"e": 4172,
"s": 4168,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; struct Point { int x, y;}; int main(){ // Create an array of structures struct Point arr[10]; // Access array members arr[0].x = 10; arr[0].y = 20; cout << arr[0].x << \" \" << arr[0].y; return 0;}",
"e": 4434,
"s": 4172,
"text": null
},
{
"code": null,
"e": 4440,
"s": 4434,
"text": "10 20"
},
{
"code": null,
"e": 4646,
"s": 4440,
"text": " What is a structure pointer? Like primitive types, we can have pointer to a structure. If we have a pointer to structure, members are accessed using arrow ( -> ) operator instead of the dot (.) operator."
},
{
"code": null,
"e": 4650,
"s": 4646,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; struct Point { int x, y;}; int main(){ struct Point p1 = { 1, 2 }; // p2 is a pointer to structure p1 struct Point* p2 = &p1; // Accessing structure members using // structure pointer cout << p2->x << \" \" << p2->y; return 0;}",
"e": 4942,
"s": 4650,
"text": null
},
{
"code": null,
"e": 4946,
"s": 4942,
"text": "1 2"
},
{
"code": null,
"e": 5415,
"s": 4946,
"text": "What is structure member alignment? See https://www.geeksforgeeks.org/structure-member-alignment-padding-and-data-packing/In C++, a structure is the same as a class except for a few differences. The most important of them is security. A Structure is not secure and cannot hide its implementation details from the end user while a class is secure and can hide its programming and designing details. Learn more about the differences between Structures and Class in C++. "
},
{
"code": null,
"e": 5427,
"s": 5415,
"text": "nabhaninajm"
},
{
"code": null,
"e": 5441,
"s": 5427,
"text": "shubham_singh"
},
{
"code": null,
"e": 5451,
"s": 5441,
"text": "iamsamyak"
},
{
"code": null,
"e": 5464,
"s": 5451,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 5473,
"s": 5464,
"text": "C Basics"
},
{
"code": null,
"e": 5484,
"s": 5473,
"text": "cpp-struct"
},
{
"code": null,
"e": 5488,
"s": 5484,
"text": "C++"
},
{
"code": null,
"e": 5509,
"s": 5488,
"text": "Programming Language"
},
{
"code": null,
"e": 5520,
"s": 5509,
"text": "cpp-struct"
},
{
"code": null,
"e": 5524,
"s": 5520,
"text": "CPP"
},
{
"code": null,
"e": 5622,
"s": 5524,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5665,
"s": 5622,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 5690,
"s": 5665,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 5724,
"s": 5690,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 5748,
"s": 5724,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 5765,
"s": 5748,
"text": "Substring in C++"
},
{
"code": null,
"e": 5828,
"s": 5765,
"text": "Differences between Procedural and Object Oriented Programming"
},
{
"code": null,
"e": 5869,
"s": 5828,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 5912,
"s": 5869,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 5949,
"s": 5912,
"text": "Decorators with parameters in Python"
}
] |
Find Square Root under Modulo p | Set 1 (When p is in form of 4*i + 3) | 12 Apr, 2021
Given a number ‘n’ and a prime ‘p’, find square root of n under modulo p if it exists. It may be given that p is in the form for 4*i + 3 (OR p % 4 = 3) where i is an integer. Examples of such primes are 7, 11, 19, 23, 31, ... etc,Examples:
Input: n = 2, p = 7
Output: 3 or 4
3 and 4 both are square roots of 2 under modulo
7 because (3*3) % 7 = 2 and (4*4) % 7 = 2
Input: n = 2, p = 5
Output: Square root doesn't exist
Naive Solution : Try all numbers from 2 to p-1. And for every number x, check if x is square root of n under modulo p.
C++
Java
Python3
C#
PHP
Javascript
// A Simple C++ program to find square root under modulo p// when p is 7, 11, 19, 23, 31, ... etc,#include <iostream>using namespace std; // Returns true if square root of n under modulo p existsvoid squareRoot(int n, int p){ n = n % p; // One by one check all numbers from 2 to p-1 for (int x = 2; x < p; x++) { if ((x * x) % p == n) { cout << "Square root is " << x; return; } } cout << "Square root doesn't exist";} // Driver program to testint main(){ int p = 7; int n = 2; squareRoot(n, p); return 0;}
// A Simple Java program to find square// root under modulo p when p is 7,// 11, 19, 23, 31, ... etc,import java .io.*; class GFG { // Returns true if square root of n // under modulo p exists static void squareRoot(int n, int p) { n = n % p; // One by one check all numbers // from 2 to p-1 for (int x = 2; x < p; x++) { if ((x * x) % p == n) { System.out.println("Square " + "root is " + x); return; } } System.out.println("Square root " + "doesn't exist"); } // Driver Code public static void main(String[] args) { int p = 7; int n = 2; squareRoot(n, p); }} // This code is contributed by Anuj_67
# A Simple Python program to find square# root under modulo p when p is 7, 11,# 19, 23, 31, ... etc, # Returns true if square root of n under# modulo p existsdef squareRoot(n, p): n = n % p # One by one check all numbers from # 2 to p-1 for x in range (2, p): if ((x * x) % p == n) : print( "Square root is ", x) return print( "Square root doesn't exist") # Driver program to testp = 7n = 2squareRoot(n, p) # This code is Contributed by Anuj_67
// A Simple C# program to find square// root under modulo p when p is 7,// 11, 19, 23, 31, ... etc,using System; class GFG { // Returns true if square root of n // under modulo p exists static void squareRoot(int n, int p) { n = n % p; // One by one check all numbers // from 2 to p-1 for (int x = 2; x < p; x++) { if ((x * x) % p == n) { Console.Write("Square " + "root is " + x); return; } } Console.Write("Square root " + "doesn't exist"); } // Driver Code static void Main() { int p = 7; int n = 2; squareRoot(n, p); }} // This code is contributed by Anuj_67
<?php// A Simple PHP program to find// square root under modulo p// when p is 7, 11, 19, 23, 31,// ... etc, // Returns true if square// root of n under modulo// p existsfunction squareRoot($n, $p){ $n = $n % $p; // One by one check all // numbers from 2 to p-1 for ($x = 2; $x < $p; $x++) { if (($x * $x) % $p == $n) { echo("Square root is " . $x); return; } } echo("Square root doesn't exist");} // Driver Code$p = 7;$n = 2;squareRoot($n, $p); // This code is contributed by Ajit.?>
<script>// A Simple Javascript program to find square// root under modulo p when p is 7,// 11, 19, 23, 31, ... etc, // Returns true if square root of n // under modulo p exists function squareRoot(n,p) { n = n % p; // One by one check all numbers // from 2 to p-1 for (let x = 2; x < p; x++) { if ((x * x) % p == n) { document.write("Square " + "root is " + x); return; } } document.write("Square root " + "doesn't exist"); } // Driver Code let p = 7; let n = 2; squareRoot(n, p); // This code is contributed by rag2127 </script>
Output:
Square root is 3
Time Complexity of this solution is O(p)Direct Method : If p is in the form of 4*i + 3, then there exist a Quick way of finding square root.
If n is in the form 4*i + 3 with i >= 1 (OR p % 4 = 3)
And
If Square root of n exists, then it must be
±n(p + 1)/4
Below is the implementation of above idea :
C++
Java
Python3
C#
PHP
Javascript
// An efficient C++ program to find square root under// modulo p when p is 7, 11, 19, 23, 31, ... etc.#include <iostream>using namespace std; // Utility function to do modular exponentiation.// It returns (x^y) % p.int power(int x, int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Returns true if square root of n under modulo p exists// Assumption: p is of the form 3*i + 4 where i >= 1void squareRoot(int n, int p){ if (p % 4 != 3) { cout << "Invalid Input"; return; } // Try "+(n^((p + 1)/4))" n = n % p; int x = power(n, (p + 1) / 4, p); if ((x * x) % p == n) { cout << "Square root is " << x; return; } // Try "-(n ^ ((p + 1)/4))" x = p - x; if ((x * x) % p == n) { cout << "Square root is " << x; return; } // If none of the above two work, then // square root doesn't exist cout << "Square root doesn't exist ";} // Driver program to testint main(){ int p = 7; int n = 2; squareRoot(n, p); return 0;}
// An efficient Java program to find square root under// modulo p when p is 7, 11, 19, 23, 31, ... etc.public class GFG { // Utility function to do modular exponentiation.// It returns (x^y) % p.static int power(int x, int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y %2== 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Returns true if square root of n under modulo p exists// Assumption: p is of the form 3*i + 4 where i >= 1static void squareRoot(int n, int p){ if (p % 4 != 3) { System.out.print("Invalid Input"); return; } // Try "+(n^((p + 1)/4))" n = n % p; int x = power(n, (p + 1) / 4, p); if ((x * x) % p == n) { System.out.print("Square root is " + x); return; } // Try "-(n ^ ((p + 1)/4))" x = p - x; if ((x * x) % p == n) { System.out.print("Square root is " + x); return; } // If none of the above two work, then // square root doesn't exist System.out.print("Square root doesn't exist ");} // Driver program to test static public void main(String[] args) { int p = 7; int n = 2; squareRoot(n, p); }}
# An efficient python3 program to find square root# under modulo p when p is 7, 11, 19, 23, 31, ... etc. # Utility function to do modular exponentiation.# It returns (x^y) % p.def power(x, y, p) : res = 1 # Initialize result x = x % p # Update x if it is more # than or equal to p while (y > 0): # If y is odd, multiply x with result if (y & 1): res = (res * x) % p # y must be even now y = y >> 1 # y = y/2 x = (x * x) % p return res # Returns true if square root of n under# modulo p exists. Assumption: p is of the# form 3*i + 4 where i >= 1def squareRoot(n, p): if (p % 4 != 3) : print( "Invalid Input" ) return # Try "+(n^((p + 1)/4))" n = n % p x = power(n, (p + 1) // 4, p) if ((x * x) % p == n): print( "Square root is ", x) return # Try "-(n ^ ((p + 1)/4))" x = p - x if ((x * x) % p == n): print( "Square root is ", x ) return # If none of the above two work, then # square root doesn't exist print( "Square root doesn't exist " ) # Driver Codep = 7n = 2squareRoot(n, p) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)
// An efficient C# program to find square root under// modulo p when p is 7, 11, 19, 23, 31, ... etc. using System;public class GFG { // Utility function to do modular exponentiation.// It returns (x^y) % p.static int power(int x, int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y %2 == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Returns true if square root of n under modulo p exists// Assumption: p is of the form 3*i + 4 where i >= 1static void squareRoot(int n, int p){ if (p % 4 != 3) { Console.Write("Invalid Input"); return; } // Try "+(n^((p + 1)/4))" n = n % p; int x = power(n, (p + 1) / 4, p); if ((x * x) % p == n) { Console.Write("Square root is " + x); return; } // Try "-(n ^ ((p + 1)/4))" x = p - x; if ((x * x) % p == n) { Console.Write("Square root is " + x); return; } // If none of the above two work, then // square root doesn't exist Console.Write("Square root doesn't exist ");} // Driver program to test static public void Main() { int p = 7; int n = 2; squareRoot(n, p); }}// This code is contributed by Ita_c.
<?php// An efficient PHP program// to find square root under// modulo p when p is 7, 11,// 19, 23, 31, ... etc. // Utility function to do// modular exponentiation.// It returns (x^y) % p.function power($x, $y, $p){ // Initialize result $res = 1; // Update x if it // is more than or // equal to p $x = $x % $p; while ($y > 0) { // If y is odd, multiply // x with result if ($y & 1) $res = ($res * $x) % $p; // y must be even now // y = y/2 $y = $y >> 1; $x = ($x * $x) % $p; } return $res;} // Returns true if square root// of n under modulo p exists// Assumption: p is of the// form 3*i + 4 where i >= 1function squareRoot($n, $p){ if ($p % 4 != 3) { echo "Invalid Input"; return; } // Try "+(n^((p + 1)/4))" $n = $n % $p; $x = power($n, ($p + 1) / 4, $p); if (($x * $x) % $p == $n) { echo "Square root is ", $x; return; } // Try "-(n ^ ((p + 1)/4))" $x = $p - $x; if (($x * $x) % $p == $n) { echo "Square root is ", $x; return; } // If none of the above // two work, then square // root doesn't exist echo "Square root doesn't exist ";} // Driver Code $p = 7; $n = 2; squareRoot($n, $p); // This code is contributed by ajit?>
<script>// An efficient Javascript program to find square root under// modulo p when p is 7, 11, 19, 23, 31, ... etc. // Utility function to do modular exponentiation. // It returns (x^y) % p. function power(x,y,p) { let res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y %2== 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Returns true if square root of n under modulo p exists // Assumption: p is of the form 3*i + 4 where i >= 1 function squareRoot(n, p) { if (p % 4 != 3) { document.write("Invalid Input"); return; } // Try "+(n^((p + 1)/4))" n = n % p; let x = power(n, Math.floor((p + 1) / 4), p); if ((x * x) % p == n) { document.write("Square root is " + x); return; } // Try "-(n ^ ((p + 1)/4))" x = p - x; if ((x * x) % p == n) { document.write("Square root is " + x); return; } // If none of the above two work, then // square root doesn't exist document.write("Square root doesn't exist "); } // Driver program to test let p = 7; let n = 2; squareRoot(n, p); // This code is contributed by avanitrachhadiya2155</script>
Output:
Square root is 4
Time Complexity of this solution is O(Log p)How does this work? We have discussed Euler’s Criterion in the previous post.
As per Euler's criterion, if square root exists, then
following condition is true
n(p-1)/2 % p = 1
Multiplying both sides with n, we get
n(p+1)/2 % p = n % p ------ (1)
Let x be the modulo square root. We can write,
(x * x) ≡ n mod p
(x * x) ≡ n(p+1)/2 [Using (1) given above]
(x * x) ≡ n(2i + 2) [Replacing n = 4*i + 3]
x ≡ ±n(i + 1) [Taking Square root of both sides]
x ≡ ±n(p + 1)/4 [Putting 4*i + 3 = p or i = (p-3)/4]
We will soon be discussing methods when p is not in above form.This article is contributed by Shivam Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
jit_t
vt_m
Rajput-Ji
ukasp
SHUBHAMSINGH10
Archit_Dwevedi0
rag2127
avanitrachhadiya2155
Modular Arithmetic
Mathematical
Mathematical
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n12 Apr, 2021"
},
{
"code": null,
"e": 296,
"s": 54,
"text": "Given a number ‘n’ and a prime ‘p’, find square root of n under modulo p if it exists. It may be given that p is in the form for 4*i + 3 (OR p % 4 = 3) where i is an integer. Examples of such primes are 7, 11, 19, 23, 31, ... etc,Examples: "
},
{
"code": null,
"e": 478,
"s": 296,
"text": "Input: n = 2, p = 7\nOutput: 3 or 4\n3 and 4 both are square roots of 2 under modulo\n7 because (3*3) % 7 = 2 and (4*4) % 7 = 2\n\nInput: n = 2, p = 5\nOutput: Square root doesn't exist"
},
{
"code": null,
"e": 599,
"s": 478,
"text": "Naive Solution : Try all numbers from 2 to p-1. And for every number x, check if x is square root of n under modulo p. "
},
{
"code": null,
"e": 603,
"s": 599,
"text": "C++"
},
{
"code": null,
"e": 608,
"s": 603,
"text": "Java"
},
{
"code": null,
"e": 616,
"s": 608,
"text": "Python3"
},
{
"code": null,
"e": 619,
"s": 616,
"text": "C#"
},
{
"code": null,
"e": 623,
"s": 619,
"text": "PHP"
},
{
"code": null,
"e": 634,
"s": 623,
"text": "Javascript"
},
{
"code": "// A Simple C++ program to find square root under modulo p// when p is 7, 11, 19, 23, 31, ... etc,#include <iostream>using namespace std; // Returns true if square root of n under modulo p existsvoid squareRoot(int n, int p){ n = n % p; // One by one check all numbers from 2 to p-1 for (int x = 2; x < p; x++) { if ((x * x) % p == n) { cout << \"Square root is \" << x; return; } } cout << \"Square root doesn't exist\";} // Driver program to testint main(){ int p = 7; int n = 2; squareRoot(n, p); return 0;}",
"e": 1205,
"s": 634,
"text": null
},
{
"code": "// A Simple Java program to find square// root under modulo p when p is 7,// 11, 19, 23, 31, ... etc,import java .io.*; class GFG { // Returns true if square root of n // under modulo p exists static void squareRoot(int n, int p) { n = n % p; // One by one check all numbers // from 2 to p-1 for (int x = 2; x < p; x++) { if ((x * x) % p == n) { System.out.println(\"Square \" + \"root is \" + x); return; } } System.out.println(\"Square root \" + \"doesn't exist\"); } // Driver Code public static void main(String[] args) { int p = 7; int n = 2; squareRoot(n, p); }} // This code is contributed by Anuj_67",
"e": 1992,
"s": 1205,
"text": null
},
{
"code": "# A Simple Python program to find square# root under modulo p when p is 7, 11,# 19, 23, 31, ... etc, # Returns true if square root of n under# modulo p existsdef squareRoot(n, p): n = n % p # One by one check all numbers from # 2 to p-1 for x in range (2, p): if ((x * x) % p == n) : print( \"Square root is \", x) return print( \"Square root doesn't exist\") # Driver program to testp = 7n = 2squareRoot(n, p) # This code is Contributed by Anuj_67",
"e": 2488,
"s": 1992,
"text": null
},
{
"code": "// A Simple C# program to find square// root under modulo p when p is 7,// 11, 19, 23, 31, ... etc,using System; class GFG { // Returns true if square root of n // under modulo p exists static void squareRoot(int n, int p) { n = n % p; // One by one check all numbers // from 2 to p-1 for (int x = 2; x < p; x++) { if ((x * x) % p == n) { Console.Write(\"Square \" + \"root is \" + x); return; } } Console.Write(\"Square root \" + \"doesn't exist\"); } // Driver Code static void Main() { int p = 7; int n = 2; squareRoot(n, p); }} // This code is contributed by Anuj_67",
"e": 3242,
"s": 2488,
"text": null
},
{
"code": "<?php// A Simple PHP program to find// square root under modulo p// when p is 7, 11, 19, 23, 31,// ... etc, // Returns true if square// root of n under modulo// p existsfunction squareRoot($n, $p){ $n = $n % $p; // One by one check all // numbers from 2 to p-1 for ($x = 2; $x < $p; $x++) { if (($x * $x) % $p == $n) { echo(\"Square root is \" . $x); return; } } echo(\"Square root doesn't exist\");} // Driver Code$p = 7;$n = 2;squareRoot($n, $p); // This code is contributed by Ajit.?>",
"e": 3791,
"s": 3242,
"text": null
},
{
"code": "<script>// A Simple Javascript program to find square// root under modulo p when p is 7,// 11, 19, 23, 31, ... etc, // Returns true if square root of n // under modulo p exists function squareRoot(n,p) { n = n % p; // One by one check all numbers // from 2 to p-1 for (let x = 2; x < p; x++) { if ((x * x) % p == n) { document.write(\"Square \" + \"root is \" + x); return; } } document.write(\"Square root \" + \"doesn't exist\"); } // Driver Code let p = 7; let n = 2; squareRoot(n, p); // This code is contributed by rag2127 </script>",
"e": 4502,
"s": 3791,
"text": null
},
{
"code": null,
"e": 4511,
"s": 4502,
"text": "Output: "
},
{
"code": null,
"e": 4528,
"s": 4511,
"text": "Square root is 3"
},
{
"code": null,
"e": 4671,
"s": 4528,
"text": "Time Complexity of this solution is O(p)Direct Method : If p is in the form of 4*i + 3, then there exist a Quick way of finding square root. "
},
{
"code": null,
"e": 4795,
"s": 4671,
"text": "If n is in the form 4*i + 3 with i >= 1 (OR p % 4 = 3)\nAnd \nIf Square root of n exists, then it must be\n ±n(p + 1)/4"
},
{
"code": null,
"e": 4841,
"s": 4795,
"text": "Below is the implementation of above idea : "
},
{
"code": null,
"e": 4845,
"s": 4841,
"text": "C++"
},
{
"code": null,
"e": 4850,
"s": 4845,
"text": "Java"
},
{
"code": null,
"e": 4858,
"s": 4850,
"text": "Python3"
},
{
"code": null,
"e": 4861,
"s": 4858,
"text": "C#"
},
{
"code": null,
"e": 4865,
"s": 4861,
"text": "PHP"
},
{
"code": null,
"e": 4876,
"s": 4865,
"text": "Javascript"
},
{
"code": "// An efficient C++ program to find square root under// modulo p when p is 7, 11, 19, 23, 31, ... etc.#include <iostream>using namespace std; // Utility function to do modular exponentiation.// It returns (x^y) % p.int power(int x, int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Returns true if square root of n under modulo p exists// Assumption: p is of the form 3*i + 4 where i >= 1void squareRoot(int n, int p){ if (p % 4 != 3) { cout << \"Invalid Input\"; return; } // Try \"+(n^((p + 1)/4))\" n = n % p; int x = power(n, (p + 1) / 4, p); if ((x * x) % p == n) { cout << \"Square root is \" << x; return; } // Try \"-(n ^ ((p + 1)/4))\" x = p - x; if ((x * x) % p == n) { cout << \"Square root is \" << x; return; } // If none of the above two work, then // square root doesn't exist cout << \"Square root doesn't exist \";} // Driver program to testint main(){ int p = 7; int n = 2; squareRoot(n, p); return 0;}",
"e": 6185,
"s": 4876,
"text": null
},
{
"code": "// An efficient Java program to find square root under// modulo p when p is 7, 11, 19, 23, 31, ... etc.public class GFG { // Utility function to do modular exponentiation.// It returns (x^y) % p.static int power(int x, int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y %2== 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Returns true if square root of n under modulo p exists// Assumption: p is of the form 3*i + 4 where i >= 1static void squareRoot(int n, int p){ if (p % 4 != 3) { System.out.print(\"Invalid Input\"); return; } // Try \"+(n^((p + 1)/4))\" n = n % p; int x = power(n, (p + 1) / 4, p); if ((x * x) % p == n) { System.out.print(\"Square root is \" + x); return; } // Try \"-(n ^ ((p + 1)/4))\" x = p - x; if ((x * x) % p == n) { System.out.print(\"Square root is \" + x); return; } // If none of the above two work, then // square root doesn't exist System.out.print(\"Square root doesn't exist \");} // Driver program to test static public void main(String[] args) { int p = 7; int n = 2; squareRoot(n, p); }}",
"e": 7547,
"s": 6185,
"text": null
},
{
"code": "# An efficient python3 program to find square root# under modulo p when p is 7, 11, 19, 23, 31, ... etc. # Utility function to do modular exponentiation.# It returns (x^y) % p.def power(x, y, p) : res = 1 # Initialize result x = x % p # Update x if it is more # than or equal to p while (y > 0): # If y is odd, multiply x with result if (y & 1): res = (res * x) % p # y must be even now y = y >> 1 # y = y/2 x = (x * x) % p return res # Returns true if square root of n under# modulo p exists. Assumption: p is of the# form 3*i + 4 where i >= 1def squareRoot(n, p): if (p % 4 != 3) : print( \"Invalid Input\" ) return # Try \"+(n^((p + 1)/4))\" n = n % p x = power(n, (p + 1) // 4, p) if ((x * x) % p == n): print( \"Square root is \", x) return # Try \"-(n ^ ((p + 1)/4))\" x = p - x if ((x * x) % p == n): print( \"Square root is \", x ) return # If none of the above two work, then # square root doesn't exist print( \"Square root doesn't exist \" ) # Driver Codep = 7n = 2squareRoot(n, p) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)",
"e": 8753,
"s": 7547,
"text": null
},
{
"code": "// An efficient C# program to find square root under// modulo p when p is 7, 11, 19, 23, 31, ... etc. using System;public class GFG { // Utility function to do modular exponentiation.// It returns (x^y) % p.static int power(int x, int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y %2 == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Returns true if square root of n under modulo p exists// Assumption: p is of the form 3*i + 4 where i >= 1static void squareRoot(int n, int p){ if (p % 4 != 3) { Console.Write(\"Invalid Input\"); return; } // Try \"+(n^((p + 1)/4))\" n = n % p; int x = power(n, (p + 1) / 4, p); if ((x * x) % p == n) { Console.Write(\"Square root is \" + x); return; } // Try \"-(n ^ ((p + 1)/4))\" x = p - x; if ((x * x) % p == n) { Console.Write(\"Square root is \" + x); return; } // If none of the above two work, then // square root doesn't exist Console.Write(\"Square root doesn't exist \");} // Driver program to test static public void Main() { int p = 7; int n = 2; squareRoot(n, p); }}// This code is contributed by Ita_c.",
"e": 10147,
"s": 8753,
"text": null
},
{
"code": "<?php// An efficient PHP program// to find square root under// modulo p when p is 7, 11,// 19, 23, 31, ... etc. // Utility function to do// modular exponentiation.// It returns (x^y) % p.function power($x, $y, $p){ // Initialize result $res = 1; // Update x if it // is more than or // equal to p $x = $x % $p; while ($y > 0) { // If y is odd, multiply // x with result if ($y & 1) $res = ($res * $x) % $p; // y must be even now // y = y/2 $y = $y >> 1; $x = ($x * $x) % $p; } return $res;} // Returns true if square root// of n under modulo p exists// Assumption: p is of the// form 3*i + 4 where i >= 1function squareRoot($n, $p){ if ($p % 4 != 3) { echo \"Invalid Input\"; return; } // Try \"+(n^((p + 1)/4))\" $n = $n % $p; $x = power($n, ($p + 1) / 4, $p); if (($x * $x) % $p == $n) { echo \"Square root is \", $x; return; } // Try \"-(n ^ ((p + 1)/4))\" $x = $p - $x; if (($x * $x) % $p == $n) { echo \"Square root is \", $x; return; } // If none of the above // two work, then square // root doesn't exist echo \"Square root doesn't exist \";} // Driver Code $p = 7; $n = 2; squareRoot($n, $p); // This code is contributed by ajit?>",
"e": 11502,
"s": 10147,
"text": null
},
{
"code": "<script>// An efficient Javascript program to find square root under// modulo p when p is 7, 11, 19, 23, 31, ... etc. // Utility function to do modular exponentiation. // It returns (x^y) % p. function power(x,y,p) { let res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y %2== 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Returns true if square root of n under modulo p exists // Assumption: p is of the form 3*i + 4 where i >= 1 function squareRoot(n, p) { if (p % 4 != 3) { document.write(\"Invalid Input\"); return; } // Try \"+(n^((p + 1)/4))\" n = n % p; let x = power(n, Math.floor((p + 1) / 4), p); if ((x * x) % p == n) { document.write(\"Square root is \" + x); return; } // Try \"-(n ^ ((p + 1)/4))\" x = p - x; if ((x * x) % p == n) { document.write(\"Square root is \" + x); return; } // If none of the above two work, then // square root doesn't exist document.write(\"Square root doesn't exist \"); } // Driver program to test let p = 7; let n = 2; squareRoot(n, p); // This code is contributed by avanitrachhadiya2155</script>",
"e": 13085,
"s": 11502,
"text": null
},
{
"code": null,
"e": 13093,
"s": 13085,
"text": "Output:"
},
{
"code": null,
"e": 13110,
"s": 13093,
"text": "Square root is 4"
},
{
"code": null,
"e": 13233,
"s": 13110,
"text": "Time Complexity of this solution is O(Log p)How does this work? We have discussed Euler’s Criterion in the previous post. "
},
{
"code": null,
"e": 13686,
"s": 13233,
"text": "As per Euler's criterion, if square root exists, then \nfollowing condition is true\n n(p-1)/2 % p = 1\n\nMultiplying both sides with n, we get\n n(p+1)/2 % p = n % p ------ (1)\n\nLet x be the modulo square root. We can write,\n (x * x) ≡ n mod p\n (x * x) ≡ n(p+1)/2 [Using (1) given above]\n (x * x) ≡ n(2i + 2) [Replacing n = 4*i + 3]\n x ≡ ±n(i + 1) [Taking Square root of both sides]\n x ≡ ±n(p + 1)/4 [Putting 4*i + 3 = p or i = (p-3)/4]"
},
{
"code": null,
"e": 13919,
"s": 13686,
"text": "We will soon be discussing methods when p is not in above form.This article is contributed by Shivam Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 13925,
"s": 13919,
"text": "jit_t"
},
{
"code": null,
"e": 13930,
"s": 13925,
"text": "vt_m"
},
{
"code": null,
"e": 13940,
"s": 13930,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 13946,
"s": 13940,
"text": "ukasp"
},
{
"code": null,
"e": 13961,
"s": 13946,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 13977,
"s": 13961,
"text": "Archit_Dwevedi0"
},
{
"code": null,
"e": 13985,
"s": 13977,
"text": "rag2127"
},
{
"code": null,
"e": 14006,
"s": 13985,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 14025,
"s": 14006,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 14038,
"s": 14025,
"text": "Mathematical"
},
{
"code": null,
"e": 14051,
"s": 14038,
"text": "Mathematical"
},
{
"code": null,
"e": 14070,
"s": 14051,
"text": "Modular Arithmetic"
}
] |
How to do pagination in Node.js using sorting ids ? | 21 Jun, 2021
Pagination in NodeJS is defined as adding the numbers to identify the sequential number of the pages. In pagination, we used to skip and limit for reducing the size of data in the database when they are very large in numbers. In this article, we will do pagination in NodeJS using sorting IDs.
Approach: Sorting in the NodeJS helps to sort the result in ascending or descending order. We use the sort() method in which we pass one parameter that results in ascending or descending order. Use the value -1 in the sort object to sort descending and 1 to sort the object in the ascending order.
Installing module: You can install the required module using the following command.
npm install mongoose
npm install express
npm install bcryptjs
npm install body-parser
Project Structure: It will look like this.
MongoDB Database: Following is the sample data stored in your database for this example.
Method 1: Sorting in ascending order using IDs.
user.js
var mongoose = require("mongoose"); var userSchema = new mongoose.Schema({ username:String, password:String}); module.exports = mongoose.model("User",userSchema);
app.js
var express = require('express'), Mongoose = require('mongoose'), Bcrypt = require('bcryptjs'), bodyParser = require('body-parser'), jsonParser = bodyParser.json(), User = require('./user') const app = express(); const db = `mongodb+srv://pallavi:[email protected]/user?retryWrites=true&w=majority` Mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true}).then(() => console.log('MongoDB Connected....')) // Handling GET /send Requestapp.get("/send", async (req, res, next) => { try { let { page, size, sort } = req.query; // If the page is not applied in query. if (!page) { // Make the Default value one. page = 1; } if (!size) { size = 10; } // We have to make it integer because // query parameter passed is string const limit = parseInt(size); // We pass 1 for sorting data in // ascending order using ids const user = await User.find().sort( { votes: 1, _id: 1 }).limit(limit) res.send({ page, size, Info: user, }); } catch (error) { res.sendStatus(500); }}); // Handling POST /send Requestapp.post('/send', jsonParser, (req, res) => { req.body.password = Bcrypt.hashSync(req.body.password, 10); var newUser = new User({ username: req.body.username, password: req.body.password, }) newUser.save() .then(result => { console.log(result); });}) // Server setupapp.listen(3000, function () { console.log("Express Started on Port 3000");});
Run app.js file using the following command:
node app.js
Output: Now open your browser and go to http://localhost:3000/send?sort, you will see the following output:
Method 2: Sorting in descending order using IDs
user.js
var mongoose = require("mongoose"); var userSchema = new mongoose.Schema({ username:String, password:String}); module.exports = mongoose.model("User", userSchema);
app.js
var express = require('express'), Mongoose = require('mongoose'), Bcrypt = require('bcryptjs'), bodyParser = require('body-parser'), jsonParser = bodyParser.json(), User = require('./user') const app = express(); const db = `mongodb+srv://pallavi:[email protected]/user?retryWrites=true&w=majority` Mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true}).then(() => console.log('MongoDB Connected....')) // Handling GET /send Requestapp.get("/send", async (req, res, next) => { try { let { page, size, sort } = req.query; // If the page is not applied in query if (!page) { // Make the Default value one page = 1; } if (!size) { size = 10; } // We have to make it integer because // the query parameter passed is string const limit = parseInt(size); // We pass 1 for sorting data in // descending order using ids const user = await User.find().sort( { votes: 1, _id: -1 }).limit(limit) res.send({ page, size, Info: user, }); } catch (error) { res.sendStatus(500); }}); // Handling POST /send Requestapp.post('/send', jsonParser, (req, res) => { req.body.password = Bcrypt.hashSync(req.body.password, 10); var newUser = new User({ username: req.body.username, password: req.body.password, }) newUser. save() .then(result => { console.log(result); });}) // Server setupapp.listen(3000, function () { console.log("Express Started on Port 3000");});
Run app.js file using the following command:
node app.js
Output: Now open your browser and go to http://localhost:3000/send?sort, you will see the following output:
Node.js-Methods
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
Installation of Node.js on Windows
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Jun, 2021"
},
{
"code": null,
"e": 348,
"s": 54,
"text": "Pagination in NodeJS is defined as adding the numbers to identify the sequential number of the pages. In pagination, we used to skip and limit for reducing the size of data in the database when they are very large in numbers. In this article, we will do pagination in NodeJS using sorting IDs."
},
{
"code": null,
"e": 646,
"s": 348,
"text": "Approach: Sorting in the NodeJS helps to sort the result in ascending or descending order. We use the sort() method in which we pass one parameter that results in ascending or descending order. Use the value -1 in the sort object to sort descending and 1 to sort the object in the ascending order."
},
{
"code": null,
"e": 731,
"s": 646,
"text": "Installing module: You can install the required module using the following command. "
},
{
"code": null,
"e": 820,
"s": 731,
"text": "npm install mongoose \nnpm install express \nnpm install bcryptjs \nnpm install body-parser"
},
{
"code": null,
"e": 863,
"s": 820,
"text": "Project Structure: It will look like this."
},
{
"code": null,
"e": 952,
"s": 863,
"text": "MongoDB Database: Following is the sample data stored in your database for this example."
},
{
"code": null,
"e": 1000,
"s": 952,
"text": "Method 1: Sorting in ascending order using IDs."
},
{
"code": null,
"e": 1008,
"s": 1000,
"text": "user.js"
},
{
"code": "var mongoose = require(\"mongoose\"); var userSchema = new mongoose.Schema({ username:String, password:String}); module.exports = mongoose.model(\"User\",userSchema);",
"e": 1179,
"s": 1008,
"text": null
},
{
"code": null,
"e": 1186,
"s": 1179,
"text": "app.js"
},
{
"code": "var express = require('express'), Mongoose = require('mongoose'), Bcrypt = require('bcryptjs'), bodyParser = require('body-parser'), jsonParser = bodyParser.json(), User = require('./user') const app = express(); const db = `mongodb+srv://pallavi:[email protected]/user?retryWrites=true&w=majority` Mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true}).then(() => console.log('MongoDB Connected....')) // Handling GET /send Requestapp.get(\"/send\", async (req, res, next) => { try { let { page, size, sort } = req.query; // If the page is not applied in query. if (!page) { // Make the Default value one. page = 1; } if (!size) { size = 10; } // We have to make it integer because // query parameter passed is string const limit = parseInt(size); // We pass 1 for sorting data in // ascending order using ids const user = await User.find().sort( { votes: 1, _id: 1 }).limit(limit) res.send({ page, size, Info: user, }); } catch (error) { res.sendStatus(500); }}); // Handling POST /send Requestapp.post('/send', jsonParser, (req, res) => { req.body.password = Bcrypt.hashSync(req.body.password, 10); var newUser = new User({ username: req.body.username, password: req.body.password, }) newUser.save() .then(result => { console.log(result); });}) // Server setupapp.listen(3000, function () { console.log(\"Express Started on Port 3000\");});",
"e": 2892,
"s": 1186,
"text": null
},
{
"code": null,
"e": 2937,
"s": 2892,
"text": "Run app.js file using the following command:"
},
{
"code": null,
"e": 2949,
"s": 2937,
"text": "node app.js"
},
{
"code": null,
"e": 3057,
"s": 2949,
"text": "Output: Now open your browser and go to http://localhost:3000/send?sort, you will see the following output:"
},
{
"code": null,
"e": 3105,
"s": 3057,
"text": "Method 2: Sorting in descending order using IDs"
},
{
"code": null,
"e": 3113,
"s": 3105,
"text": "user.js"
},
{
"code": "var mongoose = require(\"mongoose\"); var userSchema = new mongoose.Schema({ username:String, password:String}); module.exports = mongoose.model(\"User\", userSchema);",
"e": 3285,
"s": 3113,
"text": null
},
{
"code": null,
"e": 3292,
"s": 3285,
"text": "app.js"
},
{
"code": "var express = require('express'), Mongoose = require('mongoose'), Bcrypt = require('bcryptjs'), bodyParser = require('body-parser'), jsonParser = bodyParser.json(), User = require('./user') const app = express(); const db = `mongodb+srv://pallavi:[email protected]/user?retryWrites=true&w=majority` Mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true}).then(() => console.log('MongoDB Connected....')) // Handling GET /send Requestapp.get(\"/send\", async (req, res, next) => { try { let { page, size, sort } = req.query; // If the page is not applied in query if (!page) { // Make the Default value one page = 1; } if (!size) { size = 10; } // We have to make it integer because // the query parameter passed is string const limit = parseInt(size); // We pass 1 for sorting data in // descending order using ids const user = await User.find().sort( { votes: 1, _id: -1 }).limit(limit) res.send({ page, size, Info: user, }); } catch (error) { res.sendStatus(500); }}); // Handling POST /send Requestapp.post('/send', jsonParser, (req, res) => { req.body.password = Bcrypt.hashSync(req.body.password, 10); var newUser = new User({ username: req.body.username, password: req.body.password, }) newUser. save() .then(result => { console.log(result); });}) // Server setupapp.listen(3000, function () { console.log(\"Express Started on Port 3000\");});",
"e": 5022,
"s": 3292,
"text": null
},
{
"code": null,
"e": 5067,
"s": 5022,
"text": "Run app.js file using the following command:"
},
{
"code": null,
"e": 5079,
"s": 5067,
"text": "node app.js"
},
{
"code": null,
"e": 5187,
"s": 5079,
"text": "Output: Now open your browser and go to http://localhost:3000/send?sort, you will see the following output:"
},
{
"code": null,
"e": 5203,
"s": 5187,
"text": "Node.js-Methods"
},
{
"code": null,
"e": 5220,
"s": 5203,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 5227,
"s": 5220,
"text": "Picked"
},
{
"code": null,
"e": 5235,
"s": 5227,
"text": "Node.js"
},
{
"code": null,
"e": 5252,
"s": 5235,
"text": "Web Technologies"
},
{
"code": null,
"e": 5350,
"s": 5252,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5380,
"s": 5350,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 5437,
"s": 5380,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 5491,
"s": 5437,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 5531,
"s": 5491,
"text": "Mongoose | findByIdAndUpdate() Function"
},
{
"code": null,
"e": 5566,
"s": 5531,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 5628,
"s": 5566,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5689,
"s": 5628,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5739,
"s": 5689,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 5782,
"s": 5739,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
HTTP headers | ETag | 06 Sep, 2021
ETag or Entity Tag is a response-type header that works as a validator to let client make conditional requests. It makes re-validation requests more efficient by triggering request headers which help with web cache validation that makes economical use of network bandwidth.
ETag is generated as identification for specific browser resources. Each time the user opens the same resource, the browser sends a small token to verify if this version of the resource already present in the browser’s HTTP cache matches with the current version on the webserver. If the resource matches then web server need not send a full response. This makes process faster and saves data.
Syntax:
ETag : "etag-value" (strong validation)
ETag : W/"etag-value" (weak validation)
Directives : This header accepts two directive as mentioned above and described below:
“etag-value”: It is a string of ASCII characters in double-quotes. A new value is generated every time the browser resource changes and it is unique. There is no HTTP specification about the order of value generated. Therefore , the method of value generation is completely dependent on the webserver.
W/ : This is symbolic of weak validation. They are very easy to generate compared to strong validator tags but differ in performing a comparison process. A weak comparison considers two tags equivalent if their opaque-tags match character-by-character, irrespective either or both being tagged as “weak”. While a strong comparison considers two tags equivalent only if both match character by character and both tags are not weak.
Working of ETag with Request Headers :
If-Match Header : This is primarily used when multiple agents might be working on the same resource , thereby to prevent accidental overwrites while using methods such as POST, PUT, DELETE etc. Here, a ETag header value for a particular resource is contained within an If-Match header to check if while performing the specified action the resource undergoes any change or not. 412 Precondition Failed error is shown if the match does not occur. It can also be used to abort a request if the current representation does not match the prior request completely or partially.
ETag : "21e92a357b3434b5aa"
If-Match : "21e92a357b3434b5aa"
If-None-Match Header : This header is used when the already stored response of a specific website previously visited by the user has expired. Here , server generates If-None-Match value for the current version and compares it with the ETag value stored in user’s browser. A 304 Not Modified status code is shown if both values match. Weak comparison must be used in this scenario while comparing entity tags.
If-None-Match : "21e92a357b3434b5aa"
Examples :
ETag: "21e92a357b3434b5aa" (strong validation)
ETag: W/"21e92a457b3434b5aa" (weak validation)
Supported Browsers : The browsers are supported by HTTP header | ETag header are listed below:
Microsoft Edge
Google Chrome
Mozilla Firefox
Safari
Opera
Internet Explorer
sumitgumber28
HTTP-headers
Picked
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": "\n06 Sep, 2021"
},
{
"code": null,
"e": 303,
"s": 28,
"text": "ETag or Entity Tag is a response-type header that works as a validator to let client make conditional requests. It makes re-validation requests more efficient by triggering request headers which help with web cache validation that makes economical use of network bandwidth. "
},
{
"code": null,
"e": 698,
"s": 303,
"text": "ETag is generated as identification for specific browser resources. Each time the user opens the same resource, the browser sends a small token to verify if this version of the resource already present in the browser’s HTTP cache matches with the current version on the webserver. If the resource matches then web server need not send a full response. This makes process faster and saves data. "
},
{
"code": null,
"e": 706,
"s": 698,
"text": "Syntax:"
},
{
"code": null,
"e": 792,
"s": 706,
"text": "ETag : \"etag-value\" (strong validation)\nETag : W/\"etag-value\" (weak validation) "
},
{
"code": null,
"e": 879,
"s": 792,
"text": "Directives : This header accepts two directive as mentioned above and described below:"
},
{
"code": null,
"e": 1181,
"s": 879,
"text": "“etag-value”: It is a string of ASCII characters in double-quotes. A new value is generated every time the browser resource changes and it is unique. There is no HTTP specification about the order of value generated. Therefore , the method of value generation is completely dependent on the webserver."
},
{
"code": null,
"e": 1612,
"s": 1181,
"text": "W/ : This is symbolic of weak validation. They are very easy to generate compared to strong validator tags but differ in performing a comparison process. A weak comparison considers two tags equivalent if their opaque-tags match character-by-character, irrespective either or both being tagged as “weak”. While a strong comparison considers two tags equivalent only if both match character by character and both tags are not weak."
},
{
"code": null,
"e": 1652,
"s": 1612,
"text": "Working of ETag with Request Headers : "
},
{
"code": null,
"e": 2224,
"s": 1652,
"text": "If-Match Header : This is primarily used when multiple agents might be working on the same resource , thereby to prevent accidental overwrites while using methods such as POST, PUT, DELETE etc. Here, a ETag header value for a particular resource is contained within an If-Match header to check if while performing the specified action the resource undergoes any change or not. 412 Precondition Failed error is shown if the match does not occur. It can also be used to abort a request if the current representation does not match the prior request completely or partially."
},
{
"code": null,
"e": 2284,
"s": 2224,
"text": "ETag : \"21e92a357b3434b5aa\"\nIf-Match : \"21e92a357b3434b5aa\""
},
{
"code": null,
"e": 2693,
"s": 2284,
"text": "If-None-Match Header : This header is used when the already stored response of a specific website previously visited by the user has expired. Here , server generates If-None-Match value for the current version and compares it with the ETag value stored in user’s browser. A 304 Not Modified status code is shown if both values match. Weak comparison must be used in this scenario while comparing entity tags."
},
{
"code": null,
"e": 2730,
"s": 2693,
"text": "If-None-Match : \"21e92a357b3434b5aa\""
},
{
"code": null,
"e": 2742,
"s": 2730,
"text": "Examples : "
},
{
"code": null,
"e": 2838,
"s": 2742,
"text": "ETag: \"21e92a357b3434b5aa\" (strong validation)\nETag: W/\"21e92a457b3434b5aa\" (weak validation)"
},
{
"code": null,
"e": 2933,
"s": 2838,
"text": "Supported Browsers : The browsers are supported by HTTP header | ETag header are listed below:"
},
{
"code": null,
"e": 2948,
"s": 2933,
"text": "Microsoft Edge"
},
{
"code": null,
"e": 2962,
"s": 2948,
"text": "Google Chrome"
},
{
"code": null,
"e": 2978,
"s": 2962,
"text": "Mozilla Firefox"
},
{
"code": null,
"e": 2985,
"s": 2978,
"text": "Safari"
},
{
"code": null,
"e": 2991,
"s": 2985,
"text": "Opera"
},
{
"code": null,
"e": 3009,
"s": 2991,
"text": "Internet Explorer"
},
{
"code": null,
"e": 3023,
"s": 3009,
"text": "sumitgumber28"
},
{
"code": null,
"e": 3036,
"s": 3023,
"text": "HTTP-headers"
},
{
"code": null,
"e": 3043,
"s": 3036,
"text": "Picked"
},
{
"code": null,
"e": 3060,
"s": 3043,
"text": "Web Technologies"
}
] |
GSmartControl – Tool to Check SSD/HDD Health on Linux | 29 Jan, 2021
Gsmart control (Self-Monitoring, Analysis, and Reporting Technology)is a GUI tool that clearly shows if there is a problem with your hard drive/SSDs or not, It generally checks and displays the present condition of your hard drive/SSDs and also run the various test on it.
Installation (for Debian GNU/Linux):
sudo apt-get install gsmartcontrol
sudo apt-get install gsmartcontrol
If you are in another Linux distro you can check the download process from the official documentation page Linux.
You can open it from your terminal
sudo gsmartcontrol
Output:
You can also open it from your desktop menu:
GSmartControl
Features:
SMART automatically reports and highlights any anomalies that your HDD/SSD has ;
You can be enabling/disabling SMART;
You can allow enabling/disabling Automatic Offline Data Collection – a short self-check that the drive will perform automatically every four hours with no impact on performance;
SMART supports configuration of global and per-drive options for smartctl;
SMART performs some self-tests;
dSMART displays drive identity information, capabilities, attributes, device statistics, etc...;
You can read in smartctl output from a saved file, interpreting it as a read-only virtual device;
It also works on most smartctl-supported operating systems;
It has extensive help information.
Usage:
Your connected drives will be listed like this :
1. Attributes: Then there are Attributes option that will tell about the health of your drive.
You can take your mouse over the section you want to know about and you will get the details about what it is actually. like it is shown in the screenshot
2. Statistics: You can also see the statistics of your drive which basically shows how many times the device has processed a power-on reset and many more things.
statistics
3. Self-Tests: Most importantly you can perform tests with self-test sections like I have performed a short self-test which lasted for 2 minutes, you can also do an extended self-test which will take 2 hrs approx and the result will show whether your drive has any faults or not.
self-test
4. Error log: Error-log section shows whether your drive has encountered any error or not.
If the drive has any error then the error with complete error log will be displayed
5. Temperature: The temperature log displays the current temperature with some more detailed logs.
Temperature-log
6. Advanced: The last one comes the Advanced section which contains some advanced options, the capabilities are also written aside by which you can understand the uses much better.
Advanced
This tool is generally a great tool if you are concerned about your HDD/SSD, And always want to look after whether the drives are doing well or not as this tool is simply very easy to use all in one tool.
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
chmod command in Linux with examples
mv command in Linux with examples
Basic Operators in Shell Scripting | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 Jan, 2021"
},
{
"code": null,
"e": 328,
"s": 54,
"text": "Gsmart control (Self-Monitoring, Analysis, and Reporting Technology)is a GUI tool that clearly shows if there is a problem with your hard drive/SSDs or not, It generally checks and displays the present condition of your hard drive/SSDs and also run the various test on it."
},
{
"code": null,
"e": 365,
"s": 328,
"text": "Installation (for Debian GNU/Linux):"
},
{
"code": null,
"e": 400,
"s": 365,
"text": "sudo apt-get install gsmartcontrol"
},
{
"code": null,
"e": 436,
"s": 400,
"text": "sudo apt-get install gsmartcontrol "
},
{
"code": null,
"e": 550,
"s": 436,
"text": "If you are in another Linux distro you can check the download process from the official documentation page Linux."
},
{
"code": null,
"e": 585,
"s": 550,
"text": "You can open it from your terminal"
},
{
"code": null,
"e": 604,
"s": 585,
"text": "sudo gsmartcontrol"
},
{
"code": null,
"e": 612,
"s": 604,
"text": "Output:"
},
{
"code": null,
"e": 657,
"s": 612,
"text": "You can also open it from your desktop menu:"
},
{
"code": null,
"e": 671,
"s": 657,
"text": "GSmartControl"
},
{
"code": null,
"e": 681,
"s": 671,
"text": "Features:"
},
{
"code": null,
"e": 762,
"s": 681,
"text": "SMART automatically reports and highlights any anomalies that your HDD/SSD has ;"
},
{
"code": null,
"e": 799,
"s": 762,
"text": "You can be enabling/disabling SMART;"
},
{
"code": null,
"e": 977,
"s": 799,
"text": "You can allow enabling/disabling Automatic Offline Data Collection – a short self-check that the drive will perform automatically every four hours with no impact on performance;"
},
{
"code": null,
"e": 1052,
"s": 977,
"text": "SMART supports configuration of global and per-drive options for smartctl;"
},
{
"code": null,
"e": 1085,
"s": 1052,
"text": "SMART performs some self-tests;"
},
{
"code": null,
"e": 1182,
"s": 1085,
"text": "dSMART displays drive identity information, capabilities, attributes, device statistics, etc...;"
},
{
"code": null,
"e": 1280,
"s": 1182,
"text": "You can read in smartctl output from a saved file, interpreting it as a read-only virtual device;"
},
{
"code": null,
"e": 1340,
"s": 1280,
"text": "It also works on most smartctl-supported operating systems;"
},
{
"code": null,
"e": 1375,
"s": 1340,
"text": "It has extensive help information."
},
{
"code": null,
"e": 1382,
"s": 1375,
"text": "Usage:"
},
{
"code": null,
"e": 1431,
"s": 1382,
"text": "Your connected drives will be listed like this :"
},
{
"code": null,
"e": 1526,
"s": 1431,
"text": "1. Attributes: Then there are Attributes option that will tell about the health of your drive."
},
{
"code": null,
"e": 1681,
"s": 1526,
"text": "You can take your mouse over the section you want to know about and you will get the details about what it is actually. like it is shown in the screenshot"
},
{
"code": null,
"e": 1843,
"s": 1681,
"text": "2. Statistics: You can also see the statistics of your drive which basically shows how many times the device has processed a power-on reset and many more things."
},
{
"code": null,
"e": 1854,
"s": 1843,
"text": "statistics"
},
{
"code": null,
"e": 2134,
"s": 1854,
"text": "3. Self-Tests: Most importantly you can perform tests with self-test sections like I have performed a short self-test which lasted for 2 minutes, you can also do an extended self-test which will take 2 hrs approx and the result will show whether your drive has any faults or not."
},
{
"code": null,
"e": 2144,
"s": 2134,
"text": "self-test"
},
{
"code": null,
"e": 2236,
"s": 2144,
"text": "4. Error log: Error-log section shows whether your drive has encountered any error or not."
},
{
"code": null,
"e": 2321,
"s": 2236,
"text": "If the drive has any error then the error with complete error log will be displayed"
},
{
"code": null,
"e": 2420,
"s": 2321,
"text": "5. Temperature: The temperature log displays the current temperature with some more detailed logs."
},
{
"code": null,
"e": 2436,
"s": 2420,
"text": "Temperature-log"
},
{
"code": null,
"e": 2617,
"s": 2436,
"text": "6. Advanced: The last one comes the Advanced section which contains some advanced options, the capabilities are also written aside by which you can understand the uses much better."
},
{
"code": null,
"e": 2626,
"s": 2617,
"text": "Advanced"
},
{
"code": null,
"e": 2831,
"s": 2626,
"text": "This tool is generally a great tool if you are concerned about your HDD/SSD, And always want to look after whether the drives are doing well or not as this tool is simply very easy to use all in one tool."
},
{
"code": null,
"e": 2838,
"s": 2831,
"text": "Picked"
},
{
"code": null,
"e": 2849,
"s": 2838,
"text": "Linux-Unix"
},
{
"code": null,
"e": 2947,
"s": 2849,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2973,
"s": 2947,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 3008,
"s": 2973,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 3045,
"s": 3008,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 3074,
"s": 3045,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 3111,
"s": 3074,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 3150,
"s": 3111,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 3190,
"s": 3150,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 3227,
"s": 3190,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 3261,
"s": 3227,
"text": "mv command in Linux with examples"
}
] |
How to Compute a Discrete-Fourier Transform Coefficients Directly in Java? | 19 Nov, 2021
The Discrete Fourier Transform (DFT) generally varies from 0 to 360. There are basically N-sample DFT, where N is the number of samples. It ranges from n=0 to N-1. We can get the co-efficient by getting the cosine term which is the real part and the sine term which is the imaginary part.
The formula of DFT:
Example :
Input:
Enter the values of simple linear equation
ax+by=c
3
4
5
Enter the k DFT value
2
Output:
(-35.00000000000003) - (-48.17336721649107i)
Input:
Enter the values of simple linear equation
ax+by=c
2
4
5
Enter the k DFT value
4
Output:
(-30.00000000000001) - (-9.747590886987172i)
Approach:
First, let us declare the value of N is 10
We know the formula of DFT sequence is X(k)= e^jw ranges from 0 to N-1
Now we first take the inputs of a, b, c, and then we try to calculate in “ax+by=c” linear form
We try to take the function in an array called ‘newvar’.
newvar[i] = (((a*(double)i) + (b*(double)i)) -c);
Now let us take the input variable k, and also declare sin and cosine arrays so that we can calculate real and imaginary parts separately.
cos[i]=Math.cos((2*i*k*Math.PI)/N);
sin[i]=Math.sin((2*i*k*Math.PI)/N);
Now let us take real and imaginary variables
Calculating imaginary variables and real variables like
real+=newvar[i]*cos[i];
img+=newvar[i]*sin[i];
Now we will print this output in a+ ib form
Implementation:
Java
// Java program to Compute a Discrete-Fourier// Transform Coefficients Directly import java.io.*;import java.util.Scanner; class GFG { public static void main(String[] args) { // Size of the N value int N = 10; // Enter the values of simple linear equation System.out.println( "Enter the values of simple linear equation"); System.out.println("ax+by=c"); // We declare them in data_type double.. double a = 3.0; double b = 4.0; double c = 5.0; // Here newvar function array is declared in size // N.. double[] newvar = new double[N]; // Now let us loop it over N and take the function // Now the newvar array will calculate the function // ax+by=c for N times for (int i = 0; i < N; i++) { // This is the way we write that, // We are taking array A as of 'a'x // array B as of 'b'y newvar[i] = (((a * (double)i) + (b * (double)i)) - c); } System.out.println("Enter the k DFT value"); // Here we declare the variable k int k = 2; // Here we take 2 terms cos and sin arrays // which will be useful to calculate the real and // imaginary part The size of both arrays will be 10 double[] cos = new double[N]; double[] sin = new double[N]; // Iterating it to N // Now let us calculate the formula of cos and sin for (int i = 0; i < N; i++) { // Here cos term is real part which is // multiplied into 2ikpie/N cos[i] = Math.cos((2 * i * k * Math.PI) / N); // Here sin term is imaginary part which is also // multiplied into 2ikpie/N sin[i] = Math.sin((2 * i * k * Math.PI) / N); } // Now to know the value of real and imaginary terms // First we declare their respective variables double real = 0, img = 0; // Now let us iterate it till N for (int i = 0; i < N; i++) { // real part can be calculated by adding it // with newvar and multiplying it with cosine // array real += newvar[i] * cos[i]; // Imaginary part is calculated by adding it // with newvar and multiplying it with sine // array img += newvar[i] * sin[i]; } // Now real and imaginary part can be written in // this equation form System.out.println("(" + real + ") - " + "(" + img + "i)"); }}
Enter the values of simple linear equation
ax+by=c
Enter the k DFT value
(-35.00000000000003) - (-48.17336721649107i)
prachisoda1234
surinderdawra388
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Nov, 2021"
},
{
"code": null,
"e": 318,
"s": 28,
"text": "The Discrete Fourier Transform (DFT) generally varies from 0 to 360. There are basically N-sample DFT, where N is the number of samples. It ranges from n=0 to N-1. We can get the co-efficient by getting the cosine term which is the real part and the sine term which is the imaginary part. "
},
{
"code": null,
"e": 338,
"s": 318,
"text": "The formula of DFT:"
},
{
"code": null,
"e": 348,
"s": 338,
"text": "Example :"
},
{
"code": null,
"e": 638,
"s": 348,
"text": "Input:\n\nEnter the values of simple linear equation\nax+by=c\n3\n4\n5\nEnter the k DFT value\n2\n\n\nOutput:\n\n(-35.00000000000003) - (-48.17336721649107i)\n\nInput:\n\nEnter the values of simple linear equation\nax+by=c\n2\n4\n5\nEnter the k DFT value\n4\n\nOutput:\n\n(-30.00000000000001) - (-9.747590886987172i)"
},
{
"code": null,
"e": 648,
"s": 638,
"text": "Approach:"
},
{
"code": null,
"e": 691,
"s": 648,
"text": "First, let us declare the value of N is 10"
},
{
"code": null,
"e": 762,
"s": 691,
"text": "We know the formula of DFT sequence is X(k)= e^jw ranges from 0 to N-1"
},
{
"code": null,
"e": 857,
"s": 762,
"text": "Now we first take the inputs of a, b, c, and then we try to calculate in “ax+by=c” linear form"
},
{
"code": null,
"e": 914,
"s": 857,
"text": "We try to take the function in an array called ‘newvar’."
},
{
"code": null,
"e": 964,
"s": 914,
"text": "newvar[i] = (((a*(double)i) + (b*(double)i)) -c);"
},
{
"code": null,
"e": 1103,
"s": 964,
"text": "Now let us take the input variable k, and also declare sin and cosine arrays so that we can calculate real and imaginary parts separately."
},
{
"code": null,
"e": 1139,
"s": 1103,
"text": "cos[i]=Math.cos((2*i*k*Math.PI)/N);"
},
{
"code": null,
"e": 1175,
"s": 1139,
"text": "sin[i]=Math.sin((2*i*k*Math.PI)/N);"
},
{
"code": null,
"e": 1220,
"s": 1175,
"text": "Now let us take real and imaginary variables"
},
{
"code": null,
"e": 1276,
"s": 1220,
"text": "Calculating imaginary variables and real variables like"
},
{
"code": null,
"e": 1300,
"s": 1276,
"text": "real+=newvar[i]*cos[i];"
},
{
"code": null,
"e": 1323,
"s": 1300,
"text": "img+=newvar[i]*sin[i];"
},
{
"code": null,
"e": 1367,
"s": 1323,
"text": "Now we will print this output in a+ ib form"
},
{
"code": null,
"e": 1383,
"s": 1367,
"text": "Implementation:"
},
{
"code": null,
"e": 1388,
"s": 1383,
"text": "Java"
},
{
"code": "// Java program to Compute a Discrete-Fourier// Transform Coefficients Directly import java.io.*;import java.util.Scanner; class GFG { public static void main(String[] args) { // Size of the N value int N = 10; // Enter the values of simple linear equation System.out.println( \"Enter the values of simple linear equation\"); System.out.println(\"ax+by=c\"); // We declare them in data_type double.. double a = 3.0; double b = 4.0; double c = 5.0; // Here newvar function array is declared in size // N.. double[] newvar = new double[N]; // Now let us loop it over N and take the function // Now the newvar array will calculate the function // ax+by=c for N times for (int i = 0; i < N; i++) { // This is the way we write that, // We are taking array A as of 'a'x // array B as of 'b'y newvar[i] = (((a * (double)i) + (b * (double)i)) - c); } System.out.println(\"Enter the k DFT value\"); // Here we declare the variable k int k = 2; // Here we take 2 terms cos and sin arrays // which will be useful to calculate the real and // imaginary part The size of both arrays will be 10 double[] cos = new double[N]; double[] sin = new double[N]; // Iterating it to N // Now let us calculate the formula of cos and sin for (int i = 0; i < N; i++) { // Here cos term is real part which is // multiplied into 2ikpie/N cos[i] = Math.cos((2 * i * k * Math.PI) / N); // Here sin term is imaginary part which is also // multiplied into 2ikpie/N sin[i] = Math.sin((2 * i * k * Math.PI) / N); } // Now to know the value of real and imaginary terms // First we declare their respective variables double real = 0, img = 0; // Now let us iterate it till N for (int i = 0; i < N; i++) { // real part can be calculated by adding it // with newvar and multiplying it with cosine // array real += newvar[i] * cos[i]; // Imaginary part is calculated by adding it // with newvar and multiplying it with sine // array img += newvar[i] * sin[i]; } // Now real and imaginary part can be written in // this equation form System.out.println(\"(\" + real + \") - \" + \"(\" + img + \"i)\"); }}",
"e": 3987,
"s": 1388,
"text": null
},
{
"code": null,
"e": 4105,
"s": 3987,
"text": "Enter the values of simple linear equation\nax+by=c\nEnter the k DFT value\n(-35.00000000000003) - (-48.17336721649107i)"
},
{
"code": null,
"e": 4122,
"s": 4107,
"text": "prachisoda1234"
},
{
"code": null,
"e": 4139,
"s": 4122,
"text": "surinderdawra388"
},
{
"code": null,
"e": 4146,
"s": 4139,
"text": "Picked"
},
{
"code": null,
"e": 4170,
"s": 4146,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 4175,
"s": 4170,
"text": "Java"
},
{
"code": null,
"e": 4189,
"s": 4175,
"text": "Java Programs"
},
{
"code": null,
"e": 4208,
"s": 4189,
"text": "Technical Scripter"
},
{
"code": null,
"e": 4213,
"s": 4208,
"text": "Java"
},
{
"code": null,
"e": 4311,
"s": 4213,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4326,
"s": 4311,
"text": "Stream In Java"
},
{
"code": null,
"e": 4347,
"s": 4326,
"text": "Introduction to Java"
},
{
"code": null,
"e": 4368,
"s": 4347,
"text": "Constructors in Java"
},
{
"code": null,
"e": 4387,
"s": 4368,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 4404,
"s": 4387,
"text": "Generics in Java"
},
{
"code": null,
"e": 4430,
"s": 4404,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 4464,
"s": 4430,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 4511,
"s": 4464,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 4549,
"s": 4511,
"text": "Factory method design pattern in Java"
}
] |
HTML | <video> controls Attribute | 28 Jun, 2019
The HTML <video> controls Attribute is used to specify the control to play video. It is the Boolean value. This attribute is new in HTML5.
The video control should include:
Play
Pause
Volume
Full-screen Mode
Seeking
Captions/Subtitles(if available)
Track(if available)
Syntax:
<video controls>
Example:
<!DOCTYPE html><html> <head> <title>HTML video controls Attribute</title></head> <body> <center> <h1 style="color:green;">GeeksforGeeks</h1> <h3>HTML video controls Attribute</h3> <video width="400" height="200" controls> <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.mp4" type="video/mp4"> <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.ogg" type="video/ogg"> </video> </center></body> </html>
Output:
Note: Always specify the width and the height of the video else web page will be confused that how much space that video will be required due to that reason web page become slow down.
Supported Browsers: The browser supported by HTML <video> controls Attribute are listed below:
Google Chrome 4.0
Internet Explorer 9.0
Firefox 3.5
Safari 4.0
Opera 10.5
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jun, 2019"
},
{
"code": null,
"e": 167,
"s": 28,
"text": "The HTML <video> controls Attribute is used to specify the control to play video. It is the Boolean value. This attribute is new in HTML5."
},
{
"code": null,
"e": 201,
"s": 167,
"text": "The video control should include:"
},
{
"code": null,
"e": 206,
"s": 201,
"text": "Play"
},
{
"code": null,
"e": 212,
"s": 206,
"text": "Pause"
},
{
"code": null,
"e": 219,
"s": 212,
"text": "Volume"
},
{
"code": null,
"e": 236,
"s": 219,
"text": "Full-screen Mode"
},
{
"code": null,
"e": 244,
"s": 236,
"text": "Seeking"
},
{
"code": null,
"e": 277,
"s": 244,
"text": "Captions/Subtitles(if available)"
},
{
"code": null,
"e": 297,
"s": 277,
"text": "Track(if available)"
},
{
"code": null,
"e": 305,
"s": 297,
"text": "Syntax:"
},
{
"code": null,
"e": 322,
"s": 305,
"text": "<video controls>"
},
{
"code": null,
"e": 331,
"s": 322,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>HTML video controls Attribute</title></head> <body> <center> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h3>HTML video controls Attribute</h3> <video width=\"400\" height=\"200\" controls> <source src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.mp4\" type=\"video/mp4\"> <source src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.ogg\" type=\"video/ogg\"> </video> </center></body> </html>",
"e": 947,
"s": 331,
"text": null
},
{
"code": null,
"e": 955,
"s": 947,
"text": "Output:"
},
{
"code": null,
"e": 1139,
"s": 955,
"text": "Note: Always specify the width and the height of the video else web page will be confused that how much space that video will be required due to that reason web page become slow down."
},
{
"code": null,
"e": 1234,
"s": 1139,
"text": "Supported Browsers: The browser supported by HTML <video> controls Attribute are listed below:"
},
{
"code": null,
"e": 1252,
"s": 1234,
"text": "Google Chrome 4.0"
},
{
"code": null,
"e": 1274,
"s": 1252,
"text": "Internet Explorer 9.0"
},
{
"code": null,
"e": 1286,
"s": 1274,
"text": "Firefox 3.5"
},
{
"code": null,
"e": 1297,
"s": 1286,
"text": "Safari 4.0"
},
{
"code": null,
"e": 1308,
"s": 1297,
"text": "Opera 10.5"
},
{
"code": null,
"e": 1324,
"s": 1308,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 1329,
"s": 1324,
"text": "HTML"
},
{
"code": null,
"e": 1346,
"s": 1329,
"text": "Web Technologies"
},
{
"code": null,
"e": 1351,
"s": 1346,
"text": "HTML"
}
] |
AIML - <set>, <get> Tags | <set> and <get> tags are used to work with variables in AIML. Variables can be predefined variables or programmer created variables.
<set> tag is used to set value in a variable.
<set name = "variable-name"> variable-value </set>
<get> tag is used to get value from a variable.
<get name = "variable-name"></get>
For example, consider the following conversation.
Human: I am Mahesh
Robot: Hello Mahesh!
Human: Good Night
Robot: Good Night Mahesh! Thanks for the conversation!
Create setget.aiml inside C > ab > bots > test > aiml and setget.aiml.csv inside C > ab > bots > test > aimlif directories.
<?xml version = "1.0" encoding = "UTF-8"?>
<aiml version = "1.0.1" encoding = "UTF-8"?>
<category>
<pattern>I am *</pattern>
<template>
Hello <set name = "username"> <star/>! </set>
</template>
</category>
<category>
<pattern>Good Night</pattern>
<template>
Hi <get name = "username"/> Thanks for the conversation!
</template>
</category>
</aiml>
0,I am *,*,*, Hello <set name = "username"> <star/>! </set>,setget.aiml
0,Good Night,*,*, Hi <get name = "username"/> Thanks for the conversation!,setget.aiml
Open the command prompt. Go to C > ab > and type the following command −
java -cp lib/Ab.jar Main bot = test action = chat trace = false
You will see the following output −
Human: I am Mahesh
Robot: Hello Mahesh!
Human: Good Night
Robot: Good Night Mahesh! Thanks for the conversation!
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1944,
"s": 1811,
"text": "<set> and <get> tags are used to work with variables in AIML. Variables can be predefined variables or programmer created variables."
},
{
"code": null,
"e": 1990,
"s": 1944,
"text": "<set> tag is used to set value in a variable."
},
{
"code": null,
"e": 2042,
"s": 1990,
"text": "<set name = \"variable-name\"> variable-value </set>\n"
},
{
"code": null,
"e": 2090,
"s": 2042,
"text": "<get> tag is used to get value from a variable."
},
{
"code": null,
"e": 2126,
"s": 2090,
"text": "<get name = \"variable-name\"></get>\n"
},
{
"code": null,
"e": 2176,
"s": 2126,
"text": "For example, consider the following conversation."
},
{
"code": null,
"e": 2290,
"s": 2176,
"text": "Human: I am Mahesh\nRobot: Hello Mahesh!\nHuman: Good Night\nRobot: Good Night Mahesh! Thanks for the conversation!\n"
},
{
"code": null,
"e": 2414,
"s": 2290,
"text": "Create setget.aiml inside C > ab > bots > test > aiml and setget.aiml.csv inside C > ab > bots > test > aimlif directories."
},
{
"code": null,
"e": 2843,
"s": 2414,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<aiml version = \"1.0.1\" encoding = \"UTF-8\"?>\n <category>\n <pattern>I am *</pattern>\n <template>\n Hello <set name = \"username\"> <star/>! </set>\n </template> \n </category> \n \n <category>\n <pattern>Good Night</pattern>\n <template>\n Hi <get name = \"username\"/> Thanks for the conversation!\n </template> \n </category> \n \n</aiml>"
},
{
"code": null,
"e": 3002,
"s": 2843,
"text": "0,I am *,*,*, Hello <set name = \"username\"> <star/>! </set>,setget.aiml\n0,Good Night,*,*, Hi <get name = \"username\"/> Thanks for the conversation!,setget.aiml"
},
{
"code": null,
"e": 3075,
"s": 3002,
"text": "Open the command prompt. Go to C > ab > and type the following command −"
},
{
"code": null,
"e": 3140,
"s": 3075,
"text": "java -cp lib/Ab.jar Main bot = test action = chat trace = false\n"
},
{
"code": null,
"e": 3176,
"s": 3140,
"text": "You will see the following output −"
},
{
"code": null,
"e": 3290,
"s": 3176,
"text": "Human: I am Mahesh\nRobot: Hello Mahesh!\nHuman: Good Night\nRobot: Good Night Mahesh! Thanks for the conversation!\n"
},
{
"code": null,
"e": 3297,
"s": 3290,
"text": " Print"
},
{
"code": null,
"e": 3308,
"s": 3297,
"text": " Add Notes"
}
] |
JavaScript Array Methods | The JavaScript method toString() converts an array to a
string of (comma separated) array values.
Result:
The join() method also joins all array elements into a string.
It behaves just like toString(), but in addition you can specify the separator:
Result:
When you work with arrays, it is easy to remove elements and add
new elements.
This is what popping and pushing is:
Popping items out of an array, or pushing
items into an array.
The pop() method removes the last element from an array:
The pop() method returns the value that was "popped out":
The push() method adds a new element to an array (at the end):
The push() method returns the new array length:
Shifting is equivalent to popping, but working on the first element instead of
the last.
The shift() method removes the first array element and "shifts" all
other elements to a lower index.
The shift() method returns the value that was "shifted out":
The unshift() method adds a new element to an array (at the beginning), and "unshifts"
older elements:
The unshift() method returns the new array length.
Array elements are accessed using their index number:
Array indexes start with 0:
[0] is the first array element[1] is the second[2] is the third ...
The length property provides an easy way to append a new element to an array:
Array elements can be deleted using the JavaScript operator delete.
Using delete leaves undefined holes in the
array.
Use pop() or shift() instead.
The concat() method creates a new array by merging (concatenating)
existing arrays:
The concat() method does not change the existing arrays. It always returns a new array.
The concat() method can take any number of array arguments:
The concat() method can also take strings as arguments:
The splice() method adds new items to an array.
The slice() method slices out a piece of an array.
The splice() method can be used to add new items to an array:
The first parameter (2) defines the position where new elements should be
added (spliced in).
The second parameter (0) defines how many elements should be
removed.
The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be
added.
The splice() method returns an array with the deleted items:
With clever parameter setting, you can use splice() to remove elements without leaving
"holes" in the array:
The first parameter (0) defines the position where new elements should be
added (spliced in).
The second parameter (1) defines how many elements should be
removed.
The rest of the parameters are omitted. No new elements will be added.
The slice() method slices out a piece of an array into a new
array.
This example slices out a part of an array starting from array element 1
("Orange"):
The slice() method creates a new array.
The slice() method does not remove any elements from the source array.
This example slices out a part of an array starting from array element 3
("Apple"):
The slice() method can take two arguments like slice(1, 3).
The method then selects elements from the start argument, and up to (but not
including) the end argument.
If the end argument is omitted, like in the first examples, the slice()
method slices out the rest of the array.
JavaScript automatically converts an array to a comma separated string when a
primitive value is expected.
This is always the case when you try to output an array.
These two examples will produce the same result:
All JavaScript objects have a toString() method.
There are no built-in functions for finding the highest
or lowest value in a JavaScript array.
You will learn how you solve this problem in the next
chapter of this tutorial.
Sorting arrays are covered in the next chapter of this tutorial.
For a complete Array reference, go to our:
Complete JavaScript Array Reference.
The reference contains descriptions and examples of all Array
properties and methods.
Use the correct Array method to remove the last item of the fruits array.
const fruits = ["Banana", "Orange", "Apple"];
;
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 99,
"s": 0,
"text": "The JavaScript method toString() converts an array to a \nstring of (comma separated) array values."
},
{
"code": null,
"e": 107,
"s": 99,
"text": "Result:"
},
{
"code": null,
"e": 170,
"s": 107,
"text": "The join() method also joins all array elements into a string."
},
{
"code": null,
"e": 250,
"s": 170,
"text": "It behaves just like toString(), but in addition you can specify the separator:"
},
{
"code": null,
"e": 258,
"s": 250,
"text": "Result:"
},
{
"code": null,
"e": 338,
"s": 258,
"text": "When you work with arrays, it is easy to remove elements and add \nnew elements."
},
{
"code": null,
"e": 375,
"s": 338,
"text": "This is what popping and pushing is:"
},
{
"code": null,
"e": 439,
"s": 375,
"text": "Popping items out of an array, or pushing \nitems into an array."
},
{
"code": null,
"e": 497,
"s": 439,
"text": "The pop() method removes the last element from an array: "
},
{
"code": null,
"e": 555,
"s": 497,
"text": "The pop() method returns the value that was \"popped out\":"
},
{
"code": null,
"e": 618,
"s": 555,
"text": "The push() method adds a new element to an array (at the end):"
},
{
"code": null,
"e": 666,
"s": 618,
"text": "The push() method returns the new array length:"
},
{
"code": null,
"e": 756,
"s": 666,
"text": "Shifting is equivalent to popping, but working on the first element instead of \nthe last."
},
{
"code": null,
"e": 858,
"s": 756,
"text": "The shift() method removes the first array element and \"shifts\" all \nother elements to a lower index."
},
{
"code": null,
"e": 919,
"s": 858,
"text": "The shift() method returns the value that was \"shifted out\":"
},
{
"code": null,
"e": 1024,
"s": 919,
"text": "The unshift() method adds a new element to an array (at the beginning), and \"unshifts\" \nolder elements: "
},
{
"code": null,
"e": 1075,
"s": 1024,
"text": "The unshift() method returns the new array length."
},
{
"code": null,
"e": 1129,
"s": 1075,
"text": "Array elements are accessed using their index number:"
},
{
"code": null,
"e": 1157,
"s": 1129,
"text": "Array indexes start with 0:"
},
{
"code": null,
"e": 1225,
"s": 1157,
"text": "[0] is the first array element[1] is the second[2] is the third ..."
},
{
"code": null,
"e": 1303,
"s": 1225,
"text": "The length property provides an easy way to append a new element to an array:"
},
{
"code": null,
"e": 1371,
"s": 1303,
"text": "Array elements can be deleted using the JavaScript operator delete."
},
{
"code": null,
"e": 1422,
"s": 1371,
"text": "Using delete leaves undefined holes in the \narray."
},
{
"code": null,
"e": 1452,
"s": 1422,
"text": "Use pop() or shift() instead."
},
{
"code": null,
"e": 1537,
"s": 1452,
"text": "The concat() method creates a new array by merging (concatenating) \nexisting arrays:"
},
{
"code": null,
"e": 1625,
"s": 1537,
"text": "The concat() method does not change the existing arrays. It always returns a new array."
},
{
"code": null,
"e": 1685,
"s": 1625,
"text": "The concat() method can take any number of array arguments:"
},
{
"code": null,
"e": 1741,
"s": 1685,
"text": "The concat() method can also take strings as arguments:"
},
{
"code": null,
"e": 1789,
"s": 1741,
"text": "The splice() method adds new items to an array."
},
{
"code": null,
"e": 1840,
"s": 1789,
"text": "The slice() method slices out a piece of an array."
},
{
"code": null,
"e": 1903,
"s": 1840,
"text": "The splice() method can be used to add new items to an array: "
},
{
"code": null,
"e": 1998,
"s": 1903,
"text": "The first parameter (2) defines the position where new elements should be \nadded (spliced in)."
},
{
"code": null,
"e": 2068,
"s": 1998,
"text": "The second parameter (0) defines how many elements should be\nremoved."
},
{
"code": null,
"e": 2151,
"s": 2068,
"text": "The rest of the parameters (\"Lemon\" , \"Kiwi\") define the new elements to be\nadded."
},
{
"code": null,
"e": 2213,
"s": 2151,
"text": "The splice() method returns an array with the deleted items: "
},
{
"code": null,
"e": 2324,
"s": 2213,
"text": "With clever parameter setting, you can use splice() to remove elements without leaving \n\"holes\" in the array: "
},
{
"code": null,
"e": 2419,
"s": 2324,
"text": "The first parameter (0) defines the position where new elements should be \nadded (spliced in)."
},
{
"code": null,
"e": 2489,
"s": 2419,
"text": "The second parameter (1) defines how many elements should be\nremoved."
},
{
"code": null,
"e": 2560,
"s": 2489,
"text": "The rest of the parameters are omitted. No new elements will be added."
},
{
"code": null,
"e": 2629,
"s": 2560,
"text": "The slice() method slices out a piece of an array into a new \narray."
},
{
"code": null,
"e": 2715,
"s": 2629,
"text": "This example slices out a part of an array starting from array element 1 \n(\"Orange\"):"
},
{
"code": null,
"e": 2755,
"s": 2715,
"text": "The slice() method creates a new array."
},
{
"code": null,
"e": 2826,
"s": 2755,
"text": "The slice() method does not remove any elements from the source array."
},
{
"code": null,
"e": 2911,
"s": 2826,
"text": "This example slices out a part of an array starting from array element 3 \n(\"Apple\"):"
},
{
"code": null,
"e": 2971,
"s": 2911,
"text": "The slice() method can take two arguments like slice(1, 3)."
},
{
"code": null,
"e": 3078,
"s": 2971,
"text": "The method then selects elements from the start argument, and up to (but not \nincluding) the end argument."
},
{
"code": null,
"e": 3192,
"s": 3078,
"text": "If the end argument is omitted, like in the first examples, the slice() \nmethod slices out the rest of the array."
},
{
"code": null,
"e": 3300,
"s": 3192,
"text": "JavaScript automatically converts an array to a comma separated string when a \nprimitive value is expected."
},
{
"code": null,
"e": 3358,
"s": 3300,
"text": "This is always the case when you try to output an array. "
},
{
"code": null,
"e": 3407,
"s": 3358,
"text": "These two examples will produce the same result:"
},
{
"code": null,
"e": 3456,
"s": 3407,
"text": "All JavaScript objects have a toString() method."
},
{
"code": null,
"e": 3552,
"s": 3456,
"text": "There are no built-in functions for finding the highest \nor lowest value in a JavaScript array."
},
{
"code": null,
"e": 3633,
"s": 3552,
"text": "You will learn how you solve this problem in the next \nchapter of this tutorial."
},
{
"code": null,
"e": 3698,
"s": 3633,
"text": "Sorting arrays are covered in the next chapter of this tutorial."
},
{
"code": null,
"e": 3741,
"s": 3698,
"text": "For a complete Array reference, go to our:"
},
{
"code": null,
"e": 3778,
"s": 3741,
"text": "Complete JavaScript Array Reference."
},
{
"code": null,
"e": 3865,
"s": 3778,
"text": "The reference contains descriptions and examples of all Array \nproperties and methods."
},
{
"code": null,
"e": 3939,
"s": 3865,
"text": "Use the correct Array method to remove the last item of the fruits array."
},
{
"code": null,
"e": 3988,
"s": 3939,
"text": "const fruits = [\"Banana\", \"Orange\", \"Apple\"];\n;\n"
},
{
"code": null,
"e": 4007,
"s": 3988,
"text": "Start the Exercise"
},
{
"code": null,
"e": 4040,
"s": 4007,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 4082,
"s": 4040,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 4189,
"s": 4082,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 4208,
"s": 4189,
"text": "[email protected]"
}
] |
How to Specify the Path to save Newman report on Jenkins using Postman? | We can specify the path to save Newman's report on Jenkins. Jenkins reports are available in various formats and can be managed by appending flags in the build commands. Besides, we can mention the path of the directory where the reports shall get saved with the help of these build commands.
The steps to specify the path to save Newman reports on Jenkins are listed below −
As a pre-condition, Jenkins should be established in the system. The steps to work with Jenkins are available in the link − https://www.tutorialspoint.com/jenkins/index.htm. Moreover, the Newman should be installed in the system and a Collection with requests should be created.
Step1 − Click on the arrow to the right of the name of the Collection in the sidebar. Then click on Share.
Step2 − The pop-up - SHARE COLLECTION1 opens up. Navigate to Get public link and copy the link which marked in the below image.
Step3 − Open Jenkins and navigate to the Jenkins Job below the Build section. Enter the below command to generate CLI and JUNIT reports in a specific path −
newman run "<link in Step2>" --reporters cli, junit --reporter-junit-export "reportGenerate/report_newman.xml"
In the above command, reportGenerate/report_newman.xml is the path of the file where the report shall be saved. If it is non-existent, the report is generated inside the Jenkins Workspace directory automatically. | [
{
"code": null,
"e": 1355,
"s": 1062,
"text": "We can specify the path to save Newman's report on Jenkins. Jenkins reports are available in various formats and can be managed by appending flags in the build commands. Besides, we can mention the path of the directory where the reports shall get saved with the help of these build commands."
},
{
"code": null,
"e": 1438,
"s": 1355,
"text": "The steps to specify the path to save Newman reports on Jenkins are listed below −"
},
{
"code": null,
"e": 1717,
"s": 1438,
"text": "As a pre-condition, Jenkins should be established in the system. The steps to work with Jenkins are available in the link − https://www.tutorialspoint.com/jenkins/index.htm. Moreover, the Newman should be installed in the system and a Collection with requests should be created."
},
{
"code": null,
"e": 1824,
"s": 1717,
"text": "Step1 − Click on the arrow to the right of the name of the Collection in the sidebar. Then click on Share."
},
{
"code": null,
"e": 1952,
"s": 1824,
"text": "Step2 − The pop-up - SHARE COLLECTION1 opens up. Navigate to Get public link and copy the link which marked in the below image."
},
{
"code": null,
"e": 2109,
"s": 1952,
"text": "Step3 − Open Jenkins and navigate to the Jenkins Job below the Build section. Enter the below command to generate CLI and JUNIT reports in a specific path −"
},
{
"code": null,
"e": 2220,
"s": 2109,
"text": "newman run \"<link in Step2>\" --reporters cli, junit --reporter-junit-export \"reportGenerate/report_newman.xml\""
},
{
"code": null,
"e": 2433,
"s": 2220,
"text": "In the above command, reportGenerate/report_newman.xml is the path of the file where the report shall be saved. If it is non-existent, the report is generated inside the Jenkins Workspace directory automatically."
}
] |
How to get selected option using Selenium WebDriver with Python? | We can obtain the option selected in a dropdown with Selenium webdriver. The first_selected_option method fetches the option selected in the dropdown. Once the option is returned we need to apply a text method to get option text.
Let us consider the select dropdown Continents and fetch its selected item −
from selenium import webdriver
from selenium.webdriver.support.select import Select
import time driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm")
# identify dropdown
s = Select(driver.find_element_by_xpath("//select[@name='continents']"))
#select by option index
s.select_by_index(4)
#get selected item with method first_selected_option
o= s.first_selected_option
#text method for selected option text
print("Selected option is: "+ o.text)
driver.close() | [
{
"code": null,
"e": 1292,
"s": 1062,
"text": "We can obtain the option selected in a dropdown with Selenium webdriver. The first_selected_option method fetches the option selected in the dropdown. Once the option is returned we need to apply a text method to get option text."
},
{
"code": null,
"e": 1369,
"s": 1292,
"text": "Let us consider the select dropdown Continents and fetch its selected item −"
},
{
"code": null,
"e": 1955,
"s": 1369,
"text": "from selenium import webdriver\nfrom selenium.webdriver.support.select import Select\nimport time driver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\ndriver.implicitly_wait(0.5)\ndriver.get(\"https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm\")\n# identify dropdown\ns = Select(driver.find_element_by_xpath(\"//select[@name='continents']\"))\n#select by option index\ns.select_by_index(4)\n#get selected item with method first_selected_option\no= s.first_selected_option\n#text method for selected option text\nprint(\"Selected option is: \"+ o.text)\ndriver.close()"
}
] |
Super Prime in c programming | A super-prime number is A number that occupies prime number position in the sequence of all prime numbers. also known as high order primes, These numbers occupy the position in the sequence of prime number which is equal to Prime number. some super prime numbers are 3,5,11,1 7...
For Example let us Find all super prime numbers less than 13 -
Input
13
Output
3, 5, 11.
Explanation − to find the super prime number less than 13 we will find all prime numbers that are less than 13. So, show all prime numbers less than 13 are 2,3,5,7,11,13. Now, 2 is a prime number, so we will consider the prime number at position to as a super prime number. this means three is a prime number. Similarly, 5 at position 3 , and 11 at position 5 are super prime numbers.
to find all super-prime numbers that are less than a given prime number the will first find all prime numbers that are are less than that number and Store then in an array. from this array will print only those numbers whose position is equal to any of the prime numbers. For example, the prime number at 2nd 3rd 5th 7th 11th 13th.... are considered.
#include<iostream>
using namespace std;
bool SieveOfEratosthenes(int n, bool isPrime[]) {
isPrime[0] = isPrime[1] = false;
for (int i=2; i<=n; i++)
isPrime[i] = true;
for (int p=2; p*p<=n; p++) {
if (isPrime[p] == true) {
for (int i=p*2; i<=n; i += p)
isPrime[i] = false;
}
}
}
void superPrimes(int n) {
bool isPrime[n+1];
SieveOfEratosthenes(n, isPrime);
int primes[n+1], j = 0;
for (int p=2; p<=n; p++)
if (isPrime[p])
primes[j++] = p;
for (int k=0; k<j; k++)
if (isPrime[k+1])
cout << primes[k] << " ";
}
int main() {
int n = 343;
cout << "Super-Primes less than "<< n << " are :"<<endl;
superPrimes(n);
return 0;
}
Super-Primes less than 343 are :
3 5 11 17 31 41 59 67 83 109 127 157 179 191 211 241 277 283 331 | [
{
"code": null,
"e": 1343,
"s": 1062,
"text": "A super-prime number is A number that occupies prime number position in the sequence of all prime numbers. also known as high order primes, These numbers occupy the position in the sequence of prime number which is equal to Prime number. some super prime numbers are 3,5,11,1 7..."
},
{
"code": null,
"e": 1406,
"s": 1343,
"text": "For Example let us Find all super prime numbers less than 13 -"
},
{
"code": null,
"e": 1413,
"s": 1406,
"text": "Input "
},
{
"code": null,
"e": 1416,
"s": 1413,
"text": "13"
},
{
"code": null,
"e": 1423,
"s": 1416,
"text": "Output"
},
{
"code": null,
"e": 1433,
"s": 1423,
"text": "3, 5, 11."
},
{
"code": null,
"e": 1818,
"s": 1433,
"text": "Explanation − to find the super prime number less than 13 we will find all prime numbers that are less than 13. So, show all prime numbers less than 13 are 2,3,5,7,11,13. Now, 2 is a prime number, so we will consider the prime number at position to as a super prime number. this means three is a prime number. Similarly, 5 at position 3 , and 11 at position 5 are super prime numbers."
},
{
"code": null,
"e": 2169,
"s": 1818,
"text": "to find all super-prime numbers that are less than a given prime number the will first find all prime numbers that are are less than that number and Store then in an array. from this array will print only those numbers whose position is equal to any of the prime numbers. For example, the prime number at 2nd 3rd 5th 7th 11th 13th.... are considered."
},
{
"code": null,
"e": 2884,
"s": 2169,
"text": "#include<iostream>\nusing namespace std;\nbool SieveOfEratosthenes(int n, bool isPrime[]) {\n isPrime[0] = isPrime[1] = false;\n for (int i=2; i<=n; i++)\n isPrime[i] = true;\n for (int p=2; p*p<=n; p++) {\n if (isPrime[p] == true) {\n for (int i=p*2; i<=n; i += p)\n isPrime[i] = false;\n }\n }\n}\nvoid superPrimes(int n) {\n bool isPrime[n+1];\n SieveOfEratosthenes(n, isPrime);\n int primes[n+1], j = 0;\n for (int p=2; p<=n; p++)\n if (isPrime[p])\n primes[j++] = p;\n for (int k=0; k<j; k++)\n if (isPrime[k+1])\n cout << primes[k] << \" \";\n}\nint main() {\n int n = 343;\n cout << \"Super-Primes less than \"<< n << \" are :\"<<endl;\n superPrimes(n);\n return 0;\n}"
},
{
"code": null,
"e": 2982,
"s": 2884,
"text": "Super-Primes less than 343 are :\n3 5 11 17 31 41 59 67 83 109 127 157 179 191 211 241 277 283 331"
}
] |
CherryPy - Quick Guide | CherryPy is a web framework of Python which provides a friendly interface to the HTTP protocol for Python developers. It is also called a web application library.
CherryPy uses Python’s strengths as a dynamic language to model and bind HTTP protocol into an API. It is one of the oldest web frameworks for Python, which provides clean interface and reliable platform.
Remi Delon released the first version of CherryPy in late June 2002. This was the starting point of a successful Python web library. Remi is a French hacker who has trusted Python for being one of the greatest alternatives for web application development.
The project developed by Remi attracted a number of developers who were interested in the approach. The approach included the following features −
CherryPy was close to the model-view-controller pattern.
CherryPy was close to the model-view-controller pattern.
A CherryPy class has to be processed and compiled by the CherryPy engine to produce a self-contained Python module embedding the complete application and also its own built-in web server.
A CherryPy class has to be processed and compiled by the CherryPy engine to produce a self-contained Python module embedding the complete application and also its own built-in web server.
CherryPy can map a URL and its query string into a Python method call, for example −
CherryPy can map a URL and its query string into a Python method call, for example −
http://somehost.net/echo?message=hello would map to echo(message='hello')
During the two years of development in CherryPy project, it was supported by the community and Remi released several improved versions.
In June 2004, a discussion started about the future of the project and whether it should continue with the same architecture. Brainstorming and discussion by several project regulars then led to the concept of object-publishing engine and filters, which soon became a core part of CherryPy2.Later, in October 2004, the first version of CherryPy 2 alpha was released as a proof of concept of these core ideas. CherryPy 2.0 was a real success; however, it was recognized that its design could still be improved, and needed refactoring.
After discussions based on feedbacks, CherryPy's API was further modified to improve its elegance, leading to the release of CherryPy 2.1.0 in October 2005. After various changes, the team released CherryPy 2.2.0 in April 2006.
The following features of CherryPy are considered as its strengths −
Developing a project in CherryPy is a simple task with few lines of code developed as per the conventions and indentations of Python.
CherryPy is also very modular. The primary components are well managed with correct logic concept and parent classes are expandable to child classes.
CherryPy leverages all the power of Python. It also provides tools and plugins, which are powerful extension points needed to develop world-class applications.
CherryPy is an open-source Python Web Framework (licensed under the open-source BSD license), which means this framework can be used commercially at ZERO cost.
It has a devoted community which provides complete support with various types of questions and answers. The community tries to give complete assistance to the developers starting from the beginner level to the advanced level.
There are cost effective ways to deploy the application. CherryPy includes its own production-ready HTTP server to host your application. CherryPy can also be deployed on any WSGI-compliant gateway.
CherryPy comes in packages like most open-source projects, which can be downloaded and installed in various ways which are mentioned as follows −
Using a Tarball
Using easy_install
Using Subversion
The basic requirements for installation of CherryPy framework include −
Python with version 2.4 or above
CherryPy 3.0
Installing a Python module is considered an easy process. The installation includes the use of the following commands.
python setup.py build
python setup.py install
The packages of Python are stored in the following default directories −
On UNIX or Linux,
/usr/local/lib/python2.4/site-packages
or
/usr/lib/python2.4/site-packages
On Microsoft Windows,
C:\Python or C:\Python2x
On Mac OS,
Python:Lib:site-package
A Tarball is a compressed archive of files or a directory. The CherryPy framework provides a Tarball for each of its releases (alpha, beta, and stable).
It contains complete source code of the library. The name comes from the utility used in UNIX and other operating systems.
Here are the steps to be followed for the installation of CherryPy using tar ball −
Step 1 − Download the version as per user requirements from
http://download.cherrypy.org/
Step 2 − Search for the directory where Tarball has been downloaded and uncompress it. For Linux operating system, type the following command −
tar zxvf cherrypy-x.y.z.tgz
For Microsoft Windows, the user can use a utility such as 7-Zip or Winzip to uncompress the archive via a graphical interface.
Step 3 − Move to the newly created directory and use the following command to build CherryPy −
python setup.py build
For the global installation, the following command should be used −
python setup.py install
Python Enterprise Application Kit (PEAK) provides a python module named Easy Install. This facilitates deployment of the Python packages. This module simplifies the procedure of downloading, building and deploying Python application and products.
Easy Install needs to be installed in the system before installing CherryPy.
Step 1 − Download the ez_setup.py module from http://peak.telecommunity.com and run it using the administrative rights on the computer: python ez_setup.py.
Step 2 − The following command is used to install Easy Install.
easy_install product_name
Step 3 − easy_install will search the Python Package Index (PyPI) to find the given product. PyPI is a centralized repository of information for all Python products.
Use the following command to deploy the latest available version of CherryPy −
easy_install cherrypy
Step 4 − easy_install will then download CherryPy, build, and install it globally to your Python environment.
Installation of CherryPy using Subversion is recommended in the following situations −
A feature exists or a bug has been fixed and is only available in code under development.
A feature exists or a bug has been fixed and is only available in code under development.
When the developer works on CherryPy itself.
When the developer works on CherryPy itself.
When the user needs a branch from the main branch in the versioning control repository.
When the user needs a branch from the main branch in the versioning control repository.
For bug fixing of the previous release.
For bug fixing of the previous release.
The basic principle of subversioning is to register a repository and keep a track of each of the versions, which include a series of changes in them.
Follow these steps to understand the installation of CherryPy using Subversion−
Step 1 − To use the most recent version of the project, it is necessary to check out the trunk folder found on the Subversion repository.
Step 2 − Enter the following command from a shell−
svn co http://svn.cherrypy.org/trunk cherrypy
Step 3 − Now, create a CherryPy directory and download the complete source code into it.
It needs to be verified whether the application has properly been installed in the system or not in the same way as we do for applications like Java.
You may choose any one of the three methods mentioned in the previous chapter to install and deploy CherryPy in your environment. CherryPy must be able to import from the Python shell as follows −
import cherrypy
cherrypy.__version__
'3.0.0'
If CherryPy is not installed globally to the local system’s Python environment, then you need to set the PYTHONPATH environment variable, else it will display an error in the following way −
import cherrypy
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ImportError: No module named cherrypy
There are a few important keywords which need to be defined in order to understand the working of CherryPy. The keywords and the definitions are as follows −
Web Server
It is an interface dealing with the HTTP protocol. Its goal is to transform the HTTP requests to the application server so that they get the responses.
Application
It is a piece of software which gathers information.
Application server
It is the component holding one or more applications
Web application server
It is the combination of web server and application server.
The following example shows a sample code of CherryPy −
import cherrypy
class demoExample:
def index(self):
return "Hello World!!!"
index.exposed = True
cherrypy.quickstart(demoExample())
Let us now understand how the code works −
The package named CherryPy is always imported in the specified class to ensure proper functioning.
The package named CherryPy is always imported in the specified class to ensure proper functioning.
In the above example, the function named index returns the parameter “Hello World!!!”.
In the above example, the function named index returns the parameter “Hello World!!!”.
The last line starts the web server and calls the specified class (here, demoExample) and returns the value mentioned in default function index.
The last line starts the web server and calls the specified class (here, demoExample) and returns the value mentioned in default function index.
The example code returns the following output −
CherryPy comes with its own web (HTTP) server. That is why CherryPy is self-contained and allows users to run a CherryPy application within minutes of getting the library.
The web server acts as the gateway to the application with the help of which all the requests and responses are kept in track.
To start the web server, a user must make the following call −
cherryPy.server.quickstart()
The internal engine of CherryPy is responsible for the following activities −
Creation and management of request and response objects.
Controlling and managing the CherryPy process.
The framework comes with its own configuration system allowing you to parameterize the HTTP server. The settings for the configuration can be stored either in a text file with syntax close to the INI format or as a complete Python dictionary.
To configure the CherryPy server instance, the developer needs to use the global section of the settings.
global_conf = {
'global': {
'server.socket_host': 'localhost',
'server.socket_port': 8080,
},
}
application_conf = {
'/style.css': {
'tools.staticfile.on': True,
'tools.staticfile.filename': os.path.join(_curdir, 'style.css'),
}
}
This could be represented in a file like this:
[global]
server.socket_host = "localhost"
server.socket_port = 8080
[/style.css]
tools.staticfile.on = True
tools.staticfile.filename = "/full/path/to.style.css"
CherryPy has been evolving slowly but it includes the compilation of HTTP specifications with the support of HTTP/1.0 later transferring with the support of HTTP/1.1.
CherryPy is said to be conditionally compliant with HTTP/1.1 as it implements all the must and required levels but not all the should levels of the specification. Therefore, CherryPy supports the following features of HTTP/1.1 −
If a client claims to support HTTP/1.1, it must send a header field in any request made with the specified protocol version. If it is not done, CherryPy will immediately stop the processing of the request.
If a client claims to support HTTP/1.1, it must send a header field in any request made with the specified protocol version. If it is not done, CherryPy will immediately stop the processing of the request.
CherryPy generates a Date header field which is used in all configurations.
CherryPy generates a Date header field which is used in all configurations.
CherryPy can handle response status code (100) with the support of clients.
CherryPy can handle response status code (100) with the support of clients.
CherryPy's built-in HTTP server supports persistent connections that are the default in HTTP/1.1, through the use of the Connection: Keep-Alive header.
CherryPy's built-in HTTP server supports persistent connections that are the default in HTTP/1.1, through the use of the Connection: Keep-Alive header.
CherryPy handles correctly chunked requests and responses.
CherryPy handles correctly chunked requests and responses.
CherryPy supports requests in two distinct ways − If-Modified-Since and If-Unmodified-Since headers and sends responses as per the requests accordingly.
CherryPy supports requests in two distinct ways − If-Modified-Since and If-Unmodified-Since headers and sends responses as per the requests accordingly.
CherryPy allows any HTTP method.
CherryPy allows any HTTP method.
CherryPy handles the combinations of HTTP versions between the client and the setting set for the server.
CherryPy handles the combinations of HTTP versions between the client and the setting set for the server.
CherryPy is designed based on the multithreading concept. Every time a developer gets or sets a value into the CherryPy namespace, it is done in the multi-threaded environment.
Both cherrypy.request and cherrypy.response are thread-data containers, which imply that your application calls them independently by knowing which request is proxied through them at runtime.
Application servers using the threaded pattern are not highly regarded because the use of threads is seen as increasing the likelihood of problems due to synchronization requirements.
The other alternatives include −
Each request is handled by its own Python process. Here, performance and stability of the server can be considered as better.
Here, accepting new connections and sending the data back to the client is done asynchronously from the request process. This technique is known for its efficiency.
The CherryPy community wants to be more flexible and that other solutions for dispatchers would be appreciated. CherryPy 3 provides other built-in dispatchers and offers a simple way to write and use your own dispatchers.
Applications used to develop HTTP methods. (GET, POST, PUT, etc.)
The one which defines the routes in the URL – Routes Dispatcher
In some applications, URIs are independent of the action, which is to be performed by the server on the resource.
For example,http://xyz.com/album/delete/10
The URI contains the operation the client wishes to carry out.
By default, CherryPy dispatcher would map in the following way −
album.delete(12)
The above mentioned dispatcher is mentioned correctly, but can be made independent in the following way −
http://xyz.com/album/10
The user may wonder how the server dispatches the exact page. This information is carried by the HTTP request itself. When there is request from client to server, CherryPy looks the best suiting handler, the handler is representation of the resource targeted by the URI.
DELETE /album/12 HTTP/1.1
Here is a list of the parameters for the method required in dispatching −
The name parameter is the unique name for the route to connect.
The name parameter is the unique name for the route to connect.
The route is the pattern to match URIs.
The route is the pattern to match URIs.
The controller is the instance containing page handlers.
The controller is the instance containing page handlers.
Using the Routes dispatcher connects a pattern that matches URIs and associates a specific page handler.
Using the Routes dispatcher connects a pattern that matches URIs and associates a specific page handler.
Let us take an example to understand how it works −
import random
import string
import cherrypy
class StringMaker(object):
@cherrypy.expose
def index(self):
return "Hello! How are you?"
@cherrypy.expose
def generate(self, length=9):
return ''.join(random.sample(string.hexdigits, int(length)))
if __name__ == '__main__':
cherrypy.quickstart(StringMaker ())
Follow the steps given below to get the output of the above code −
Step 1 − Save the above mentioned file as tutRoutes.py.
Step 2 − Visit the following URL −
http://localhost:8080/generate?length=10
Step 3 − You will receive the following output −
Within CherryPy, built-in tools offer a single interface to call the CherryPy library. The tools defined in CherryPy can be implemented in the following ways −
From the configuration settings
As a Python decorator or via the special _cp_config attribute of a page handler
As a Python callable that can be applied from within any function
The purpose of this tool is to provide basic authentication to the application designed in the application.
This tool uses the following arguments −
Let us take an example to understand how it works −
import sha
import cherrypy
class Root:
@cherrypy.expose
def index(self):
return """
<html>
<head></head>
<body>
<a href = "admin">Admin </a>
</body>
</html>
"""
class Admin:
@cherrypy.expose
def index(self):
return "This is a private area"
if __name__ == '__main__':
def get_users():
# 'test': 'test'
return {'test': 'b110ba61c4c0873d3101e10871082fbbfd3'}
def encrypt_pwd(token):
return sha.new(token).hexdigest()
conf = {'/admin': {'tools.basic_auth.on': True,
tools.basic_auth.realm': 'Website name',
'tools.basic_auth.users': get_users,
'tools.basic_auth.encrypt': encrypt_pwd}}
root = Root()
root.admin = Admin()
cherrypy.quickstart(root, '/', config=conf)
The get_users function returns a hard-coded dictionary but also fetches the values from a database or anywhere else. The class admin includes this function which makes use of an authentication built-in tool of CherryPy. The authentication encrypts the password and the user Id.
The basic authentication tool is not really secure, as the password can be encoded and decoded by an intruder.
The purpose of this tool is to provide memory caching of CherryPy generated content.
This tool uses the following arguments −
The purpose of this tool is to decode the incoming request parameters.
This tool uses the following arguments −
Let us take an example to understand how it works −
import cherrypy
from cherrypy import tools
class Root:
@cherrypy.expose
def index(self):
return """
<html>
<head></head>
<body>
<form action = "hello.html" method = "post">
<input type = "text" name = "name" value = "" />
<input type = ”submit” name = "submit"/>
</form>
</body>
</html>
"""
@cherrypy.expose
@tools.decode(encoding='ISO-88510-1')
def hello(self, name):
return "Hello %s" % (name, )
if __name__ == '__main__':
cherrypy.quickstart(Root(), '/')
The above code takes a string from the user and it will redirect the user to "hello.html" page where it will be displayed as “Hello” with the given name.
The output of the above code is as follows −
hello.html
Full stack applications provide a facility to create a new application via some command or execution of the file.
Consider the Python applications like web2py framework; the entire project/application is created in terms of MVC framework. Likewise, CherryPy allows the user to set up and configure the layout of the code as per their requirements.
In this chapter, we will learn in detail how to create CherryPy application and execute it.
The file system of the application is shown in the following screenshot −
Here is a brief description of the various files that we have in the file system −
config.py − Every application needs a configuration file and a way to load it. This functionality can be defined in config.py.
config.py − Every application needs a configuration file and a way to load it. This functionality can be defined in config.py.
controllers.py − MVC is a popular design pattern followed by the users. The controllers.py is where all the objects are implemented that will be mounted on the cherrypy.tree.
controllers.py − MVC is a popular design pattern followed by the users. The controllers.py is where all the objects are implemented that will be mounted on the cherrypy.tree.
models.py − This file interacts with the database directly for some services or for storing persistent data.
models.py − This file interacts with the database directly for some services or for storing persistent data.
server.py − This file interacts with production ready web server that works properly with load balancing proxy.
server.py − This file interacts with production ready web server that works properly with load balancing proxy.
Static − It includes all the CSS and image files.
Static − It includes all the CSS and image files.
Views − It includes all the template files for a given application.
Views − It includes all the template files for a given application.
Let us learn in detail the steps to create a CherryPy application.
Step 1 − Create an application that should contain the application.
Step 2 − Inside the directory, create a python package corresponding to the project. Create gedit directory and include _init_.py file within the same.
Step 3 − Inside the package, include controllers.py file with the following content −
#!/usr/bin/env python
import cherrypy
class Root(object):
def __init__(self, data):
self.data = data
@cherrypy.expose
def index(self):
return 'Hi! Welcome to your application'
def main(filename):
data = {} # will be replaced with proper functionality later
# configuration file
cherrypy.config.update({
'tools.encode.on': True, 'tools.encode.encoding': 'utf-8',
'tools.decode.on': True,
'tools.trailing_slash.on': True,
'tools.staticdir.root': os.path.abspath(os.path.dirname(__file__)),
})
cherrypy.quickstart(Root(data), '/', {
'/media': {
'tools.staticdir.on': True,
'tools.staticdir.dir': 'static'
}
})
if __name__ == '__main__':
main(sys.argv[1])
Step 4 − Consider an application where the user inputs the value through a form. Let’s include two forms — index.html and submit.html in the application.
Step 5 − In the above code for controllers, we have index(), which is a default function and loads first if a particular controller is called.
Step 6 − The implementation of the index() method can be changed in the following way −
@cherrypy.expose
def index(self):
tmpl = loader.load('index.html')
return tmpl.generate(title='Sample').render('html', doctype='html')
Step 7 − This will load index.html on starting the given application and direct it to the given output stream. The index.html file is as follows −
<!DOCTYPE html >
<html>
<head>
<title>Sample</title>
</head>
<body class = "index">
<div id = "header">
<h1>Sample Application</h1>
</div>
<p>Welcome!</p>
<div id = "footer">
<hr>
</div>
</body>
</html>
Step 8 − It is important to add a method to the Root class in controller.py if you want to create a form which accepts values such as names and titles.
@cherrypy.expose
def submit(self, cancel = False, **value):
if cherrypy.request.method == 'POST':
if cancel:
raise cherrypy.HTTPRedirect('/') # to cancel the action
link = Link(**value)
self.data[link.id] = link
raise cherrypy.HTTPRedirect('/')
tmp = loader.load('submit.html')
streamValue = tmp.generate()
return streamValue.render('html', doctype='html')
Step 9 − The code to be included in submit.html is as follows −
<!DOCTYPE html>
<head>
<title>Input the new link</title>
</head>
<body class = "submit">
<div id = " header">
<h1>Submit new link</h1>
</div>
<form action = "" method = "post">
<table summary = "">
<tr>
<th><label for = " username">Your name:</label></th>
<td><input type = " text" id = " username" name = " username" /></td>
</tr>
<tr>
<th><label for = " url">Link URL:</label></th>
<td><input type = " text" id=" url" name= " url" /></td>
</tr>
<tr>
<th><label for = " title">Title:</label></th>
<td><input type = " text" name = " title" /></td>
</tr>
<tr>
<td></td>
<td>
<input type = " submit" value = " Submit" />
<input type = " submit" name = " cancel" value = "Cancel" />
</td>
</tr>
</table>
</form>
<div id = "footer">
</div>
</body>
</html>
Step 10 − You will receive the following output −
Here, the method name is defined as “POST”. It is always important to cross verify the method specified in the file. If the method includes “POST” method, the values should be rechecked in the database in appropriate fields.
If the method includes “GET” method, the values to be saved will be visible in the URL.
A web service is a set of web-based components that helps in the exchange of data between the application or systems which also includes open protocols and standards. It can be published, used and found on the web.
Web services are of various types like RWS (RESTfUL Web Service), WSDL, SOAP and many more.
A type of remote access protocol, which, transfers state from client to server which can be used to manipulate state instead of calling remote procedures.
Does not define any specific encoding or structure and ways of returning useful error messages.
Does not define any specific encoding or structure and ways of returning useful error messages.
Uses HTTP "verbs" to perform state transfer operations.
Uses HTTP "verbs" to perform state transfer operations.
The resources are uniquely identified using URL.
The resources are uniquely identified using URL.
It is not an API but instead an API transport layer.
It is not an API but instead an API transport layer.
REST maintains the nomenclature of resources on a network and provides unified mechanism to perform operations on these resources. Each resource is identified by at least one identifier. If the REST infrastructure is implemented with the base of HTTP, then these identifiers are termed as Uniform Resource Identifiers (URIs).
The following are the two common subsets of the URI set −
Before understanding the implementation of CherryPy architecture, let’s focus on the architecture of CherryPy.
CherryPy includes the following three components −
cherrypy.engine − It controls process startup/teardown and event handling.
cherrypy.engine − It controls process startup/teardown and event handling.
cherrypy.server − It configures and controls the WSGI or HTTP server.
cherrypy.server − It configures and controls the WSGI or HTTP server.
cherrypy.tools − A toolbox of utilities that are orthogonal to processing an HTTP request.
cherrypy.tools − A toolbox of utilities that are orthogonal to processing an HTTP request.
RESTful web service implements each section of CherryPy architecture with the help of the following −
Authentication
Authorization
Structure
Encapsulation
Error Handling
Authentication helps in validating the users with whom we are interacting. CherryPy includes tools to handle each authentication method.
def authenticate():
if not hasattr(cherrypy.request, 'user') or cherrypy.request.user is None:
# < Do stuff to look up your users >
cherrypy.request.authorized = False # This only authenticates.
Authz must be handled separately.
cherrypy.request.unauthorized_reasons = []
cherrypy.request.authorization_queries = []
cherrypy.tools.authenticate = \
cherrypy.Tool('before_handler', authenticate, priority=10)
The above function authenticate() will help to validate the existence of the clients or users. The built-in tools help to complete the process in a systematic way.
Authorization helps in maintaining the sanity of the process via URI. The process also helps in morphing objects by user token leads.
def authorize_all():
cherrypy.request.authorized = 'authorize_all'
cherrypy.tools.authorize_all = cherrypy.Tool('before_handler', authorize_all, priority=11)
def is_authorized():
if not cherrypy.request.authorized:
raise cherrypy.HTTPError("403 Forbidden",
','.join(cherrypy.request.unauthorized_reasons))
cherrypy.tools.is_authorized = cherrypy.Tool('before_handler', is_authorized,
priority = 49)
cherrypy.config.update({
'tools.is_authorized.on': True,
'tools.authorize_all.on': True
})
The built-in tools of authorization help in handling the routines in a systematic way, as mentioned in the previous example.
Maintaining a structure of API helps in reducing the work load of mapping the URI of application. It is always necessary to keep API discoverable and clean. The basic structure of API for CherryPy framework should have the following −
Accounts and User
Autoresponder
Contact
File
Folder
List and field
Message and Batch
Encapsulation helps in creating API which is lightweight, human readable and accessible to various clients. The list of items along with Creation, Retrieval, Update and Deletion requires encapsulation of API.
This process manages errors, if any, if API fails to execute at the particular instinct. For example, 400 is for Bad Request and 403 is for unauthorized request.
Consider the following as an example for database, validation, or application errors.
import cherrypy
import json
def error_page_default(status, message, traceback, version):
ret = {
'status': status,
'version': version,
'message': [message],
'traceback': traceback
}
return json.dumps(ret)
class Root:
_cp_config = {'error_page.default': error_page_default}
@cherrypy.expose
def index(self):
raise cherrypy.HTTPError(500, "Internal Sever Error")
cherrypy.quickstart(Root())
The above code will produce the following output −
Management of API (Application Programming Interface) is easy through CherryPy because of the built-in access tools.
The list of HTTP methods which operate on the resources are as follows −
HEAD
Retrieves the resource metadata.
GET
Retrieves the resource metadata and content.
POST
Requests the server to create a new resource using the data enclosed in the request body.
PUT
Requests the server to replace an existing resource with the one enclosed in the request body.
DELETE
Requests the server to remove the resource identified by that URI.
OPTIONS
Requests the server to return details about capabilities either globally or specifically towards a resource.
APP has arisen from the Atom community as an application-level protocol on top of HTTP to allow the publishing and editing of web resources. The unit of messages between an APP server and a client is based on the Atom XML-document format.
The Atom Publishing Protocol defines a set of operations between an APP service and a user-agent using HTTP and its mechanisms and the Atom XML-document format as the unit of messages.
APP first defines a service document, which provides the user agent with the URI of the different collections served by the APP service.
Let us take an example to demonstrate how APP works −
<?xml version = "1.0" encoding = "UTF-8"?>
<service xmlns = "http://purl.org/atom/app#" xmlns:atom = "http://www.w3.org/2005/Atom">
<workspace>
<collection href = "http://host/service/atompub/album/">
<atom:title> Albums</atom:title>
<categories fixed = "yes">
<atom:category term = "friends" />
</categories>
</collection>
<collection href = "http://host/service/atompub/film/">
<atom:title>Films</atom:title>
<accept>image/png,image/jpeg</accept>
</collection>
</workspace>
</service>
APP specifies how to perform the basic CRUD operations against a member of a collection or the collection itself by using HTTP methods as described in the following table −
The Presentation Layer ensures that the communication passing through it targets the intended recipients. CherryPy maintains the working of presentation layer by various template engines.
A template engine takes the input of the page with the help of business logic and then processes it to the final page which targets only the intended audience.
Kid is a simple template engine which includes the name of the template to be processed (which is mandatory) and input of the data to be passed when the template is rendered.
On creation of the template for the first time, Kid creates a Python module which can be served as a cached version of the template.
The kid.Template function returns an instance of the template class which can be used to render the output content.
The template class provides the following set of commands −
serialize
It returns the output content as a string.
generate
It returns the output content as an iterator.
write
It dumps the output content into a file object.
The parameters used by these commands are as follows −
encoding
It informs how to encode the output content
fragment
It is a Boolean value which tells to XML prolog or Doctype
output
This type of serialization is used to render the content
Let us take an example to understand how kid works −
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns:py = "http://purl.org/kid/ns#">
<head>
<title>${title}</title>
<link rel = "stylesheet" href = "style.css" />
</head>
<body>
<p>${message}</p>
</body>
</html>
The next step after saving the file is to process the template via the Kid engine.
import kid
params = {'title': 'Hello world!!', 'message': 'CherryPy.'}
t = kid.Template('helloworld.kid', **params)
print t.serialize(output='html')
The following are the attributes of Kid −
It is an XML-based language. A Kid template must be a well-formed XML document with proper naming conventions.
Kid implements attributes within the XML elements to update the underlying engine on the action to be followed for reaching the element. To avoid overlapping with other existing attributes within the XML document, Kid has introduced its own namespace.
<p py:if = "...">...</p>
Kid comes with a variable substitution scheme and a simple approach — ${variable-name}.
The variables can either be used in attributes of elements or as the text content of an element. Kid will evaluate the variable each and every time the execution takes place.
If the user needs the output of a literal string as ${something}, it can be escaped using the variable substitution by doubling the dollar sign.
For toggling different cases in the template, the following syntax is used −
<tag py:if = "expression">...</tag>
Here, tag is the name of the element, for instance DIV or SPAN.
The expression is a Python expression. If as a Boolean it evaluates to True, the element will be included in the output content or else it will not be a part of the output content.
For looping an element in Kid, the following syntax is used −
<tag py:for = "expression">...</tag>
Here, tag is the name of the element. The expression is a Python expression, for example for value in [...].
The following code shows how the looping mechanism works −
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>${title}</title>
<link rel = "stylesheet" href = "style.css" />
</head>
<body>
<table>
<caption>A few songs</caption>
<tr>
<th>Artist</th>
<th>Album</th>
<th>Title</th>
</tr>
<tr py:for = "info in infos">
<td>${info['artist']}</td>
<td>${info['album']}</td>
<td>${info['song']}</td>
</tr>
</table>
</body>
</html>
import kid
params = discography.retrieve_songs()
t = kid.Template('songs.kid', **params)
print t.serialize(output='html')
The output for the above code with the looping mechanism is as follows −
Till the year 2005, the pattern followed in all web applications was to manage one HTTP request per page. The navigation of one page to another page required loading the complete page. This would reduce the performance at a greater level.
Thus, there was a rise in rich client applications which used to embed AJAX, XML, and JSON with them.
Asynchronous JavaScript and XML (AJAX) is a technique to create fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data behind the scenes with the server. This means that it is possible to update parts of a web page, without reloading the whole page.
Google Maps, Gmail, YouTube, and Facebook are a few examples of AJAX applications.
Ajax is based on the idea of sending HTTP requests using JavaScript; more specifically AJAX relies on the XMLHttpRequest object and its API to perform those operations.
JSON is a way to carry serialized JavaScript objects in such a way that JavaScript application can evaluate them and transform them into JavaScript objects which can be manipulated later.
For instance, when the user requests the server for an album object formatted with the JSON format, the server would return the output as following −
{'description': 'This is a simple demo album for you to test', 'author': ‘xyz’}
Now the data is a JavaScript associative array and the description field can be accessed via −
data ['description'];
Consider the application which includes a folder named “media” with index.html and Jquery plugin, and a file with AJAX implementation. Let us consider the name of the file as “ajax_app.py”
import cherrypy
import webbrowser
import os
import simplejson
import sys
MEDIA_DIR = os.path.join(os.path.abspath("."), u"media")
class AjaxApp(object):
@cherrypy.expose
def index(self):
return open(os.path.join(MEDIA_DIR, u'index.html'))
@cherrypy.expose
def submit(self, name):
cherrypy.response.headers['Content-Type'] = 'application/json'
return simplejson.dumps(dict(title="Hello, %s" % name))
config = {'/media':
{'tools.staticdir.on': True,
'tools.staticdir.dir': MEDIA_DIR,}
}
def open_page():
webbrowser.open("http://127.0.0.1:8080/")
cherrypy.engine.subscribe('start', open_page)
cherrypy.tree.mount(AjaxApp(), '/', config=config)
cherrypy.engine.start()
The class “AjaxApp” redirects to the web page of “index.html”, which is included in the media folder.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
" http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml" lang = "en" xml:lang = "en">
<head>
<title>AJAX with jQuery and cherrypy</title>
<meta http-equiv = " Content-Type" content = " text/html; charset=utf-8" />
<script type = " text/javascript" src = " /media/jquery-1.4.2.min.js"></script>
<script type = " text/javascript">
$(function() {
// When the testform is submitted...
$("#formtest").submit(function() {
// post the form values via AJAX...
$.post('/submit', {name: $("#name").val()}, function(data) {
// and set the title with the result
$("#title").html(data['title']) ;
});
return false ;
});
});
</script>
</head>
<body>
<h1 id = "title">What's your name?</h1>
<form id = " formtest" action = " #" method = " post">
<p>
<label for = " name">Name:</label>
<input type = " text" id = "name" /> <br />
<input type = " submit" value = " Set" />
</p>
</form>
</body>
</html>
The function for AJAX is included within <script> tags.
The above code will produce the following output −
Once the value is submitted by the user, AJAX functionality is implemented and the screen is redirected to the form as shown below −
In this chapter, we will focus on how an application is created in CherryPy framework.
Consider Photoblog application for the demo application of CherryPy. A Photoblog application is a normal blog but the principal text will be photos in place of text. The main catch of Photoblog application is that the developer can focus more on design and implementation.
The entities design the basic structure of an application. The following are the entities for the Photoblog application −
Film
Photo
Album
The following is a basic class diagram for the entity relationship −
As discussed in the previous chapter, the design structure of the project would be as shown in the following screenshot −
Consider the given application, which has sub-directories for Photoblog application. The sub-directories are Photo, Album, and Film which would include controllers.py, models.py and server.py.
Functionally, the Photoblog application will provide APIs to manipulate those entities via the traditional CRUD interface — Create, Retrieve, Update, and Delete.
A storage module includes a set of operations; connection with the database being one of the operations.
As it is a complete application, the connection with database is mandatory for API and to maintain the functionality of Create, Retrieve, Update and Delete.
import dejavu
arena = dejavu.Arena()
from model import Album, Film, Photo
def connect():
conf = {'Connect': "host=localhost dbname=Photoblog user=test password=test"}
arena.add_store("main", "postgres", conf)
arena.register_all(globals())
The arena in the above code will be our interface between the underlying storage manager and the business logic layer.
The connect function adds a storage manager to the arena object for a PostgreSQL RDBMS.
Once, the connection is obtained, we can create forms as per business requirements and complete the working of application.
The most important thing before creation of any application is entity mapping and designing the structure of the application.
Testing is a process during which the application is conducted from different perspectives in order to −
Find the list of issues
Find differences between the expected and actual result, output, states, etc.
Understand the implementation phase.
Find the application useful for realistic purposes.
The goal of testing is not to put the developer at fault but to provide tools and improve the quality to estimate the health of the application at a given time.
Testing needs to be planned in advance. This calls for defining the purpose of testing, understanding the scope of test cases, making the list of business requirements and being aware of the risks involved in the different phases of the project.
Testing is defined as a range of aspects to be validated on a system or application. Following is a list of the common test approaches −
Unit testing − This is usually carried out by the developers themselves. This aims at checking whether a unit of code works as expected or not.
Unit testing − This is usually carried out by the developers themselves. This aims at checking whether a unit of code works as expected or not.
Usability testing − Developers may usually forget that they are writing an application for the end users who do not have knowledge of the system. Usability testing verifies the pros and cons of the product.
Usability testing − Developers may usually forget that they are writing an application for the end users who do not have knowledge of the system. Usability testing verifies the pros and cons of the product.
Functional/Acceptance testing − While usability testing checks whether an application or system is usable, functional testing ensures that every specified functionality is implemented.
Functional/Acceptance testing − While usability testing checks whether an application or system is usable, functional testing ensures that every specified functionality is implemented.
Load and performance testing − This is carried out to understand whether the system can adjust to the load and performance tests to be conducted. This can lead to changes in hardware, optimizing SQL queries, etc.
Load and performance testing − This is carried out to understand whether the system can adjust to the load and performance tests to be conducted. This can lead to changes in hardware, optimizing SQL queries, etc.
Regression testing − It verifies that successive releases of a product do not break any of the previous functionalities.
Regression testing − It verifies that successive releases of a product do not break any of the previous functionalities.
Reliability and resilience testing − Reliability testing helps in validating the system application with the breakdown of one or several components.
Reliability and resilience testing − Reliability testing helps in validating the system application with the breakdown of one or several components.
Photoblog applications constantly use unit tests to check the following −
New functionalities work correctly and as expected.
Existing functionalities are not broken by new code release.
Defects are fixed and remain fixed.
Python comes in with a standard unittest module offering a different approach to unit testing.
unittest is rooted in JUnit, a Java unit test package developed by Kent Beck and Erich Gamma. Unit tests simply return defined data. Mock objects can be defined. These objects allows testing against an interface of our design without having to rely on the overall application. They also provide a way to run tests in isolation mode with other tests included.
Let’s define a dummy class in the following way −
import unittest
class DummyTest(unittest.TestCase):
def test_01_forward(self):
dummy = Dummy(right_boundary=3)
self.assertEqual(dummy.forward(), 1)
self.assertEqual(dummy.forward(), 2)
self.assertEqual(dummy.forward(), 3)
self.assertRaises(ValueError, dummy.forward)
def test_02_backward(self):
dummy = Dummy(left_boundary=-3, allow_negative=True)
self.assertEqual(dummy.backward(), -1)
self.assertEqual(dummy.backward(), -2)
self.assertEqual(dummy.backward(), -3)
self.assertRaises(ValueError, dummy.backward)
def test_03_boundaries(self):
dummy = Dummy(right_boundary=3, left_boundary=-3,allow_negative=True)
self.assertEqual(dummy.backward(), -1)
self.assertEqual(dummy.backward(), -2)
self.assertEqual(dummy.forward(), -1)
self.assertEqual(dummy.backward(), -2)
self.assertEqual(dummy.backward(), -3)
The explanation for the code is as follows −
unittest module should be imported to provide unit test capabilities for the given class.
unittest module should be imported to provide unit test capabilities for the given class.
A class should be created by subclassing unittest.
A class should be created by subclassing unittest.
Every method in the above code starts with a word test. All these methods are called by unittest handler.
Every method in the above code starts with a word test. All these methods are called by unittest handler.
The assert/fail methods are called by the test case to manage the exceptions.
The assert/fail methods are called by the test case to manage the exceptions.
Consider this as an example for running a test case −
if __name__ == '__main__':
unittest.main()
The result (output) for running the test case will be as follows −
----------------------------------------------------------------------
Ran 3 tests in 0.000s
OK
Once the application functionalities start taking shape as per the requirements, a set of functional testing can validate the application's correctness regarding the specification. However, the test should be automated for better performance which would require the use of third-party products such as Selenium.
CherryPy provides helper class like built-in functions to ease the writing of functional tests.
Depending on the application you are writing and your expectations in terms of volume, you may need to run load and performance testing in order to detect potential bottlenecks in the application that are preventing it from reaching a certain level of performance.
This section will not detail how to conduct a performance or load test as it is out of its the FunkLoad package.
The very basic example of FunkLoad is as follows −
from funkload.FunkLoadTestCase
import FunkLoadTestCase
class LoadHomePage(FunkLoadTestCase):
def test_homepage(self):
server_url = self.conf_get('main', 'url')
nb_time = self.conf_getInt('test_homepage', 'nb_time')
home_page = "%s/" % server_url
for i in range(nb_time):
self.logd('Try %i' % i)
self.get(home_page, description='Get gome page')
if __name__ in ('main', '__main__'):
import unittest
unittest.main()
Here is a detailed explanation of the above code −
The test case must inherit from the FunkLoadTestCase class so that the FunkLoad can do its internal job of tracking what happens during the test.
The test case must inherit from the FunkLoadTestCase class so that the FunkLoad can do its internal job of tracking what happens during the test.
The class name is important as FunkLoad will look for a file based on the class name.
The class name is important as FunkLoad will look for a file based on the class name.
The test cases designed have direct access to the configuration files. Get() and post() methods are simply called against the server to get the response.
The test cases designed have direct access to the configuration files. Get() and post() methods are simply called against the server to get the response.
This chapter will focus more on CherryPy-based application SSL enabled through the built-in CherryPy HTTP server.
There are different levels of configuration settings required in a web application −
Web server − Settings linked to the HTTP server
Web server − Settings linked to the HTTP server
Engine − Settings associated with the hosting of engine
Engine − Settings associated with the hosting of engine
Application − Application which is used by the user
Application − Application which is used by the user
Deployment of CherryPy application is considered to be quite an easy method where all the required packages are available from the Python system path. In shared web-hosted environment, web server will reside in the front end which allows the host provider to perform the filtering actions. The front-end server can be Apache or lighttpd.
This section will present a few solutions to run a CherryPy application behind the Apache and lighttpd web servers.
cherrypy
def setup_app():
class Root:
@cherrypy.expose
def index(self):
# Return the hostname used by CherryPy and the remote
# caller IP address
return "Hello there %s from IP: %s " %
(cherrypy.request.base, cherrypy.request.remote.ip)
cherrypy.config.update({'server.socket_port': 9091,
'environment': 'production',
'log.screen': False,
'show_tracebacks': False})
cherrypy.tree.mount(Root())
if __name__ == '__main__':
setup_app()
cherrypy.server.quickstart()
cherrypy.engine.start()
SSL (Secure Sockets Layer) can be supported in CherryPy-based applications. To enable SSL support, the following requirements must be met −
Have the PyOpenSSL package installed in user’s environment
Have an SSL certificate and private key on the server
Let's deal with the requirements of certificate and the private key −
First the user needs a private key −
openssl genrsa -out server.key 2048
This key is not protected by a password and therefore has a weak protection.
The following command will be issued −
openssl genrsa -des3 -out server.key 2048
The program will require a passphrase. If your version of OpenSSL allows you to provide an empty string, do so. Otherwise, enter a default passphrase and then remove it from the generated key as follows −
The program will require a passphrase. If your version of OpenSSL allows you to provide an empty string, do so. Otherwise, enter a default passphrase and then remove it from the generated key as follows −
openssl rsa -in server.key -out server.key
Creation of the certificate is as follows −
openssl req -new -key server.key -out server.csr
This process will request you to input some details. To do so, the following command must be issued −
This process will request you to input some details. To do so, the following command must be issued −
openssl x509 -req -days 60 -in server.csr -signkey
server.key -out server.crt
The newly signed certificate will be valid for 60 days.
The newly signed certificate will be valid for 60 days.
The following code shows its implementation −
import cherrypy
import os, os.path
localDir = os.path.abspath(os.path.dirname(__file__))
CA = os.path.join(localDir, 'server.crt')
KEY = os.path.join(localDir, 'server.key')
def setup_server():
class Root:
@cherrypy.expose
def index(self):
return "Hello there!"
cherrypy.tree.mount(Root())
if __name__ == '__main__':
setup_server()
cherrypy.config.update({'server.socket_port': 8443,
'environment': 'production',
'log.screen': True,
'server.ssl_certificate': CA,
'server.ssl_private_key': KEY})
cherrypy.server.quickstart()
cherrypy.engine.start()
The next step is to start the server; if you are successful, you would see the following message on your screen −
HTTP Serving HTTPS on https://localhost:8443/
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2048,
"s": 1885,
"text": "CherryPy is a web framework of Python which provides a friendly interface to the HTTP protocol for Python developers. It is also called a web application library."
},
{
"code": null,
"e": 2253,
"s": 2048,
"text": "CherryPy uses Python’s strengths as a dynamic language to model and bind HTTP protocol into an API. It is one of the oldest web frameworks for Python, which provides clean interface and reliable platform."
},
{
"code": null,
"e": 2509,
"s": 2253,
"text": "Remi Delon released the first version of CherryPy in late June 2002. This was the starting point of a successful Python web library. Remi is a French hacker who has trusted Python for being one of the greatest alternatives for web application development."
},
{
"code": null,
"e": 2656,
"s": 2509,
"text": "The project developed by Remi attracted a number of developers who were interested in the approach. The approach included the following features −"
},
{
"code": null,
"e": 2713,
"s": 2656,
"text": "CherryPy was close to the model-view-controller pattern."
},
{
"code": null,
"e": 2770,
"s": 2713,
"text": "CherryPy was close to the model-view-controller pattern."
},
{
"code": null,
"e": 2958,
"s": 2770,
"text": "A CherryPy class has to be processed and compiled by the CherryPy engine to produce a self-contained Python module embedding the complete application and also its own built-in web server."
},
{
"code": null,
"e": 3146,
"s": 2958,
"text": "A CherryPy class has to be processed and compiled by the CherryPy engine to produce a self-contained Python module embedding the complete application and also its own built-in web server."
},
{
"code": null,
"e": 3231,
"s": 3146,
"text": "CherryPy can map a URL and its query string into a Python method call, for example −"
},
{
"code": null,
"e": 3316,
"s": 3231,
"text": "CherryPy can map a URL and its query string into a Python method call, for example −"
},
{
"code": null,
"e": 3391,
"s": 3316,
"text": "http://somehost.net/echo?message=hello would map to echo(message='hello')\n"
},
{
"code": null,
"e": 3527,
"s": 3391,
"text": "During the two years of development in CherryPy project, it was supported by the community and Remi released several improved versions."
},
{
"code": null,
"e": 4061,
"s": 3527,
"text": "In June 2004, a discussion started about the future of the project and whether it should continue with the same architecture. Brainstorming and discussion by several project regulars then led to the concept of object-publishing engine and filters, which soon became a core part of CherryPy2.Later, in October 2004, the first version of CherryPy 2 alpha was released as a proof of concept of these core ideas. CherryPy 2.0 was a real success; however, it was recognized that its design could still be improved, and needed refactoring."
},
{
"code": null,
"e": 4289,
"s": 4061,
"text": "After discussions based on feedbacks, CherryPy's API was further modified to improve its elegance, leading to the release of CherryPy 2.1.0 in October 2005. After various changes, the team released CherryPy 2.2.0 in April 2006."
},
{
"code": null,
"e": 4358,
"s": 4289,
"text": "The following features of CherryPy are considered as its strengths −"
},
{
"code": null,
"e": 4492,
"s": 4358,
"text": "Developing a project in CherryPy is a simple task with few lines of code developed as per the conventions and indentations of Python."
},
{
"code": null,
"e": 4642,
"s": 4492,
"text": "CherryPy is also very modular. The primary components are well managed with correct logic concept and parent classes are expandable to child classes."
},
{
"code": null,
"e": 4802,
"s": 4642,
"text": "CherryPy leverages all the power of Python. It also provides tools and plugins, which are powerful extension points needed to develop world-class applications."
},
{
"code": null,
"e": 4962,
"s": 4802,
"text": "CherryPy is an open-source Python Web Framework (licensed under the open-source BSD license), which means this framework can be used commercially at ZERO cost."
},
{
"code": null,
"e": 5188,
"s": 4962,
"text": "It has a devoted community which provides complete support with various types of questions and answers. The community tries to give complete assistance to the developers starting from the beginner level to the advanced level."
},
{
"code": null,
"e": 5387,
"s": 5188,
"text": "There are cost effective ways to deploy the application. CherryPy includes its own production-ready HTTP server to host your application. CherryPy can also be deployed on any WSGI-compliant gateway."
},
{
"code": null,
"e": 5533,
"s": 5387,
"text": "CherryPy comes in packages like most open-source projects, which can be downloaded and installed in various ways which are mentioned as follows −"
},
{
"code": null,
"e": 5549,
"s": 5533,
"text": "Using a Tarball"
},
{
"code": null,
"e": 5568,
"s": 5549,
"text": "Using easy_install"
},
{
"code": null,
"e": 5585,
"s": 5568,
"text": "Using Subversion"
},
{
"code": null,
"e": 5657,
"s": 5585,
"text": "The basic requirements for installation of CherryPy framework include −"
},
{
"code": null,
"e": 5690,
"s": 5657,
"text": "Python with version 2.4 or above"
},
{
"code": null,
"e": 5703,
"s": 5690,
"text": "CherryPy 3.0"
},
{
"code": null,
"e": 5822,
"s": 5703,
"text": "Installing a Python module is considered an easy process. The installation includes the use of the following commands."
},
{
"code": null,
"e": 5869,
"s": 5822,
"text": "python setup.py build\npython setup.py install\n"
},
{
"code": null,
"e": 5942,
"s": 5869,
"text": "The packages of Python are stored in the following default directories −"
},
{
"code": null,
"e": 5960,
"s": 5942,
"text": "On UNIX or Linux,"
},
{
"code": null,
"e": 6036,
"s": 5960,
"text": "/usr/local/lib/python2.4/site-packages\nor\n/usr/lib/python2.4/site-packages\n"
},
{
"code": null,
"e": 6058,
"s": 6036,
"text": "On Microsoft Windows,"
},
{
"code": null,
"e": 6084,
"s": 6058,
"text": "C:\\Python or C:\\Python2x\n"
},
{
"code": null,
"e": 6095,
"s": 6084,
"text": "On Mac OS,"
},
{
"code": null,
"e": 6120,
"s": 6095,
"text": "Python:Lib:site-package\n"
},
{
"code": null,
"e": 6273,
"s": 6120,
"text": "A Tarball is a compressed archive of files or a directory. The CherryPy framework provides a Tarball for each of its releases (alpha, beta, and stable)."
},
{
"code": null,
"e": 6396,
"s": 6273,
"text": "It contains complete source code of the library. The name comes from the utility used in UNIX and other operating systems."
},
{
"code": null,
"e": 6480,
"s": 6396,
"text": "Here are the steps to be followed for the installation of CherryPy using tar ball −"
},
{
"code": null,
"e": 6570,
"s": 6480,
"text": "Step 1 − Download the version as per user requirements from\nhttp://download.cherrypy.org/"
},
{
"code": null,
"e": 6714,
"s": 6570,
"text": "Step 2 − Search for the directory where Tarball has been downloaded and uncompress it. For Linux operating system, type the following command −"
},
{
"code": null,
"e": 6743,
"s": 6714,
"text": "tar zxvf cherrypy-x.y.z.tgz\n"
},
{
"code": null,
"e": 6870,
"s": 6743,
"text": "For Microsoft Windows, the user can use a utility such as 7-Zip or Winzip to uncompress the archive via a graphical interface."
},
{
"code": null,
"e": 6965,
"s": 6870,
"text": "Step 3 − Move to the newly created directory and use the following command to build CherryPy −"
},
{
"code": null,
"e": 6988,
"s": 6965,
"text": "python setup.py build\n"
},
{
"code": null,
"e": 7056,
"s": 6988,
"text": "For the global installation, the following command should be used −"
},
{
"code": null,
"e": 7081,
"s": 7056,
"text": "python setup.py install\n"
},
{
"code": null,
"e": 7328,
"s": 7081,
"text": "Python Enterprise Application Kit (PEAK) provides a python module named Easy Install. This facilitates deployment of the Python packages. This module simplifies the procedure of downloading, building and deploying Python application and products."
},
{
"code": null,
"e": 7405,
"s": 7328,
"text": "Easy Install needs to be installed in the system before installing CherryPy."
},
{
"code": null,
"e": 7561,
"s": 7405,
"text": "Step 1 − Download the ez_setup.py module from http://peak.telecommunity.com and run it using the administrative rights on the computer: python ez_setup.py."
},
{
"code": null,
"e": 7625,
"s": 7561,
"text": "Step 2 − The following command is used to install Easy Install."
},
{
"code": null,
"e": 7652,
"s": 7625,
"text": "easy_install product_name\n"
},
{
"code": null,
"e": 7818,
"s": 7652,
"text": "Step 3 − easy_install will search the Python Package Index (PyPI) to find the given product. PyPI is a centralized repository of information for all Python products."
},
{
"code": null,
"e": 7897,
"s": 7818,
"text": "Use the following command to deploy the latest available version of CherryPy −"
},
{
"code": null,
"e": 7920,
"s": 7897,
"text": "easy_install cherrypy\n"
},
{
"code": null,
"e": 8030,
"s": 7920,
"text": "Step 4 − easy_install will then download CherryPy, build, and install it globally to your Python environment."
},
{
"code": null,
"e": 8117,
"s": 8030,
"text": "Installation of CherryPy using Subversion is recommended in the following situations −"
},
{
"code": null,
"e": 8207,
"s": 8117,
"text": "A feature exists or a bug has been fixed and is only available in code under development."
},
{
"code": null,
"e": 8297,
"s": 8207,
"text": "A feature exists or a bug has been fixed and is only available in code under development."
},
{
"code": null,
"e": 8342,
"s": 8297,
"text": "When the developer works on CherryPy itself."
},
{
"code": null,
"e": 8387,
"s": 8342,
"text": "When the developer works on CherryPy itself."
},
{
"code": null,
"e": 8475,
"s": 8387,
"text": "When the user needs a branch from the main branch in the versioning control repository."
},
{
"code": null,
"e": 8563,
"s": 8475,
"text": "When the user needs a branch from the main branch in the versioning control repository."
},
{
"code": null,
"e": 8603,
"s": 8563,
"text": "For bug fixing of the previous release."
},
{
"code": null,
"e": 8643,
"s": 8603,
"text": "For bug fixing of the previous release."
},
{
"code": null,
"e": 8793,
"s": 8643,
"text": "The basic principle of subversioning is to register a repository and keep a track of each of the versions, which include a series of changes in them."
},
{
"code": null,
"e": 8873,
"s": 8793,
"text": "Follow these steps to understand the installation of CherryPy using Subversion−"
},
{
"code": null,
"e": 9011,
"s": 8873,
"text": "Step 1 − To use the most recent version of the project, it is necessary to check out the trunk folder found on the Subversion repository."
},
{
"code": null,
"e": 9062,
"s": 9011,
"text": "Step 2 − Enter the following command from a shell−"
},
{
"code": null,
"e": 9109,
"s": 9062,
"text": "svn co http://svn.cherrypy.org/trunk cherrypy\n"
},
{
"code": null,
"e": 9198,
"s": 9109,
"text": "Step 3 − Now, create a CherryPy directory and download the complete source code into it."
},
{
"code": null,
"e": 9348,
"s": 9198,
"text": "It needs to be verified whether the application has properly been installed in the system or not in the same way as we do for applications like Java."
},
{
"code": null,
"e": 9545,
"s": 9348,
"text": "You may choose any one of the three methods mentioned in the previous chapter to install and deploy CherryPy in your environment. CherryPy must be able to import from the Python shell as follows −"
},
{
"code": null,
"e": 9592,
"s": 9545,
"text": "import cherrypy\n\ncherrypy.__version__\n'3.0.0'\n"
},
{
"code": null,
"e": 9783,
"s": 9592,
"text": "If CherryPy is not installed globally to the local system’s Python environment, then you need to set the PYTHONPATH environment variable, else it will display an error in the following way −"
},
{
"code": null,
"e": 9903,
"s": 9783,
"text": "import cherrypy\n\nTraceback (most recent call last):\nFile \"<stdin>\", line 1, in ?\nImportError: No module named cherrypy\n"
},
{
"code": null,
"e": 10061,
"s": 9903,
"text": "There are a few important keywords which need to be defined in order to understand the working of CherryPy. The keywords and the definitions are as follows −"
},
{
"code": null,
"e": 10072,
"s": 10061,
"text": "Web Server"
},
{
"code": null,
"e": 10224,
"s": 10072,
"text": "It is an interface dealing with the HTTP protocol. Its goal is to transform the HTTP requests to the application server so that they get the responses."
},
{
"code": null,
"e": 10236,
"s": 10224,
"text": "Application"
},
{
"code": null,
"e": 10289,
"s": 10236,
"text": "It is a piece of software which gathers information."
},
{
"code": null,
"e": 10308,
"s": 10289,
"text": "Application server"
},
{
"code": null,
"e": 10361,
"s": 10308,
"text": "It is the component holding one or more applications"
},
{
"code": null,
"e": 10384,
"s": 10361,
"text": "Web application server"
},
{
"code": null,
"e": 10444,
"s": 10384,
"text": "It is the combination of web server and application server."
},
{
"code": null,
"e": 10500,
"s": 10444,
"text": "The following example shows a sample code of CherryPy −"
},
{
"code": null,
"e": 10642,
"s": 10500,
"text": "import cherrypy\n\nclass demoExample:\n def index(self):\n return \"Hello World!!!\"\n index.exposed = True\ncherrypy.quickstart(demoExample())"
},
{
"code": null,
"e": 10685,
"s": 10642,
"text": "Let us now understand how the code works −"
},
{
"code": null,
"e": 10784,
"s": 10685,
"text": "The package named CherryPy is always imported in the specified class to ensure proper functioning."
},
{
"code": null,
"e": 10883,
"s": 10784,
"text": "The package named CherryPy is always imported in the specified class to ensure proper functioning."
},
{
"code": null,
"e": 10970,
"s": 10883,
"text": "In the above example, the function named index returns the parameter “Hello World!!!”."
},
{
"code": null,
"e": 11057,
"s": 10970,
"text": "In the above example, the function named index returns the parameter “Hello World!!!”."
},
{
"code": null,
"e": 11202,
"s": 11057,
"text": "The last line starts the web server and calls the specified class (here, demoExample) and returns the value mentioned in default function index."
},
{
"code": null,
"e": 11347,
"s": 11202,
"text": "The last line starts the web server and calls the specified class (here, demoExample) and returns the value mentioned in default function index."
},
{
"code": null,
"e": 11395,
"s": 11347,
"text": "The example code returns the following output −"
},
{
"code": null,
"e": 11567,
"s": 11395,
"text": "CherryPy comes with its own web (HTTP) server. That is why CherryPy is self-contained and allows users to run a CherryPy application within minutes of getting the library."
},
{
"code": null,
"e": 11694,
"s": 11567,
"text": "The web server acts as the gateway to the application with the help of which all the requests and responses are kept in track."
},
{
"code": null,
"e": 11757,
"s": 11694,
"text": "To start the web server, a user must make the following call −"
},
{
"code": null,
"e": 11787,
"s": 11757,
"text": "cherryPy.server.quickstart()\n"
},
{
"code": null,
"e": 11865,
"s": 11787,
"text": "The internal engine of CherryPy is responsible for the following activities −"
},
{
"code": null,
"e": 11922,
"s": 11865,
"text": "Creation and management of request and response objects."
},
{
"code": null,
"e": 11969,
"s": 11922,
"text": "Controlling and managing the CherryPy process."
},
{
"code": null,
"e": 12212,
"s": 11969,
"text": "The framework comes with its own configuration system allowing you to parameterize the HTTP server. The settings for the configuration can be stored either in a text file with syntax close to the INI format or as a complete Python dictionary."
},
{
"code": null,
"e": 12318,
"s": 12212,
"text": "To configure the CherryPy server instance, the developer needs to use the global section of the settings."
},
{
"code": null,
"e": 12796,
"s": 12318,
"text": "global_conf = {\n 'global': {\n 'server.socket_host': 'localhost',\n 'server.socket_port': 8080,\n },\n}\n\napplication_conf = {\n '/style.css': {\n 'tools.staticfile.on': True,\n 'tools.staticfile.filename': os.path.join(_curdir, 'style.css'),\n }\n}\n\nThis could be represented in a file like this:\n[global]\nserver.socket_host = \"localhost\"\nserver.socket_port = 8080\n[/style.css]\ntools.staticfile.on = True\ntools.staticfile.filename = \"/full/path/to.style.css\""
},
{
"code": null,
"e": 12963,
"s": 12796,
"text": "CherryPy has been evolving slowly but it includes the compilation of HTTP specifications with the support of HTTP/1.0 later transferring with the support of HTTP/1.1."
},
{
"code": null,
"e": 13192,
"s": 12963,
"text": "CherryPy is said to be conditionally compliant with HTTP/1.1 as it implements all the must and required levels but not all the should levels of the specification. Therefore, CherryPy supports the following features of HTTP/1.1 −"
},
{
"code": null,
"e": 13398,
"s": 13192,
"text": "If a client claims to support HTTP/1.1, it must send a header field in any request made with the specified protocol version. If it is not done, CherryPy will immediately stop the processing of the request."
},
{
"code": null,
"e": 13604,
"s": 13398,
"text": "If a client claims to support HTTP/1.1, it must send a header field in any request made with the specified protocol version. If it is not done, CherryPy will immediately stop the processing of the request."
},
{
"code": null,
"e": 13680,
"s": 13604,
"text": "CherryPy generates a Date header field which is used in all configurations."
},
{
"code": null,
"e": 13756,
"s": 13680,
"text": "CherryPy generates a Date header field which is used in all configurations."
},
{
"code": null,
"e": 13832,
"s": 13756,
"text": "CherryPy can handle response status code (100) with the support of clients."
},
{
"code": null,
"e": 13908,
"s": 13832,
"text": "CherryPy can handle response status code (100) with the support of clients."
},
{
"code": null,
"e": 14060,
"s": 13908,
"text": "CherryPy's built-in HTTP server supports persistent connections that are the default in HTTP/1.1, through the use of the Connection: Keep-Alive header."
},
{
"code": null,
"e": 14212,
"s": 14060,
"text": "CherryPy's built-in HTTP server supports persistent connections that are the default in HTTP/1.1, through the use of the Connection: Keep-Alive header."
},
{
"code": null,
"e": 14271,
"s": 14212,
"text": "CherryPy handles correctly chunked requests and responses."
},
{
"code": null,
"e": 14330,
"s": 14271,
"text": "CherryPy handles correctly chunked requests and responses."
},
{
"code": null,
"e": 14483,
"s": 14330,
"text": "CherryPy supports requests in two distinct ways − If-Modified-Since and If-Unmodified-Since headers and sends responses as per the requests accordingly."
},
{
"code": null,
"e": 14636,
"s": 14483,
"text": "CherryPy supports requests in two distinct ways − If-Modified-Since and If-Unmodified-Since headers and sends responses as per the requests accordingly."
},
{
"code": null,
"e": 14669,
"s": 14636,
"text": "CherryPy allows any HTTP method."
},
{
"code": null,
"e": 14702,
"s": 14669,
"text": "CherryPy allows any HTTP method."
},
{
"code": null,
"e": 14808,
"s": 14702,
"text": "CherryPy handles the combinations of HTTP versions between the client and the setting set for the server."
},
{
"code": null,
"e": 14914,
"s": 14808,
"text": "CherryPy handles the combinations of HTTP versions between the client and the setting set for the server."
},
{
"code": null,
"e": 15091,
"s": 14914,
"text": "CherryPy is designed based on the multithreading concept. Every time a developer gets or sets a value into the CherryPy namespace, it is done in the multi-threaded environment."
},
{
"code": null,
"e": 15283,
"s": 15091,
"text": "Both cherrypy.request and cherrypy.response are thread-data containers, which imply that your application calls them independently by knowing which request is proxied through them at runtime."
},
{
"code": null,
"e": 15467,
"s": 15283,
"text": "Application servers using the threaded pattern are not highly regarded because the use of threads is seen as increasing the likelihood of problems due to synchronization requirements."
},
{
"code": null,
"e": 15500,
"s": 15467,
"text": "The other alternatives include −"
},
{
"code": null,
"e": 15626,
"s": 15500,
"text": "Each request is handled by its own Python process. Here, performance and stability of the server can be considered as better."
},
{
"code": null,
"e": 15791,
"s": 15626,
"text": "Here, accepting new connections and sending the data back to the client is done asynchronously from the request process. This technique is known for its efficiency."
},
{
"code": null,
"e": 16013,
"s": 15791,
"text": "The CherryPy community wants to be more flexible and that other solutions for dispatchers would be appreciated. CherryPy 3 provides other built-in dispatchers and offers a simple way to write and use your own dispatchers."
},
{
"code": null,
"e": 16079,
"s": 16013,
"text": "Applications used to develop HTTP methods. (GET, POST, PUT, etc.)"
},
{
"code": null,
"e": 16143,
"s": 16079,
"text": "The one which defines the routes in the URL – Routes Dispatcher"
},
{
"code": null,
"e": 16257,
"s": 16143,
"text": "In some applications, URIs are independent of the action, which is to be performed by the server on the resource."
},
{
"code": null,
"e": 16300,
"s": 16257,
"text": "For example,http://xyz.com/album/delete/10"
},
{
"code": null,
"e": 16363,
"s": 16300,
"text": "The URI contains the operation the client wishes to carry out."
},
{
"code": null,
"e": 16428,
"s": 16363,
"text": "By default, CherryPy dispatcher would map in the following way −"
},
{
"code": null,
"e": 16446,
"s": 16428,
"text": "album.delete(12)\n"
},
{
"code": null,
"e": 16552,
"s": 16446,
"text": "The above mentioned dispatcher is mentioned correctly, but can be made independent in the following way −"
},
{
"code": null,
"e": 16577,
"s": 16552,
"text": "http://xyz.com/album/10\n"
},
{
"code": null,
"e": 16848,
"s": 16577,
"text": "The user may wonder how the server dispatches the exact page. This information is carried by the HTTP request itself. When there is request from client to server, CherryPy looks the best suiting handler, the handler is representation of the resource targeted by the URI."
},
{
"code": null,
"e": 16875,
"s": 16848,
"text": "DELETE /album/12 HTTP/1.1\n"
},
{
"code": null,
"e": 16949,
"s": 16875,
"text": "Here is a list of the parameters for the method required in dispatching −"
},
{
"code": null,
"e": 17013,
"s": 16949,
"text": "The name parameter is the unique name for the route to connect."
},
{
"code": null,
"e": 17077,
"s": 17013,
"text": "The name parameter is the unique name for the route to connect."
},
{
"code": null,
"e": 17117,
"s": 17077,
"text": "The route is the pattern to match URIs."
},
{
"code": null,
"e": 17157,
"s": 17117,
"text": "The route is the pattern to match URIs."
},
{
"code": null,
"e": 17214,
"s": 17157,
"text": "The controller is the instance containing page handlers."
},
{
"code": null,
"e": 17271,
"s": 17214,
"text": "The controller is the instance containing page handlers."
},
{
"code": null,
"e": 17376,
"s": 17271,
"text": "Using the Routes dispatcher connects a pattern that matches URIs and associates a specific page handler."
},
{
"code": null,
"e": 17481,
"s": 17376,
"text": "Using the Routes dispatcher connects a pattern that matches URIs and associates a specific page handler."
},
{
"code": null,
"e": 17533,
"s": 17481,
"text": "Let us take an example to understand how it works −"
},
{
"code": null,
"e": 17873,
"s": 17533,
"text": "import random\nimport string\nimport cherrypy\n\nclass StringMaker(object):\n @cherrypy.expose\n def index(self):\n return \"Hello! How are you?\"\n \n @cherrypy.expose\n def generate(self, length=9):\n return ''.join(random.sample(string.hexdigits, int(length)))\n\t\t\nif __name__ == '__main__':\n cherrypy.quickstart(StringMaker ())"
},
{
"code": null,
"e": 17940,
"s": 17873,
"text": "Follow the steps given below to get the output of the above code −"
},
{
"code": null,
"e": 17996,
"s": 17940,
"text": "Step 1 − Save the above mentioned file as tutRoutes.py."
},
{
"code": null,
"e": 18031,
"s": 17996,
"text": "Step 2 − Visit the following URL −"
},
{
"code": null,
"e": 18073,
"s": 18031,
"text": "http://localhost:8080/generate?length=10\n"
},
{
"code": null,
"e": 18122,
"s": 18073,
"text": "Step 3 − You will receive the following output −"
},
{
"code": null,
"e": 18282,
"s": 18122,
"text": "Within CherryPy, built-in tools offer a single interface to call the CherryPy library. The tools defined in CherryPy can be implemented in the following ways −"
},
{
"code": null,
"e": 18314,
"s": 18282,
"text": "From the configuration settings"
},
{
"code": null,
"e": 18394,
"s": 18314,
"text": "As a Python decorator or via the special _cp_config attribute of a page handler"
},
{
"code": null,
"e": 18460,
"s": 18394,
"text": "As a Python callable that can be applied from within any function"
},
{
"code": null,
"e": 18568,
"s": 18460,
"text": "The purpose of this tool is to provide basic authentication to the application designed in the application."
},
{
"code": null,
"e": 18609,
"s": 18568,
"text": "This tool uses the following arguments −"
},
{
"code": null,
"e": 18661,
"s": 18609,
"text": "Let us take an example to understand how it works −"
},
{
"code": null,
"e": 19368,
"s": 18661,
"text": "import sha\nimport cherrypy\n\nclass Root:\[email protected]\ndef index(self):\n\nreturn \"\"\"\n<html>\n <head></head>\n <body>\n <a href = \"admin\">Admin </a>\n </body>\n</html>\n\"\"\" \n\nclass Admin:\n\[email protected]\ndef index(self):\nreturn \"This is a private area\"\n\nif __name__ == '__main__':\ndef get_users():\n# 'test': 'test'\nreturn {'test': 'b110ba61c4c0873d3101e10871082fbbfd3'}\ndef encrypt_pwd(token):\n\nreturn sha.new(token).hexdigest()\n conf = {'/admin': {'tools.basic_auth.on': True,\n tools.basic_auth.realm': 'Website name',\n 'tools.basic_auth.users': get_users,\n 'tools.basic_auth.encrypt': encrypt_pwd}}\n root = Root()\nroot.admin = Admin()\ncherrypy.quickstart(root, '/', config=conf)"
},
{
"code": null,
"e": 19646,
"s": 19368,
"text": "The get_users function returns a hard-coded dictionary but also fetches the values from a database or anywhere else. The class admin includes this function which makes use of an authentication built-in tool of CherryPy. The authentication encrypts the password and the user Id."
},
{
"code": null,
"e": 19757,
"s": 19646,
"text": "The basic authentication tool is not really secure, as the password can be encoded and decoded by an intruder."
},
{
"code": null,
"e": 19842,
"s": 19757,
"text": "The purpose of this tool is to provide memory caching of CherryPy generated content."
},
{
"code": null,
"e": 19883,
"s": 19842,
"text": "This tool uses the following arguments −"
},
{
"code": null,
"e": 19954,
"s": 19883,
"text": "The purpose of this tool is to decode the incoming request parameters."
},
{
"code": null,
"e": 19995,
"s": 19954,
"text": "This tool uses the following arguments −"
},
{
"code": null,
"e": 20047,
"s": 19995,
"text": "Let us take an example to understand how it works −"
},
{
"code": null,
"e": 20548,
"s": 20047,
"text": "import cherrypy\nfrom cherrypy import tools\n\nclass Root:\[email protected]\ndef index(self):\n\nreturn \"\"\" \n<html>\n <head></head>\n <body>\n <form action = \"hello.html\" method = \"post\">\n <input type = \"text\" name = \"name\" value = \"\" />\n <input type = ”submit” name = \"submit\"/>\n </form>\n </body>\n</html>\n\"\"\"\n\[email protected]\[email protected](encoding='ISO-88510-1')\ndef hello(self, name):\nreturn \"Hello %s\" % (name, )\nif __name__ == '__main__':\ncherrypy.quickstart(Root(), '/')"
},
{
"code": null,
"e": 20702,
"s": 20548,
"text": "The above code takes a string from the user and it will redirect the user to \"hello.html\" page where it will be displayed as “Hello” with the given name."
},
{
"code": null,
"e": 20747,
"s": 20702,
"text": "The output of the above code is as follows −"
},
{
"code": null,
"e": 20759,
"s": 20747,
"text": "hello.html\n"
},
{
"code": null,
"e": 20873,
"s": 20759,
"text": "Full stack applications provide a facility to create a new application via some command or execution of the file."
},
{
"code": null,
"e": 21107,
"s": 20873,
"text": "Consider the Python applications like web2py framework; the entire project/application is created in terms of MVC framework. Likewise, CherryPy allows the user to set up and configure the layout of the code as per their requirements."
},
{
"code": null,
"e": 21199,
"s": 21107,
"text": "In this chapter, we will learn in detail how to create CherryPy application and execute it."
},
{
"code": null,
"e": 21273,
"s": 21199,
"text": "The file system of the application is shown in the following screenshot −"
},
{
"code": null,
"e": 21356,
"s": 21273,
"text": "Here is a brief description of the various files that we have in the file system −"
},
{
"code": null,
"e": 21483,
"s": 21356,
"text": "config.py − Every application needs a configuration file and a way to load it. This functionality can be defined in config.py."
},
{
"code": null,
"e": 21610,
"s": 21483,
"text": "config.py − Every application needs a configuration file and a way to load it. This functionality can be defined in config.py."
},
{
"code": null,
"e": 21785,
"s": 21610,
"text": "controllers.py − MVC is a popular design pattern followed by the users. The controllers.py is where all the objects are implemented that will be mounted on the cherrypy.tree."
},
{
"code": null,
"e": 21960,
"s": 21785,
"text": "controllers.py − MVC is a popular design pattern followed by the users. The controllers.py is where all the objects are implemented that will be mounted on the cherrypy.tree."
},
{
"code": null,
"e": 22069,
"s": 21960,
"text": "models.py − This file interacts with the database directly for some services or for storing persistent data."
},
{
"code": null,
"e": 22178,
"s": 22069,
"text": "models.py − This file interacts with the database directly for some services or for storing persistent data."
},
{
"code": null,
"e": 22290,
"s": 22178,
"text": "server.py − This file interacts with production ready web server that works properly with load balancing proxy."
},
{
"code": null,
"e": 22402,
"s": 22290,
"text": "server.py − This file interacts with production ready web server that works properly with load balancing proxy."
},
{
"code": null,
"e": 22452,
"s": 22402,
"text": "Static − It includes all the CSS and image files."
},
{
"code": null,
"e": 22502,
"s": 22452,
"text": "Static − It includes all the CSS and image files."
},
{
"code": null,
"e": 22570,
"s": 22502,
"text": "Views − It includes all the template files for a given application."
},
{
"code": null,
"e": 22638,
"s": 22570,
"text": "Views − It includes all the template files for a given application."
},
{
"code": null,
"e": 22705,
"s": 22638,
"text": "Let us learn in detail the steps to create a CherryPy application."
},
{
"code": null,
"e": 22773,
"s": 22705,
"text": "Step 1 − Create an application that should contain the application."
},
{
"code": null,
"e": 22925,
"s": 22773,
"text": "Step 2 − Inside the directory, create a python package corresponding to the project. Create gedit directory and include _init_.py file within the same."
},
{
"code": null,
"e": 23011,
"s": 22925,
"text": "Step 3 − Inside the package, include controllers.py file with the following content −"
},
{
"code": null,
"e": 23765,
"s": 23011,
"text": "#!/usr/bin/env python\n\nimport cherrypy\n\nclass Root(object):\n\n def __init__(self, data):\n self.data = data\n\n @cherrypy.expose\n def index(self):\n return 'Hi! Welcome to your application'\n\ndef main(filename):\n data = {} # will be replaced with proper functionality later\n\n # configuration file\n cherrypy.config.update({\n 'tools.encode.on': True, 'tools.encode.encoding': 'utf-8',\n 'tools.decode.on': True,\n 'tools.trailing_slash.on': True,\n 'tools.staticdir.root': os.path.abspath(os.path.dirname(__file__)),\n })\n\n cherrypy.quickstart(Root(data), '/', {\n '/media': {\n 'tools.staticdir.on': True,\n 'tools.staticdir.dir': 'static'\n }\n })\n\t\nif __name__ == '__main__':\nmain(sys.argv[1])"
},
{
"code": null,
"e": 23919,
"s": 23765,
"text": "Step 4 − Consider an application where the user inputs the value through a form. Let’s include two forms — index.html and submit.html in the application."
},
{
"code": null,
"e": 24062,
"s": 23919,
"text": "Step 5 − In the above code for controllers, we have index(), which is a default function and loads first if a particular controller is called."
},
{
"code": null,
"e": 24150,
"s": 24062,
"text": "Step 6 − The implementation of the index() method can be changed in the following way −"
},
{
"code": null,
"e": 24303,
"s": 24150,
"text": "@cherrypy.expose\n def index(self):\n tmpl = loader.load('index.html')\n\t \n return tmpl.generate(title='Sample').render('html', doctype='html')"
},
{
"code": null,
"e": 24450,
"s": 24303,
"text": "Step 7 − This will load index.html on starting the given application and direct it to the given output stream. The index.html file is as follows −"
},
{
"code": null,
"e": 24732,
"s": 24450,
"text": "<!DOCTYPE html >\n<html>\n <head>\n <title>Sample</title>\n </head>\n\t\n <body class = \"index\">\n <div id = \"header\">\n <h1>Sample Application</h1>\n </div>\n\t\t\n <p>Welcome!</p>\n\t\t\n <div id = \"footer\">\n <hr>\n </div>\n\t\t\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 24884,
"s": 24732,
"text": "Step 8 − It is important to add a method to the Root class in controller.py if you want to create a form which accepts values such as names and titles."
},
{
"code": null,
"e": 25321,
"s": 24884,
"text": "@cherrypy.expose\n def submit(self, cancel = False, **value):\n\t\n if cherrypy.request.method == 'POST':\n if cancel:\n raise cherrypy.HTTPRedirect('/') # to cancel the action\n link = Link(**value)\n self.data[link.id] = link\n raise cherrypy.HTTPRedirect('/')\n tmp = loader.load('submit.html')\n streamValue = tmp.generate()\n\t\t\n return streamValue.render('html', doctype='html')"
},
{
"code": null,
"e": 25385,
"s": 25321,
"text": "Step 9 − The code to be included in submit.html is as follows −"
},
{
"code": null,
"e": 26519,
"s": 25385,
"text": "<!DOCTYPE html>\n <head>\n <title>Input the new link</title>\n </head>\n\t\n <body class = \"submit\">\n <div id = \" header\">\n <h1>Submit new link</h1>\n </div>\n\t\t\n <form action = \"\" method = \"post\">\n <table summary = \"\">\n <tr>\n <th><label for = \" username\">Your name:</label></th>\n <td><input type = \" text\" id = \" username\" name = \" username\" /></td>\n </tr>\n\t\t\t\t\n <tr>\n <th><label for = \" url\">Link URL:</label></th>\n <td><input type = \" text\" id=\" url\" name= \" url\" /></td>\n </tr>\n\t\t\t\t\n <tr>\n <th><label for = \" title\">Title:</label></th>\n <td><input type = \" text\" name = \" title\" /></td>\n </tr>\n\t\t\t\t\n <tr>\n <td></td>\n <td>\n <input type = \" submit\" value = \" Submit\" />\n <input type = \" submit\" name = \" cancel\" value = \"Cancel\" />\n </td>\n </tr>\n\t\t\t\t\n </table>\n\t\t\t\n </form>\n <div id = \"footer\">\n </div>\n\t\t\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 26569,
"s": 26519,
"text": "Step 10 − You will receive the following output −"
},
{
"code": null,
"e": 26794,
"s": 26569,
"text": "Here, the method name is defined as “POST”. It is always important to cross verify the method specified in the file. If the method includes “POST” method, the values should be rechecked in the database in appropriate fields."
},
{
"code": null,
"e": 26882,
"s": 26794,
"text": "If the method includes “GET” method, the values to be saved will be visible in the URL."
},
{
"code": null,
"e": 27097,
"s": 26882,
"text": "A web service is a set of web-based components that helps in the exchange of data between the application or systems which also includes open protocols and standards. It can be published, used and found on the web."
},
{
"code": null,
"e": 27189,
"s": 27097,
"text": "Web services are of various types like RWS (RESTfUL Web Service), WSDL, SOAP and many more."
},
{
"code": null,
"e": 27344,
"s": 27189,
"text": "A type of remote access protocol, which, transfers state from client to server which can be used to manipulate state instead of calling remote procedures."
},
{
"code": null,
"e": 27440,
"s": 27344,
"text": "Does not define any specific encoding or structure and ways of returning useful error messages."
},
{
"code": null,
"e": 27536,
"s": 27440,
"text": "Does not define any specific encoding or structure and ways of returning useful error messages."
},
{
"code": null,
"e": 27592,
"s": 27536,
"text": "Uses HTTP \"verbs\" to perform state transfer operations."
},
{
"code": null,
"e": 27648,
"s": 27592,
"text": "Uses HTTP \"verbs\" to perform state transfer operations."
},
{
"code": null,
"e": 27697,
"s": 27648,
"text": "The resources are uniquely identified using URL."
},
{
"code": null,
"e": 27746,
"s": 27697,
"text": "The resources are uniquely identified using URL."
},
{
"code": null,
"e": 27799,
"s": 27746,
"text": "It is not an API but instead an API transport layer."
},
{
"code": null,
"e": 27852,
"s": 27799,
"text": "It is not an API but instead an API transport layer."
},
{
"code": null,
"e": 28178,
"s": 27852,
"text": "REST maintains the nomenclature of resources on a network and provides unified mechanism to perform operations on these resources. Each resource is identified by at least one identifier. If the REST infrastructure is implemented with the base of HTTP, then these identifiers are termed as Uniform Resource Identifiers (URIs)."
},
{
"code": null,
"e": 28236,
"s": 28178,
"text": "The following are the two common subsets of the URI set −"
},
{
"code": null,
"e": 28347,
"s": 28236,
"text": "Before understanding the implementation of CherryPy architecture, let’s focus on the architecture of CherryPy."
},
{
"code": null,
"e": 28398,
"s": 28347,
"text": "CherryPy includes the following three components −"
},
{
"code": null,
"e": 28473,
"s": 28398,
"text": "cherrypy.engine − It controls process startup/teardown and event handling."
},
{
"code": null,
"e": 28548,
"s": 28473,
"text": "cherrypy.engine − It controls process startup/teardown and event handling."
},
{
"code": null,
"e": 28618,
"s": 28548,
"text": "cherrypy.server − It configures and controls the WSGI or HTTP server."
},
{
"code": null,
"e": 28688,
"s": 28618,
"text": "cherrypy.server − It configures and controls the WSGI or HTTP server."
},
{
"code": null,
"e": 28779,
"s": 28688,
"text": "cherrypy.tools − A toolbox of utilities that are orthogonal to processing an HTTP request."
},
{
"code": null,
"e": 28870,
"s": 28779,
"text": "cherrypy.tools − A toolbox of utilities that are orthogonal to processing an HTTP request."
},
{
"code": null,
"e": 28972,
"s": 28870,
"text": "RESTful web service implements each section of CherryPy architecture with the help of the following −"
},
{
"code": null,
"e": 28987,
"s": 28972,
"text": "Authentication"
},
{
"code": null,
"e": 29001,
"s": 28987,
"text": "Authorization"
},
{
"code": null,
"e": 29011,
"s": 29001,
"text": "Structure"
},
{
"code": null,
"e": 29025,
"s": 29011,
"text": "Encapsulation"
},
{
"code": null,
"e": 29040,
"s": 29025,
"text": "Error Handling"
},
{
"code": null,
"e": 29177,
"s": 29040,
"text": "Authentication helps in validating the users with whom we are interacting. CherryPy includes tools to handle each authentication method."
},
{
"code": null,
"e": 29633,
"s": 29177,
"text": "def authenticate():\n if not hasattr(cherrypy.request, 'user') or cherrypy.request.user is None:\n # < Do stuff to look up your users >\n\t\t\n cherrypy.request.authorized = False # This only authenticates. \n Authz must be handled separately.\n\t\t\n cherrypy.request.unauthorized_reasons = []\n cherrypy.request.authorization_queries = []\n\t\t\ncherrypy.tools.authenticate = \\\n cherrypy.Tool('before_handler', authenticate, priority=10)"
},
{
"code": null,
"e": 29797,
"s": 29633,
"text": "The above function authenticate() will help to validate the existence of the clients or users. The built-in tools help to complete the process in a systematic way."
},
{
"code": null,
"e": 29931,
"s": 29797,
"text": "Authorization helps in maintaining the sanity of the process via URI. The process also helps in morphing objects by user token leads."
},
{
"code": null,
"e": 30457,
"s": 29931,
"text": "def authorize_all():\n cherrypy.request.authorized = 'authorize_all'\n\t\ncherrypy.tools.authorize_all = cherrypy.Tool('before_handler', authorize_all, priority=11)\n\ndef is_authorized():\n if not cherrypy.request.authorized:\n raise cherrypy.HTTPError(\"403 Forbidden\",\n ','.join(cherrypy.request.unauthorized_reasons))\n\t\t\t\ncherrypy.tools.is_authorized = cherrypy.Tool('before_handler', is_authorized, \npriority = 49)\n\ncherrypy.config.update({\n 'tools.is_authorized.on': True,\n 'tools.authorize_all.on': True\n})"
},
{
"code": null,
"e": 30582,
"s": 30457,
"text": "The built-in tools of authorization help in handling the routines in a systematic way, as mentioned in the previous example."
},
{
"code": null,
"e": 30817,
"s": 30582,
"text": "Maintaining a structure of API helps in reducing the work load of mapping the URI of application. It is always necessary to keep API discoverable and clean. The basic structure of API for CherryPy framework should have the following −"
},
{
"code": null,
"e": 30835,
"s": 30817,
"text": "Accounts and User"
},
{
"code": null,
"e": 30849,
"s": 30835,
"text": "Autoresponder"
},
{
"code": null,
"e": 30857,
"s": 30849,
"text": "Contact"
},
{
"code": null,
"e": 30862,
"s": 30857,
"text": "File"
},
{
"code": null,
"e": 30869,
"s": 30862,
"text": "Folder"
},
{
"code": null,
"e": 30884,
"s": 30869,
"text": "List and field"
},
{
"code": null,
"e": 30902,
"s": 30884,
"text": "Message and Batch"
},
{
"code": null,
"e": 31111,
"s": 30902,
"text": "Encapsulation helps in creating API which is lightweight, human readable and accessible to various clients. The list of items along with Creation, Retrieval, Update and Deletion requires encapsulation of API."
},
{
"code": null,
"e": 31273,
"s": 31111,
"text": "This process manages errors, if any, if API fails to execute at the particular instinct. For example, 400 is for Bad Request and 403 is for unauthorized request."
},
{
"code": null,
"e": 31359,
"s": 31273,
"text": "Consider the following as an example for database, validation, or application errors."
},
{
"code": null,
"e": 31800,
"s": 31359,
"text": "import cherrypy\nimport json\n\ndef error_page_default(status, message, traceback, version):\n ret = {\n 'status': status,\n 'version': version,\n 'message': [message],\n 'traceback': traceback\n }\n\t\n return json.dumps(ret)\n\t\nclass Root:\n _cp_config = {'error_page.default': error_page_default}\n\t\[email protected]\n def index(self):\n raise cherrypy.HTTPError(500, \"Internal Sever Error\")\ncherrypy.quickstart(Root())"
},
{
"code": null,
"e": 31851,
"s": 31800,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 31968,
"s": 31851,
"text": "Management of API (Application Programming Interface) is easy through CherryPy because of the built-in access tools."
},
{
"code": null,
"e": 32041,
"s": 31968,
"text": "The list of HTTP methods which operate on the resources are as follows −"
},
{
"code": null,
"e": 32046,
"s": 32041,
"text": "HEAD"
},
{
"code": null,
"e": 32079,
"s": 32046,
"text": "Retrieves the resource metadata."
},
{
"code": null,
"e": 32083,
"s": 32079,
"text": "GET"
},
{
"code": null,
"e": 32128,
"s": 32083,
"text": "Retrieves the resource metadata and content."
},
{
"code": null,
"e": 32133,
"s": 32128,
"text": "POST"
},
{
"code": null,
"e": 32223,
"s": 32133,
"text": "Requests the server to create a new resource using the data enclosed in the request body."
},
{
"code": null,
"e": 32227,
"s": 32223,
"text": "PUT"
},
{
"code": null,
"e": 32322,
"s": 32227,
"text": "Requests the server to replace an existing resource with the one enclosed in the request body."
},
{
"code": null,
"e": 32329,
"s": 32322,
"text": "DELETE"
},
{
"code": null,
"e": 32396,
"s": 32329,
"text": "Requests the server to remove the resource identified by that URI."
},
{
"code": null,
"e": 32404,
"s": 32396,
"text": "OPTIONS"
},
{
"code": null,
"e": 32513,
"s": 32404,
"text": "Requests the server to return details about capabilities either globally or specifically towards a resource."
},
{
"code": null,
"e": 32752,
"s": 32513,
"text": "APP has arisen from the Atom community as an application-level protocol on top of HTTP to allow the publishing and editing of web resources. The unit of messages between an APP server and a client is based on the Atom XML-document format."
},
{
"code": null,
"e": 32937,
"s": 32752,
"text": "The Atom Publishing Protocol defines a set of operations between an APP service and a user-agent using HTTP and its mechanisms and the Atom XML-document format as the unit of messages."
},
{
"code": null,
"e": 33074,
"s": 32937,
"text": "APP first defines a service document, which provides the user agent with the URI of the different collections served by the APP service."
},
{
"code": null,
"e": 33128,
"s": 33074,
"text": "Let us take an example to demonstrate how APP works −"
},
{
"code": null,
"e": 33715,
"s": 33128,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<service xmlns = \"http://purl.org/atom/app#\" xmlns:atom = \"http://www.w3.org/2005/Atom\">\n \n <workspace>\n <collection href = \"http://host/service/atompub/album/\">\n <atom:title> Albums</atom:title>\n <categories fixed = \"yes\">\n <atom:category term = \"friends\" />\n </categories>\n </collection>\n \n <collection href = \"http://host/service/atompub/film/\">\n <atom:title>Films</atom:title>\n <accept>image/png,image/jpeg</accept>\n </collection>\n </workspace>\n\t\n</service>"
},
{
"code": null,
"e": 33888,
"s": 33715,
"text": "APP specifies how to perform the basic CRUD operations against a member of a collection or the collection itself by using HTTP methods as described in the following table −"
},
{
"code": null,
"e": 34076,
"s": 33888,
"text": "The Presentation Layer ensures that the communication passing through it targets the intended recipients. CherryPy maintains the working of presentation layer by various template engines."
},
{
"code": null,
"e": 34236,
"s": 34076,
"text": "A template engine takes the input of the page with the help of business logic and then processes it to the final page which targets only the intended audience."
},
{
"code": null,
"e": 34411,
"s": 34236,
"text": "Kid is a simple template engine which includes the name of the template to be processed (which is mandatory) and input of the data to be passed when the template is rendered."
},
{
"code": null,
"e": 34544,
"s": 34411,
"text": "On creation of the template for the first time, Kid creates a Python module which can be served as a cached version of the template."
},
{
"code": null,
"e": 34660,
"s": 34544,
"text": "The kid.Template function returns an instance of the template class which can be used to render the output content."
},
{
"code": null,
"e": 34720,
"s": 34660,
"text": "The template class provides the following set of commands −"
},
{
"code": null,
"e": 34730,
"s": 34720,
"text": "serialize"
},
{
"code": null,
"e": 34773,
"s": 34730,
"text": "It returns the output content as a string."
},
{
"code": null,
"e": 34782,
"s": 34773,
"text": "generate"
},
{
"code": null,
"e": 34828,
"s": 34782,
"text": "It returns the output content as an iterator."
},
{
"code": null,
"e": 34834,
"s": 34828,
"text": "write"
},
{
"code": null,
"e": 34882,
"s": 34834,
"text": "It dumps the output content into a file object."
},
{
"code": null,
"e": 34937,
"s": 34882,
"text": "The parameters used by these commands are as follows −"
},
{
"code": null,
"e": 34946,
"s": 34937,
"text": "encoding"
},
{
"code": null,
"e": 34990,
"s": 34946,
"text": "It informs how to encode the output content"
},
{
"code": null,
"e": 34999,
"s": 34990,
"text": "fragment"
},
{
"code": null,
"e": 35058,
"s": 34999,
"text": "It is a Boolean value which tells to XML prolog or Doctype"
},
{
"code": null,
"e": 35065,
"s": 35058,
"text": "output"
},
{
"code": null,
"e": 35122,
"s": 35065,
"text": "This type of serialization is used to render the content"
},
{
"code": null,
"e": 35175,
"s": 35122,
"text": "Let us take an example to understand how kid works −"
},
{
"code": null,
"e": 35705,
"s": 35175,
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n<html xmlns:py = \"http://purl.org/kid/ns#\">\n <head>\n <title>${title}</title>\n <link rel = \"stylesheet\" href = \"style.css\" />\n </head>\n\t\n <body> \n <p>${message}</p>\n </body>\n</html>\n\nThe next step after saving the file is to process the template via the Kid engine.\n\nimport kid\n\nparams = {'title': 'Hello world!!', 'message': 'CherryPy.'}\nt = kid.Template('helloworld.kid', **params)\nprint t.serialize(output='html')"
},
{
"code": null,
"e": 35747,
"s": 35705,
"text": "The following are the attributes of Kid −"
},
{
"code": null,
"e": 35858,
"s": 35747,
"text": "It is an XML-based language. A Kid template must be a well-formed XML document with proper naming conventions."
},
{
"code": null,
"e": 36110,
"s": 35858,
"text": "Kid implements attributes within the XML elements to update the underlying engine on the action to be followed for reaching the element. To avoid overlapping with other existing attributes within the XML document, Kid has introduced its own namespace."
},
{
"code": null,
"e": 36136,
"s": 36110,
"text": "<p py:if = \"...\">...</p>\n"
},
{
"code": null,
"e": 36224,
"s": 36136,
"text": "Kid comes with a variable substitution scheme and a simple approach — ${variable-name}."
},
{
"code": null,
"e": 36399,
"s": 36224,
"text": "The variables can either be used in attributes of elements or as the text content of an element. Kid will evaluate the variable each and every time the execution takes place."
},
{
"code": null,
"e": 36544,
"s": 36399,
"text": "If the user needs the output of a literal string as ${something}, it can be escaped using the variable substitution by doubling the dollar sign."
},
{
"code": null,
"e": 36621,
"s": 36544,
"text": "For toggling different cases in the template, the following syntax is used −"
},
{
"code": null,
"e": 36658,
"s": 36621,
"text": "<tag py:if = \"expression\">...</tag>\n"
},
{
"code": null,
"e": 36722,
"s": 36658,
"text": "Here, tag is the name of the element, for instance DIV or SPAN."
},
{
"code": null,
"e": 36903,
"s": 36722,
"text": "The expression is a Python expression. If as a Boolean it evaluates to True, the element will be included in the output content or else it will not be a part of the output content."
},
{
"code": null,
"e": 36965,
"s": 36903,
"text": "For looping an element in Kid, the following syntax is used −"
},
{
"code": null,
"e": 37003,
"s": 36965,
"text": "<tag py:for = \"expression\">...</tag>\n"
},
{
"code": null,
"e": 37112,
"s": 37003,
"text": "Here, tag is the name of the element. The expression is a Python expression, for example for value in [...]."
},
{
"code": null,
"e": 37171,
"s": 37112,
"text": "The following code shows how the looping mechanism works −"
},
{
"code": null,
"e": 37880,
"s": 37171,
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n<html>\n <head>\n <title>${title}</title>\n <link rel = \"stylesheet\" href = \"style.css\" />\n </head>\n\t\n <body>\n <table>\n <caption>A few songs</caption>\n <tr>\n <th>Artist</th>\n <th>Album</th>\n <th>Title</th>\n </tr>\n\t\t\t\n <tr py:for = \"info in infos\">\n <td>${info['artist']}</td>\n <td>${info['album']}</td>\n <td>${info['song']}</td>\n </tr>\n </table>\n </body>\n</html>\n\nimport kid\n\nparams = discography.retrieve_songs()\nt = kid.Template('songs.kid', **params)\nprint t.serialize(output='html')"
},
{
"code": null,
"e": 37953,
"s": 37880,
"text": "The output for the above code with the looping mechanism is as follows −"
},
{
"code": null,
"e": 38192,
"s": 37953,
"text": "Till the year 2005, the pattern followed in all web applications was to manage one HTTP request per page. The navigation of one page to another page required loading the complete page. This would reduce the performance at a greater level."
},
{
"code": null,
"e": 38294,
"s": 38192,
"text": "Thus, there was a rise in rich client applications which used to embed AJAX, XML, and JSON with them."
},
{
"code": null,
"e": 38604,
"s": 38294,
"text": "Asynchronous JavaScript and XML (AJAX) is a technique to create fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data behind the scenes with the server. This means that it is possible to update parts of a web page, without reloading the whole page."
},
{
"code": null,
"e": 38687,
"s": 38604,
"text": "Google Maps, Gmail, YouTube, and Facebook are a few examples of AJAX applications."
},
{
"code": null,
"e": 38856,
"s": 38687,
"text": "Ajax is based on the idea of sending HTTP requests using JavaScript; more specifically AJAX relies on the XMLHttpRequest object and its API to perform those operations."
},
{
"code": null,
"e": 39044,
"s": 38856,
"text": "JSON is a way to carry serialized JavaScript objects in such a way that JavaScript application can evaluate them and transform them into JavaScript objects which can be manipulated later."
},
{
"code": null,
"e": 39194,
"s": 39044,
"text": "For instance, when the user requests the server for an album object formatted with the JSON format, the server would return the output as following −"
},
{
"code": null,
"e": 39275,
"s": 39194,
"text": "{'description': 'This is a simple demo album for you to test', 'author': ‘xyz’}\n"
},
{
"code": null,
"e": 39370,
"s": 39275,
"text": "Now the data is a JavaScript associative array and the description field can be accessed via −"
},
{
"code": null,
"e": 39393,
"s": 39370,
"text": "data ['description'];\n"
},
{
"code": null,
"e": 39582,
"s": 39393,
"text": "Consider the application which includes a folder named “media” with index.html and Jquery plugin, and a file with AJAX implementation. Let us consider the name of the file as “ajax_app.py”"
},
{
"code": null,
"e": 40293,
"s": 39582,
"text": "import cherrypy\nimport webbrowser\nimport os\nimport simplejson\nimport sys\n\nMEDIA_DIR = os.path.join(os.path.abspath(\".\"), u\"media\")\n\nclass AjaxApp(object):\n @cherrypy.expose\n def index(self):\n return open(os.path.join(MEDIA_DIR, u'index.html'))\n\n @cherrypy.expose\n def submit(self, name):\n cherrypy.response.headers['Content-Type'] = 'application/json'\n return simplejson.dumps(dict(title=\"Hello, %s\" % name))\n\t\t\nconfig = {'/media':\n {'tools.staticdir.on': True,\n 'tools.staticdir.dir': MEDIA_DIR,}\n}\n\t\t\t\ndef open_page():\nwebbrowser.open(\"http://127.0.0.1:8080/\")\ncherrypy.engine.subscribe('start', open_page)\ncherrypy.tree.mount(AjaxApp(), '/', config=config)\ncherrypy.engine.start()"
},
{
"code": null,
"e": 40395,
"s": 40293,
"text": "The class “AjaxApp” redirects to the web page of “index.html”, which is included in the media folder."
},
{
"code": null,
"e": 41689,
"s": 40395,
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \n \" http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\t\n<html xmlns = \"http://www.w3.org/1999/xhtml\" lang = \"en\" xml:lang = \"en\">\n <head>\n <title>AJAX with jQuery and cherrypy</title>\n <meta http-equiv = \" Content-Type\" content = \" text/html; charset=utf-8\" />\n <script type = \" text/javascript\" src = \" /media/jquery-1.4.2.min.js\"></script>\n\t\t\n <script type = \" text/javascript\">\n $(function() {\n \n // When the testform is submitted...\n $(\"#formtest\").submit(function() {\n \n // post the form values via AJAX...\n $.post('/submit', {name: $(\"#name\").val()}, function(data) {\n \n // and set the title with the result\n $(\"#title\").html(data['title']) ;\n });\n return false ;\n });\n });\n </script>\n\t\t\n </head>\n\t\n <body>\n <h1 id = \"title\">What's your name?</h1>\n <form id = \" formtest\" action = \" #\" method = \" post\">\n <p>\n <label for = \" name\">Name:</label>\n <input type = \" text\" id = \"name\" /> <br />\n <input type = \" submit\" value = \" Set\" />\n </p>\n </form>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 41745,
"s": 41689,
"text": "The function for AJAX is included within <script> tags."
},
{
"code": null,
"e": 41796,
"s": 41745,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 41929,
"s": 41796,
"text": "Once the value is submitted by the user, AJAX functionality is implemented and the screen is redirected to the form as shown below −"
},
{
"code": null,
"e": 42016,
"s": 41929,
"text": "In this chapter, we will focus on how an application is created in CherryPy framework."
},
{
"code": null,
"e": 42289,
"s": 42016,
"text": "Consider Photoblog application for the demo application of CherryPy. A Photoblog application is a normal blog but the principal text will be photos in place of text. The main catch of Photoblog application is that the developer can focus more on design and implementation."
},
{
"code": null,
"e": 42411,
"s": 42289,
"text": "The entities design the basic structure of an application. The following are the entities for the Photoblog application −"
},
{
"code": null,
"e": 42416,
"s": 42411,
"text": "Film"
},
{
"code": null,
"e": 42422,
"s": 42416,
"text": "Photo"
},
{
"code": null,
"e": 42428,
"s": 42422,
"text": "Album"
},
{
"code": null,
"e": 42497,
"s": 42428,
"text": "The following is a basic class diagram for the entity relationship −"
},
{
"code": null,
"e": 42619,
"s": 42497,
"text": "As discussed in the previous chapter, the design structure of the project would be as shown in the following screenshot −"
},
{
"code": null,
"e": 42812,
"s": 42619,
"text": "Consider the given application, which has sub-directories for Photoblog application. The sub-directories are Photo, Album, and Film which would include controllers.py, models.py and server.py."
},
{
"code": null,
"e": 42974,
"s": 42812,
"text": "Functionally, the Photoblog application will provide APIs to manipulate those entities via the traditional CRUD interface — Create, Retrieve, Update, and Delete."
},
{
"code": null,
"e": 43079,
"s": 42974,
"text": "A storage module includes a set of operations; connection with the database being one of the operations."
},
{
"code": null,
"e": 43236,
"s": 43079,
"text": "As it is a complete application, the connection with database is mandatory for API and to maintain the functionality of Create, Retrieve, Update and Delete."
},
{
"code": null,
"e": 43477,
"s": 43236,
"text": "import dejavu\n\narena = dejavu.Arena()\nfrom model import Album, Film, Photo\ndef connect():\n\nconf = {'Connect': \"host=localhost dbname=Photoblog user=test password=test\"}\narena.add_store(\"main\", \"postgres\", conf)\narena.register_all(globals())"
},
{
"code": null,
"e": 43596,
"s": 43477,
"text": "The arena in the above code will be our interface between the underlying storage manager and the business logic layer."
},
{
"code": null,
"e": 43684,
"s": 43596,
"text": "The connect function adds a storage manager to the arena object for a PostgreSQL RDBMS."
},
{
"code": null,
"e": 43808,
"s": 43684,
"text": "Once, the connection is obtained, we can create forms as per business requirements and complete the working of application."
},
{
"code": null,
"e": 43934,
"s": 43808,
"text": "The most important thing before creation of any application is entity mapping and designing the structure of the application."
},
{
"code": null,
"e": 44039,
"s": 43934,
"text": "Testing is a process during which the application is conducted from different perspectives in order to −"
},
{
"code": null,
"e": 44063,
"s": 44039,
"text": "Find the list of issues"
},
{
"code": null,
"e": 44141,
"s": 44063,
"text": "Find differences between the expected and actual result, output, states, etc."
},
{
"code": null,
"e": 44178,
"s": 44141,
"text": "Understand the implementation phase."
},
{
"code": null,
"e": 44230,
"s": 44178,
"text": "Find the application useful for realistic purposes."
},
{
"code": null,
"e": 44391,
"s": 44230,
"text": "The goal of testing is not to put the developer at fault but to provide tools and improve the quality to estimate the health of the application at a given time."
},
{
"code": null,
"e": 44637,
"s": 44391,
"text": "Testing needs to be planned in advance. This calls for defining the purpose of testing, understanding the scope of test cases, making the list of business requirements and being aware of the risks involved in the different phases of the project."
},
{
"code": null,
"e": 44774,
"s": 44637,
"text": "Testing is defined as a range of aspects to be validated on a system or application. Following is a list of the common test approaches −"
},
{
"code": null,
"e": 44918,
"s": 44774,
"text": "Unit testing − This is usually carried out by the developers themselves. This aims at checking whether a unit of code works as expected or not."
},
{
"code": null,
"e": 45062,
"s": 44918,
"text": "Unit testing − This is usually carried out by the developers themselves. This aims at checking whether a unit of code works as expected or not."
},
{
"code": null,
"e": 45269,
"s": 45062,
"text": "Usability testing − Developers may usually forget that they are writing an application for the end users who do not have knowledge of the system. Usability testing verifies the pros and cons of the product."
},
{
"code": null,
"e": 45476,
"s": 45269,
"text": "Usability testing − Developers may usually forget that they are writing an application for the end users who do not have knowledge of the system. Usability testing verifies the pros and cons of the product."
},
{
"code": null,
"e": 45661,
"s": 45476,
"text": "Functional/Acceptance testing − While usability testing checks whether an application or system is usable, functional testing ensures that every specified functionality is implemented."
},
{
"code": null,
"e": 45846,
"s": 45661,
"text": "Functional/Acceptance testing − While usability testing checks whether an application or system is usable, functional testing ensures that every specified functionality is implemented."
},
{
"code": null,
"e": 46059,
"s": 45846,
"text": "Load and performance testing − This is carried out to understand whether the system can adjust to the load and performance tests to be conducted. This can lead to changes in hardware, optimizing SQL queries, etc."
},
{
"code": null,
"e": 46272,
"s": 46059,
"text": "Load and performance testing − This is carried out to understand whether the system can adjust to the load and performance tests to be conducted. This can lead to changes in hardware, optimizing SQL queries, etc."
},
{
"code": null,
"e": 46393,
"s": 46272,
"text": "Regression testing − It verifies that successive releases of a product do not break any of the previous functionalities."
},
{
"code": null,
"e": 46514,
"s": 46393,
"text": "Regression testing − It verifies that successive releases of a product do not break any of the previous functionalities."
},
{
"code": null,
"e": 46663,
"s": 46514,
"text": "Reliability and resilience testing − Reliability testing helps in validating the system application with the breakdown of one or several components."
},
{
"code": null,
"e": 46812,
"s": 46663,
"text": "Reliability and resilience testing − Reliability testing helps in validating the system application with the breakdown of one or several components."
},
{
"code": null,
"e": 46886,
"s": 46812,
"text": "Photoblog applications constantly use unit tests to check the following −"
},
{
"code": null,
"e": 46938,
"s": 46886,
"text": "New functionalities work correctly and as expected."
},
{
"code": null,
"e": 46999,
"s": 46938,
"text": "Existing functionalities are not broken by new code release."
},
{
"code": null,
"e": 47035,
"s": 46999,
"text": "Defects are fixed and remain fixed."
},
{
"code": null,
"e": 47130,
"s": 47035,
"text": "Python comes in with a standard unittest module offering a different approach to unit testing."
},
{
"code": null,
"e": 47489,
"s": 47130,
"text": "unittest is rooted in JUnit, a Java unit test package developed by Kent Beck and Erich Gamma. Unit tests simply return defined data. Mock objects can be defined. These objects allows testing against an interface of our design without having to rely on the overall application. They also provide a way to run tests in isolation mode with other tests included."
},
{
"code": null,
"e": 47539,
"s": 47489,
"text": "Let’s define a dummy class in the following way −"
},
{
"code": null,
"e": 48386,
"s": 47539,
"text": "import unittest\n\nclass DummyTest(unittest.TestCase):\ndef test_01_forward(self):\ndummy = Dummy(right_boundary=3)\n self.assertEqual(dummy.forward(), 1)\n self.assertEqual(dummy.forward(), 2)\n self.assertEqual(dummy.forward(), 3)\n self.assertRaises(ValueError, dummy.forward)\n\ndef test_02_backward(self):\ndummy = Dummy(left_boundary=-3, allow_negative=True)\n self.assertEqual(dummy.backward(), -1)\n self.assertEqual(dummy.backward(), -2)\n self.assertEqual(dummy.backward(), -3)\n self.assertRaises(ValueError, dummy.backward)\n\ndef test_03_boundaries(self):\ndummy = Dummy(right_boundary=3, left_boundary=-3,allow_negative=True)\n self.assertEqual(dummy.backward(), -1)\n self.assertEqual(dummy.backward(), -2)\n self.assertEqual(dummy.forward(), -1)\n self.assertEqual(dummy.backward(), -2)\n self.assertEqual(dummy.backward(), -3)"
},
{
"code": null,
"e": 48431,
"s": 48386,
"text": "The explanation for the code is as follows −"
},
{
"code": null,
"e": 48521,
"s": 48431,
"text": "unittest module should be imported to provide unit test capabilities for the given class."
},
{
"code": null,
"e": 48611,
"s": 48521,
"text": "unittest module should be imported to provide unit test capabilities for the given class."
},
{
"code": null,
"e": 48662,
"s": 48611,
"text": "A class should be created by subclassing unittest."
},
{
"code": null,
"e": 48713,
"s": 48662,
"text": "A class should be created by subclassing unittest."
},
{
"code": null,
"e": 48819,
"s": 48713,
"text": "Every method in the above code starts with a word test. All these methods are called by unittest handler."
},
{
"code": null,
"e": 48925,
"s": 48819,
"text": "Every method in the above code starts with a word test. All these methods are called by unittest handler."
},
{
"code": null,
"e": 49003,
"s": 48925,
"text": "The assert/fail methods are called by the test case to manage the exceptions."
},
{
"code": null,
"e": 49081,
"s": 49003,
"text": "The assert/fail methods are called by the test case to manage the exceptions."
},
{
"code": null,
"e": 49135,
"s": 49081,
"text": "Consider this as an example for running a test case −"
},
{
"code": null,
"e": 49179,
"s": 49135,
"text": "if __name__ == '__main__':\nunittest.main()\n"
},
{
"code": null,
"e": 49246,
"s": 49179,
"text": "The result (output) for running the test case will be as follows −"
},
{
"code": null,
"e": 49343,
"s": 49246,
"text": "----------------------------------------------------------------------\nRan 3 tests in 0.000s\nOK\n"
},
{
"code": null,
"e": 49655,
"s": 49343,
"text": "Once the application functionalities start taking shape as per the requirements, a set of functional testing can validate the application's correctness regarding the specification. However, the test should be automated for better performance which would require the use of third-party products such as Selenium."
},
{
"code": null,
"e": 49751,
"s": 49655,
"text": "CherryPy provides helper class like built-in functions to ease the writing of functional tests."
},
{
"code": null,
"e": 50016,
"s": 49751,
"text": "Depending on the application you are writing and your expectations in terms of volume, you may need to run load and performance testing in order to detect potential bottlenecks in the application that are preventing it from reaching a certain level of performance."
},
{
"code": null,
"e": 50129,
"s": 50016,
"text": "This section will not detail how to conduct a performance or load test as it is out of its the FunkLoad package."
},
{
"code": null,
"e": 50180,
"s": 50129,
"text": "The very basic example of FunkLoad is as follows −"
},
{
"code": null,
"e": 50599,
"s": 50180,
"text": "from funkload.FunkLoadTestCase \nimport FunkLoadTestCase\n\nclass LoadHomePage(FunkLoadTestCase):\ndef test_homepage(self):\n\nserver_url = self.conf_get('main', 'url')\nnb_time = self.conf_getInt('test_homepage', 'nb_time')\nhome_page = \"%s/\" % server_url\n\nfor i in range(nb_time):\nself.logd('Try %i' % i)\nself.get(home_page, description='Get gome page')\nif __name__ in ('main', '__main__'):\n\nimport unittest\n\nunittest.main()"
},
{
"code": null,
"e": 50650,
"s": 50599,
"text": "Here is a detailed explanation of the above code −"
},
{
"code": null,
"e": 50796,
"s": 50650,
"text": "The test case must inherit from the FunkLoadTestCase class so that the FunkLoad can do its internal job of tracking what happens during the test."
},
{
"code": null,
"e": 50942,
"s": 50796,
"text": "The test case must inherit from the FunkLoadTestCase class so that the FunkLoad can do its internal job of tracking what happens during the test."
},
{
"code": null,
"e": 51028,
"s": 50942,
"text": "The class name is important as FunkLoad will look for a file based on the class name."
},
{
"code": null,
"e": 51114,
"s": 51028,
"text": "The class name is important as FunkLoad will look for a file based on the class name."
},
{
"code": null,
"e": 51268,
"s": 51114,
"text": "The test cases designed have direct access to the configuration files. Get() and post() methods are simply called against the server to get the response."
},
{
"code": null,
"e": 51422,
"s": 51268,
"text": "The test cases designed have direct access to the configuration files. Get() and post() methods are simply called against the server to get the response."
},
{
"code": null,
"e": 51536,
"s": 51422,
"text": "This chapter will focus more on CherryPy-based application SSL enabled through the built-in CherryPy HTTP server."
},
{
"code": null,
"e": 51621,
"s": 51536,
"text": "There are different levels of configuration settings required in a web application −"
},
{
"code": null,
"e": 51669,
"s": 51621,
"text": "Web server − Settings linked to the HTTP server"
},
{
"code": null,
"e": 51717,
"s": 51669,
"text": "Web server − Settings linked to the HTTP server"
},
{
"code": null,
"e": 51773,
"s": 51717,
"text": "Engine − Settings associated with the hosting of engine"
},
{
"code": null,
"e": 51829,
"s": 51773,
"text": "Engine − Settings associated with the hosting of engine"
},
{
"code": null,
"e": 51881,
"s": 51829,
"text": "Application − Application which is used by the user"
},
{
"code": null,
"e": 51933,
"s": 51881,
"text": "Application − Application which is used by the user"
},
{
"code": null,
"e": 52271,
"s": 51933,
"text": "Deployment of CherryPy application is considered to be quite an easy method where all the required packages are available from the Python system path. In shared web-hosted environment, web server will reside in the front end which allows the host provider to perform the filtering actions. The front-end server can be Apache or lighttpd."
},
{
"code": null,
"e": 52387,
"s": 52271,
"text": "This section will present a few solutions to run a CherryPy application behind the Apache and lighttpd web servers."
},
{
"code": null,
"e": 52894,
"s": 52387,
"text": "cherrypy\ndef setup_app():\n\nclass Root:\[email protected]\ndef index(self):\n # Return the hostname used by CherryPy and the remote\n # caller IP address\n\t\nreturn \"Hello there %s from IP: %s \" %\n(cherrypy.request.base, cherrypy.request.remote.ip)\ncherrypy.config.update({'server.socket_port': 9091,\n 'environment': 'production',\n 'log.screen': False,\n 'show_tracebacks': False})\n\t\ncherrypy.tree.mount(Root())\nif __name__ == '__main__':\n\nsetup_app()\ncherrypy.server.quickstart()\ncherrypy.engine.start()"
},
{
"code": null,
"e": 53034,
"s": 52894,
"text": "SSL (Secure Sockets Layer) can be supported in CherryPy-based applications. To enable SSL support, the following requirements must be met −"
},
{
"code": null,
"e": 53093,
"s": 53034,
"text": "Have the PyOpenSSL package installed in user’s environment"
},
{
"code": null,
"e": 53147,
"s": 53093,
"text": "Have an SSL certificate and private key on the server"
},
{
"code": null,
"e": 53217,
"s": 53147,
"text": "Let's deal with the requirements of certificate and the private key −"
},
{
"code": null,
"e": 53254,
"s": 53217,
"text": "First the user needs a private key −"
},
{
"code": null,
"e": 53291,
"s": 53254,
"text": "openssl genrsa -out server.key 2048\n"
},
{
"code": null,
"e": 53368,
"s": 53291,
"text": "This key is not protected by a password and therefore has a weak protection."
},
{
"code": null,
"e": 53407,
"s": 53368,
"text": "The following command will be issued −"
},
{
"code": null,
"e": 53450,
"s": 53407,
"text": "openssl genrsa -des3 -out server.key 2048\n"
},
{
"code": null,
"e": 53655,
"s": 53450,
"text": "The program will require a passphrase. If your version of OpenSSL allows you to provide an empty string, do so. Otherwise, enter a default passphrase and then remove it from the generated key as follows −"
},
{
"code": null,
"e": 53860,
"s": 53655,
"text": "The program will require a passphrase. If your version of OpenSSL allows you to provide an empty string, do so. Otherwise, enter a default passphrase and then remove it from the generated key as follows −"
},
{
"code": null,
"e": 53904,
"s": 53860,
"text": "openssl rsa -in server.key -out server.key\n"
},
{
"code": null,
"e": 53948,
"s": 53904,
"text": "Creation of the certificate is as follows −"
},
{
"code": null,
"e": 53998,
"s": 53948,
"text": "openssl req -new -key server.key -out server.csr\n"
},
{
"code": null,
"e": 54100,
"s": 53998,
"text": "This process will request you to input some details. To do so, the following command must be issued −"
},
{
"code": null,
"e": 54202,
"s": 54100,
"text": "This process will request you to input some details. To do so, the following command must be issued −"
},
{
"code": null,
"e": 54281,
"s": 54202,
"text": "openssl x509 -req -days 60 -in server.csr -signkey\nserver.key -out server.crt\n"
},
{
"code": null,
"e": 54337,
"s": 54281,
"text": "The newly signed certificate will be valid for 60 days."
},
{
"code": null,
"e": 54393,
"s": 54337,
"text": "The newly signed certificate will be valid for 60 days."
},
{
"code": null,
"e": 54439,
"s": 54393,
"text": "The following code shows its implementation −"
},
{
"code": null,
"e": 55009,
"s": 54439,
"text": "import cherrypy\nimport os, os.path\n\nlocalDir = os.path.abspath(os.path.dirname(__file__))\nCA = os.path.join(localDir, 'server.crt')\nKEY = os.path.join(localDir, 'server.key')\ndef setup_server():\n\nclass Root:\[email protected]\ndef index(self):\n return \"Hello there!\"\n\t\ncherrypy.tree.mount(Root())\nif __name__ == '__main__':\n\nsetup_server()\ncherrypy.config.update({'server.socket_port': 8443,\n 'environment': 'production',\n 'log.screen': True,\n 'server.ssl_certificate': CA,\n 'server.ssl_private_key': KEY})\n\t\ncherrypy.server.quickstart()\ncherrypy.engine.start()"
},
{
"code": null,
"e": 55123,
"s": 55009,
"text": "The next step is to start the server; if you are successful, you would see the following message on your screen −"
},
{
"code": null,
"e": 55170,
"s": 55123,
"text": "HTTP Serving HTTPS on https://localhost:8443/\n"
},
{
"code": null,
"e": 55177,
"s": 55170,
"text": " Print"
},
{
"code": null,
"e": 55188,
"s": 55177,
"text": " Add Notes"
}
] |
The Birthday Paradox. How this counter-intuitive statistical... | by Richard Farnworth | Towards Data Science | If you have a group of people in a room, how many do you need to for it to be more likely than not, that two or more will have the same birthday?
Theoretically, the chances of two people having the same birthday are 1 in 365 (not accounting for leap years and the uneven distribution of birthdays across the year), and so odds are you’ll only meet a handful of people in your life who enjoy the same birthday as you. This leads many people to intuitively guess around 180.
The correct answer is just 23.
That means in each of your classes at school, amongst the fellow commuters on the bus to work and amongst the players on a soccer field, there are more than likely at least two people with the same birthday.
Humans have a notoriously poor intuition when it comes to probability. The multi-billion dollar gambling industry is proof of this.
The source of confusion within the Birthday Paradox is that the probability grows relative to the number of possible pairings of people, not just the group’s size. The number of pairings grows with respect to the square of the number of participants, such that a group of 23 people contains 253 (23 x 22 / 2) unique pairs of people.
In each of these pairings, there is a 364/365 chance of having different birthdays, but this needs to happen for every pair for there to be no matching birthdays across the entire group. Therefore the probability of two people having the same birthday in a group of 23 is:
1 — (364/365)^253 = 50.05%
If we plot the probability vs different group sizes, we see how the probability grows as the group size increases.
The line crosses 50% just before a group size of 23. Our previous guess of 180 has a probability so close to 100%, it’s not worth showing. In fact, the chance of choosing a group of 180 people at random, and having none of them share the same birthday, is roughly 6x10^-20 — 100 times less likely than two people picking the same grain of sand out of all the sand on Earth!
We can generalise the Birthday Paradox to look at other phenomena with a similar structure.
The probability of two people having the same PIN on their bank card is 1 in 10,000, or 0.01%. It would only take a group of 119 people however, to have odds in favour of two people having the same PIN.
Of course, these numbers assume a randomly sampled, uniform distribution of birthdays and PINs. In reality, birthdays peak at certain times of year and people are more likely to pick certain numbers than others for their PIN. But the lack of a uniform distribution in fact reduces the size of group that you need.
If we decrease the probability of a coincidence occurring, the size of group required to get an even chance of a collision obviously increases. However, it increases much more slowly than inverse of the probability.
For example, with a probability of 1 in 10,000, the minimum group size is 119. For a coincidence 10x less likely, the minimum group is 373, or only 3.15 times bigger. Therefore, even for incredibly tiny probabilities, the group size doesn’t grow particularly large. For odds of one in a million, the group required is only 1178.
This has implications in the area of satellite collisions and space junk. The odds of two particular orbiting objects colliding with each other over the course of a year are almost infinitesimally small. However, given that there are around 5,500 satellites and approximately 900,000 objects of greater than 1 cm in size whizzing above our heads, collisions occur more regularly than you might expect.
Various governments are able to track the larger pieces of space junk. This allows avoidance manoeuvres to take place to shift active satellites and the space station out of harm’s way. But with around 20,000 close approaches per week and growing, this could become an increasingly difficult and costly procedure.
In 2009, two satellites — an 16 year old defunct Russian military satellite and a still active Iridium communications satellite — collided, at a relative velocity of almost 12 km /s. Both satellites shattered into clouds of debris fragments, with over 1,000 pieces larger than a grapefruit in size.
More space junk means a higher chance of collisions occurring. And each collision increases the number of pieces of space junk. This positive feedback loop, if it exceeds the rate at which objects fall into the atmosphere and burn up, could lead to something called the Kessler Syndrome. This is a chain reaction in which collisions become increasingly common, spraying out more and more debris, until placing a satellite in low earth orbit becomes too dangerous to be feasible.
Over the past forty years, DNA evidence has revolutionised the field of forensic investigation. As we go about our daily business, we leave behind us a trail of genetic material, mostly via skin cells and hair. Governments compile huge databases of DNA “profiles”, recording a series of uncorrelated genetic markers.
For some systems, the probability of two people matching on all recorded genetic markers is estimated at one in one trillion (excluding identical twins). Given this number is over 100x the number of people on the planet, if a person’s DNA is found at the scene, you can be pretty sure they were there, right?
Well, not necessarily. Following on from the previous examples, a tiny probability can inflate into something tangible when you have a large enough group of people.
In a country the size of the US (328 million people), a match rate of one in a trillion converts to a 1 in 3,000 chance of you having a genetic profile ‘twin’, somewhere out there. In 2019, there were 16k murders in the US. This means there are likely around 5 murders per year, for which the perpetrator’s DNA matches perfectly with that of another American (again, excluding identical twins). Even with the incredibly low probabilities involved, the power of the Birthday Paradox means that you shouldn’t convict based on DNA evidence alone, and other circumstantial evidence needs to be taken into consideration as well.
It’s worth considering also, that DNA profiling systems have improved greatly in the last thirty years. Earlier in the application of the technology, probabilities of 1 in a billion were often quoted. This would have given around 5,000 murders with a DNA ambiguity.
The Birthday Paradox can be leveraged in a cryptographic attack on digital signatures. Digital signatures rely on something called a hash function f(x), which transforms a message or document into a very large number (hash value). This number is then combined with the signer’s secret key to create a signature. Someone reading the document could then “de-crypt” the signature using the signer’s public key, and this would prove that the signer had digitally signed the document.
These signatures can be used to verify the authenticity of a document. By reading this article on Medium.com, you’re using a digital signature right now, via the HTTPS protocol. The security relies on the difficulty of finding another document with the same hash value as the signed original.
However, the Birthday Paradox lets us potentially abuse this system by attacking this hash function.
Let’s say Bob is an authority that digitally signs contracts. We want to trick Bob into signing a fraudulent contract, without knowing, so that we can later suggest that he approved it. What we need to find are two contracts, one legitimate and one fraudulent, which produce the same hash value when passed through f(x).
For each contract, we can identify many ways of subtly changing it, without altering its meaning. For example, you could add differing amounts of white-space at the end of each line, slightly alter the pixels in a logo, or make small changes to the formatting. In combination this gives us millions of technically different but semantically identical documents, which in Bob’s eyes would all get the stamp of approval. It also gives us millions of variations on the fraudulent document. If we find a pair of documents, one legitimate, one fraudulent, that produce the same hash, then we can pass the legitimate one to Bob for signing, and then use that signature to “prove” the authenticity of the fraudulent contract.
Thanks to the Birthday Paradox, the likelihood of at least one hash value collision between one of the legitimate and one of the fraudulent documents is much higher than might be expected, given the huge range of the hash function. In fact, the number of documents you need to produce is around the square root of the number of possible outputs of the hash function. This is improved by the fact that no hash function is perfectly uniformly distributed, which has led to many popular hashing algorithms becoming insecure. | [
{
"code": null,
"e": 318,
"s": 172,
"text": "If you have a group of people in a room, how many do you need to for it to be more likely than not, that two or more will have the same birthday?"
},
{
"code": null,
"e": 645,
"s": 318,
"text": "Theoretically, the chances of two people having the same birthday are 1 in 365 (not accounting for leap years and the uneven distribution of birthdays across the year), and so odds are you’ll only meet a handful of people in your life who enjoy the same birthday as you. This leads many people to intuitively guess around 180."
},
{
"code": null,
"e": 676,
"s": 645,
"text": "The correct answer is just 23."
},
{
"code": null,
"e": 884,
"s": 676,
"text": "That means in each of your classes at school, amongst the fellow commuters on the bus to work and amongst the players on a soccer field, there are more than likely at least two people with the same birthday."
},
{
"code": null,
"e": 1016,
"s": 884,
"text": "Humans have a notoriously poor intuition when it comes to probability. The multi-billion dollar gambling industry is proof of this."
},
{
"code": null,
"e": 1349,
"s": 1016,
"text": "The source of confusion within the Birthday Paradox is that the probability grows relative to the number of possible pairings of people, not just the group’s size. The number of pairings grows with respect to the square of the number of participants, such that a group of 23 people contains 253 (23 x 22 / 2) unique pairs of people."
},
{
"code": null,
"e": 1622,
"s": 1349,
"text": "In each of these pairings, there is a 364/365 chance of having different birthdays, but this needs to happen for every pair for there to be no matching birthdays across the entire group. Therefore the probability of two people having the same birthday in a group of 23 is:"
},
{
"code": null,
"e": 1649,
"s": 1622,
"text": "1 — (364/365)^253 = 50.05%"
},
{
"code": null,
"e": 1764,
"s": 1649,
"text": "If we plot the probability vs different group sizes, we see how the probability grows as the group size increases."
},
{
"code": null,
"e": 2138,
"s": 1764,
"text": "The line crosses 50% just before a group size of 23. Our previous guess of 180 has a probability so close to 100%, it’s not worth showing. In fact, the chance of choosing a group of 180 people at random, and having none of them share the same birthday, is roughly 6x10^-20 — 100 times less likely than two people picking the same grain of sand out of all the sand on Earth!"
},
{
"code": null,
"e": 2230,
"s": 2138,
"text": "We can generalise the Birthday Paradox to look at other phenomena with a similar structure."
},
{
"code": null,
"e": 2433,
"s": 2230,
"text": "The probability of two people having the same PIN on their bank card is 1 in 10,000, or 0.01%. It would only take a group of 119 people however, to have odds in favour of two people having the same PIN."
},
{
"code": null,
"e": 2747,
"s": 2433,
"text": "Of course, these numbers assume a randomly sampled, uniform distribution of birthdays and PINs. In reality, birthdays peak at certain times of year and people are more likely to pick certain numbers than others for their PIN. But the lack of a uniform distribution in fact reduces the size of group that you need."
},
{
"code": null,
"e": 2963,
"s": 2747,
"text": "If we decrease the probability of a coincidence occurring, the size of group required to get an even chance of a collision obviously increases. However, it increases much more slowly than inverse of the probability."
},
{
"code": null,
"e": 3292,
"s": 2963,
"text": "For example, with a probability of 1 in 10,000, the minimum group size is 119. For a coincidence 10x less likely, the minimum group is 373, or only 3.15 times bigger. Therefore, even for incredibly tiny probabilities, the group size doesn’t grow particularly large. For odds of one in a million, the group required is only 1178."
},
{
"code": null,
"e": 3694,
"s": 3292,
"text": "This has implications in the area of satellite collisions and space junk. The odds of two particular orbiting objects colliding with each other over the course of a year are almost infinitesimally small. However, given that there are around 5,500 satellites and approximately 900,000 objects of greater than 1 cm in size whizzing above our heads, collisions occur more regularly than you might expect."
},
{
"code": null,
"e": 4008,
"s": 3694,
"text": "Various governments are able to track the larger pieces of space junk. This allows avoidance manoeuvres to take place to shift active satellites and the space station out of harm’s way. But with around 20,000 close approaches per week and growing, this could become an increasingly difficult and costly procedure."
},
{
"code": null,
"e": 4307,
"s": 4008,
"text": "In 2009, two satellites — an 16 year old defunct Russian military satellite and a still active Iridium communications satellite — collided, at a relative velocity of almost 12 km /s. Both satellites shattered into clouds of debris fragments, with over 1,000 pieces larger than a grapefruit in size."
},
{
"code": null,
"e": 4786,
"s": 4307,
"text": "More space junk means a higher chance of collisions occurring. And each collision increases the number of pieces of space junk. This positive feedback loop, if it exceeds the rate at which objects fall into the atmosphere and burn up, could lead to something called the Kessler Syndrome. This is a chain reaction in which collisions become increasingly common, spraying out more and more debris, until placing a satellite in low earth orbit becomes too dangerous to be feasible."
},
{
"code": null,
"e": 5103,
"s": 4786,
"text": "Over the past forty years, DNA evidence has revolutionised the field of forensic investigation. As we go about our daily business, we leave behind us a trail of genetic material, mostly via skin cells and hair. Governments compile huge databases of DNA “profiles”, recording a series of uncorrelated genetic markers."
},
{
"code": null,
"e": 5412,
"s": 5103,
"text": "For some systems, the probability of two people matching on all recorded genetic markers is estimated at one in one trillion (excluding identical twins). Given this number is over 100x the number of people on the planet, if a person’s DNA is found at the scene, you can be pretty sure they were there, right?"
},
{
"code": null,
"e": 5577,
"s": 5412,
"text": "Well, not necessarily. Following on from the previous examples, a tiny probability can inflate into something tangible when you have a large enough group of people."
},
{
"code": null,
"e": 6201,
"s": 5577,
"text": "In a country the size of the US (328 million people), a match rate of one in a trillion converts to a 1 in 3,000 chance of you having a genetic profile ‘twin’, somewhere out there. In 2019, there were 16k murders in the US. This means there are likely around 5 murders per year, for which the perpetrator’s DNA matches perfectly with that of another American (again, excluding identical twins). Even with the incredibly low probabilities involved, the power of the Birthday Paradox means that you shouldn’t convict based on DNA evidence alone, and other circumstantial evidence needs to be taken into consideration as well."
},
{
"code": null,
"e": 6467,
"s": 6201,
"text": "It’s worth considering also, that DNA profiling systems have improved greatly in the last thirty years. Earlier in the application of the technology, probabilities of 1 in a billion were often quoted. This would have given around 5,000 murders with a DNA ambiguity."
},
{
"code": null,
"e": 6947,
"s": 6467,
"text": "The Birthday Paradox can be leveraged in a cryptographic attack on digital signatures. Digital signatures rely on something called a hash function f(x), which transforms a message or document into a very large number (hash value). This number is then combined with the signer’s secret key to create a signature. Someone reading the document could then “de-crypt” the signature using the signer’s public key, and this would prove that the signer had digitally signed the document."
},
{
"code": null,
"e": 7240,
"s": 6947,
"text": "These signatures can be used to verify the authenticity of a document. By reading this article on Medium.com, you’re using a digital signature right now, via the HTTPS protocol. The security relies on the difficulty of finding another document with the same hash value as the signed original."
},
{
"code": null,
"e": 7341,
"s": 7240,
"text": "However, the Birthday Paradox lets us potentially abuse this system by attacking this hash function."
},
{
"code": null,
"e": 7662,
"s": 7341,
"text": "Let’s say Bob is an authority that digitally signs contracts. We want to trick Bob into signing a fraudulent contract, without knowing, so that we can later suggest that he approved it. What we need to find are two contracts, one legitimate and one fraudulent, which produce the same hash value when passed through f(x)."
},
{
"code": null,
"e": 8381,
"s": 7662,
"text": "For each contract, we can identify many ways of subtly changing it, without altering its meaning. For example, you could add differing amounts of white-space at the end of each line, slightly alter the pixels in a logo, or make small changes to the formatting. In combination this gives us millions of technically different but semantically identical documents, which in Bob’s eyes would all get the stamp of approval. It also gives us millions of variations on the fraudulent document. If we find a pair of documents, one legitimate, one fraudulent, that produce the same hash, then we can pass the legitimate one to Bob for signing, and then use that signature to “prove” the authenticity of the fraudulent contract."
}
] |
Support Vector Machine (SVM) | Support vector machines (SVMs) are powerful yet flexible supervised machine learning algorithms which are used both for classification and regression. But generally, they are used in classification problems. In 1960s, SVMs were first introduced but later they got refined in 1990. SVMs have their unique way of implementation as compared to other machine learning algorithms. Lately, they are extremely popular because of their ability to handle multiple continuous and categorical variables.
An SVM model is basically a representation of different classes in a hyperplane in multidimensional space. The hyperplane will be generated in an iterative manner by SVM so that the error can be minimized. The goal of SVM is to divide the datasets into classes to find a maximum marginal hyperplane (MMH).
The followings are important concepts in SVM −
Support Vectors − Datapoints that are closest to the hyperplane is called support vectors. Separating line will be defined with the help of these data points.
Support Vectors − Datapoints that are closest to the hyperplane is called support vectors. Separating line will be defined with the help of these data points.
Hyperplane − As we can see in the above diagram, it is a decision plane or space which is divided between a set of objects having different classes.
Hyperplane − As we can see in the above diagram, it is a decision plane or space which is divided between a set of objects having different classes.
Margin − It may be defined as the gap between two lines on the closet data points of different classes. It can be calculated as the perpendicular distance from the line to the support vectors. Large margin is considered as a good margin and small margin is considered as a bad margin.
Margin − It may be defined as the gap between two lines on the closet data points of different classes. It can be calculated as the perpendicular distance from the line to the support vectors. Large margin is considered as a good margin and small margin is considered as a bad margin.
The main goal of SVM is to divide the datasets into classes to find a maximum marginal hyperplane (MMH) and it can be done in the following two steps −
First, SVM will generate hyperplanes iteratively that segregates the classes in best way.
First, SVM will generate hyperplanes iteratively that segregates the classes in best way.
Then, it will choose the hyperplane that separates the classes correctly.
Then, it will choose the hyperplane that separates the classes correctly.
For implementing SVM in Python we will start with the standard libraries import as follows −
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
import seaborn as sns; sns.set()
Next, we are creating a sample dataset, having linearly separable data, from sklearn.dataset.sample_generator for classification using SVM −
from sklearn.datasets.samples_generator import make_blobs
X, y = make_blobs(n_samples=100, centers=2, random_state=0, cluster_std=0.50)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='summer');
The following would be the output after generating sample dataset having 100 samples and 2 clusters −
We know that SVM supports discriminative classification. it divides the classes from each other by simply finding a line in case of two dimensions or manifold in case of multiple dimensions. It is implemented on the above dataset as follows −
xfit = np.linspace(-1, 3.5)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='summer')
plt.plot([0.6], [2.1], 'x', color='black', markeredgewidth=4, markersize=12)
for m, b in [(1, 0.65), (0.5, 1.6), (-0.2, 2.9)]:
plt.plot(xfit, m * xfit + b, '-k')
plt.xlim(-1, 3.5);
The output is as follows −
We can see from the above output that there are three different separators that perfectly discriminate the above samples.
As discussed, the main goal of SVM is to divide the datasets into classes to find a maximum marginal hyperplane (MMH) hence rather than drawing a zero line between classes we can draw around each line a margin of some width up to the nearest point. It can be done as follows −
xfit = np.linspace(-1, 3.5)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='summer')
for m, b, d in [(1, 0.65, 0.33), (0.5, 1.6, 0.55), (-0.2, 2.9, 0.2)]:
yfit = m * xfit + b
plt.plot(xfit, yfit, '-k')
plt.fill_between(xfit, yfit - d, yfit + d, edgecolor='none',
color='#AAAAAA', alpha=0.4)
plt.xlim(-1, 3.5);
From the above image in output, we can easily observe the “margins” within the discriminative classifiers. SVM will choose the line that maximizes the margin.
Next, we will use Scikit-Learn’s support vector classifier to train an SVM model on this data. Here, we are using linear kernel to fit SVM as follows −
from sklearn.svm import SVC # "Support vector classifier"
model = SVC(kernel='linear', C=1E10)
model.fit(X, y)
The output is as follows −
SVC(C=10000000000.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape='ovr', degree=3, gamma='auto_deprecated',
kernel='linear', max_iter=-1, probability=False, random_state=None,
shrinking=True, tol=0.001, verbose=False)
Now, for a better understanding, the following will plot the decision functions for 2D SVC −
def decision_function(model, ax=None, plot_support=True):
if ax is None:
ax = plt.gca()
xlim = ax.get_xlim()
ylim = ax.get_ylim()
For evaluating model, we need to create grid as follows −
x = np.linspace(xlim[0], xlim[1], 30)
y = np.linspace(ylim[0], ylim[1], 30)
Y, X = np.meshgrid(y, x)
xy = np.vstack([X.ravel(), Y.ravel()]).T
P = model.decision_function(xy).reshape(X.shape)
Next, we need to plot decision boundaries and margins as follows −
ax.contour(X, Y, P, colors='k',
levels=[-1, 0, 1], alpha=0.5,
linestyles=['--', '-', '--'])
Now, similarly plot the support vectors as follows −
if plot_support:
ax.scatter(model.support_vectors_[:, 0],
model.support_vectors_[:, 1],
s=300, linewidth=1, facecolors='none');
ax.set_xlim(xlim)
ax.set_ylim(ylim)
Now, use this function to fit our models as follows −
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='summer')
decision_function(model);
We can observe from the above output that an SVM classifier fit to the data with margins i.e. dashed lines and support vectors, the pivotal elements of this fit, touching the dashed line. These support vector points are stored in the support_vectors_ attribute of the classifier as follows −
model.support_vectors_
The output is as follows −
array([[0.5323772 , 3.31338909],
[2.11114739, 3.57660449],
[1.46870582, 1.86947425]])
In practice, SVM algorithm is implemented with kernel that transforms an input data space into the required form. SVM uses a technique called the kernel trick in which kernel takes a low dimensional input space and transforms it into a higher dimensional space. In simple words, kernel converts non-separable problems into separable problems by adding more dimensions to it. It makes SVM more powerful, flexible and accurate. The following are some of the types of kernels used by SVM −
It can be used as a dot product between any two observations. The formula of linear kernel is as below −
k(x,xi) = sum(x*xi)
From the above formula, we can see that the product between two vectors say x & xi is the sum of the multiplication of each pair of input values.
It is more generalized form of linear kernel and distinguish curved or nonlinear input space. Following is the formula for polynomial kernel −
K(x, xi) = 1 + sum(x * xi)^d
Here d is the degree of polynomial, which we need to specify manually in the learning algorithm.
RBF kernel, mostly used in SVM classification, maps input space in indefinite dimensional space. Following formula explains it mathematically −
K(x,xi) = exp(-gamma * sum((x – xi^2))
Here, gamma ranges from 0 to 1. We need to manually specify it in the learning algorithm. A good default value of gamma is 0.1.
As we implemented SVM for linearly separable data, we can implement it in Python for the data that is not linearly separable. It can be done by using kernels.
The following is an example for creating an SVM classifier by using kernels. We will be using iris dataset from scikit-learn −
We will start by importing following packages −
import pandas as pd
import numpy as np
from sklearn import svm, datasets
import matplotlib.pyplot as plt
Now, we need to load the input data −
iris = datasets.load_iris()
From this dataset, we are taking first two features as follows −
X = iris.data[:, :2]
y = iris.target
Next, we will plot the SVM boundaries with original data as follows −
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
h = (x_max / x_min)/100
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
X_plot = np.c_[xx.ravel(), yy.ravel()]
Now, we need to provide the value of regularization parameter as follows −
C = 1.0
Next, SVM classifier object can be created as follows −
Svc_classifier = svm.SVC(kernel='linear', C=C).fit(X, y)
Z = svc_classifier.predict(X_plot)
Z = Z.reshape(xx.shape)
plt.figure(figsize=(15, 5))
plt.subplot(121)
plt.contourf(xx, yy, Z, cmap=plt.cm.tab10, alpha=0.3)
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Set1)
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.xlim(xx.min(), xx.max())
plt.title('Support Vector Classifier with linear kernel')
Text(0.5, 1.0, 'Support Vector Classifier with linear kernel')
For creating SVM classifier with rbf kernel, we can change the kernel to rbf as follows −
Svc_classifier = svm.SVC(kernel='rbf', gamma =‘auto’,C=C).fit(X, y)
Z = svc_classifier.predict(X_plot)
Z = Z.reshape(xx.shape)
plt.figure(figsize=(15, 5))
plt.subplot(121)
plt.contourf(xx, yy, Z, cmap=plt.cm.tab10, alpha=0.3)
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Set1)
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.xlim(xx.min(), xx.max())
plt.title('Support Vector Classifier with rbf kernel')
Text(0.5, 1.0, 'Support Vector Classifier with rbf kernel')
We put the value of gamma to ‘auto’ but you can provide its value between 0 to 1 also.
SVM classifiers offers great accuracy and work well with high dimensional space. SVM classifiers basically use a subset of training points hence in result uses very less memory.
They have high training time hence in practice not suitable for large datasets. Another disadvantage is that SVM classifiers do not work well with overlapping classes.
168 Lectures
13.5 hours
Er. Himanshu Vasishta
64 Lectures
10.5 hours
Eduonix Learning Solutions
91 Lectures
10 hours
Abhilash Nelson
54 Lectures
6 hours
Abhishek And Pukhraj
49 Lectures
5 hours
Abhishek And Pukhraj
35 Lectures
4 hours
Abhishek And Pukhraj
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2797,
"s": 2304,
"text": "Support vector machines (SVMs) are powerful yet flexible supervised machine learning algorithms which are used both for classification and regression. But generally, they are used in classification problems. In 1960s, SVMs were first introduced but later they got refined in 1990. SVMs have their unique way of implementation as compared to other machine learning algorithms. Lately, they are extremely popular because of their ability to handle multiple continuous and categorical variables."
},
{
"code": null,
"e": 3103,
"s": 2797,
"text": "An SVM model is basically a representation of different classes in a hyperplane in multidimensional space. The hyperplane will be generated in an iterative manner by SVM so that the error can be minimized. The goal of SVM is to divide the datasets into classes to find a maximum marginal hyperplane (MMH)."
},
{
"code": null,
"e": 3150,
"s": 3103,
"text": "The followings are important concepts in SVM −"
},
{
"code": null,
"e": 3309,
"s": 3150,
"text": "Support Vectors − Datapoints that are closest to the hyperplane is called support vectors. Separating line will be defined with the help of these data points."
},
{
"code": null,
"e": 3468,
"s": 3309,
"text": "Support Vectors − Datapoints that are closest to the hyperplane is called support vectors. Separating line will be defined with the help of these data points."
},
{
"code": null,
"e": 3617,
"s": 3468,
"text": "Hyperplane − As we can see in the above diagram, it is a decision plane or space which is divided between a set of objects having different classes."
},
{
"code": null,
"e": 3766,
"s": 3617,
"text": "Hyperplane − As we can see in the above diagram, it is a decision plane or space which is divided between a set of objects having different classes."
},
{
"code": null,
"e": 4051,
"s": 3766,
"text": "Margin − It may be defined as the gap between two lines on the closet data points of different classes. It can be calculated as the perpendicular distance from the line to the support vectors. Large margin is considered as a good margin and small margin is considered as a bad margin."
},
{
"code": null,
"e": 4336,
"s": 4051,
"text": "Margin − It may be defined as the gap between two lines on the closet data points of different classes. It can be calculated as the perpendicular distance from the line to the support vectors. Large margin is considered as a good margin and small margin is considered as a bad margin."
},
{
"code": null,
"e": 4488,
"s": 4336,
"text": "The main goal of SVM is to divide the datasets into classes to find a maximum marginal hyperplane (MMH) and it can be done in the following two steps −"
},
{
"code": null,
"e": 4578,
"s": 4488,
"text": "First, SVM will generate hyperplanes iteratively that segregates the classes in best way."
},
{
"code": null,
"e": 4668,
"s": 4578,
"text": "First, SVM will generate hyperplanes iteratively that segregates the classes in best way."
},
{
"code": null,
"e": 4742,
"s": 4668,
"text": "Then, it will choose the hyperplane that separates the classes correctly."
},
{
"code": null,
"e": 4816,
"s": 4742,
"text": "Then, it will choose the hyperplane that separates the classes correctly."
},
{
"code": null,
"e": 4909,
"s": 4816,
"text": "For implementing SVM in Python we will start with the standard libraries import as follows −"
},
{
"code": null,
"e": 5017,
"s": 4909,
"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import stats\nimport seaborn as sns; sns.set()"
},
{
"code": null,
"e": 5158,
"s": 5017,
"text": "Next, we are creating a sample dataset, having linearly separable data, from sklearn.dataset.sample_generator for classification using SVM −"
},
{
"code": null,
"e": 5352,
"s": 5158,
"text": "from sklearn.datasets.samples_generator import make_blobs\nX, y = make_blobs(n_samples=100, centers=2, random_state=0, cluster_std=0.50)\nplt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='summer');\n"
},
{
"code": null,
"e": 5454,
"s": 5352,
"text": "The following would be the output after generating sample dataset having 100 samples and 2 clusters −"
},
{
"code": null,
"e": 5697,
"s": 5454,
"text": "We know that SVM supports discriminative classification. it divides the classes from each other by simply finding a line in case of two dimensions or manifold in case of multiple dimensions. It is implemented on the above dataset as follows −"
},
{
"code": null,
"e": 5968,
"s": 5697,
"text": "xfit = np.linspace(-1, 3.5)\nplt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='summer')\nplt.plot([0.6], [2.1], 'x', color='black', markeredgewidth=4, markersize=12)\nfor m, b in [(1, 0.65), (0.5, 1.6), (-0.2, 2.9)]:\n plt.plot(xfit, m * xfit + b, '-k')\nplt.xlim(-1, 3.5); "
},
{
"code": null,
"e": 5995,
"s": 5968,
"text": "The output is as follows −"
},
{
"code": null,
"e": 6117,
"s": 5995,
"text": "We can see from the above output that there are three different separators that perfectly discriminate the above samples."
},
{
"code": null,
"e": 6394,
"s": 6117,
"text": "As discussed, the main goal of SVM is to divide the datasets into classes to find a maximum marginal hyperplane (MMH) hence rather than drawing a zero line between classes we can draw around each line a margin of some width up to the nearest point. It can be done as follows −"
},
{
"code": null,
"e": 6724,
"s": 6394,
"text": "xfit = np.linspace(-1, 3.5)\nplt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='summer')\n for m, b, d in [(1, 0.65, 0.33), (0.5, 1.6, 0.55), (-0.2, 2.9, 0.2)]:\n yfit = m * xfit + b\n plt.plot(xfit, yfit, '-k')\n plt.fill_between(xfit, yfit - d, yfit + d, edgecolor='none',\n color='#AAAAAA', alpha=0.4)\nplt.xlim(-1, 3.5);"
},
{
"code": null,
"e": 6883,
"s": 6724,
"text": "From the above image in output, we can easily observe the “margins” within the discriminative classifiers. SVM will choose the line that maximizes the margin."
},
{
"code": null,
"e": 7035,
"s": 6883,
"text": "Next, we will use Scikit-Learn’s support vector classifier to train an SVM model on this data. Here, we are using linear kernel to fit SVM as follows −"
},
{
"code": null,
"e": 7146,
"s": 7035,
"text": "from sklearn.svm import SVC # \"Support vector classifier\"\nmodel = SVC(kernel='linear', C=1E10)\nmodel.fit(X, y)"
},
{
"code": null,
"e": 7173,
"s": 7146,
"text": "The output is as follows −"
},
{
"code": null,
"e": 7417,
"s": 7173,
"text": "SVC(C=10000000000.0, cache_size=200, class_weight=None, coef0=0.0,\ndecision_function_shape='ovr', degree=3, gamma='auto_deprecated',\nkernel='linear', max_iter=-1, probability=False, random_state=None,\nshrinking=True, tol=0.001, verbose=False)\n"
},
{
"code": null,
"e": 7510,
"s": 7417,
"text": "Now, for a better understanding, the following will plot the decision functions for 2D SVC −"
},
{
"code": null,
"e": 7655,
"s": 7510,
"text": "def decision_function(model, ax=None, plot_support=True):\n if ax is None:\n ax = plt.gca()\n xlim = ax.get_xlim()\n ylim = ax.get_ylim()"
},
{
"code": null,
"e": 7713,
"s": 7655,
"text": "For evaluating model, we need to create grid as follows −"
},
{
"code": null,
"e": 7905,
"s": 7713,
"text": "x = np.linspace(xlim[0], xlim[1], 30)\ny = np.linspace(ylim[0], ylim[1], 30)\nY, X = np.meshgrid(y, x)\nxy = np.vstack([X.ravel(), Y.ravel()]).T\nP = model.decision_function(xy).reshape(X.shape)\n"
},
{
"code": null,
"e": 7972,
"s": 7905,
"text": "Next, we need to plot decision boundaries and margins as follows −"
},
{
"code": null,
"e": 8071,
"s": 7972,
"text": "ax.contour(X, Y, P, colors='k',\n levels=[-1, 0, 1], alpha=0.5,\n linestyles=['--', '-', '--'])\n"
},
{
"code": null,
"e": 8124,
"s": 8071,
"text": "Now, similarly plot the support vectors as follows −"
},
{
"code": null,
"e": 8303,
"s": 8124,
"text": "if plot_support:\n ax.scatter(model.support_vectors_[:, 0],\n model.support_vectors_[:, 1],\n s=300, linewidth=1, facecolors='none');\nax.set_xlim(xlim)\nax.set_ylim(ylim)"
},
{
"code": null,
"e": 8357,
"s": 8303,
"text": "Now, use this function to fit our models as follows −"
},
{
"code": null,
"e": 8440,
"s": 8357,
"text": "plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='summer')\ndecision_function(model);\n"
},
{
"code": null,
"e": 8732,
"s": 8440,
"text": "We can observe from the above output that an SVM classifier fit to the data with margins i.e. dashed lines and support vectors, the pivotal elements of this fit, touching the dashed line. These support vector points are stored in the support_vectors_ attribute of the classifier as follows −"
},
{
"code": null,
"e": 8756,
"s": 8732,
"text": "model.support_vectors_\n"
},
{
"code": null,
"e": 8783,
"s": 8756,
"text": "The output is as follows −"
},
{
"code": null,
"e": 8876,
"s": 8783,
"text": "array([[0.5323772 , 3.31338909],\n [2.11114739, 3.57660449],\n [1.46870582, 1.86947425]])\n"
},
{
"code": null,
"e": 9363,
"s": 8876,
"text": "In practice, SVM algorithm is implemented with kernel that transforms an input data space into the required form. SVM uses a technique called the kernel trick in which kernel takes a low dimensional input space and transforms it into a higher dimensional space. In simple words, kernel converts non-separable problems into separable problems by adding more dimensions to it. It makes SVM more powerful, flexible and accurate. The following are some of the types of kernels used by SVM −"
},
{
"code": null,
"e": 9468,
"s": 9363,
"text": "It can be used as a dot product between any two observations. The formula of linear kernel is as below −"
},
{
"code": null,
"e": 9488,
"s": 9468,
"text": "k(x,xi) = sum(x*xi)"
},
{
"code": null,
"e": 9634,
"s": 9488,
"text": "From the above formula, we can see that the product between two vectors say x & xi is the sum of the multiplication of each pair of input values."
},
{
"code": null,
"e": 9777,
"s": 9634,
"text": "It is more generalized form of linear kernel and distinguish curved or nonlinear input space. Following is the formula for polynomial kernel −"
},
{
"code": null,
"e": 9806,
"s": 9777,
"text": "K(x, xi) = 1 + sum(x * xi)^d"
},
{
"code": null,
"e": 9903,
"s": 9806,
"text": "Here d is the degree of polynomial, which we need to specify manually in the learning algorithm."
},
{
"code": null,
"e": 10047,
"s": 9903,
"text": "RBF kernel, mostly used in SVM classification, maps input space in indefinite dimensional space. Following formula explains it mathematically −"
},
{
"code": null,
"e": 10086,
"s": 10047,
"text": "K(x,xi) = exp(-gamma * sum((x – xi^2))"
},
{
"code": null,
"e": 10214,
"s": 10086,
"text": "Here, gamma ranges from 0 to 1. We need to manually specify it in the learning algorithm. A good default value of gamma is 0.1."
},
{
"code": null,
"e": 10373,
"s": 10214,
"text": "As we implemented SVM for linearly separable data, we can implement it in Python for the data that is not linearly separable. It can be done by using kernels."
},
{
"code": null,
"e": 10500,
"s": 10373,
"text": "The following is an example for creating an SVM classifier by using kernels. We will be using iris dataset from scikit-learn −"
},
{
"code": null,
"e": 10548,
"s": 10500,
"text": "We will start by importing following packages −"
},
{
"code": null,
"e": 10653,
"s": 10548,
"text": "import pandas as pd\nimport numpy as np\nfrom sklearn import svm, datasets\nimport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 10691,
"s": 10653,
"text": "Now, we need to load the input data −"
},
{
"code": null,
"e": 10720,
"s": 10691,
"text": "iris = datasets.load_iris()\n"
},
{
"code": null,
"e": 10785,
"s": 10720,
"text": "From this dataset, we are taking first two features as follows −"
},
{
"code": null,
"e": 10823,
"s": 10785,
"text": "X = iris.data[:, :2]\ny = iris.target\n"
},
{
"code": null,
"e": 10893,
"s": 10823,
"text": "Next, we will plot the SVM boundaries with original data as follows −"
},
{
"code": null,
"e": 11140,
"s": 10893,
"text": "x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1\ny_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1\nh = (x_max / x_min)/100\nxx, yy = np.meshgrid(np.arange(x_min, x_max, h),\n np.arange(y_min, y_max, h))\nX_plot = np.c_[xx.ravel(), yy.ravel()]"
},
{
"code": null,
"e": 11215,
"s": 11140,
"text": "Now, we need to provide the value of regularization parameter as follows −"
},
{
"code": null,
"e": 11224,
"s": 11215,
"text": "C = 1.0\n"
},
{
"code": null,
"e": 11280,
"s": 11224,
"text": "Next, SVM classifier object can be created as follows −"
},
{
"code": null,
"e": 11337,
"s": 11280,
"text": "Svc_classifier = svm.SVC(kernel='linear', C=C).fit(X, y)"
},
{
"code": null,
"e": 11689,
"s": 11337,
"text": "Z = svc_classifier.predict(X_plot)\nZ = Z.reshape(xx.shape)\nplt.figure(figsize=(15, 5))\nplt.subplot(121)\nplt.contourf(xx, yy, Z, cmap=plt.cm.tab10, alpha=0.3)\nplt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Set1)\nplt.xlabel('Sepal length')\nplt.ylabel('Sepal width')\nplt.xlim(xx.min(), xx.max())\nplt.title('Support Vector Classifier with linear kernel')\n"
},
{
"code": null,
"e": 11753,
"s": 11689,
"text": "Text(0.5, 1.0, 'Support Vector Classifier with linear kernel')\n"
},
{
"code": null,
"e": 11843,
"s": 11753,
"text": "For creating SVM classifier with rbf kernel, we can change the kernel to rbf as follows −"
},
{
"code": null,
"e": 12259,
"s": 11843,
"text": "Svc_classifier = svm.SVC(kernel='rbf', gamma =‘auto’,C=C).fit(X, y)\nZ = svc_classifier.predict(X_plot)\nZ = Z.reshape(xx.shape)\nplt.figure(figsize=(15, 5))\nplt.subplot(121)\nplt.contourf(xx, yy, Z, cmap=plt.cm.tab10, alpha=0.3)\nplt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Set1)\nplt.xlabel('Sepal length')\nplt.ylabel('Sepal width')\nplt.xlim(xx.min(), xx.max())\nplt.title('Support Vector Classifier with rbf kernel')"
},
{
"code": null,
"e": 12320,
"s": 12259,
"text": "Text(0.5, 1.0, 'Support Vector Classifier with rbf kernel')\n"
},
{
"code": null,
"e": 12407,
"s": 12320,
"text": "We put the value of gamma to ‘auto’ but you can provide its value between 0 to 1 also."
},
{
"code": null,
"e": 12585,
"s": 12407,
"text": "SVM classifiers offers great accuracy and work well with high dimensional space. SVM classifiers basically use a subset of training points hence in result uses very less memory."
},
{
"code": null,
"e": 12753,
"s": 12585,
"text": "They have high training time hence in practice not suitable for large datasets. Another disadvantage is that SVM classifiers do not work well with overlapping classes."
},
{
"code": null,
"e": 12790,
"s": 12753,
"text": "\n 168 Lectures \n 13.5 hours \n"
},
{
"code": null,
"e": 12813,
"s": 12790,
"text": " Er. Himanshu Vasishta"
},
{
"code": null,
"e": 12849,
"s": 12813,
"text": "\n 64 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 12877,
"s": 12849,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 12911,
"s": 12877,
"text": "\n 91 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 12928,
"s": 12911,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 12961,
"s": 12928,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 12983,
"s": 12961,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 13016,
"s": 12983,
"text": "\n 49 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 13038,
"s": 13016,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 13071,
"s": 13038,
"text": "\n 35 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 13093,
"s": 13071,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 13100,
"s": 13093,
"text": " Print"
},
{
"code": null,
"e": 13111,
"s": 13100,
"text": " Add Notes"
}
] |
How to get data from 2 different collections of mongoDB using Node.js ? - GeeksforGeeks | 22 Jun, 2021
Mongoose is an Object Data Modeling (ODM) library for MongoDB. It defines a strongly-typed-schema, with default values and schema validations which are later mapped to a MongoDB document.
For getting data from a collection with Mongoose in NodeJS you have to have two necessary things:
Schema: It is a document structure that contains the property with its types (default value, validations, etc. when required) as a key-value pair.Model: It is a class created with the help of defined Schema and a MongoDB document is an instance of Model. Therefore, it acts as an interface for the MongoDB database for creating, reading, updating, and deleting a document.
Schema: It is a document structure that contains the property with its types (default value, validations, etc. when required) as a key-value pair.
Model: It is a class created with the help of defined Schema and a MongoDB document is an instance of Model. Therefore, it acts as an interface for the MongoDB database for creating, reading, updating, and deleting a document.
After having a model, we can use method find() on the model of a particular collection to get documents of the collection.
Syntax:
<Model_Name>.find(<query>,<projection>)
<query>: It is optional. It specifies a selection filter that is used to filter documents using various MongoDB query operators. If not passed, all the documents are returned.
<projection>: It is optional. It contains fields that we want to be returned to the documents that match the query filter. If not passed, all the fields are returned.
Install Mongoose:
Step 1: You can visit the link Install mongoose to install the mongoose module. You can install this package by using this command.
npm install mongoose
Step 2: Now you can import the mongoose module in your file using:
const mongoose = require('mongoose');
Implementation:
Step 1: Create a folder and add model.js and main.js files into it.
model.js: It contains schemas and models for all the collections you want to use, and then we are exporting all the models created so that they can be imported into the file in which we will get data from different collections.
main.js: It is the main server file here we will get data from two different collections.
Step 2: Write down the following code in the model.js file.
model.js
// Requiring moduleconst mongoose = require('mongoose'); // Course Modal Schemaconst courseSchema = new mongoose.Schema({ _id: Number, name: String, category: String}); // Student Modal Schemaconst studentSchema = new mongoose.Schema({ name: String, enroll: Number, courseId: Number}); // Creating model objectsconst Course = mongoose.model('course', courseSchema);const Student = mongoose.model('student', studentSchema); // Exporting our model objectsmodule.exports = { Student, Course}
Database: We already have documents in our Courses and Students collections from which we are going to get data as shown below:
Collections Courses and Students in Database GFG
Step 3: Database connection can be easily established using mongoose like:
mongoose.connect('mongodb://localhost:27017/GFG',
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
});
Step 4: Write down the following code in the main.js file.
main.js
// Requiring mongoose moduleconst mongoose = require('mongoose'); // Importing Models Student and Course from model.jsconst { Student, Course } = require('./model'); // Connecting to databasemongoose.connect('mongodb://localhost:27017/GFG', { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false }); var dbcourse = []; // Finding courses of category DatabaseCourse.find({ category: "Database" }) .then(data => { console.log("Database Courses:") console.log(data); // Putting all course id's in dbcourse arrray data.map((d, k) => { dbcourse.push(d._id); }) // Getting students who are enrolled in any // database course by filtering students // whose courseId matches with any id in // dbcourse array Student.find({ courseId: { $in: dbcourse } }) .then(data => { console.log("Students in Database Courses:") console.log(data); }) .catch(error => { console.log(error); }) }) .catch(error => { console.log(error); })
Step 5: Run main.js file using the below command:
node main.js
Explanation: In the above code, in the file main.js, we are getting all the documents of Course collection whose category is Database then storing _id of each course in dbcourse array then getting all the documents from the Student collection whose is enrolled in any course of category Database.
Output: We are getting data from two different collections Courses and Students in the console shown below:
Output after executing main.js
Mongoose
Node.js-Methods
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to build a basic CRUD app with Node.js and ReactJS ?
How to connect Node.js with React.js ?
Mongoose Populate() Method
Express.js req.params Property
How to Convert CSV to JSON file having Comma Separated values in Node.js ?
Top 10 Front End Developer Skills That You Need in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 24557,
"s": 24529,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 24745,
"s": 24557,
"text": "Mongoose is an Object Data Modeling (ODM) library for MongoDB. It defines a strongly-typed-schema, with default values and schema validations which are later mapped to a MongoDB document."
},
{
"code": null,
"e": 24843,
"s": 24745,
"text": "For getting data from a collection with Mongoose in NodeJS you have to have two necessary things:"
},
{
"code": null,
"e": 25216,
"s": 24843,
"text": "Schema: It is a document structure that contains the property with its types (default value, validations, etc. when required) as a key-value pair.Model: It is a class created with the help of defined Schema and a MongoDB document is an instance of Model. Therefore, it acts as an interface for the MongoDB database for creating, reading, updating, and deleting a document."
},
{
"code": null,
"e": 25363,
"s": 25216,
"text": "Schema: It is a document structure that contains the property with its types (default value, validations, etc. when required) as a key-value pair."
},
{
"code": null,
"e": 25590,
"s": 25363,
"text": "Model: It is a class created with the help of defined Schema and a MongoDB document is an instance of Model. Therefore, it acts as an interface for the MongoDB database for creating, reading, updating, and deleting a document."
},
{
"code": null,
"e": 25713,
"s": 25590,
"text": "After having a model, we can use method find() on the model of a particular collection to get documents of the collection."
},
{
"code": null,
"e": 25722,
"s": 25713,
"text": "Syntax: "
},
{
"code": null,
"e": 25762,
"s": 25722,
"text": "<Model_Name>.find(<query>,<projection>)"
},
{
"code": null,
"e": 25938,
"s": 25762,
"text": "<query>: It is optional. It specifies a selection filter that is used to filter documents using various MongoDB query operators. If not passed, all the documents are returned."
},
{
"code": null,
"e": 26105,
"s": 25938,
"text": "<projection>: It is optional. It contains fields that we want to be returned to the documents that match the query filter. If not passed, all the fields are returned."
},
{
"code": null,
"e": 26125,
"s": 26107,
"text": "Install Mongoose:"
},
{
"code": null,
"e": 26257,
"s": 26125,
"text": "Step 1: You can visit the link Install mongoose to install the mongoose module. You can install this package by using this command."
},
{
"code": null,
"e": 26278,
"s": 26257,
"text": "npm install mongoose"
},
{
"code": null,
"e": 26345,
"s": 26278,
"text": "Step 2: Now you can import the mongoose module in your file using:"
},
{
"code": null,
"e": 26383,
"s": 26345,
"text": "const mongoose = require('mongoose');"
},
{
"code": null,
"e": 26399,
"s": 26383,
"text": "Implementation:"
},
{
"code": null,
"e": 26467,
"s": 26399,
"text": "Step 1: Create a folder and add model.js and main.js files into it."
},
{
"code": null,
"e": 26695,
"s": 26467,
"text": "model.js: It contains schemas and models for all the collections you want to use, and then we are exporting all the models created so that they can be imported into the file in which we will get data from different collections."
},
{
"code": null,
"e": 26785,
"s": 26695,
"text": "main.js: It is the main server file here we will get data from two different collections."
},
{
"code": null,
"e": 26845,
"s": 26785,
"text": "Step 2: Write down the following code in the model.js file."
},
{
"code": null,
"e": 26854,
"s": 26845,
"text": "model.js"
},
{
"code": "// Requiring moduleconst mongoose = require('mongoose'); // Course Modal Schemaconst courseSchema = new mongoose.Schema({ _id: Number, name: String, category: String}); // Student Modal Schemaconst studentSchema = new mongoose.Schema({ name: String, enroll: Number, courseId: Number}); // Creating model objectsconst Course = mongoose.model('course', courseSchema);const Student = mongoose.model('student', studentSchema); // Exporting our model objectsmodule.exports = { Student, Course}",
"e": 27377,
"s": 26854,
"text": null
},
{
"code": null,
"e": 27505,
"s": 27377,
"text": "Database: We already have documents in our Courses and Students collections from which we are going to get data as shown below:"
},
{
"code": null,
"e": 27554,
"s": 27505,
"text": "Collections Courses and Students in Database GFG"
},
{
"code": null,
"e": 27629,
"s": 27554,
"text": "Step 3: Database connection can be easily established using mongoose like:"
},
{
"code": null,
"e": 27770,
"s": 27629,
"text": "mongoose.connect('mongodb://localhost:27017/GFG',\n{ \n useNewUrlParser: true, \n useUnifiedTopology: true, \n useFindAndModify: false\n});"
},
{
"code": null,
"e": 27829,
"s": 27770,
"text": "Step 4: Write down the following code in the main.js file."
},
{
"code": null,
"e": 27837,
"s": 27829,
"text": "main.js"
},
{
"code": "// Requiring mongoose moduleconst mongoose = require('mongoose'); // Importing Models Student and Course from model.jsconst { Student, Course } = require('./model'); // Connecting to databasemongoose.connect('mongodb://localhost:27017/GFG', { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false }); var dbcourse = []; // Finding courses of category DatabaseCourse.find({ category: \"Database\" }) .then(data => { console.log(\"Database Courses:\") console.log(data); // Putting all course id's in dbcourse arrray data.map((d, k) => { dbcourse.push(d._id); }) // Getting students who are enrolled in any // database course by filtering students // whose courseId matches with any id in // dbcourse array Student.find({ courseId: { $in: dbcourse } }) .then(data => { console.log(\"Students in Database Courses:\") console.log(data); }) .catch(error => { console.log(error); }) }) .catch(error => { console.log(error); })",
"e": 28995,
"s": 27837,
"text": null
},
{
"code": null,
"e": 29045,
"s": 28995,
"text": "Step 5: Run main.js file using the below command:"
},
{
"code": null,
"e": 29058,
"s": 29045,
"text": "node main.js"
},
{
"code": null,
"e": 29355,
"s": 29058,
"text": "Explanation: In the above code, in the file main.js, we are getting all the documents of Course collection whose category is Database then storing _id of each course in dbcourse array then getting all the documents from the Student collection whose is enrolled in any course of category Database."
},
{
"code": null,
"e": 29463,
"s": 29355,
"text": "Output: We are getting data from two different collections Courses and Students in the console shown below:"
},
{
"code": null,
"e": 29494,
"s": 29463,
"text": "Output after executing main.js"
},
{
"code": null,
"e": 29503,
"s": 29494,
"text": "Mongoose"
},
{
"code": null,
"e": 29519,
"s": 29503,
"text": "Node.js-Methods"
},
{
"code": null,
"e": 29536,
"s": 29519,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 29543,
"s": 29536,
"text": "Picked"
},
{
"code": null,
"e": 29551,
"s": 29543,
"text": "Node.js"
},
{
"code": null,
"e": 29568,
"s": 29551,
"text": "Web Technologies"
},
{
"code": null,
"e": 29666,
"s": 29568,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29675,
"s": 29666,
"text": "Comments"
},
{
"code": null,
"e": 29688,
"s": 29675,
"text": "Old Comments"
},
{
"code": null,
"e": 29745,
"s": 29688,
"text": "How to build a basic CRUD app with Node.js and ReactJS ?"
},
{
"code": null,
"e": 29784,
"s": 29745,
"text": "How to connect Node.js with React.js ?"
},
{
"code": null,
"e": 29811,
"s": 29784,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 29842,
"s": 29811,
"text": "Express.js req.params Property"
},
{
"code": null,
"e": 29917,
"s": 29842,
"text": "How to Convert CSV to JSON file having Comma Separated values in Node.js ?"
},
{
"code": null,
"e": 29973,
"s": 29917,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 30035,
"s": 29973,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 30078,
"s": 30035,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 30128,
"s": 30078,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Table Variable in SQL Server | 24 Sep, 2020
Table variable is a type of local variable that used to store data temporarily, similar to the temp table in SQL Server. Tempdb database is used to store table variables.
To declare a table variable, start the DECLARE statement. The name of table variable must start with at(@) sign. The TABLE keyword defines that used variable is a table variable. After the TABLE keyword, define column names and datatypes of the table variable in SQL Server.
Syntax :
DECLARE @TABLEVARIABLE TABLE
(column1 datatype,
column2 datatype,
columnN datatype
)
Example-1 :DECLARE @WeekDays TABLE (Number INT, Day VARCHAR(40), Name VARCHAR(40))
INSERT INTO @WeekDays
VALUES
(1, 'Mon', 'Monday'),
(2, 'Tue', 'Tuesday'),
(3, 'Wed', 'Wednesday'),
(4, 'Thu', 'Thursday'),
(5, 'Fri', 'Friday'),
(6, 'Sat', 'Saturday'),
(7, 'Sun', 'Sunday')
SELECT * FROM @WeekDays;
Update and delete statement usage for table variable in SQL Server
Here we will update and delete the data in the table variables.
Example-2 :
DELETE @WeekDays WHERE Number=7;
UPDATE @WeekDays SET Name='Saturday is a holiday' WHERE Number=6 ;
SELECT * FROM @WeekDays;
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Sep, 2020"
},
{
"code": null,
"e": 199,
"s": 28,
"text": "Table variable is a type of local variable that used to store data temporarily, similar to the temp table in SQL Server. Tempdb database is used to store table variables."
},
{
"code": null,
"e": 474,
"s": 199,
"text": "To declare a table variable, start the DECLARE statement. The name of table variable must start with at(@) sign. The TABLE keyword defines that used variable is a table variable. After the TABLE keyword, define column names and datatypes of the table variable in SQL Server."
},
{
"code": null,
"e": 483,
"s": 474,
"text": "Syntax :"
},
{
"code": null,
"e": 572,
"s": 483,
"text": "DECLARE @TABLEVARIABLE TABLE\n(column1 datatype, \ncolumn2 datatype, \ncolumnN datatype\n)"
},
{
"code": null,
"e": 655,
"s": 572,
"text": "Example-1 :DECLARE @WeekDays TABLE (Number INT, Day VARCHAR(40), Name VARCHAR(40))"
},
{
"code": null,
"e": 847,
"s": 655,
"text": "INSERT INTO @WeekDays\nVALUES\n\n(1, 'Mon', 'Monday'),\n(2, 'Tue', 'Tuesday'),\n(3, 'Wed', 'Wednesday'),\n(4, 'Thu', 'Thursday'),\n(5, 'Fri', 'Friday'),\n(6, 'Sat', 'Saturday'),\n(7, 'Sun', 'Sunday')\n"
},
{
"code": null,
"e": 872,
"s": 847,
"text": "SELECT * FROM @WeekDays;"
},
{
"code": null,
"e": 939,
"s": 872,
"text": "Update and delete statement usage for table variable in SQL Server"
},
{
"code": null,
"e": 1003,
"s": 939,
"text": "Here we will update and delete the data in the table variables."
},
{
"code": null,
"e": 1015,
"s": 1003,
"text": "Example-2 :"
},
{
"code": null,
"e": 1142,
"s": 1015,
"text": "DELETE @WeekDays WHERE Number=7;\n\nUPDATE @WeekDays SET Name='Saturday is a holiday' WHERE Number=6 ;\nSELECT * FROM @WeekDays;\n"
},
{
"code": null,
"e": 1151,
"s": 1142,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 1162,
"s": 1151,
"text": "SQL-Server"
},
{
"code": null,
"e": 1166,
"s": 1162,
"text": "SQL"
},
{
"code": null,
"e": 1170,
"s": 1166,
"text": "SQL"
}
] |
Remove Trailing Zeros From string in C++ | 31 May, 2017
Given a string of digits, remove trailing zeros from it.
Examples:
Input : 00000123569
Output : 123569
Input : 000012356090
Output : 12356090
1) Count trailing zeros.2) Use string erase function to remove characters equal to above count.
Below is C++ implementation.
// C++ program to remove trailing/preceding zeros// from a given string#include<iostream>using namespace std; string removeZero(string str){ // Count trailing zeros int i = 0; while (str[i] == '0') i++; // The erase function removes i characters // from given index (0 here) str.erase(0, i); return str;} // Driver codeint main(){ string str; str = "00000123569"; str = removeZero(str); cout << str << endl; return 0;}
Output :
123569
This article is contributed by Prakhar Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
cpp-string
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Substring in C++
unordered_map in C++ STL
Priority Queue in C++ Standard Template Library (STL)
The C++ Standard Template Library (STL)
Sorting a vector in C++
2D Vector In C++ With User Defined Size
C++ Data Types | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n31 May, 2017"
},
{
"code": null,
"e": 111,
"s": 54,
"text": "Given a string of digits, remove trailing zeros from it."
},
{
"code": null,
"e": 121,
"s": 111,
"text": "Examples:"
},
{
"code": null,
"e": 198,
"s": 121,
"text": "Input : 00000123569\nOutput : 123569\n\nInput : 000012356090\nOutput : 12356090\n"
},
{
"code": null,
"e": 294,
"s": 198,
"text": "1) Count trailing zeros.2) Use string erase function to remove characters equal to above count."
},
{
"code": null,
"e": 323,
"s": 294,
"text": "Below is C++ implementation."
},
{
"code": "// C++ program to remove trailing/preceding zeros// from a given string#include<iostream>using namespace std; string removeZero(string str){ // Count trailing zeros int i = 0; while (str[i] == '0') i++; // The erase function removes i characters // from given index (0 here) str.erase(0, i); return str;} // Driver codeint main(){ string str; str = \"00000123569\"; str = removeZero(str); cout << str << endl; return 0;}",
"e": 790,
"s": 323,
"text": null
},
{
"code": null,
"e": 799,
"s": 790,
"text": "Output :"
},
{
"code": null,
"e": 806,
"s": 799,
"text": "123569"
},
{
"code": null,
"e": 1109,
"s": 806,
"text": "This article is contributed by Prakhar Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 1234,
"s": 1109,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 1245,
"s": 1234,
"text": "cpp-string"
},
{
"code": null,
"e": 1249,
"s": 1245,
"text": "C++"
},
{
"code": null,
"e": 1253,
"s": 1249,
"text": "CPP"
},
{
"code": null,
"e": 1351,
"s": 1253,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1378,
"s": 1351,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 1421,
"s": 1378,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1455,
"s": 1421,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 1472,
"s": 1455,
"text": "Substring in C++"
},
{
"code": null,
"e": 1497,
"s": 1472,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 1551,
"s": 1497,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1591,
"s": 1551,
"text": "The C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1615,
"s": 1591,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 1655,
"s": 1615,
"text": "2D Vector In C++ With User Defined Size"
}
] |
GATE | GATE CS 2008 | Question 41 | 28 Jun, 2021
A B-tree of order 4 is built from scratch by 10 successive insertions. What is the maximum number of node splitting operations that may take place?(A) 3(B) 4(C) 5(D) 6Answer: (C)Explanation:
Insertion of 3 keys
10 20 30
Insertion of 4th key (1st split)
30
/ \
10*20 40
Insertion of 5th key no split
To maximize splits, let us insert a value in a node that has
key in access. Let us insert 5
30
/ \
5*10*20 40
Insertion of 6th key (2nd Split)
To maximize splits, let us insert a value in a node that has
key in access. Let us insert 6
8*30
/ | \
5 10*20 40
Insertion of 7th key
To maximize splits, let us insert a value in a node that has
key in access. Let us insert 15
8*30
/ | \
5 10*15*20 40
Insertion of 8th key (3rd Split)
To maximize splits, let us insert a value in a node that has
key in access. Let us insert 12
8*12*30
/ / \ \
5 10 15*20 40
Insertion of 9th key
To maximize splits, let us insert a value in a node that has
key in access. Let us insert 17
8*12*30
/ / \ \
5 10 15*17*20 40
Insertion of 10th key (4th and 5th Splits)
To maximize splits, let us insert a value in a node that has
key in access. Let us insert 13
12
/ \
8 15*30
/ \ / | \
5 10 13 17*20 40
Quiz of this Question
GATE-CS-2008
GATE-GATE CS 2008
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 245,
"s": 54,
"text": "A B-tree of order 4 is built from scratch by 10 successive insertions. What is the maximum number of node splitting operations that may take place?(A) 3(B) 4(C) 5(D) 6Answer: (C)Explanation:"
},
{
"code": null,
"e": 1407,
"s": 245,
"text": "Insertion of 3 keys\n10 20 30\n\nInsertion of 4th key (1st split)\n 30\n / \\\n10*20 40\n\n\nInsertion of 5th key no split \nTo maximize splits, let us insert a value in a node that has\nkey in access. Let us insert 5\n 30\n / \\\n5*10*20 40\n\n\nInsertion of 6th key (2nd Split)\nTo maximize splits, let us insert a value in a node that has\nkey in access. Let us insert 6\n 8*30\n / | \\\n5 10*20 40 \n\n\nInsertion of 7th key\nTo maximize splits, let us insert a value in a node that has\nkey in access. Let us insert 15\n 8*30\n / | \\\n5 10*15*20 40 \n\n\n\nInsertion of 8th key (3rd Split)\nTo maximize splits, let us insert a value in a node that has\nkey in access. Let us insert 12\n 8*12*30\n / / \\ \\\n 5 10 15*20 40 \n\n\nInsertion of 9th key \nTo maximize splits, let us insert a value in a node that has\nkey in access. Let us insert 17\n 8*12*30\n / / \\ \\\n5 10 15*17*20 40 \n\nInsertion of 10th key (4th and 5th Splits)\nTo maximize splits, let us insert a value in a node that has\nkey in access. Let us insert 13\n 12\n / \\\n 8 15*30\n / \\ / | \\ \n 5 10 13 17*20 40 \n"
},
{
"code": null,
"e": 1429,
"s": 1407,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 1442,
"s": 1429,
"text": "GATE-CS-2008"
},
{
"code": null,
"e": 1460,
"s": 1442,
"text": "GATE-GATE CS 2008"
},
{
"code": null,
"e": 1465,
"s": 1460,
"text": "GATE"
}
] |
How to get the path of current script in R ? | 30 May, 2021
In this article, we will see how to determine the path of the current script in R Programming Language.
If we want to check the current directory of the R script, we can use getwd( ) function. For getwd( ), no need to pass any parameters. If we run this function we will get the current working directory or current path of the R script. To change the current working directory we need to use a function called setwd( ). We need to pass the path as a parameter.
syntax : getwd( )
Example :
R
getwd()
Output :
To use the functions of rstudioapi we need to install this package first. To install this package type the below command in the terminal.
install.packages(rstudioapi)
From rstudioapi package we need to use getSourceEditorConext(). It’s like a list. We need to retrieve the path from it. So we need to use $ operator along with getSourceEditorConext(). Before executing this we need to save the R script with some name and with .R extension. Then run the below code for getting the current path of R script.
Example :
R
# importing rstudioapi packagelibrary("rstudioapi") # retrieving path from getSourceEditorContext() # using $ operator getSourceEditorContext()$path
Output :
In the here library we are going to use here( ) function. This function determines the path of the current R script. No need to pass any parameters. Just import the library using the library( ) function. If the package is not available, install using install.packages( ) function by passing package name as parameter within quotations. After installing package, call here( ) function.
Syntax : here( )
Example :
R
library("here") here()
Output :
Picked
R directory-programs
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 May, 2021"
},
{
"code": null,
"e": 132,
"s": 28,
"text": "In this article, we will see how to determine the path of the current script in R Programming Language."
},
{
"code": null,
"e": 490,
"s": 132,
"text": "If we want to check the current directory of the R script, we can use getwd( ) function. For getwd( ), no need to pass any parameters. If we run this function we will get the current working directory or current path of the R script. To change the current working directory we need to use a function called setwd( ). We need to pass the path as a parameter."
},
{
"code": null,
"e": 509,
"s": 490,
"text": "syntax : getwd( ) "
},
{
"code": null,
"e": 519,
"s": 509,
"text": "Example :"
},
{
"code": null,
"e": 521,
"s": 519,
"text": "R"
},
{
"code": "getwd()",
"e": 529,
"s": 521,
"text": null
},
{
"code": null,
"e": 538,
"s": 529,
"text": "Output :"
},
{
"code": null,
"e": 676,
"s": 538,
"text": "To use the functions of rstudioapi we need to install this package first. To install this package type the below command in the terminal."
},
{
"code": null,
"e": 705,
"s": 676,
"text": "install.packages(rstudioapi)"
},
{
"code": null,
"e": 1045,
"s": 705,
"text": "From rstudioapi package we need to use getSourceEditorConext(). It’s like a list. We need to retrieve the path from it. So we need to use $ operator along with getSourceEditorConext(). Before executing this we need to save the R script with some name and with .R extension. Then run the below code for getting the current path of R script."
},
{
"code": null,
"e": 1056,
"s": 1045,
"text": "Example : "
},
{
"code": null,
"e": 1058,
"s": 1056,
"text": "R"
},
{
"code": "# importing rstudioapi packagelibrary(\"rstudioapi\") # retrieving path from getSourceEditorContext() # using $ operator getSourceEditorContext()$path ",
"e": 1210,
"s": 1058,
"text": null
},
{
"code": null,
"e": 1219,
"s": 1210,
"text": "Output :"
},
{
"code": null,
"e": 1605,
"s": 1219,
"text": "In the here library we are going to use here( ) function. This function determines the path of the current R script. No need to pass any parameters. Just import the library using the library( ) function. If the package is not available, install using install.packages( ) function by passing package name as parameter within quotations. After installing package, call here( ) function. "
},
{
"code": null,
"e": 1622,
"s": 1605,
"text": "Syntax : here( )"
},
{
"code": null,
"e": 1632,
"s": 1622,
"text": "Example :"
},
{
"code": null,
"e": 1634,
"s": 1632,
"text": "R"
},
{
"code": "library(\"here\") here()",
"e": 1658,
"s": 1634,
"text": null
},
{
"code": null,
"e": 1667,
"s": 1658,
"text": "Output :"
},
{
"code": null,
"e": 1674,
"s": 1667,
"text": "Picked"
},
{
"code": null,
"e": 1695,
"s": 1674,
"text": "R directory-programs"
},
{
"code": null,
"e": 1706,
"s": 1695,
"text": "R Language"
}
] |
PHP Multidimensional Array. | A multidimensional array in PHP an be treated as an array of arrays so that each element within the array is an array itself. Inner elements of a multi dimensional array may be associative or indexed.
Although arrays can be nested upto any levels, two dimensional array with more than one dimensional arrays inside outermost is of realistic use
//two dimensional associative array
twodim = array(
"row1"=>array(k1=>v1,k2=>v2,k3=>v3),
"row2"=>array(k4=>v4,k5=>v5,k6=>v6)
)
//two dimensional indexed array
twodim=array(
array(v1,v2,v3),
array(v4,v5,v6)
)
In case of indexed two dimensional array, we can access an element from the array by its index with following syntax:
$arr[row][column];
Use of square brackets for assignment of array is available since PHP 5.4
Following example shows indexed 2D array in which each element is an indexed array
Live Demo
<?php
$arrs=array(
array(1,2,3,4,5),
array(11,22,33,44,55),
);
foreach ($arrs as $arr){
foreach ($arr as $i){
echo $i . " ";
}
echo "\n";
}
$cols=count($arrs[0]);
$rows=count($arrs);
for ($i=0; $i<$rows; $i++){
for ($j=0;$j<$cols;$j++){
echo $arrs[$i][$j] . " ";
}
echo "\n";
}
?>
This will produce following result −
1 2 3 4 5
11 22 33 44 55
1 2 3 4 5
11 22 33 44 55
Following example has indexed 2D array whaving associative arrays as element
Live Demo
<?php
$arrs=array(
array(1=>100, 2=>200, 3=>300),
array(1=>'aa', 2=>'bb', 3=>'cc'),
);
foreach ($arrs as $arr){
foreach ($arr as $i=>$j){
echo $i . "->" .$j . " ";
}
echo "\n";
}
for ($row=0; $row < count($arrs); $row++){
foreach ($arrs[$row] as $i=>$j){
echo $i . "->" .$j . " ";
}
echo "\n";
}
?>
This will produce following result −
1->100 2->200 3->300
1->aa 2->bb 3->cc
1->100 2->200 3->300
1->aa 2->bb 3->cc
}
In following example we have an associative two dimensional array:
Live Demo
<?php
$arr1=array("rno"=>11,"marks"=>50);
$arr2=array("rno"=>22,"marks"=>60);
$arrs=array(
"Manav"=>$arr1,
"Ravi"=>$arr2
);
foreach ($arrs as $key=>$val){
echo "name : " . $key . " ";
foreach ($val as $i=>$j){
echo $i . "->" .$j . " ";
}
echo "\n";
}
?>
This will produce following result −
name : Manav rno->11 marks->50
name : Ravi rno->22 marks->60
This Example has associative array with each value as indexed array
Live Demo
<?php
$arr1=array("PHP","Java","Python");
$arr2=array("Oracle","MySQL","SQLite");
$arrs=array(
"Langs"=>$arr1,
"DB"=>$arr2
);
foreach ($arrs as $key=>$val){
echo $key . ": ";
for ($i=0; $i < count($val); $i++){
echo $val[$i] . " ";
}
echo "\n";
}
?>
This will produce following result −
Langs: PHP Java Python
DB: Oracle MySQL SQLite | [
{
"code": null,
"e": 1388,
"s": 1187,
"text": "A multidimensional array in PHP an be treated as an array of arrays so that each element within the array is an array itself. Inner elements of a multi dimensional array may be associative or indexed."
},
{
"code": null,
"e": 1532,
"s": 1388,
"text": "Although arrays can be nested upto any levels, two dimensional array with more than one dimensional arrays inside outermost is of realistic use"
},
{
"code": null,
"e": 1752,
"s": 1532,
"text": "//two dimensional associative array\ntwodim = array(\n \"row1\"=>array(k1=>v1,k2=>v2,k3=>v3),\n \"row2\"=>array(k4=>v4,k5=>v5,k6=>v6)\n)\n//two dimensional indexed array\ntwodim=array(\n array(v1,v2,v3),\n array(v4,v5,v6)\n)"
},
{
"code": null,
"e": 1870,
"s": 1752,
"text": "In case of indexed two dimensional array, we can access an element from the array by its index with following syntax:"
},
{
"code": null,
"e": 1889,
"s": 1870,
"text": "$arr[row][column];"
},
{
"code": null,
"e": 1963,
"s": 1889,
"text": "Use of square brackets for assignment of array is available since PHP 5.4"
},
{
"code": null,
"e": 2046,
"s": 1963,
"text": "Following example shows indexed 2D array in which each element is an indexed array"
},
{
"code": null,
"e": 2057,
"s": 2046,
"text": " Live Demo"
},
{
"code": null,
"e": 2374,
"s": 2057,
"text": "<?php\n$arrs=array(\n array(1,2,3,4,5),\n array(11,22,33,44,55),\n);\nforeach ($arrs as $arr){\n foreach ($arr as $i){\n echo $i . \" \";\n }\n echo \"\\n\";\n}\n$cols=count($arrs[0]);\n$rows=count($arrs);\nfor ($i=0; $i<$rows; $i++){\n for ($j=0;$j<$cols;$j++){\n echo $arrs[$i][$j] . \" \";\n }\n echo \"\\n\";\n}\n?>"
},
{
"code": null,
"e": 2411,
"s": 2374,
"text": "This will produce following result −"
},
{
"code": null,
"e": 2461,
"s": 2411,
"text": "1 2 3 4 5\n11 22 33 44 55\n1 2 3 4 5\n11 22 33 44 55"
},
{
"code": null,
"e": 2538,
"s": 2461,
"text": "Following example has indexed 2D array whaving associative arrays as element"
},
{
"code": null,
"e": 2549,
"s": 2538,
"text": " Live Demo"
},
{
"code": null,
"e": 2884,
"s": 2549,
"text": "<?php\n$arrs=array(\n array(1=>100, 2=>200, 3=>300),\n array(1=>'aa', 2=>'bb', 3=>'cc'),\n);\nforeach ($arrs as $arr){\n foreach ($arr as $i=>$j){\n echo $i . \"->\" .$j . \" \";\n }\n echo \"\\n\";\n}\nfor ($row=0; $row < count($arrs); $row++){\n foreach ($arrs[$row] as $i=>$j){\n echo $i . \"->\" .$j . \" \";\n }\n echo \"\\n\";\n}\n?>"
},
{
"code": null,
"e": 2921,
"s": 2884,
"text": "This will produce following result −"
},
{
"code": null,
"e": 3002,
"s": 2921,
"text": "1->100 2->200 3->300\n1->aa 2->bb 3->cc\n\n1->100 2->200 3->300\n1->aa 2->bb 3->cc\n}"
},
{
"code": null,
"e": 3069,
"s": 3002,
"text": "In following example we have an associative two dimensional array:"
},
{
"code": null,
"e": 3080,
"s": 3069,
"text": " Live Demo"
},
{
"code": null,
"e": 3358,
"s": 3080,
"text": "<?php\n$arr1=array(\"rno\"=>11,\"marks\"=>50);\n$arr2=array(\"rno\"=>22,\"marks\"=>60);\n$arrs=array(\n \"Manav\"=>$arr1,\n \"Ravi\"=>$arr2\n);\nforeach ($arrs as $key=>$val){\n echo \"name : \" . $key . \" \";\n foreach ($val as $i=>$j){\n echo $i . \"->\" .$j . \" \";\n }\n echo \"\\n\";\n}\n?>"
},
{
"code": null,
"e": 3395,
"s": 3358,
"text": "This will produce following result −"
},
{
"code": null,
"e": 3456,
"s": 3395,
"text": "name : Manav rno->11 marks->50\nname : Ravi rno->22 marks->60"
},
{
"code": null,
"e": 3524,
"s": 3456,
"text": "This Example has associative array with each value as indexed array"
},
{
"code": null,
"e": 3535,
"s": 3524,
"text": " Live Demo"
},
{
"code": null,
"e": 3809,
"s": 3535,
"text": "<?php\n$arr1=array(\"PHP\",\"Java\",\"Python\");\n$arr2=array(\"Oracle\",\"MySQL\",\"SQLite\");\n$arrs=array(\n \"Langs\"=>$arr1,\n \"DB\"=>$arr2\n);\nforeach ($arrs as $key=>$val){\n echo $key . \": \";\n for ($i=0; $i < count($val); $i++){\n echo $val[$i] . \" \";\n }\n echo \"\\n\";\n}\n?>"
},
{
"code": null,
"e": 3846,
"s": 3809,
"text": "This will produce following result −"
},
{
"code": null,
"e": 3893,
"s": 3846,
"text": "Langs: PHP Java Python\nDB: Oracle MySQL SQLite"
}
] |
Python | Sort a list according to the second element in sublist | 21 Nov, 2018
In this article, we will learn how to sort any list, according to the second element of the sublist present within the main list. We will see two methods of doing this. We will learn three methods of performing this sort. One by the use of Bubble Sort, second by using the sort() method and last but not the least by the use of sorted() method. In this program, we have sorted the list in ascending order.Examples:
Input : [['rishav', 10], ['akash', 5], ['ram', 20], ['gaurav', 15]]
Output : [['akash', 5], ['rishav', 10], ['gaurav', 15], ['ram', 20]]
Input : [['452', 10], ['256', 5], ['100', 20], ['135', 15]]
Output : [['256', 5], ['452', 10], ['135', 15], ['100', 20]]
Method 1: Using the Bubble Sort techniqueHere we have used the technique of Bubble Sort to perform the sorting. We have tried to access the second element of the sublists using the nested loops. This performs the in-place method of sorting. The time complexity is similar to the Bubble Sort i.e., O(n^2)
# Python code to sort the lists using the second element of sublists# Inplace way to sort, use of third variabledef Sort(sub_li): l = len(sub_li) for i in range(0, l): for j in range(0, l-i-1): if (sub_li[j][1] > sub_li[j + 1][1]): tempo = sub_li[j] sub_li[j]= sub_li[j + 1] sub_li[j + 1]= tempo return sub_li # Driver Codesub_li =[['rishav', 10], ['akash', 5], ['ram', 20], ['gaurav', 15]]print(Sort(sub_li))
Output:
[['akash', 5], ['rishav', 10], ['gaurav', 15], ['ram', 20]]
Method 2: Sorting by the use of sort() methodWhile sorting via this method the actual content of the tuple is changed, and just like the previous method, in-place method of sort is performed.
# Python code to sort the tuples using second element # of sublist Inplace way to sort using sort()def Sort(sub_li): # reverse = None (Sorts in Ascending order) # key is set to sort using second element of # sublist lambda has been used sub_li.sort(key = lambda x: x[1]) return sub_li # Driver Codesub_li =[['rishav', 10], ['akash', 5], ['ram', 20], ['gaurav', 15]]print(Sort(sub_li))
Output:
[['akash', 5], ['rishav', 10], ['gaurav', 15], ['ram', 20]]
Method 3: Sorting by the use of sorted() methodSorted() sorts a list and always returns a list with the elements in a sorted manner, without modifying the original sequence. It takes three parameters from which two are optional, here we tried to use all of the three:
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 server as a key or a basis of sort comparison.Reverse(optional) : To sort this in ascending order we could have just ignored the third parameter, which we did in this program. If set true, then the iterable would be sorted in reverse (descending) order, by default it is set as false.
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 server as a key or a basis of sort comparison.
Reverse(optional) : To sort this in ascending order we could have just ignored the third parameter, which we did in this program. If set true, then the iterable would be sorted in reverse (descending) order, by default it is set as false.
# Python code to sort the tuples using second element # of sublist Function to sort using sorted()def Sort(sub_li): # reverse = None (Sorts in Ascending order) # key is set to sort using second element of # sublist lambda has been used return(sorted(sub_li, key = lambda x: x[1])) # Driver Codesub_li =[['rishav', 10], ['akash', 5], ['ram', 20], ['gaurav', 15]]print(Sort(sub_li))
Output:
[['akash', 5], ['rishav', 10], ['gaurav', 15], ['ram', 20]]
Python list-programs
python-list
Python
Sorting
python-list
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Nov, 2018"
},
{
"code": null,
"e": 467,
"s": 52,
"text": "In this article, we will learn how to sort any list, according to the second element of the sublist present within the main list. We will see two methods of doing this. We will learn three methods of performing this sort. One by the use of Bubble Sort, second by using the sort() method and last but not the least by the use of sorted() method. In this program, we have sorted the list in ascending order.Examples:"
},
{
"code": null,
"e": 727,
"s": 467,
"text": "Input : [['rishav', 10], ['akash', 5], ['ram', 20], ['gaurav', 15]]\nOutput : [['akash', 5], ['rishav', 10], ['gaurav', 15], ['ram', 20]]\n\nInput : [['452', 10], ['256', 5], ['100', 20], ['135', 15]]\nOutput : [['256', 5], ['452', 10], ['135', 15], ['100', 20]]\n"
},
{
"code": null,
"e": 1031,
"s": 727,
"text": "Method 1: Using the Bubble Sort techniqueHere we have used the technique of Bubble Sort to perform the sorting. We have tried to access the second element of the sublists using the nested loops. This performs the in-place method of sorting. The time complexity is similar to the Bubble Sort i.e., O(n^2)"
},
{
"code": "# Python code to sort the lists using the second element of sublists# Inplace way to sort, use of third variabledef Sort(sub_li): l = len(sub_li) for i in range(0, l): for j in range(0, l-i-1): if (sub_li[j][1] > sub_li[j + 1][1]): tempo = sub_li[j] sub_li[j]= sub_li[j + 1] sub_li[j + 1]= tempo return sub_li # Driver Codesub_li =[['rishav', 10], ['akash', 5], ['ram', 20], ['gaurav', 15]]print(Sort(sub_li))",
"e": 1514,
"s": 1031,
"text": null
},
{
"code": null,
"e": 1522,
"s": 1514,
"text": "Output:"
},
{
"code": null,
"e": 1583,
"s": 1522,
"text": "[['akash', 5], ['rishav', 10], ['gaurav', 15], ['ram', 20]]\n"
},
{
"code": null,
"e": 1775,
"s": 1583,
"text": "Method 2: Sorting by the use of sort() methodWhile sorting via this method the actual content of the tuple is changed, and just like the previous method, in-place method of sort is performed."
},
{
"code": "# Python code to sort the tuples using second element # of sublist Inplace way to sort using sort()def Sort(sub_li): # reverse = None (Sorts in Ascending order) # key is set to sort using second element of # sublist lambda has been used sub_li.sort(key = lambda x: x[1]) return sub_li # Driver Codesub_li =[['rishav', 10], ['akash', 5], ['ram', 20], ['gaurav', 15]]print(Sort(sub_li))",
"e": 2179,
"s": 1775,
"text": null
},
{
"code": null,
"e": 2187,
"s": 2179,
"text": "Output:"
},
{
"code": null,
"e": 2248,
"s": 2187,
"text": "[['akash', 5], ['rishav', 10], ['gaurav', 15], ['ram', 20]]\n"
},
{
"code": null,
"e": 2516,
"s": 2248,
"text": "Method 3: Sorting by the use of sorted() methodSorted() sorts a list and always returns a list with the elements in a sorted manner, without modifying the original sequence. It takes three parameters from which two are optional, here we tried to use all of the three:"
},
{
"code": null,
"e": 2970,
"s": 2516,
"text": "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 server as a key or a basis of sort comparison.Reverse(optional) : To sort this in ascending order we could have just ignored the third parameter, which we did in this program. If set true, then the iterable would be sorted in reverse (descending) order, by default it is set as false."
},
{
"code": null,
"e": 3102,
"s": 2970,
"text": "Iterable : sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other iterator that needs to be sorted."
},
{
"code": null,
"e": 3187,
"s": 3102,
"text": "Key(optional) : A function that would server as a key or a basis of sort comparison."
},
{
"code": null,
"e": 3426,
"s": 3187,
"text": "Reverse(optional) : To sort this in ascending order we could have just ignored the third parameter, which we did in this program. If set true, then the iterable would be sorted in reverse (descending) order, by default it is set as false."
},
{
"code": "# Python code to sort the tuples using second element # of sublist Function to sort using sorted()def Sort(sub_li): # reverse = None (Sorts in Ascending order) # key is set to sort using second element of # sublist lambda has been used return(sorted(sub_li, key = lambda x: x[1])) # Driver Codesub_li =[['rishav', 10], ['akash', 5], ['ram', 20], ['gaurav', 15]]print(Sort(sub_li))",
"e": 3827,
"s": 3426,
"text": null
},
{
"code": null,
"e": 3835,
"s": 3827,
"text": "Output:"
},
{
"code": null,
"e": 3896,
"s": 3835,
"text": "[['akash', 5], ['rishav', 10], ['gaurav', 15], ['ram', 20]]\n"
},
{
"code": null,
"e": 3917,
"s": 3896,
"text": "Python list-programs"
},
{
"code": null,
"e": 3929,
"s": 3917,
"text": "python-list"
},
{
"code": null,
"e": 3936,
"s": 3929,
"text": "Python"
},
{
"code": null,
"e": 3944,
"s": 3936,
"text": "Sorting"
},
{
"code": null,
"e": 3956,
"s": 3944,
"text": "python-list"
},
{
"code": null,
"e": 3964,
"s": 3956,
"text": "Sorting"
}
] |
TypeScript | String toString() Method | 18 Jun, 2020
The toString() is an inbuilt function in TypeScript which is used to return a string representing the specified object.
Syntax:
string.toString( )
Parameter: This methods does not accept any parameter. Return Value: This method returns the string representing the specified object. Below examples illustrate the String toString() method in TypeScript
Example 1:
JavaScript
<script> // Original strings var str = "Geeksforgeeks - Best Platform"; // use of String toString() Method var newstr = str.toString() console.log(newstr);</script>
Output:
Geeksforgeeks - Best Platform
Example 2:
JavaScript
<script> // Original strings var str = "TypeScript - String toString()"; // use of String toString() Method var newstr = str.toString() console.log(newstr);</script>
Output:
TypeScript - String toString()
TypeScript
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": "\n18 Jun, 2020"
},
{
"code": null,
"e": 148,
"s": 28,
"text": "The toString() is an inbuilt function in TypeScript which is used to return a string representing the specified object."
},
{
"code": null,
"e": 157,
"s": 148,
"text": "Syntax: "
},
{
"code": null,
"e": 177,
"s": 157,
"text": "string.toString( ) "
},
{
"code": null,
"e": 381,
"s": 177,
"text": "Parameter: This methods does not accept any parameter. Return Value: This method returns the string representing the specified object. Below examples illustrate the String toString() method in TypeScript"
},
{
"code": null,
"e": 393,
"s": 381,
"text": "Example 1: "
},
{
"code": null,
"e": 404,
"s": 393,
"text": "JavaScript"
},
{
"code": "<script> // Original strings var str = \"Geeksforgeeks - Best Platform\"; // use of String toString() Method var newstr = str.toString() console.log(newstr);</script>",
"e": 588,
"s": 404,
"text": null
},
{
"code": null,
"e": 597,
"s": 588,
"text": "Output: "
},
{
"code": null,
"e": 628,
"s": 597,
"text": "Geeksforgeeks - Best Platform\n"
},
{
"code": null,
"e": 640,
"s": 628,
"text": "Example 2: "
},
{
"code": null,
"e": 651,
"s": 640,
"text": "JavaScript"
},
{
"code": "<script> // Original strings var str = \"TypeScript - String toString()\"; // use of String toString() Method var newstr = str.toString() console.log(newstr);</script>",
"e": 836,
"s": 651,
"text": null
},
{
"code": null,
"e": 845,
"s": 836,
"text": "Output: "
},
{
"code": null,
"e": 877,
"s": 845,
"text": "TypeScript - String toString()\n"
},
{
"code": null,
"e": 888,
"s": 877,
"text": "TypeScript"
},
{
"code": null,
"e": 899,
"s": 888,
"text": "JavaScript"
},
{
"code": null,
"e": 916,
"s": 899,
"text": "Web Technologies"
}
] |
Create the Mean and Standard Deviation of the Data of a Pandas Series | 17 Aug, 2020
Standard Deviation is the square root of the Variance. The Standard Deviation denoted by sigma is a measure of the spread of numbers. In pandas, the std() function is used to find the standard Deviation of the series.The mean can be simply defined as the average of numbers. In pandas, the mean() function is used to find the mean of the series.
Example 1 : Finding the mean and Standard Deviation of a Pandas Series.
# importing the moduleimport pandas as pd # creating a seriess = pd.Series(data = [5, 9, 8, 5, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 5, 3]) # displaying the seriesprint(s)
Output :
Finding the mean of the series using the mean() function.
# finding the meanprint(s.mean())
Output :
Finding the standard deviation of the series using the std() function.
# finding the Standard deviationprint(s.std())
Output :
Example 2 : Finding the mean and Standard Deviation of a Pandas DataFrame.
# importing the moduleimport pandas as pd # creating a dataframe df = pd.DataFrame({'ID':[114, 345, 157788, 5626], 'Product':['shirt', 'trousers', 'tie', 'belt'], 'Color':['White', 'Black', 'Red', 'Brown'], 'Discount':[10, 10, 10, 10]}) # displaying the DataFrameprint(df)
Output :
Finding the mean of the DataFrame using the mean() function.
# finding the meanprint(df.mean())
Output :
Finding the standard deviation of the DataFrame using the std() function.
# finding the Standard deviationprint(df.std())
Output :
Python pandas-series
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Aug, 2020"
},
{
"code": null,
"e": 374,
"s": 28,
"text": "Standard Deviation is the square root of the Variance. The Standard Deviation denoted by sigma is a measure of the spread of numbers. In pandas, the std() function is used to find the standard Deviation of the series.The mean can be simply defined as the average of numbers. In pandas, the mean() function is used to find the mean of the series."
},
{
"code": null,
"e": 446,
"s": 374,
"text": "Example 1 : Finding the mean and Standard Deviation of a Pandas Series."
},
{
"code": "# importing the moduleimport pandas as pd # creating a seriess = pd.Series(data = [5, 9, 8, 5, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 5, 3]) # displaying the seriesprint(s)",
"e": 636,
"s": 446,
"text": null
},
{
"code": null,
"e": 645,
"s": 636,
"text": "Output :"
},
{
"code": null,
"e": 703,
"s": 645,
"text": "Finding the mean of the series using the mean() function."
},
{
"code": "# finding the meanprint(s.mean())",
"e": 737,
"s": 703,
"text": null
},
{
"code": null,
"e": 746,
"s": 737,
"text": "Output :"
},
{
"code": null,
"e": 817,
"s": 746,
"text": "Finding the standard deviation of the series using the std() function."
},
{
"code": "# finding the Standard deviationprint(s.std())",
"e": 864,
"s": 817,
"text": null
},
{
"code": null,
"e": 873,
"s": 864,
"text": "Output :"
},
{
"code": null,
"e": 948,
"s": 873,
"text": "Example 2 : Finding the mean and Standard Deviation of a Pandas DataFrame."
},
{
"code": "# importing the moduleimport pandas as pd # creating a dataframe df = pd.DataFrame({'ID':[114, 345, 157788, 5626], 'Product':['shirt', 'trousers', 'tie', 'belt'], 'Color':['White', 'Black', 'Red', 'Brown'], 'Discount':[10, 10, 10, 10]}) # displaying the DataFrameprint(df)",
"e": 1277,
"s": 948,
"text": null
},
{
"code": null,
"e": 1286,
"s": 1277,
"text": "Output :"
},
{
"code": null,
"e": 1347,
"s": 1286,
"text": "Finding the mean of the DataFrame using the mean() function."
},
{
"code": "# finding the meanprint(df.mean())",
"e": 1382,
"s": 1347,
"text": null
},
{
"code": null,
"e": 1391,
"s": 1382,
"text": "Output :"
},
{
"code": null,
"e": 1465,
"s": 1391,
"text": "Finding the standard deviation of the DataFrame using the std() function."
},
{
"code": "# finding the Standard deviationprint(df.std())",
"e": 1513,
"s": 1465,
"text": null
},
{
"code": null,
"e": 1522,
"s": 1513,
"text": "Output :"
},
{
"code": null,
"e": 1543,
"s": 1522,
"text": "Python pandas-series"
},
{
"code": null,
"e": 1557,
"s": 1543,
"text": "Python-pandas"
},
{
"code": null,
"e": 1564,
"s": 1557,
"text": "Python"
}
] |
Runge-Kutta 4th Order Method to Solve Differential Equation | 09 Jun, 2022
Given following inputs,
An ordinary differential equation that defines value of dy/dx in the form x and y.
Initial value of y, i.e., y(0)
Thus we are given below.The task is to find value of unknown function y at a given point x.The Runge-Kutta method finds approximate value of y for a given x. Only first order ordinary differential equations can be solved by using the Runge Kutta 4th order method.Below is the formula used to compute next value yn+1 from previous value yn. The value of n are 0, 1, 2, 3, ....(x – x0)/h. Here h is step height and xn+1 = x0 + h. Lower step size means more accuracy.
The formula basically computes next value yn+1 using current yn plus weighted average of four increments.
k1 is the increment based on the slope at the beginning of the interval, using y
k2 is the increment based on the slope at the midpoint of the interval, using y + hk1/2.
k3 is again the increment based on the slope at the midpoint, using y + hk2/2.
k4 is the increment based on the slope at the end of the interval, using y + hk3.
The method is a fourth-order method, meaning that the local truncation error is on the order of O(h5), while the total accumulated error is order O(h4).Source: https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods
Below is implementation for the above formula.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program of th above approach#include <bits/stdc++.h>using namespace std; // A sample differential equation "dy/dx = (x - y)/2"float dydx(float x, float y){ return((x - y)/2);} // Finds value of y for a given x using step size h// and initial value y0 at x0.float rungeKutta(float x0, float y0, float x, float h){ // Count number of iterations using step size or // step height h int n = (int)((x - x0) / h); float k1, k2, k3, k4, k5; // Iterate for number of iterations float y = y0; for (int i=1; i<=n; i++) { // Apply Runge Kutta Formulas to find // next value of y k1 = h*dydx(x0, y); k2 = h*dydx(x0 + 0.5*h, y + 0.5*k1); k3 = h*dydx(x0 + 0.5*h, y + 0.5*k2); k4 = h*dydx(x0 + h, y + k3); // Update next value of y y = y + (1.0/6.0)*(k1 + 2*k2 + 2*k3 + k4);; // Update next value of x x0 = x0 + h; } return y;} // Driver Codeint main(){ float x0 = 0, y = 1, x = 2, h = 0.2; cout << "The value of y at x is : " << rungeKutta(x0, y, x, h); return 0;} // This code is contributed by code_hunt.
// C program to implement Runge Kutta method#include<stdio.h> // A sample differential equation "dy/dx = (x - y)/2"float dydx(float x, float y){ return((x - y)/2);} // Finds value of y for a given x using step size h// and initial value y0 at x0.float rungeKutta(float x0, float y0, float x, float h){ // Count number of iterations using step size or // step height h int n = (int)((x - x0) / h); float k1, k2, k3, k4, k5; // Iterate for number of iterations float y = y0; for (int i=1; i<=n; i++) { // Apply Runge Kutta Formulas to find // next value of y k1 = h*dydx(x0, y); k2 = h*dydx(x0 + 0.5*h, y + 0.5*k1); k3 = h*dydx(x0 + 0.5*h, y + 0.5*k2); k4 = h*dydx(x0 + h, y + k3); // Update next value of y y = y + (1.0/6.0)*(k1 + 2*k2 + 2*k3 + k4);; // Update next value of x x0 = x0 + h; } return y;} // Driver methodint main(){ float x0 = 0, y = 1, x = 2, h = 0.2; printf("\nThe value of y at x is : %f", rungeKutta(x0, y, x, h)); return 0;}
// Java program to implement Runge Kutta methodimport java.io.*;class differential{ double dydx(double x, double y) { return ((x - y) / 2); } // Finds value of y for a given x using step size h // and initial value y0 at x0. double rungeKutta(double x0, double y0, double x, double h) { differential d1 = new differential(); // Count number of iterations using step size or // step height h int n = (int)((x - x0) / h); double k1, k2, k3, k4, k5; // Iterate for number of iterations double y = y0; for (int i = 1; i <= n; i++) { // Apply Runge Kutta Formulas to find // next value of y k1 = h * (d1.dydx(x0, y)); k2 = h * (d1.dydx(x0 + 0.5 * h, y + 0.5 * k1)); k3 = h * (d1.dydx(x0 + 0.5 * h, y + 0.5 * k2)); k4 = h * (d1.dydx(x0 + h, y + k3)); // Update next value of y y = y + (1.0 / 6.0) * (k1 + 2 * k2 + 2 * k3 + k4); // Update next value of x x0 = x0 + h; } return y; } public static void main(String args[]) { differential d2 = new differential(); double x0 = 0, y = 1, x = 2, h = 0.2; System.out.println("\nThe value of y at x is : " + d2.rungeKutta(x0, y, x, h)); }} // This code is contributed by Prateek Bhindwar
# Python program to implement Runge Kutta method# A sample differential equation "dy / dx = (x - y)/2"def dydx(x, y): return ((x - y)/2) # Finds value of y for a given x using step size h# and initial value y0 at x0.def rungeKutta(x0, y0, x, h): # Count number of iterations using step size or # step height h n = (int)((x - x0)/h) # Iterate for number of iterations y = y0 for i in range(1, n + 1): "Apply Runge Kutta Formulas to find next value of y" k1 = h * dydx(x0, y) k2 = h * dydx(x0 + 0.5 * h, y + 0.5 * k1) k3 = h * dydx(x0 + 0.5 * h, y + 0.5 * k2) k4 = h * dydx(x0 + h, y + k3) # Update next value of y y = y + (1.0 / 6.0)*(k1 + 2 * k2 + 2 * k3 + k4) # Update next value of x x0 = x0 + h return y # Driver methodx0 = 0y = 1x = 2h = 0.2print ('The value of y at x is:', rungeKutta(x0, y, x, h)) # This code is contributed by Prateek Bhindwar
// C# program to implement Runge// Kutta methodusing System; class GFG { static double dydx(double x, double y) { return ((x - y) / 2); } // Finds value of y for a given x // using step size h and initial // value y0 at x0. static double rungeKutta(double x0, double y0, double x, double h) { // Count number of iterations using // step size or step height h int n = (int)((x - x0) / h); double k1, k2, k3, k4; // Iterate for number of iterations double y = y0; for (int i = 1; i <= n; i++) { // Apply Runge Kutta Formulas // to find next value of y k1 = h * (dydx(x0, y)); k2 = h * (dydx(x0 + 0.5 * h, y + 0.5 * k1)); k3 = h * (dydx(x0 + 0.5 * h, y + 0.5 * k2)); k4 = h * (dydx(x0 + h, y + k3)); // Update next value of y y = y + (1.0 / 6.0) * (k1 + 2 * k2 + 2 * k3 + k4); // Update next value of x x0 = x0 + h; } return y; } // Driver code public static void Main() { double x0 = 0, y = 1, x = 2, h = 0.2; Console.WriteLine("\nThe value of y" + " at x is : " + rungeKutta(x0, y, x, h)); }} // This code is contributed by Sam007.
<?php// PHP program to implement// Runge Kutta method // A sample differential equation// "dy/dx = (x - y)/2"function dydx($x, $y){ return(($x - $y) / 2);} // Finds value of y for a// given x using step size h// and initial value y0 at x0.function rungeKutta($x0, $y0, $x, $h){ // Count number of iterations // using step size or step // height h $n = (($x - $x0) / $h); $k1; $k2; $k3; $k4; $k5; // Iterate for number // of iterations $y = $y0; for($i = 1; $i <= $n; $i++) { // Apply Runge Kutta // Formulas to find // next value of y $k1 = $h * dydx($x0, $y); $k2 = $h * dydx($x0 + 0.5 * $h, $y + 0.5 * $k1); $k3 = $h * dydx($x0 + 0.5 * $h, $y + 0.5 * $k2); $k4 = $h * dydx($x0 + $h, $y + $k3); // Update next value of y $y = $y + (1.0 / 6.0) * ($k1 + 2 * $k2 + 2 * $k3 + $k4);; // Update next value of x $x0 = $x0 + $h; } return $y;} // Driver method $x0 = 0; $y = 1; $x = 2; $h = 0.2; echo "The value of y at x is : ", rungeKutta($x0, $y, $x, $h); // This code is contributed by anuj_67.?>
<script> // Javascript program to implement Runge Kutta method // A sample differential equation "dy/dx = (x - y)/2"function dydx(x, y){ return((x - y) / 2);} // Finds value of y for a given x using step size h// and initial value y0 at x0.function rungeKutta(x0, y0, x, h){ // Count number of iterations using // step size or step height h let n = parseInt((x - x0) / h, 10); let k1, k2, k3, k4, k5; // Iterate for number of iterations let y = y0; for(let i = 1; i <= n; i++) { // Apply Runge Kutta Formulas to find // next value of y k1 = h * dydx(x0, y); k2 = h * dydx(x0 + 0.5 * h, y + 0.5 * k1); k3 = h * dydx(x0 + 0.5 * h, y + 0.5 * k2); k4 = h * dydx(x0 + h, y + k3); // Update next value of y y = y + (1 / 6) * (k1 + 2 * k2 + 2 * k3 + k4);; // Update next value of x x0 = x0 + h; } return y.toFixed(6);} // Driver codelet x0 = 0, y = 1, x = 2, h = 0.2; document.write("The value of y at x is : " + rungeKutta(x0, y, x, h)); // This code is contributed by divyesh072019 </script>
Output:
The value of y at x is : 1.103639
Time Complexity of above solution is O(n) where n is (x-x0)/h.Some useful resources for detailed examples and more explanation. http://w3.gazi.edu.tr/~balbasi/mws_gen_ode_txt_runge4th.pdf https://www.youtube.com/watch?v=kUcc8vAgoQ0
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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Sam007
vt_m
divyesh072019
piotrkopec
amartyaghoshgfg
code_hunt
sweetyty
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Sieve of Eratosthenes
Prime Numbers
Program to find GCD or HCF of two numbers
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
Algorithm to solve Rubik's Cube
The Knight's tour problem | Backtracking-1
Program for Decimal to Binary Conversion | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 79,
"s": 54,
"text": "Given following inputs, "
},
{
"code": null,
"e": 162,
"s": 79,
"text": "An ordinary differential equation that defines value of dy/dx in the form x and y."
},
{
"code": null,
"e": 193,
"s": 162,
"text": "Initial value of y, i.e., y(0)"
},
{
"code": null,
"e": 658,
"s": 193,
"text": "Thus we are given below.The task is to find value of unknown function y at a given point x.The Runge-Kutta method finds approximate value of y for a given x. Only first order ordinary differential equations can be solved by using the Runge Kutta 4th order method.Below is the formula used to compute next value yn+1 from previous value yn. The value of n are 0, 1, 2, 3, ....(x – x0)/h. Here h is step height and xn+1 = x0 + h. Lower step size means more accuracy."
},
{
"code": null,
"e": 765,
"s": 658,
"text": "The formula basically computes next value yn+1 using current yn plus weighted average of four increments. "
},
{
"code": null,
"e": 846,
"s": 765,
"text": "k1 is the increment based on the slope at the beginning of the interval, using y"
},
{
"code": null,
"e": 935,
"s": 846,
"text": "k2 is the increment based on the slope at the midpoint of the interval, using y + hk1/2."
},
{
"code": null,
"e": 1015,
"s": 935,
"text": "k3 is again the increment based on the slope at the midpoint, using y + hk2/2."
},
{
"code": null,
"e": 1097,
"s": 1015,
"text": "k4 is the increment based on the slope at the end of the interval, using y + hk3."
},
{
"code": null,
"e": 1315,
"s": 1097,
"text": "The method is a fourth-order method, meaning that the local truncation error is on the order of O(h5), while the total accumulated error is order O(h4).Source: https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods"
},
{
"code": null,
"e": 1363,
"s": 1315,
"text": "Below is implementation for the above formula. "
},
{
"code": null,
"e": 1367,
"s": 1363,
"text": "C++"
},
{
"code": null,
"e": 1369,
"s": 1367,
"text": "C"
},
{
"code": null,
"e": 1374,
"s": 1369,
"text": "Java"
},
{
"code": null,
"e": 1382,
"s": 1374,
"text": "Python3"
},
{
"code": null,
"e": 1385,
"s": 1382,
"text": "C#"
},
{
"code": null,
"e": 1389,
"s": 1385,
"text": "PHP"
},
{
"code": null,
"e": 1400,
"s": 1389,
"text": "Javascript"
},
{
"code": "// C++ program of th above approach#include <bits/stdc++.h>using namespace std; // A sample differential equation \"dy/dx = (x - y)/2\"float dydx(float x, float y){ return((x - y)/2);} // Finds value of y for a given x using step size h// and initial value y0 at x0.float rungeKutta(float x0, float y0, float x, float h){ // Count number of iterations using step size or // step height h int n = (int)((x - x0) / h); float k1, k2, k3, k4, k5; // Iterate for number of iterations float y = y0; for (int i=1; i<=n; i++) { // Apply Runge Kutta Formulas to find // next value of y k1 = h*dydx(x0, y); k2 = h*dydx(x0 + 0.5*h, y + 0.5*k1); k3 = h*dydx(x0 + 0.5*h, y + 0.5*k2); k4 = h*dydx(x0 + h, y + k3); // Update next value of y y = y + (1.0/6.0)*(k1 + 2*k2 + 2*k3 + k4);; // Update next value of x x0 = x0 + h; } return y;} // Driver Codeint main(){ float x0 = 0, y = 1, x = 2, h = 0.2; cout << \"The value of y at x is : \" << rungeKutta(x0, y, x, h); return 0;} // This code is contributed by code_hunt.",
"e": 2535,
"s": 1400,
"text": null
},
{
"code": "// C program to implement Runge Kutta method#include<stdio.h> // A sample differential equation \"dy/dx = (x - y)/2\"float dydx(float x, float y){ return((x - y)/2);} // Finds value of y for a given x using step size h// and initial value y0 at x0.float rungeKutta(float x0, float y0, float x, float h){ // Count number of iterations using step size or // step height h int n = (int)((x - x0) / h); float k1, k2, k3, k4, k5; // Iterate for number of iterations float y = y0; for (int i=1; i<=n; i++) { // Apply Runge Kutta Formulas to find // next value of y k1 = h*dydx(x0, y); k2 = h*dydx(x0 + 0.5*h, y + 0.5*k1); k3 = h*dydx(x0 + 0.5*h, y + 0.5*k2); k4 = h*dydx(x0 + h, y + k3); // Update next value of y y = y + (1.0/6.0)*(k1 + 2*k2 + 2*k3 + k4);; // Update next value of x x0 = x0 + h; } return y;} // Driver methodint main(){ float x0 = 0, y = 1, x = 2, h = 0.2; printf(\"\\nThe value of y at x is : %f\", rungeKutta(x0, y, x, h)); return 0;}",
"e": 3607,
"s": 2535,
"text": null
},
{
"code": "// Java program to implement Runge Kutta methodimport java.io.*;class differential{ double dydx(double x, double y) { return ((x - y) / 2); } // Finds value of y for a given x using step size h // and initial value y0 at x0. double rungeKutta(double x0, double y0, double x, double h) { differential d1 = new differential(); // Count number of iterations using step size or // step height h int n = (int)((x - x0) / h); double k1, k2, k3, k4, k5; // Iterate for number of iterations double y = y0; for (int i = 1; i <= n; i++) { // Apply Runge Kutta Formulas to find // next value of y k1 = h * (d1.dydx(x0, y)); k2 = h * (d1.dydx(x0 + 0.5 * h, y + 0.5 * k1)); k3 = h * (d1.dydx(x0 + 0.5 * h, y + 0.5 * k2)); k4 = h * (d1.dydx(x0 + h, y + k3)); // Update next value of y y = y + (1.0 / 6.0) * (k1 + 2 * k2 + 2 * k3 + k4); // Update next value of x x0 = x0 + h; } return y; } public static void main(String args[]) { differential d2 = new differential(); double x0 = 0, y = 1, x = 2, h = 0.2; System.out.println(\"\\nThe value of y at x is : \" + d2.rungeKutta(x0, y, x, h)); }} // This code is contributed by Prateek Bhindwar",
"e": 5032,
"s": 3607,
"text": null
},
{
"code": "# Python program to implement Runge Kutta method# A sample differential equation \"dy / dx = (x - y)/2\"def dydx(x, y): return ((x - y)/2) # Finds value of y for a given x using step size h# and initial value y0 at x0.def rungeKutta(x0, y0, x, h): # Count number of iterations using step size or # step height h n = (int)((x - x0)/h) # Iterate for number of iterations y = y0 for i in range(1, n + 1): \"Apply Runge Kutta Formulas to find next value of y\" k1 = h * dydx(x0, y) k2 = h * dydx(x0 + 0.5 * h, y + 0.5 * k1) k3 = h * dydx(x0 + 0.5 * h, y + 0.5 * k2) k4 = h * dydx(x0 + h, y + k3) # Update next value of y y = y + (1.0 / 6.0)*(k1 + 2 * k2 + 2 * k3 + k4) # Update next value of x x0 = x0 + h return y # Driver methodx0 = 0y = 1x = 2h = 0.2print ('The value of y at x is:', rungeKutta(x0, y, x, h)) # This code is contributed by Prateek Bhindwar",
"e": 5972,
"s": 5032,
"text": null
},
{
"code": "// C# program to implement Runge// Kutta methodusing System; class GFG { static double dydx(double x, double y) { return ((x - y) / 2); } // Finds value of y for a given x // using step size h and initial // value y0 at x0. static double rungeKutta(double x0, double y0, double x, double h) { // Count number of iterations using // step size or step height h int n = (int)((x - x0) / h); double k1, k2, k3, k4; // Iterate for number of iterations double y = y0; for (int i = 1; i <= n; i++) { // Apply Runge Kutta Formulas // to find next value of y k1 = h * (dydx(x0, y)); k2 = h * (dydx(x0 + 0.5 * h, y + 0.5 * k1)); k3 = h * (dydx(x0 + 0.5 * h, y + 0.5 * k2)); k4 = h * (dydx(x0 + h, y + k3)); // Update next value of y y = y + (1.0 / 6.0) * (k1 + 2 * k2 + 2 * k3 + k4); // Update next value of x x0 = x0 + h; } return y; } // Driver code public static void Main() { double x0 = 0, y = 1, x = 2, h = 0.2; Console.WriteLine(\"\\nThe value of y\" + \" at x is : \" + rungeKutta(x0, y, x, h)); }} // This code is contributed by Sam007.",
"e": 7536,
"s": 5972,
"text": null
},
{
"code": "<?php// PHP program to implement// Runge Kutta method // A sample differential equation// \"dy/dx = (x - y)/2\"function dydx($x, $y){ return(($x - $y) / 2);} // Finds value of y for a// given x using step size h// and initial value y0 at x0.function rungeKutta($x0, $y0, $x, $h){ // Count number of iterations // using step size or step // height h $n = (($x - $x0) / $h); $k1; $k2; $k3; $k4; $k5; // Iterate for number // of iterations $y = $y0; for($i = 1; $i <= $n; $i++) { // Apply Runge Kutta // Formulas to find // next value of y $k1 = $h * dydx($x0, $y); $k2 = $h * dydx($x0 + 0.5 * $h, $y + 0.5 * $k1); $k3 = $h * dydx($x0 + 0.5 * $h, $y + 0.5 * $k2); $k4 = $h * dydx($x0 + $h, $y + $k3); // Update next value of y $y = $y + (1.0 / 6.0) * ($k1 + 2 * $k2 + 2 * $k3 + $k4);; // Update next value of x $x0 = $x0 + $h; } return $y;} // Driver method $x0 = 0; $y = 1; $x = 2; $h = 0.2; echo \"The value of y at x is : \", rungeKutta($x0, $y, $x, $h); // This code is contributed by anuj_67.?>",
"e": 8757,
"s": 7536,
"text": null
},
{
"code": "<script> // Javascript program to implement Runge Kutta method // A sample differential equation \"dy/dx = (x - y)/2\"function dydx(x, y){ return((x - y) / 2);} // Finds value of y for a given x using step size h// and initial value y0 at x0.function rungeKutta(x0, y0, x, h){ // Count number of iterations using // step size or step height h let n = parseInt((x - x0) / h, 10); let k1, k2, k3, k4, k5; // Iterate for number of iterations let y = y0; for(let i = 1; i <= n; i++) { // Apply Runge Kutta Formulas to find // next value of y k1 = h * dydx(x0, y); k2 = h * dydx(x0 + 0.5 * h, y + 0.5 * k1); k3 = h * dydx(x0 + 0.5 * h, y + 0.5 * k2); k4 = h * dydx(x0 + h, y + k3); // Update next value of y y = y + (1 / 6) * (k1 + 2 * k2 + 2 * k3 + k4);; // Update next value of x x0 = x0 + h; } return y.toFixed(6);} // Driver codelet x0 = 0, y = 1, x = 2, h = 0.2; document.write(\"The value of y at x is : \" + rungeKutta(x0, y, x, h)); // This code is contributed by divyesh072019 </script>",
"e": 9924,
"s": 8757,
"text": null
},
{
"code": null,
"e": 9933,
"s": 9924,
"text": "Output: "
},
{
"code": null,
"e": 9967,
"s": 9933,
"text": "The value of y at x is : 1.103639"
},
{
"code": null,
"e": 10201,
"s": 9967,
"text": "Time Complexity of above solution is O(n) where n is (x-x0)/h.Some useful resources for detailed examples and more explanation. http://w3.gazi.edu.tr/~balbasi/mws_gen_ode_txt_runge4th.pdf https://www.youtube.com/watch?v=kUcc8vAgoQ0 "
},
{
"code": null,
"e": 10469,
"s": 10201,
"text": "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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 10594,
"s": 10469,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 10601,
"s": 10594,
"text": "Sam007"
},
{
"code": null,
"e": 10606,
"s": 10601,
"text": "vt_m"
},
{
"code": null,
"e": 10620,
"s": 10606,
"text": "divyesh072019"
},
{
"code": null,
"e": 10631,
"s": 10620,
"text": "piotrkopec"
},
{
"code": null,
"e": 10647,
"s": 10631,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 10657,
"s": 10647,
"text": "code_hunt"
},
{
"code": null,
"e": 10666,
"s": 10657,
"text": "sweetyty"
},
{
"code": null,
"e": 10679,
"s": 10666,
"text": "Mathematical"
},
{
"code": null,
"e": 10692,
"s": 10679,
"text": "Mathematical"
},
{
"code": null,
"e": 10790,
"s": 10692,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10814,
"s": 10790,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 10835,
"s": 10814,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 10857,
"s": 10835,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 10871,
"s": 10857,
"text": "Prime Numbers"
},
{
"code": null,
"e": 10913,
"s": 10871,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 10966,
"s": 10913,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 11003,
"s": 10966,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 11035,
"s": 11003,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 11078,
"s": 11035,
"text": "The Knight's tour problem | Backtracking-1"
}
] |
Comparing Maps in Golang | 06 Nov, 2020
In Go language, a map is a powerful, ingenious, and versatile data structure. Golang Maps is a collection of unordered pairs of key-value. It is widely used because it provides fast lookups and values that can retrieve, update, or delete with the help of keys. In Go language, you are allowed to compare two maps with each other using DeepEqual() function provided by the reflect package. This function returns true if both the maps satisfy the following conditions:
Both maps are nil or non-nil.
Both maps have the same length.
Both maps are the same map object or their corresponding keys map to deeply equal values.
Otherwise, this function returns false.
Syntax:
reflect.DeepEqual(a, b)
Here, a and b are maps, and this function checks whether a and b are deeply equal or not, then return boolean type result.
Example:
Go
// Go program to illustrate// how to compare two mapspackage main import ( "fmt" "reflect") func main() { map_1 := map[int]string{ 200: "Anita", 201: "Neha", 203: "Suman", 204: "Robin", 205: "Rohit", } map_2 := map[int]string{ 200: "Anita", 201: "Neha", 203: "Suman", 204: "Robin", 205: "Rohit", 206: "Sumit", } map_3 := map[int]string{ 200: "Anita", 201: "Neha", 203: "Suman", 204: "Robin", 205: "Rohit", } map_4 := map[string]int{ "Anita": 200, "Neha": 201, "Suman": 203, "Robin": 204, "Rohit": 205, } // Comparing maps // Using DeepEqual() function res1 := reflect.DeepEqual(map_1, map_2) res2 := reflect.DeepEqual(map_1, map_3) res3 := reflect.DeepEqual(map_1, map_4) res4 := reflect.DeepEqual(map_2, map_3) res5 := reflect.DeepEqual(map_3, map_4) res6 := reflect.DeepEqual(map_4, map_4) res7 := reflect.DeepEqual(map_2, map_4) // Displaying result fmt.Println("Is Map 1 is equal to Map 2: ", res1) fmt.Println("Is Map 1 is equal to Map 3: ", res2) fmt.Println("Is Map 1 is equal to Map 4: ", res3) fmt.Println("Is Map 2 is equal to Map 3: ", res4) fmt.Println("Is Map 3 is equal to Map 4: ", res5) fmt.Println("Is Map 4 is equal to Map 4: ", res6) fmt.Println("Is Map 2 is equal to Map 4: ", res7) }
Output:
Is Map 1 is equal to Map 2: false
Is Map 1 is equal to Map 3: true
Is Map 1 is equal to Map 4: false
Is Map 2 is equal to Map 3: false
Is Map 3 is equal to Map 4: false
Is Map 4 is equal to Map 4: true
Is Map 2 is equal to Map 4: false
warrenbrodskyfacebook
Golang
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
How to Split a String in Golang?
Interfaces in Golang
Different Ways to Find the Type of Variable in Golang
How to Parse JSON in Golang?
How to Trim a String in Golang?
How to convert a string in lower case in Golang?
How to compare times in Golang?
Inheritance in GoLang | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Nov, 2020"
},
{
"code": null,
"e": 519,
"s": 52,
"text": "In Go language, a map is a powerful, ingenious, and versatile data structure. Golang Maps is a collection of unordered pairs of key-value. It is widely used because it provides fast lookups and values that can retrieve, update, or delete with the help of keys. In Go language, you are allowed to compare two maps with each other using DeepEqual() function provided by the reflect package. This function returns true if both the maps satisfy the following conditions:"
},
{
"code": null,
"e": 549,
"s": 519,
"text": "Both maps are nil or non-nil."
},
{
"code": null,
"e": 581,
"s": 549,
"text": "Both maps have the same length."
},
{
"code": null,
"e": 671,
"s": 581,
"text": "Both maps are the same map object or their corresponding keys map to deeply equal values."
},
{
"code": null,
"e": 711,
"s": 671,
"text": "Otherwise, this function returns false."
},
{
"code": null,
"e": 720,
"s": 711,
"text": "Syntax: "
},
{
"code": null,
"e": 746,
"s": 720,
"text": "reflect.DeepEqual(a, b)\n\n"
},
{
"code": null,
"e": 870,
"s": 746,
"text": "Here, a and b are maps, and this function checks whether a and b are deeply equal or not, then return boolean type result. "
},
{
"code": null,
"e": 880,
"s": 870,
"text": "Example: "
},
{
"code": null,
"e": 883,
"s": 880,
"text": "Go"
},
{
"code": "// Go program to illustrate// how to compare two mapspackage main import ( \"fmt\" \"reflect\") func main() { map_1 := map[int]string{ 200: \"Anita\", 201: \"Neha\", 203: \"Suman\", 204: \"Robin\", 205: \"Rohit\", } map_2 := map[int]string{ 200: \"Anita\", 201: \"Neha\", 203: \"Suman\", 204: \"Robin\", 205: \"Rohit\", 206: \"Sumit\", } map_3 := map[int]string{ 200: \"Anita\", 201: \"Neha\", 203: \"Suman\", 204: \"Robin\", 205: \"Rohit\", } map_4 := map[string]int{ \"Anita\": 200, \"Neha\": 201, \"Suman\": 203, \"Robin\": 204, \"Rohit\": 205, } // Comparing maps // Using DeepEqual() function res1 := reflect.DeepEqual(map_1, map_2) res2 := reflect.DeepEqual(map_1, map_3) res3 := reflect.DeepEqual(map_1, map_4) res4 := reflect.DeepEqual(map_2, map_3) res5 := reflect.DeepEqual(map_3, map_4) res6 := reflect.DeepEqual(map_4, map_4) res7 := reflect.DeepEqual(map_2, map_4) // Displaying result fmt.Println(\"Is Map 1 is equal to Map 2: \", res1) fmt.Println(\"Is Map 1 is equal to Map 3: \", res2) fmt.Println(\"Is Map 1 is equal to Map 4: \", res3) fmt.Println(\"Is Map 2 is equal to Map 3: \", res4) fmt.Println(\"Is Map 3 is equal to Map 4: \", res5) fmt.Println(\"Is Map 4 is equal to Map 4: \", res6) fmt.Println(\"Is Map 2 is equal to Map 4: \", res7) }",
"e": 2325,
"s": 883,
"text": null
},
{
"code": null,
"e": 2333,
"s": 2325,
"text": "Output:"
},
{
"code": null,
"e": 2580,
"s": 2333,
"text": "Is Map 1 is equal to Map 2: false\nIs Map 1 is equal to Map 3: true\nIs Map 1 is equal to Map 4: false\nIs Map 2 is equal to Map 3: false\nIs Map 3 is equal to Map 4: false\nIs Map 4 is equal to Map 4: true\nIs Map 2 is equal to Map 4: false\n\n\n\n"
},
{
"code": null,
"e": 2602,
"s": 2580,
"text": "warrenbrodskyfacebook"
},
{
"code": null,
"e": 2609,
"s": 2602,
"text": "Golang"
},
{
"code": null,
"e": 2621,
"s": 2609,
"text": "Go Language"
},
{
"code": null,
"e": 2719,
"s": 2621,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2770,
"s": 2719,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 2817,
"s": 2770,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 2850,
"s": 2817,
"text": "How to Split a String in Golang?"
},
{
"code": null,
"e": 2871,
"s": 2850,
"text": "Interfaces in Golang"
},
{
"code": null,
"e": 2925,
"s": 2871,
"text": "Different Ways to Find the Type of Variable in Golang"
},
{
"code": null,
"e": 2954,
"s": 2925,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 2986,
"s": 2954,
"text": "How to Trim a String in Golang?"
},
{
"code": null,
"e": 3035,
"s": 2986,
"text": "How to convert a string in lower case in Golang?"
},
{
"code": null,
"e": 3067,
"s": 3035,
"text": "How to compare times in Golang?"
}
] |
GATE | GATE-CS-2005 | Question 45 | 28 Jun, 2021
Consider three decision problems P1, P2 and P3. It is known that P1 is decidable and P2 is undecidable. Which one of the following is TRUE?(A) P3 is decidable if P1 is reducible to P3(B) P3 is undecidable if P3 is reducible to P2(C) P3 is undecidable if P2 is reducible to P3(D) P3 is decidable if P3 is reducible to P2’s complementAnswer: (C)Explanation: Background: In computational complexity theory, a decision problem has only two possible outputs yes or no.A decision problem is said to be decidable if there exists an effective method or algorithm that returns a correct yes/no answer to that problem.A decision problem is said to be undecidable if there does not exist a single algorithm that always lead to a correct yes/no solution.
In terms of reducibility: A ≤p B denotes A is a decision problem that is reducible to B in polynomial time p. This simply means that A’s instance can be transformed into B’s instance and following the solution of B we can get a solution for the problem A.So here we can draw some conclusions:
1. If A ≤p B and B is decidable then A is also decidable.
This is because if there exists a specific algorithm for solving B and we can
also reduce A to B then we can have a solution of A as well. Hence A is decidable.
However the reverse is not true i.e. if A ≤p B and A is decidable
then B is also decidable because A can have an algorithm existing for its correct
solution but might be the case that B does not.
2. If A ≤p B and A is undecidable then B is also undecidable.
This is because if A is undecidable even when it can be reduced to B that simply
reflects even B cannot provide an algorithm by which we can solve B and hence A.
So decision problem B is also undecidable.
However the reverse is not true here as well i.e. if A ≤p B and B is undecidable then A is also undecidable because there might exist an algorithm for A that can provide a solution to A.
Using the above stated conclusions we can say that option 1, 2 and 4 are false and option 3 is true.
Option 1: P1 ≤p P3 and given P1 is decidable gives no conclusion for P3.
Option 2: P3 ≤p P2 and given P2 is undecidable gives no conclusion for P3.
Option 3: P2 ≤p P3 and given P2 is undecidable gives conclusion for P3 to be
undecidable.
Option 4: P3 ≤p P2’s complement and given P2 is undecidable therefore P2’s
complement is also undecidable gives no conclusion for P3.
This explanation is contributed by Yashika Arora.
Visit the following articles to learn more:undecidability-and-reducibilityWikipedia: Reduction_(Complexity)Quiz of this Question
GATE-CS-2005
GATE-GATE-CS-2005
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 49
GATE | GATE CS 1996 | Question 38
GATE | GATE-CS-2004 | Question 31
GATE | GATE-CS-2016 (Set 1) | Question 45
GATE | GATE CS 1996 | Question 63 | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 772,
"s": 28,
"text": "Consider three decision problems P1, P2 and P3. It is known that P1 is decidable and P2 is undecidable. Which one of the following is TRUE?(A) P3 is decidable if P1 is reducible to P3(B) P3 is undecidable if P3 is reducible to P2(C) P3 is undecidable if P2 is reducible to P3(D) P3 is decidable if P3 is reducible to P2’s complementAnswer: (C)Explanation: Background: In computational complexity theory, a decision problem has only two possible outputs yes or no.A decision problem is said to be decidable if there exists an effective method or algorithm that returns a correct yes/no answer to that problem.A decision problem is said to be undecidable if there does not exist a single algorithm that always lead to a correct yes/no solution."
},
{
"code": null,
"e": 1065,
"s": 772,
"text": "In terms of reducibility: A ≤p B denotes A is a decision problem that is reducible to B in polynomial time p. This simply means that A’s instance can be transformed into B’s instance and following the solution of B we can get a solution for the problem A.So here we can draw some conclusions:"
},
{
"code": null,
"e": 1756,
"s": 1065,
"text": "1. If A ≤p B and B is decidable then A is also decidable.\nThis is because if there exists a specific algorithm for solving B and we can \nalso reduce A to B then we can have a solution of A as well. Hence A is decidable.\n\nHowever the reverse is not true i.e. if A ≤p B and A is decidable \nthen B is also decidable because A can have an algorithm existing for its correct \nsolution but might be the case that B does not.\n\n2. If A ≤p B and A is undecidable then B is also undecidable.\nThis is because if A is undecidable even when it can be reduced to B that simply \nreflects even B cannot provide an algorithm by which we can solve B and hence A. \nSo decision problem B is also undecidable.\n\n"
},
{
"code": null,
"e": 1943,
"s": 1756,
"text": "However the reverse is not true here as well i.e. if A ≤p B and B is undecidable then A is also undecidable because there might exist an algorithm for A that can provide a solution to A."
},
{
"code": null,
"e": 2044,
"s": 1943,
"text": "Using the above stated conclusions we can say that option 1, 2 and 4 are false and option 3 is true."
},
{
"code": null,
"e": 2440,
"s": 2044,
"text": "Option 1: P1 ≤p P3 and given P1 is decidable gives no conclusion for P3.\nOption 2: P3 ≤p P2 and given P2 is undecidable gives no conclusion for P3.\nOption 3: P2 ≤p P3 and given P2 is undecidable gives conclusion for P3 to be \n undecidable.\nOption 4: P3 ≤p P2’s complement and given P2 is undecidable therefore P2’s \n complement is also undecidable gives no conclusion for P3.\n"
},
{
"code": null,
"e": 2490,
"s": 2440,
"text": "This explanation is contributed by Yashika Arora."
},
{
"code": null,
"e": 2619,
"s": 2490,
"text": "Visit the following articles to learn more:undecidability-and-reducibilityWikipedia: Reduction_(Complexity)Quiz of this Question"
},
{
"code": null,
"e": 2632,
"s": 2619,
"text": "GATE-CS-2005"
},
{
"code": null,
"e": 2650,
"s": 2632,
"text": "GATE-GATE-CS-2005"
},
{
"code": null,
"e": 2655,
"s": 2650,
"text": "GATE"
},
{
"code": null,
"e": 2753,
"s": 2655,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2795,
"s": 2753,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
},
{
"code": null,
"e": 2857,
"s": 2795,
"text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33"
},
{
"code": null,
"e": 2891,
"s": 2857,
"text": "GATE | GATE CS 2008 | Question 46"
},
{
"code": null,
"e": 2933,
"s": 2891,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 2975,
"s": 2933,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 3009,
"s": 2975,
"text": "GATE | GATE CS 2011 | Question 49"
},
{
"code": null,
"e": 3043,
"s": 3009,
"text": "GATE | GATE CS 1996 | Question 38"
},
{
"code": null,
"e": 3077,
"s": 3043,
"text": "GATE | GATE-CS-2004 | Question 31"
},
{
"code": null,
"e": 3119,
"s": 3077,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 45"
}
] |
turtle.left() method in Python | 16 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
The turtle.left() method is used to change the direction of the turtle by the value of the argument that it takes. It gives the moving of the head of the turtle in a direction.
turtle.left(angle)
The argument it takes is angle { a number (integer or float) }. So, it turns turtle left by angle units. (Units are by default degrees but can be set via the degrees() and radians() functions.) Angle orientation depends on the mode.
Below is the implementation of the above method with some examples :
Example 1:
Python3
# importing packageimport turtle # move the turtle forward by # 100 unit distance in the# direction of head of turtleturtle.forward(100) # change the direction of turtle# by 90 degrees to the left.turtle.left(90) # move the turtle forward by # 100 unit distance in the # direction of head of turtleturtle.forward(100)
Output:
Example 2:
Python3
# importing packageimport turtle # Loop for patternfor i in range(10): # move the turtle forward by # 100+variable unit distance # in the direction of head of # turtle turtle.forward(100+10*i) # change the direction of turtle # by 90 degrees to the left. turtle.left(90)
Output :
Python-turtle
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Jul, 2020"
},
{
"code": null,
"e": 245,
"s": 28,
"text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support."
},
{
"code": null,
"e": 423,
"s": 245,
"text": "The turtle.left() method is used to change the direction of the turtle by the value of the argument that it takes. It gives the moving of the head of the turtle in a direction. "
},
{
"code": null,
"e": 443,
"s": 423,
"text": "turtle.left(angle)\n"
},
{
"code": null,
"e": 676,
"s": 443,
"text": "The argument it takes is angle { a number (integer or float) }. So, it turns turtle left by angle units. (Units are by default degrees but can be set via the degrees() and radians() functions.) Angle orientation depends on the mode."
},
{
"code": null,
"e": 745,
"s": 676,
"text": "Below is the implementation of the above method with some examples :"
},
{
"code": null,
"e": 756,
"s": 745,
"text": "Example 1:"
},
{
"code": null,
"e": 764,
"s": 756,
"text": "Python3"
},
{
"code": "# importing packageimport turtle # move the turtle forward by # 100 unit distance in the# direction of head of turtleturtle.forward(100) # change the direction of turtle# by 90 degrees to the left.turtle.left(90) # move the turtle forward by # 100 unit distance in the # direction of head of turtleturtle.forward(100)",
"e": 1087,
"s": 764,
"text": null
},
{
"code": null,
"e": 1095,
"s": 1087,
"text": "Output:"
},
{
"code": null,
"e": 1106,
"s": 1095,
"text": "Example 2:"
},
{
"code": null,
"e": 1114,
"s": 1106,
"text": "Python3"
},
{
"code": "# importing packageimport turtle # Loop for patternfor i in range(10): # move the turtle forward by # 100+variable unit distance # in the direction of head of # turtle turtle.forward(100+10*i) # change the direction of turtle # by 90 degrees to the left. turtle.left(90)",
"e": 1403,
"s": 1114,
"text": null
},
{
"code": null,
"e": 1412,
"s": 1403,
"text": "Output :"
},
{
"code": null,
"e": 1426,
"s": 1412,
"text": "Python-turtle"
},
{
"code": null,
"e": 1433,
"s": 1426,
"text": "Python"
},
{
"code": null,
"e": 1531,
"s": 1433,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1563,
"s": 1531,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1590,
"s": 1563,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1611,
"s": 1590,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1642,
"s": 1611,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1698,
"s": 1642,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1721,
"s": 1698,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1763,
"s": 1721,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1805,
"s": 1763,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1844,
"s": 1805,
"text": "Python | datetime.timedelta() function"
}
] |
Union of two arrays | Practice | GeeksforGeeks | Given two arrays a[] and b[] of size n and m respectively. The task is to find union between these two arrays.
Union of the two arrays can be defined as the set containing distinct elements from both the arrays. If there are repetitions, then only one occurrence of element should be printed in the union.
Example 1:
Input:
5 3
1 2 3 4 5
1 2 3
Output:
5
Explanation:
1, 2, 3, 4 and 5 are the
elements which comes in the union set
of both arrays. So count is 5.
Example 2:
Input:
6 2
85 25 1 32 54 6
85 2
Output:
7
Explanation:
85, 25, 1, 32, 54, 6, and
2 are the elements which comes in the
union set of both arrays. So count is 7.
Your Task:
Complete doUnion funciton that takes a, n, b, m as parameters and returns the count of union elements of the two arrays. The printing is done by the driver code.
Constraints:
1 ≤ n, m ≤ 105
0 ≤ a[i], b[i] < 105
Elements are not necessarily distinct.
Expected Time Complexity : O((n+m)log(n+m))
Expected Auxilliary Space : O(n+m)
0
kumartanwar123in 9 hours
Easiest C++ solution:
Just make a frequency table (use unordered_map), and add both the arrays in it, and its size is the answer.
int doUnion(int a[], int n, int b[], int m) {
unordered_map<int, int> frequency;
for(int i = 0;i<n;i++)
{
frequency[a[i]]++;
}
for(int i = 0;i<m;i++)
{
frequency[b[i]]++;
}
return frequency.size();
}
0
madhusudhanreddyg72in 8 hours
class Solution{ public static int doUnion(int a[], int n, int b[], int m) { //Your code here int len=m+n; int x[]= new int [m+n]; int q=0; for(int i=0;i<n;i++) x[q++]=a[i]; for(int i=0;i<m;i++) x[q++]=b[i]; Arrays.sort(x); for(int i=1;i<m+n;i++) if(x[i-1]==x[i]) len--; return len; }}
0
aakasshuitin 4 hours
Simplest Java Solution :
HashSet<Integer> set = new HashSet<>();
for(int i=0;i<n;i++){
set.add(a[i]);
}
for(int i=0;i<m;i++){
set.add(b[i]);
}
return set.size();
0
nishantshah1729in 1 hour
EASIEST JAVA SOLUTION:O(N)
HashSet<Integer> set=new HashSet<>(); for(int x:a)set.add(x); for(int x:b)set.add(x); int k=0; return set.size();
0
jyash812611 hours ago
Here is my approach to this question
class Solution{ public: //Function to return the count of number of elements in union of two arrays. int doUnion(int a[], int n, int b[], int m) { set<int>s; for(int i=0;i<n;i++){ s.insert(a[i]); } for(int i=0;i<m;i++){ s.insert(b[i]); } return s.size(); }};
0
dhanakdeepak4219 hours ago
class Solution{ public static int doUnion(int a[], int n, int b[], int m) { //Your code here int c=0; HashMap<Integer,Integer> hs=new HashMap<Integer,Integer>(); for(int i=0;i<n;i++) { hs.put(a[i],i); } for(int i=0;i<m;i++) { hs.put(b[i],i); } c=hs.size(); return c; }}
0
dhanakdeepak4219 hours ago
class Solution{ public static int doUnion(int a[], int n, int b[], int m) { //Your code here int c=0; HashSet<Integer> hs=new HashSet<>(); for(int i=0;i<n;i++) { hs.add(a[i]); } for(int i=0;i<m;i++) { hs.add(b[i]); } c=hs.size(); return c; }}
0
rathodumang3191 day ago
Java Solution:
class Solution{
public static int doUnion(int a[], int n, int b[], int m)
{
HashSet<Integer> set = new HashSet<>();
for(int x : a){
set.add(x);
}
for(int x : b){
set.add(x);
}
return set.size();
}
}
0
user_j52mzyl2 days ago
public static int doUnion(int a[], int n, int b[], int m)
{
int[] arr = new int[n+m];
int k=0;
for(int i=0;i<n;i++){
arr[k] = a[i];
k++;
}
for(int j=0;j<m;j++){
arr[k] = b[j];
k++;
}
Arrays.sort(arr);
int count=0;
for(int i=0;i<k;i++){
if(i< k-1 && arr[i]==arr[i+1]){
count++;
}
}
return k-count;
}
0
kanishk2512963 days ago
int doUnion(int a[], int n, int b[], int m) {
//code here
unordered_set<int> res(a,a+n);
for(int i=0; i<m; i++){
res.insert(b[i]);
}
return res.size();
}
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.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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": 350,
"s": 238,
"text": "Given two arrays a[] and b[] of size n and m respectively. The task is to find union between these two arrays. "
},
{
"code": null,
"e": 545,
"s": 350,
"text": "Union of the two arrays can be defined as the set containing distinct elements from both the arrays. If there are repetitions, then only one occurrence of element should be printed in the union."
},
{
"code": null,
"e": 556,
"s": 545,
"text": "Example 1:"
},
{
"code": null,
"e": 703,
"s": 556,
"text": "Input:\n5 3\n1 2 3 4 5\n1 2 3\nOutput: \n5\nExplanation: \n1, 2, 3, 4 and 5 are the\nelements which comes in the union set\nof both arrays. So count is 5.\n"
},
{
"code": null,
"e": 714,
"s": 703,
"text": "Example 2:"
},
{
"code": null,
"e": 878,
"s": 714,
"text": "Input:\n6 2 \n85 25 1 32 54 6\n85 2 \nOutput: \n7\nExplanation: \n85, 25, 1, 32, 54, 6, and\n2 are the elements which comes in the\nunion set of both arrays. So count is 7."
},
{
"code": null,
"e": 1051,
"s": 878,
"text": "Your Task:\nComplete doUnion funciton that takes a, n, b, m as parameters and returns the count of union elements of the two arrays. The printing is done by the driver code."
},
{
"code": null,
"e": 1100,
"s": 1051,
"text": "Constraints:\n1 ≤ n, m ≤ 105\n0 ≤ a[i], b[i] < 105"
},
{
"code": null,
"e": 1139,
"s": 1100,
"text": "Elements are not necessarily distinct."
},
{
"code": null,
"e": 1218,
"s": 1139,
"text": "Expected Time Complexity : O((n+m)log(n+m))\nExpected Auxilliary Space : O(n+m)"
},
{
"code": null,
"e": 1220,
"s": 1218,
"text": "0"
},
{
"code": null,
"e": 1245,
"s": 1220,
"text": "kumartanwar123in 9 hours"
},
{
"code": null,
"e": 1267,
"s": 1245,
"text": "Easiest C++ solution:"
},
{
"code": null,
"e": 1375,
"s": 1267,
"text": "Just make a frequency table (use unordered_map), and add both the arrays in it, and its size is the answer."
},
{
"code": null,
"e": 1668,
"s": 1375,
"text": "int doUnion(int a[], int n, int b[], int m) {\n unordered_map<int, int> frequency;\n for(int i = 0;i<n;i++)\n {\n frequency[a[i]]++;\n }\n for(int i = 0;i<m;i++)\n {\n frequency[b[i]]++;\n }\n return frequency.size();\n }"
},
{
"code": null,
"e": 1670,
"s": 1668,
"text": "0"
},
{
"code": null,
"e": 1700,
"s": 1670,
"text": "madhusudhanreddyg72in 8 hours"
},
{
"code": null,
"e": 2097,
"s": 1700,
"text": "class Solution{ public static int doUnion(int a[], int n, int b[], int m) { //Your code here int len=m+n; int x[]= new int [m+n]; int q=0; for(int i=0;i<n;i++) x[q++]=a[i]; for(int i=0;i<m;i++) x[q++]=b[i]; Arrays.sort(x); for(int i=1;i<m+n;i++) if(x[i-1]==x[i]) len--; return len; }}"
},
{
"code": null,
"e": 2099,
"s": 2097,
"text": "0"
},
{
"code": null,
"e": 2120,
"s": 2099,
"text": "aakasshuitin 4 hours"
},
{
"code": null,
"e": 2145,
"s": 2120,
"text": "Simplest Java Solution :"
},
{
"code": null,
"e": 2369,
"s": 2147,
"text": " HashSet<Integer> set = new HashSet<>();\n \n for(int i=0;i<n;i++){\n set.add(a[i]);\n }\n for(int i=0;i<m;i++){\n set.add(b[i]);\n }\n return set.size();"
},
{
"code": null,
"e": 2371,
"s": 2369,
"text": "0"
},
{
"code": null,
"e": 2396,
"s": 2371,
"text": "nishantshah1729in 1 hour"
},
{
"code": null,
"e": 2423,
"s": 2396,
"text": "EASIEST JAVA SOLUTION:O(N)"
},
{
"code": null,
"e": 2561,
"s": 2423,
"text": "HashSet<Integer> set=new HashSet<>(); for(int x:a)set.add(x); for(int x:b)set.add(x); int k=0; return set.size();"
},
{
"code": null,
"e": 2563,
"s": 2561,
"text": "0"
},
{
"code": null,
"e": 2585,
"s": 2563,
"text": "jyash812611 hours ago"
},
{
"code": null,
"e": 2622,
"s": 2585,
"text": "Here is my approach to this question"
},
{
"code": null,
"e": 2948,
"s": 2624,
"text": "class Solution{ public: //Function to return the count of number of elements in union of two arrays. int doUnion(int a[], int n, int b[], int m) { set<int>s; for(int i=0;i<n;i++){ s.insert(a[i]); } for(int i=0;i<m;i++){ s.insert(b[i]); } return s.size(); }};"
},
{
"code": null,
"e": 2950,
"s": 2948,
"text": "0"
},
{
"code": null,
"e": 2977,
"s": 2950,
"text": "dhanakdeepak4219 hours ago"
},
{
"code": null,
"e": 3340,
"s": 2977,
"text": "class Solution{ public static int doUnion(int a[], int n, int b[], int m) { //Your code here int c=0; HashMap<Integer,Integer> hs=new HashMap<Integer,Integer>(); for(int i=0;i<n;i++) { hs.put(a[i],i); } for(int i=0;i<m;i++) { hs.put(b[i],i); } c=hs.size(); return c; }}"
},
{
"code": null,
"e": 3342,
"s": 3340,
"text": "0"
},
{
"code": null,
"e": 3369,
"s": 3342,
"text": "dhanakdeepak4219 hours ago"
},
{
"code": null,
"e": 3705,
"s": 3369,
"text": "class Solution{ public static int doUnion(int a[], int n, int b[], int m) { //Your code here int c=0; HashSet<Integer> hs=new HashSet<>(); for(int i=0;i<n;i++) { hs.add(a[i]); } for(int i=0;i<m;i++) { hs.add(b[i]); } c=hs.size(); return c; }}"
},
{
"code": null,
"e": 3707,
"s": 3705,
"text": "0"
},
{
"code": null,
"e": 3731,
"s": 3707,
"text": "rathodumang3191 day ago"
},
{
"code": null,
"e": 3746,
"s": 3731,
"text": "Java Solution:"
},
{
"code": null,
"e": 4030,
"s": 3746,
"text": "class Solution{\n public static int doUnion(int a[], int n, int b[], int m) \n {\n HashSet<Integer> set = new HashSet<>();\n for(int x : a){\n set.add(x);\n }\n for(int x : b){\n set.add(x);\n }\n return set.size();\n }\n}"
},
{
"code": null,
"e": 4032,
"s": 4030,
"text": "0"
},
{
"code": null,
"e": 4055,
"s": 4032,
"text": "user_j52mzyl2 days ago"
},
{
"code": null,
"e": 4556,
"s": 4055,
"text": "public static int doUnion(int a[], int n, int b[], int m) \n {\n int[] arr = new int[n+m];\n int k=0;\n for(int i=0;i<n;i++){\n arr[k] = a[i];\n k++;\n }\n for(int j=0;j<m;j++){\n arr[k] = b[j];\n k++;\n }\n \n Arrays.sort(arr);\n int count=0;\n for(int i=0;i<k;i++){\n if(i< k-1 && arr[i]==arr[i+1]){\n count++;\n }\n }\n return k-count;\n }"
},
{
"code": null,
"e": 4558,
"s": 4556,
"text": "0"
},
{
"code": null,
"e": 4582,
"s": 4558,
"text": "kanishk2512963 days ago"
},
{
"code": null,
"e": 4797,
"s": 4582,
"text": " int doUnion(int a[], int n, int b[], int m) {\n //code here\n unordered_set<int> res(a,a+n);\n for(int i=0; i<m; i++){\n res.insert(b[i]);\n }\n return res.size();\n }"
},
{
"code": null,
"e": 4943,
"s": 4797,
"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": 4979,
"s": 4943,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4989,
"s": 4979,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4999,
"s": 4989,
"text": "\nContest\n"
},
{
"code": null,
"e": 5062,
"s": 4999,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5247,
"s": 5062,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 5531,
"s": 5247,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 5677,
"s": 5531,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 5754,
"s": 5677,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 5795,
"s": 5754,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 5823,
"s": 5795,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 5894,
"s": 5823,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 6081,
"s": 5894,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
Sort an array according to the order defined by another array | 23 Jun, 2022
Given two arrays A1[] and A2[], sort A1 in such a way that the relative order among the elements will be same as those are in A2. For the elements not present in A2, append them at last in sorted order.
Example:
Input: A1[] = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8}
A2[] = {2, 1, 8, 3}
Output: A1[] = {2, 2, 1, 1, 8, 8, 3, 5, 6, 7, 9}
The code should handle all cases like the number of elements in A2[] may be more or less compared to A1[]. A2[] may have some elements which may not be there in A1[] and vice versa is also possible.
Source: Amazon Interview | Set 110 (On-Campus)
Method 1 (Using Sorting and Binary Search) Let the size of A1[] be m and the size of A2[] be n.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Create a temporary array temp of size m and copy the contents of A1[] to it.
Create another array visited[] and initialize all entries in it as false. visited[] is used to mark those elements in temp[] which are copied to A1[].
Sort temp[]
Initialize the output index ind as 0.
Do following for every element of A2[i] in A2[] Binary search for all occurrences of A2[i] in temp[], if present then copy all occurrences to A1[ind] and increment ind. Also mark the copied elements visited[]
Binary search for all occurrences of A2[i] in temp[], if present then copy all occurrences to A1[ind] and increment ind. Also mark the copied elements visited[]
Copy all unvisited elements from temp[] to A1[]
Below image is a dry run of the above approach:
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// A C++ program to sort an array according to the order defined// by another array#include <bits/stdc++.h>using namespace std; // A Binary Search based function to find index of FIRST occurrence// of x in arr[]. If x is not present, then it returns -1 // The same can be done using the lower_bound// function in C++ STLint first(int arr[], int low, int high, int x, int n){ // Checking condition if (high >= low) { // FInd the mid element int mid = low + (high - low) / 2; // Check if the element is the extreme left // in the left half of the array if ((mid == 0 || x > arr[mid - 1]) && arr[mid] == x) return mid; // If the element lies on the right half if (x > arr[mid]) return first(arr, (mid + 1), high, x, n); // Check for element in the left half return first(arr, low, (mid - 1), x, n); } // ELement not found return -1;} // Sort A1[0..m-1] according to the order defined by A2[0..n-1].void sortAccording(int A1[], int A2[], int m, int n){ // The temp array is used to store a copy of A1[] and visited[] // is used mark the visited elements in temp[]. int temp[m], visited[m]; for (int i = 0; i < m; i++) { temp[i] = A1[i]; visited[i] = 0; } // Sort elements in temp sort(temp, temp + m); // for index of output which is sorted A1[] int ind = 0; // Consider all elements of A2[], find them in temp[] // and copy to A1[] in order. for (int i = 0; i < n; i++) { // Find index of the first occurrence of A2[i] in temp int f = first(temp, 0, m - 1, A2[i], m); // If not present, no need to proceed if (f == -1) continue; // Copy all occurrences of A2[i] to A1[] for (int j = f; (j < m && temp[j] == A2[i]); j++) { A1[ind++] = temp[j]; visited[j] = 1; } } // Now copy all items of temp[] // which are not present in A2[] for (int i = 0; i < m; i++) if (visited[i] == 0) A1[ind++] = temp[i];} // Utility function to print an arrayvoid printArray(int arr[], int n){ // Iterate in the array for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << endl;} // Driver Codeint main(){ int A1[] = { 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 }; int A2[] = { 2, 1, 8, 3 }; int m = sizeof(A1) / sizeof(A1[0]); int n = sizeof(A2) / sizeof(A2[0]); // Prints the sorted array cout << "Sorted array is \n"; sortAccording(A1, A2, m, n); printArray(A1, m); return 0;}
// A JAVA program to sort an array according// to the order defined by another arrayimport java.io.*;import java.util.Arrays; class GFG { /* A Binary Search based function to find index of FIRST occurrence of x in arr[]. If x is not present, then it returns -1 */ static int first(int arr[], int low, int high, int x, int n) { if (high >= low) { /* (low + high)/2; */ int mid = low + (high - low) / 2; if ((mid == 0 || x > arr[mid - 1]) && arr[mid] == x) return mid; if (x > arr[mid]) return first(arr, (mid + 1), high, x, n); return first(arr, low, (mid - 1), x, n); } return -1; } // Sort A1[0..m-1] according to the order // defined by A2[0..n-1]. static void sortAccording(int A1[], int A2[], int m, int n) { // The temp array is used to store a copy // of A1[] and visited[] is used to mark the // visited elements in temp[]. int temp[] = new int[m], visited[] = new int[m]; for (int i = 0; i < m; i++) { temp[i] = A1[i]; visited[i] = 0; } // Sort elements in temp Arrays.sort(temp); // for index of output which is sorted A1[] int ind = 0; // Consider all elements of A2[], find them // in temp[] and copy to A1[] in order. for (int i = 0; i < n; i++) { // Find index of the first occurrence // of A2[i] in temp int f = first(temp, 0, m - 1, A2[i], m); // If not present, no need to proceed if (f == -1) continue; // Copy all occurrences of A2[i] to A1[] for (int j = f; (j < m && temp[j] == A2[i]); j++) { A1[ind++] = temp[j]; visited[j] = 1; } } // Now copy all items of temp[] which are // not present in A2[] for (int i = 0; i < m; i++) if (visited[i] == 0) A1[ind++] = temp[i]; } // Utility function to print an array static void printArray(int arr[], int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); System.out.println(); } // Driver program to test above function. public static void main(String args[]) { int A1[] = { 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 }; int A2[] = { 2, 1, 8, 3 }; int m = A1.length; int n = A2.length; System.out.println("Sorted array is "); sortAccording(A1, A2, m, n); printArray(A1, m); }} /*This code is contributed by Nikita Tiwari.*/
"""A Python 3 program to sort an arrayaccording to the order defined byanother array""" """A Binary Search based function to findindex of FIRST occurrence of x in arr[].If x is not present, then it returns -1 """ def first(arr, low, high, x, n) : if (high >= low) : mid = low + (high - low) // 2; # (low + high)/2; if ((mid == 0 or x > arr[mid-1]) and arr[mid] == x) : return mid if (x > arr[mid]) : return first(arr, (mid + 1), high, x, n) return first(arr, low, (mid -1), x, n) return -1 # Sort A1[0..m-1] according to the order# defined by A2[0..n-1].def sortAccording(A1, A2, m, n) : """The temp array is used to store a copy of A1[] and visited[] is used mark the visited elements in temp[].""" temp = [0] * m visited = [0] * m for i in range(0, m) : temp[i] = A1[i] visited[i] = 0 # Sort elements in temp temp.sort() # for index of output which is sorted A1[] ind = 0 """Consider all elements of A2[], find them in temp[] and copy to A1[] in order.""" for i in range(0, n) : # Find index of the first occurrence # of A2[i] in temp f = first(temp, 0, m-1, A2[i], m) # If not present, no need to proceed if (f == -1) : continue # Copy all occurrences of A2[i] to A1[] j = f while (j<m and temp[j]== A2[i]) : A1[ind] = temp[j]; ind = ind + 1 visited[j] = 1 j = j + 1 # Now copy all items of temp[] which are # not present in A2[] for i in range(0, m) : if (visited[i] == 0) : A1[ind] = temp[i] ind = ind + 1 # Utility function to print an arraydef printArray(arr, n) : for i in range(0, n) : print(arr[i], end = " ") print("") # Driver program to test above function.A1 = [2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8]A2 = [2, 1, 8, 3]m = len(A1)n = len(A2)print("Sorted array is ")sortAccording(A1, A2, m, n)printArray(A1, m) # This code is contributed by Nikita Tiwari.
// A C# program to sort an array according// to the order defined by another arrayusing System; class GFG { /* A Binary Search based function to find index of FIRST occurrence of x in arr[]. If x is not present, then it returns -1 */ static int first(int[] arr, int low, int high, int x, int n) { if (high >= low) { /* (low + high)/2; */ int mid = low + (high - low) / 2; if ((mid == 0 || x > arr[mid - 1]) && arr[mid] == x) return mid; if (x > arr[mid]) return first(arr, (mid + 1), high, x, n); return first(arr, low, (mid - 1), x, n); } return -1; } // Sort A1[0..m-1] according to the order // defined by A2[0..n-1]. static void sortAccording(int[] A1, int[] A2, int m, int n) { // The temp array is used to store a copy // of A1[] and visited[] is used to mark // the visited elements in temp[]. int[] temp = new int[m]; int[] visited = new int[m]; for (int i = 0; i < m; i++) { temp[i] = A1[i]; visited[i] = 0; } // Sort elements in temp Array.Sort(temp); // for index of output which is // sorted A1[] int ind = 0; // Consider all elements of A2[], find // them in temp[] and copy to A1[] in // order. for (int i = 0; i < n; i++) { // Find index of the first occurrence // of A2[i] in temp int f = first(temp, 0, m - 1, A2[i], m); // If not present, no need to proceed if (f == -1) continue; // Copy all occurrences of A2[i] to A1[] for (int j = f; (j < m && temp[j] == A2[i]); j++) { A1[ind++] = temp[j]; visited[j] = 1; } } // Now copy all items of temp[] which are // not present in A2[] for (int i = 0; i < m; i++) if (visited[i] == 0) A1[ind++] = temp[i]; } // Utility function to print an array static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); Console.WriteLine(); } // Driver program to test above function. public static void Main() { int[] A1 = { 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 }; int[] A2 = { 2, 1, 8, 3 }; int m = A1.Length; int n = A2.Length; Console.WriteLine("Sorted array is "); sortAccording(A1, A2, m, n); printArray(A1, m); }} // This code is contributed by nitin mittal.
<?php// A PHP program to sort an array according// to the order defined by another array /* A Binary Search based function to find indexof FIRST occurrence of x in arr[]. If x is notpresent, then it returns -1 */function first(&$arr, $low, $high, $x, $n){ if ($high >= $low) { $mid = intval($low + ($high - $low) / 2); if (($mid == 0 || $x > $arr[$mid - 1]) && $arr[$mid] == $x) return $mid; if ($x > $arr[$mid]) return first($arr, ($mid + 1), $high, $x, $n); return first($arr, $low, ($mid - 1), $x, $n); } return -1;} // Sort A1[0..m-1] according to the order// defined by A2[0..n-1].function sortAccording(&$A1, &$A2, $m, $n){ // The temp array is used to store a copy // of A1[] and visited[] is used mark the // visited elements in temp[]. $temp = array_fill(0, $m, NULL); $visited = array_fill(0, $m, NULL); for ($i = 0; $i < $m; $i++) { $temp[$i] = $A1[$i]; $visited[$i] = 0; } // Sort elements in temp sort($temp); $ind = 0; // for index of output which is sorted A1[] // Consider all elements of A2[], find // them in temp[] and copy to A1[] in order. for ($i = 0; $i < $n; $i++) { // Find index of the first occurrence // of A2[i] in temp $f = first($temp, 0, $m - 1, $A2[$i], $m); // If not present, no need to proceed if ($f == -1) continue; // Copy all occurrences of A2[i] to A1[] for ($j = $f; ($j < $m && $temp[$j] == $A2[$i]); $j++) { $A1[$ind++] = $temp[$j]; $visited[$j] = 1; } } // Now copy all items of temp[] which // are not present in A2[] for ($i = 0; $i < $m; $i++) if ($visited[$i] == 0) $A1[$ind++] = $temp[$i];} // Utility function to print an arrayfunction printArray(&$arr, $n){ for ($i = 0; $i < $n; $i++) echo $arr[$i] . " "; echo "\n";} // Driver Code$A1 = array(2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8);$A2 = array(2, 1, 8, 3);$m = sizeof($A1);$n = sizeof($A2);echo "Sorted array is \n";sortAccording($A1, $A2, $m, $n);printArray($A1, $m); // This code is contributed by ita_c?>
<script> // A JavaScript program to sort an array according// to the order defined by another array /* A Binary Search based function to find index of FIRST occurrence of x in arr[]. If x is not present, then it returns -1 */ function first(arr,low,high,x,n) { if (high >= low) { // (low + high)/2; let mid = low + Math.floor((high - low) / 2); if ((mid == 0 || x > arr[mid - 1]) && arr[mid] == x) return mid; if (x > arr[mid]) return first(arr, (mid + 1), high,x, n); return first(arr, low, (mid - 1), x, n); } return -1; } // Sort A1[0..m-1] according to the order // defined by A2[0..n-1]. function sortAccording(A1,A2,m,n) { // The temp array is used to store a copy // of A1[] and visited[] is used to mark the // visited elements in temp[]. let temp=[]; let visited=[]; for (let i = 0; i < m; i++) { temp[i] = A1[i]; visited[i] = 0; } // Sort elements in temp temp.sort(function(a, b){return a-b}); // for index of output which is sorted A1[] let ind = 0; // Consider all elements of A2[], find them // in temp[] and copy to A1[] in order. for (let i = 0; i < n; i++) { // Find index of the first occurrence // of A2[i] in temp let f = first(temp, 0, m - 1, A2[i], m); // If not present, no need to proceed if (f == -1) { continue; } // Copy all occurrences of A2[i] to A1[] for (let j = f; (j < m && temp[j] == A2[i]);j++) { A1[ind++] = temp[j]; visited[j] = 1; } } // Now copy all items of temp[] which are // not present in A2[] for (let i = 0; i < m; i++) { if (visited[i] == 0) A1[ind++] = temp[i]; } } // Utility function to print an array function printArray(arr,n) { for (let i = 0; i < n; i++) { document.write(arr[i] + " "); } document.write("<br>"); } // Driver program to test above function. let A1=[2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 ]; let A2=[2, 1, 8, 3 ]; let m = A1.length; let n = A2.length; document.write("Sorted array is <br>"); sortAccording(A1, A2, m, n); printArray(A1, m); // This code is contributed by avanitrachhadiya2155 </script>
Sorted array is
2 2 1 1 8 8 3 5 6 7 9
Time complexity: The steps 1 and 2 require O(m) time. Step 3 requires O(M * Log M) time. Step 5 requires O(N Log M) time. Therefore overall time complexity is O(M Log M + N Log M).
Method 2 (Using Self-Balancing Binary Search Tree) :
We can also use a self-balancing BST like AVL Tree, Red Black Tree, etc. Following are detailed steps.
Create a self-balancing BST of all elements in A1[]. In every node of BST, also keep track of count of occurrences of the key and a bool field visited which is initialized as false for all nodes.
Initialize the output index ind as 0.
Do following for every element of A2[i] in A2[] Search for A2[i] in the BST, if present then copy all occurrences to A1[ind] and increment ind. Also mark the copied elements visited in the BST node.
Search for A2[i] in the BST, if present then copy all occurrences to A1[ind] and increment ind. Also mark the copied elements visited in the BST node.
Search for A2[i] in the BST, if present then copy all occurrences to A1[ind] and increment ind. Also mark the copied elements visited in the BST node.
Do an inorder traversal of BST and copy all unvisited keys to A1[].
Time Complexity of this method is the same as the previous method. Note that in a self-balancing Binary Search Tree, all operations require logm time.
Method 3 (Use Hashing):
Loop through A1[], store the count of every number in a HashMap (key: number, value: count of number)
Loop through A2[], check if it is present in HashMap, if so, put in output array that many times and remove the number from HashMap.
Sort the rest of the numbers present in HashMap and put in the output array.
Below is the implementation of the above approach:
C++
Java
Python3
Javascript
// A C++ program to sort an array according to the order// defined by another array#include <bits/stdc++.h>using namespace std; // function to sort A1 according to A2 using hash map in C++void sortA1ByA2(int A1[], int N, int A2[], int M, int ans[]){ map<int, int> mp; // indexing for answer = ans array int ind = 0; // initially storing frequency of each element of A1 in // map [ key, value ] = [ A1[i] , frequency[ A1[i] ] ] for (int i = 0; i < N; i++) { mp[A1[i]] += 1; } // traversing each element of A2, first come first serve for (int i = 0; i < M; i++) { // checking if current element of A2 is present in // A1 or not if not present go to next iteration // else store number of times it is appearing in A1 // in ans array if (mp[A2[i]] != 0) { // mp[ A2[i] ] = frequency of A2[i] element in // A1 array for (int j = 1; j <= mp[A2[i]]; j++) ans[ind++] = A2[i]; } // to avoid duplicate storing of same element of A2 // in ans array mp.erase(A2[i]); } // store the remaining elements of A1 in sorted order in // ans array for (auto it : mp) { // it.second = frequency of remaining elements for (int j = 1; j <= it.second; j++) ans[ind++] = it.first; }} // Utility function to print an arrayvoid printArray(int arr[], int n){ // Iterate in the array for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << endl;} // Driver Codeint main(){ int A1[] = { 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 }; int A2[] = { 2, 1, 8, 3 }; int n = sizeof(A1) / sizeof(A1[0]); int m = sizeof(A2) / sizeof(A2[0]); // The ans array is used to store the final sorted array int ans[n]; sortA1ByA2(A1, n, A2, m, ans); // Prints the sorted array cout << "Sorted array is \n"; printArray(ans, n); return 0;}
// A Java program to sort an array according to the order// defined by another array import java.io.*;import java.util.Arrays;import java.util.HashMap; class GFG { // function to sort A1 according to A2 using hash map in C++static void sortA1ByA2(int A1[], int N, int A2[], int M, int ans[]){ HashMap<Integer, Integer> mp = new HashMap<>(); // indexing for answer = ans array int ind = 0; // initially storing frequency of each element of A1 in // map [ key, value ] = [ A1[i] , frequency[ A1[i] ] ] for (int i = 0; i < N; i++) { if (!mp.containsKey(A1[i])) mp.put(A1[i],1); else mp.put(A1[i],mp.get(A1[i])+1); } // traversing each element of A2, first come first serve for (int i = 0; i < M; i++) { // checking if current element of A2 is present in // A1 or not if not present go to next iteration // else store number of times it is appearing in A1 // in ans array if (mp.containsKey(A2[i])) { // mp[ A2[i] ] = frequency of A2[i] element in // A1 array for (int j = 1; j <= mp.get(A2[i]); j++) ans[ind++] = A2[i]; } // to avoid duplicate storing of same element of A2 // in ans array mp.remove(A2[i]); } // store the remaining elements of A1 in sorted order in // ans array for (HashMap.Entry<Integer,Integer> it : mp.entrySet()) { // it.second = frequency of remaining elements for (int j = 1; j <= it.getValue(); j++) ans[ind++] = it.getKey(); }} // Utility function to print an array static void printArray(int arr[], int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); System.out.println(); } // Driver code public static void main(String[] args) { int A1[] = { 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 }; int A2[] = { 2, 1, 8, 3 }; int n = A1.length; int m = A2.length; // The ans array is used to store the final sorted array int ans[]=new int[n]; sortA1ByA2(A1, n, A2, m, ans); System.out.println("Sorted array is "); printArray(ans, n); }} // This code is contributed by Pushpesh Raj.
from collections import Counter # Function to sort arr1# according to arr2def solve(arr1, arr2): # Our output array res = [] # Counting Frequency of each # number in arr1 f = Counter(arr1) # Iterate over arr2 and append all # occurrences of element of # arr2 from arr1 for e in arr2: # Appending element 'e', # f[e] number of times res.extend([e]*f[e]) # Count of 'e' after appending is zero f[e] = 0 # Remaining numbers in arr1 in sorted # order (Numbers with non-zero frequency) rem = list(sorted(filter( lambda x: f[x] != 0, f.keys()))) # Append them also for e in rem: res.extend([e]*f[e]) return res # Driver Codeif __name__ == "__main__": arr1 = [2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8] arr2 = [2, 1, 8, 3] print(*solve(arr1, arr2))
<script> // A JavaScript program to sort an array according to the order// defined by another array // function to sort A1 according to A2 using hash map in C++function sortA1ByA2(A1, N, A2, M, ans){ let mp = new Map(); // indexing for answer = ans array let ind = 0; // initially storing frequency of each element of A1 in // map [ key, value ] = [ A1[i] , frequency[ A1[i] ] ] for (let i = 0; i < N; i++) { if(!mp.has(A1[i])){ mp.set(A1[i],1); } else mp.set(A1[i],mp.get(A1[i]) + 1); } // traversing each element of A2, first come first serve for (let i = 0; i < M; i++) { // checking if current element of A2 is present in // A1 or not if not present go to next iteration // else store number of times it is appearing in A1 // in ans array if (mp.has(A2[i])) { // mp[ A2[i] ] = frequency of A2[i] element in // A1 array for (let j = 1; j <= mp.get(A2[i]); j++) ans[ind++] = A2[i]; } // to avoid duplicate storing of same element of A2 // in ans array mp.delete(A2[i]); } // store the remaining elements of A1 in sorted order in // ans array mp = new Map([...mp.entries()].sort()); for (let [key,value] of mp) { // it.second = frequency of remaining elements for (let j = 1; j <= value; j++) ans[ind++] = key; }} // Utility function to print an arrayfunction printArray(arr, n){ // Iterate in the array for (let i = 0; i <n; i++) document.write(arr[i]," "); document.write("</br>");} // Driver Code let A1 = [ 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 ];let A2 = [ 2, 1, 8, 3 ];let n = A1.length;let m = A2.length; // The ans array is used to store the final sorted arraylet ans = new Array(n);sortA1ByA2(A1, n, A2, m, ans); // Prints the sorted arraydocument.write("Sorted array is ");printArray(ans, n); // This code is contributed by shinjanpatra</script>
2 2 1 1 8 8 3 5 6 7 9
Steps 1 and 2 on average take O(m+n) time under the assumption that we have a good hashing function that takes O(1) time for insertion and search on average. The third step takes O(p Log p) time where p is the number of elements remained after considering elements of A2[].
Method 4 (By Writing a Customized Compare Method):
We can also customize compare method of a sorting algorithm to solve the above problem. For example, qsort() in C allows us to pass our own customized compare method.
If num1 and num2 both are in A2 then the number with a lower index in A2 will be treated smaller than others.
If only one of num1 or num2 present in A2, then that number will be treated smaller than the other which doesn’t present in A2.
If both are not in A2, then the natural ordering will be taken.
The time complexity of this method is O(mnLogm) if we use a O(nLogn) time complexity sorting algorithm. We can improve time complexity to O(mLogm) by using a Hashing instead of doing linear search.
Below is the implementation of the above approach:
C++
C
Java
// A C++ program to sort an array according to the order defined// by another array #include<bits/stdc++.h>using namespace std; //function that sorts the first array based on order of them in second arrayvoid sortA1ByA2(vector<int> &arr1 , vector<int> &arr2){ //map to store the indices of second array // so that we can easily judge the position of two elements in first array unordered_map<int , int> index; for(int i=0; i<arr2.size(); i++){ //assigning i+1 // because by default value of map is zero // Consider only first occurrence of element if (index[arr2[i]] == 0) { index[arr2[i]] = i+1; } } //comparator function that sorts arr1 based on order // defined in arr2 auto comp = [&](int a , int b){ // if indices of two elements are equal // we need to sort them in increasing order if(index[a] == 0 && index[b]==0) return a<b; //if a not present in arr2 then b should come before it if(index[a] == 0) return false; //if b not present in arr2 then no swap if(index[b] == 0) return true; // sorting in increasing order return index[a] < index[b]; }; sort(arr1.begin(), arr1.end() , comp); } int main(){ vector<int> arr1{ 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8, 7, 5, 6, 9, 7, 5 }; vector<int> arr2{2 , 1 , 8 , 3 , 4, 1}; sortA1ByA2(arr1 , arr2); //printing the array cout<<"Sorted array is \n"; for(auto i: arr1){ cout<<i<<" "; } return 0; }
// A C++ program to sort an array according to the order defined// by another array#include <stdio.h>#include <stdlib.h> // A2 is made global here so that it can be accesed by compareByA2()// The syntax of qsort() allows only two parameters to compareByA2()int A2[5]; // size of A2[]int size = 5; int search(int key){ int i = 0, idx = 0; for (i = 0; i < size; i++) if (A2[i] == key) return i; return -1;} // A custom compare method to compare elements of A1[] according// to the order defined by A2[].int compareByA2(const void* a, const void* b){ int idx1 = search(*(int*)a); int idx2 = search(*(int*)b); if (idx1 != -1 && idx2 != -1) return idx1 - idx2; else if (idx1 != -1) return -1; else if (idx2 != -1) return 1; else return (*(int*)a - *(int*)b);} // This method mainly uses qsort to sort A1[] according to A2[]void sortA1ByA2(int A1[], int size1){ qsort(A1, size1, sizeof(int), compareByA2);} // Driver program to test above functionint main(int argc, char* argv[]){ int A1[] = { 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8, 7, 5, 6, 9, 7, 5 }; // A2[] = {2, 1, 8, 3, 4}; A2[0] = 2; A2[1] = 1; A2[2] = 8; A2[3] = 3; A2[4] = 4; int size1 = sizeof(A1) / sizeof(A1[0]); sortA1ByA2(A1, size1); printf("Sorted Array is "); int i; for (i = 0; i < size1; i++) printf("%d ", A1[i]); return 0;}
// A Java program to sort an array according to the order// defined by another array import java.io.*;import java.util.Arrays;import java.util.HashMap; class GFG { static void sortAccording(int[] A1, int[] A2, int m, int n) { // HashMap to store the indices of elements in // the second array HashMap<Integer, Integer> index = new HashMap<>(); for (int i = 0; i < n; i++) { // Consider only first occurrence of element if (!index.containsKey(A2[i])) // Assign value of i+1 index.put(A2[i], i + 1); } // Since Java does not support custom comparators on // primitive data types, we box the elements in // wrapper classes. // Sorted values are stored in a temporary // array. int[] tmp = Arrays.stream(A1) .boxed() .sorted((p1, p2) -> { int idx1 = index.getOrDefault(p1, 0); int idx2 = index.getOrDefault(p2, 0); // If both p1 and p2 are not present // in the second array, // sort them in ascending order if (idx1 == 0 && idx2 == 0) return p1 - p2; // If only p2 is present in the second // array, p2 comes before p1 if (idx1 == 0) return 1; // If only p1 is present in the second // array, p1 comes before p2 (no swap) if (idx2 == 0) return -1; // If both p1 and p2 are present in // the second array, sort them // according to their respective // indices return idx1 - idx2; }) .mapToInt(i -> i) .toArray(); // Sorted values are copied to the original // array for (int i = 0; i < m; i++) { A1[i] = tmp[i]; } } // Driver program to test the above function public static void main(String[] args) { int A1[] = { 2, 1, 2, 5, 7, 1, 9, 9, 3, 6, 8, 8 }; int A2[] = { 2, 1, 8, 3, 1 }; int m = A1.length; int n = A2.length; sortAccording(A1, A2, m, n); System.out.println("Sorted array is "); System.out.println(Arrays.toString(A1)); }} // This code is contributed by anonymouscegian
Sorted Array is 2 2 1 1 8 8 3 5 5 5 6 6 7 7 7 9 9
nitin mittal
Suryaveer Singh
ukasp
lohityakumarambashta
avanitrachhadiya2155
deepaksati
sumitgumber28
anonymouscegian
shinjanpatra
rkbhola5
sweetyty
pushpeshrajdx01
hardikkoriintern
Amazon
Insertion Sort
Microsoft
Arrays
Searching
Sorting
Amazon
Microsoft
Arrays
Searching
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Largest Sum Contiguous Subarray
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
K'th Smallest/Largest Element in Unsorted Array | Set 1
Search an element in a sorted and rotated array | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 258,
"s": 54,
"text": "Given two arrays A1[] and A2[], sort A1 in such a way that the relative order among the elements will be same as those are in A2. For the elements not present in A2, append them at last in sorted order. "
},
{
"code": null,
"e": 268,
"s": 258,
"text": "Example: "
},
{
"code": null,
"e": 392,
"s": 268,
"text": "Input: A1[] = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8}\n A2[] = {2, 1, 8, 3}\nOutput: A1[] = {2, 2, 1, 1, 8, 8, 3, 5, 6, 7, 9}"
},
{
"code": null,
"e": 591,
"s": 392,
"text": "The code should handle all cases like the number of elements in A2[] may be more or less compared to A1[]. A2[] may have some elements which may not be there in A1[] and vice versa is also possible."
},
{
"code": null,
"e": 639,
"s": 591,
"text": "Source: Amazon Interview | Set 110 (On-Campus) "
},
{
"code": null,
"e": 736,
"s": 639,
"text": "Method 1 (Using Sorting and Binary Search) Let the size of A1[] be m and the size of A2[] be n. "
},
{
"code": null,
"e": 745,
"s": 736,
"text": "Chapters"
},
{
"code": null,
"e": 772,
"s": 745,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 822,
"s": 772,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 845,
"s": 822,
"text": "captions off, selected"
},
{
"code": null,
"e": 853,
"s": 845,
"text": "English"
},
{
"code": null,
"e": 877,
"s": 853,
"text": "This is a modal window."
},
{
"code": null,
"e": 946,
"s": 877,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 968,
"s": 946,
"text": "End of dialog window."
},
{
"code": null,
"e": 1045,
"s": 968,
"text": "Create a temporary array temp of size m and copy the contents of A1[] to it."
},
{
"code": null,
"e": 1196,
"s": 1045,
"text": "Create another array visited[] and initialize all entries in it as false. visited[] is used to mark those elements in temp[] which are copied to A1[]."
},
{
"code": null,
"e": 1208,
"s": 1196,
"text": "Sort temp[]"
},
{
"code": null,
"e": 1246,
"s": 1208,
"text": "Initialize the output index ind as 0."
},
{
"code": null,
"e": 1455,
"s": 1246,
"text": "Do following for every element of A2[i] in A2[] Binary search for all occurrences of A2[i] in temp[], if present then copy all occurrences to A1[ind] and increment ind. Also mark the copied elements visited[]"
},
{
"code": null,
"e": 1616,
"s": 1455,
"text": "Binary search for all occurrences of A2[i] in temp[], if present then copy all occurrences to A1[ind] and increment ind. Also mark the copied elements visited[]"
},
{
"code": null,
"e": 1664,
"s": 1616,
"text": "Copy all unvisited elements from temp[] to A1[]"
},
{
"code": null,
"e": 1712,
"s": 1664,
"text": "Below image is a dry run of the above approach:"
},
{
"code": null,
"e": 1764,
"s": 1712,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1768,
"s": 1764,
"text": "C++"
},
{
"code": null,
"e": 1773,
"s": 1768,
"text": "Java"
},
{
"code": null,
"e": 1781,
"s": 1773,
"text": "Python3"
},
{
"code": null,
"e": 1784,
"s": 1781,
"text": "C#"
},
{
"code": null,
"e": 1788,
"s": 1784,
"text": "PHP"
},
{
"code": null,
"e": 1799,
"s": 1788,
"text": "Javascript"
},
{
"code": "// A C++ program to sort an array according to the order defined// by another array#include <bits/stdc++.h>using namespace std; // A Binary Search based function to find index of FIRST occurrence// of x in arr[]. If x is not present, then it returns -1 // The same can be done using the lower_bound// function in C++ STLint first(int arr[], int low, int high, int x, int n){ // Checking condition if (high >= low) { // FInd the mid element int mid = low + (high - low) / 2; // Check if the element is the extreme left // in the left half of the array if ((mid == 0 || x > arr[mid - 1]) && arr[mid] == x) return mid; // If the element lies on the right half if (x > arr[mid]) return first(arr, (mid + 1), high, x, n); // Check for element in the left half return first(arr, low, (mid - 1), x, n); } // ELement not found return -1;} // Sort A1[0..m-1] according to the order defined by A2[0..n-1].void sortAccording(int A1[], int A2[], int m, int n){ // The temp array is used to store a copy of A1[] and visited[] // is used mark the visited elements in temp[]. int temp[m], visited[m]; for (int i = 0; i < m; i++) { temp[i] = A1[i]; visited[i] = 0; } // Sort elements in temp sort(temp, temp + m); // for index of output which is sorted A1[] int ind = 0; // Consider all elements of A2[], find them in temp[] // and copy to A1[] in order. for (int i = 0; i < n; i++) { // Find index of the first occurrence of A2[i] in temp int f = first(temp, 0, m - 1, A2[i], m); // If not present, no need to proceed if (f == -1) continue; // Copy all occurrences of A2[i] to A1[] for (int j = f; (j < m && temp[j] == A2[i]); j++) { A1[ind++] = temp[j]; visited[j] = 1; } } // Now copy all items of temp[] // which are not present in A2[] for (int i = 0; i < m; i++) if (visited[i] == 0) A1[ind++] = temp[i];} // Utility function to print an arrayvoid printArray(int arr[], int n){ // Iterate in the array for (int i = 0; i < n; i++) cout << arr[i] << \" \"; cout << endl;} // Driver Codeint main(){ int A1[] = { 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 }; int A2[] = { 2, 1, 8, 3 }; int m = sizeof(A1) / sizeof(A1[0]); int n = sizeof(A2) / sizeof(A2[0]); // Prints the sorted array cout << \"Sorted array is \\n\"; sortAccording(A1, A2, m, n); printArray(A1, m); return 0;}",
"e": 4366,
"s": 1799,
"text": null
},
{
"code": "// A JAVA program to sort an array according// to the order defined by another arrayimport java.io.*;import java.util.Arrays; class GFG { /* A Binary Search based function to find index of FIRST occurrence of x in arr[]. If x is not present, then it returns -1 */ static int first(int arr[], int low, int high, int x, int n) { if (high >= low) { /* (low + high)/2; */ int mid = low + (high - low) / 2; if ((mid == 0 || x > arr[mid - 1]) && arr[mid] == x) return mid; if (x > arr[mid]) return first(arr, (mid + 1), high, x, n); return first(arr, low, (mid - 1), x, n); } return -1; } // Sort A1[0..m-1] according to the order // defined by A2[0..n-1]. static void sortAccording(int A1[], int A2[], int m, int n) { // The temp array is used to store a copy // of A1[] and visited[] is used to mark the // visited elements in temp[]. int temp[] = new int[m], visited[] = new int[m]; for (int i = 0; i < m; i++) { temp[i] = A1[i]; visited[i] = 0; } // Sort elements in temp Arrays.sort(temp); // for index of output which is sorted A1[] int ind = 0; // Consider all elements of A2[], find them // in temp[] and copy to A1[] in order. for (int i = 0; i < n; i++) { // Find index of the first occurrence // of A2[i] in temp int f = first(temp, 0, m - 1, A2[i], m); // If not present, no need to proceed if (f == -1) continue; // Copy all occurrences of A2[i] to A1[] for (int j = f; (j < m && temp[j] == A2[i]); j++) { A1[ind++] = temp[j]; visited[j] = 1; } } // Now copy all items of temp[] which are // not present in A2[] for (int i = 0; i < m; i++) if (visited[i] == 0) A1[ind++] = temp[i]; } // Utility function to print an array static void printArray(int arr[], int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); System.out.println(); } // Driver program to test above function. public static void main(String args[]) { int A1[] = { 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 }; int A2[] = { 2, 1, 8, 3 }; int m = A1.length; int n = A2.length; System.out.println(\"Sorted array is \"); sortAccording(A1, A2, m, n); printArray(A1, m); }} /*This code is contributed by Nikita Tiwari.*/",
"e": 7097,
"s": 4366,
"text": null
},
{
"code": "\"\"\"A Python 3 program to sort an arrayaccording to the order defined byanother array\"\"\" \"\"\"A Binary Search based function to findindex of FIRST occurrence of x in arr[].If x is not present, then it returns -1 \"\"\" def first(arr, low, high, x, n) : if (high >= low) : mid = low + (high - low) // 2; # (low + high)/2; if ((mid == 0 or x > arr[mid-1]) and arr[mid] == x) : return mid if (x > arr[mid]) : return first(arr, (mid + 1), high, x, n) return first(arr, low, (mid -1), x, n) return -1 # Sort A1[0..m-1] according to the order# defined by A2[0..n-1].def sortAccording(A1, A2, m, n) : \"\"\"The temp array is used to store a copy of A1[] and visited[] is used mark the visited elements in temp[].\"\"\" temp = [0] * m visited = [0] * m for i in range(0, m) : temp[i] = A1[i] visited[i] = 0 # Sort elements in temp temp.sort() # for index of output which is sorted A1[] ind = 0 \"\"\"Consider all elements of A2[], find them in temp[] and copy to A1[] in order.\"\"\" for i in range(0, n) : # Find index of the first occurrence # of A2[i] in temp f = first(temp, 0, m-1, A2[i], m) # If not present, no need to proceed if (f == -1) : continue # Copy all occurrences of A2[i] to A1[] j = f while (j<m and temp[j]== A2[i]) : A1[ind] = temp[j]; ind = ind + 1 visited[j] = 1 j = j + 1 # Now copy all items of temp[] which are # not present in A2[] for i in range(0, m) : if (visited[i] == 0) : A1[ind] = temp[i] ind = ind + 1 # Utility function to print an arraydef printArray(arr, n) : for i in range(0, n) : print(arr[i], end = \" \") print(\"\") # Driver program to test above function.A1 = [2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8]A2 = [2, 1, 8, 3]m = len(A1)n = len(A2)print(\"Sorted array is \")sortAccording(A1, A2, m, n)printArray(A1, m) # This code is contributed by Nikita Tiwari.",
"e": 9202,
"s": 7097,
"text": null
},
{
"code": "// A C# program to sort an array according// to the order defined by another arrayusing System; class GFG { /* A Binary Search based function to find index of FIRST occurrence of x in arr[]. If x is not present, then it returns -1 */ static int first(int[] arr, int low, int high, int x, int n) { if (high >= low) { /* (low + high)/2; */ int mid = low + (high - low) / 2; if ((mid == 0 || x > arr[mid - 1]) && arr[mid] == x) return mid; if (x > arr[mid]) return first(arr, (mid + 1), high, x, n); return first(arr, low, (mid - 1), x, n); } return -1; } // Sort A1[0..m-1] according to the order // defined by A2[0..n-1]. static void sortAccording(int[] A1, int[] A2, int m, int n) { // The temp array is used to store a copy // of A1[] and visited[] is used to mark // the visited elements in temp[]. int[] temp = new int[m]; int[] visited = new int[m]; for (int i = 0; i < m; i++) { temp[i] = A1[i]; visited[i] = 0; } // Sort elements in temp Array.Sort(temp); // for index of output which is // sorted A1[] int ind = 0; // Consider all elements of A2[], find // them in temp[] and copy to A1[] in // order. for (int i = 0; i < n; i++) { // Find index of the first occurrence // of A2[i] in temp int f = first(temp, 0, m - 1, A2[i], m); // If not present, no need to proceed if (f == -1) continue; // Copy all occurrences of A2[i] to A1[] for (int j = f; (j < m && temp[j] == A2[i]); j++) { A1[ind++] = temp[j]; visited[j] = 1; } } // Now copy all items of temp[] which are // not present in A2[] for (int i = 0; i < m; i++) if (visited[i] == 0) A1[ind++] = temp[i]; } // Utility function to print an array static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); Console.WriteLine(); } // Driver program to test above function. public static void Main() { int[] A1 = { 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 }; int[] A2 = { 2, 1, 8, 3 }; int m = A1.Length; int n = A2.Length; Console.WriteLine(\"Sorted array is \"); sortAccording(A1, A2, m, n); printArray(A1, m); }} // This code is contributed by nitin mittal.",
"e": 11900,
"s": 9202,
"text": null
},
{
"code": "<?php// A PHP program to sort an array according// to the order defined by another array /* A Binary Search based function to find indexof FIRST occurrence of x in arr[]. If x is notpresent, then it returns -1 */function first(&$arr, $low, $high, $x, $n){ if ($high >= $low) { $mid = intval($low + ($high - $low) / 2); if (($mid == 0 || $x > $arr[$mid - 1]) && $arr[$mid] == $x) return $mid; if ($x > $arr[$mid]) return first($arr, ($mid + 1), $high, $x, $n); return first($arr, $low, ($mid - 1), $x, $n); } return -1;} // Sort A1[0..m-1] according to the order// defined by A2[0..n-1].function sortAccording(&$A1, &$A2, $m, $n){ // The temp array is used to store a copy // of A1[] and visited[] is used mark the // visited elements in temp[]. $temp = array_fill(0, $m, NULL); $visited = array_fill(0, $m, NULL); for ($i = 0; $i < $m; $i++) { $temp[$i] = $A1[$i]; $visited[$i] = 0; } // Sort elements in temp sort($temp); $ind = 0; // for index of output which is sorted A1[] // Consider all elements of A2[], find // them in temp[] and copy to A1[] in order. for ($i = 0; $i < $n; $i++) { // Find index of the first occurrence // of A2[i] in temp $f = first($temp, 0, $m - 1, $A2[$i], $m); // If not present, no need to proceed if ($f == -1) continue; // Copy all occurrences of A2[i] to A1[] for ($j = $f; ($j < $m && $temp[$j] == $A2[$i]); $j++) { $A1[$ind++] = $temp[$j]; $visited[$j] = 1; } } // Now copy all items of temp[] which // are not present in A2[] for ($i = 0; $i < $m; $i++) if ($visited[$i] == 0) $A1[$ind++] = $temp[$i];} // Utility function to print an arrayfunction printArray(&$arr, $n){ for ($i = 0; $i < $n; $i++) echo $arr[$i] . \" \"; echo \"\\n\";} // Driver Code$A1 = array(2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8);$A2 = array(2, 1, 8, 3);$m = sizeof($A1);$n = sizeof($A2);echo \"Sorted array is \\n\";sortAccording($A1, $A2, $m, $n);printArray($A1, $m); // This code is contributed by ita_c?>",
"e": 14103,
"s": 11900,
"text": null
},
{
"code": "<script> // A JavaScript program to sort an array according// to the order defined by another array /* A Binary Search based function to find index of FIRST occurrence of x in arr[]. If x is not present, then it returns -1 */ function first(arr,low,high,x,n) { if (high >= low) { // (low + high)/2; let mid = low + Math.floor((high - low) / 2); if ((mid == 0 || x > arr[mid - 1]) && arr[mid] == x) return mid; if (x > arr[mid]) return first(arr, (mid + 1), high,x, n); return first(arr, low, (mid - 1), x, n); } return -1; } // Sort A1[0..m-1] according to the order // defined by A2[0..n-1]. function sortAccording(A1,A2,m,n) { // The temp array is used to store a copy // of A1[] and visited[] is used to mark the // visited elements in temp[]. let temp=[]; let visited=[]; for (let i = 0; i < m; i++) { temp[i] = A1[i]; visited[i] = 0; } // Sort elements in temp temp.sort(function(a, b){return a-b}); // for index of output which is sorted A1[] let ind = 0; // Consider all elements of A2[], find them // in temp[] and copy to A1[] in order. for (let i = 0; i < n; i++) { // Find index of the first occurrence // of A2[i] in temp let f = first(temp, 0, m - 1, A2[i], m); // If not present, no need to proceed if (f == -1) { continue; } // Copy all occurrences of A2[i] to A1[] for (let j = f; (j < m && temp[j] == A2[i]);j++) { A1[ind++] = temp[j]; visited[j] = 1; } } // Now copy all items of temp[] which are // not present in A2[] for (let i = 0; i < m; i++) { if (visited[i] == 0) A1[ind++] = temp[i]; } } // Utility function to print an array function printArray(arr,n) { for (let i = 0; i < n; i++) { document.write(arr[i] + \" \"); } document.write(\"<br>\"); } // Driver program to test above function. let A1=[2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 ]; let A2=[2, 1, 8, 3 ]; let m = A1.length; let n = A2.length; document.write(\"Sorted array is <br>\"); sortAccording(A1, A2, m, n); printArray(A1, m); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 16747,
"s": 14103,
"text": null
},
{
"code": null,
"e": 16787,
"s": 16747,
"text": "Sorted array is \n2 2 1 1 8 8 3 5 6 7 9 "
},
{
"code": null,
"e": 16969,
"s": 16787,
"text": " Time complexity: The steps 1 and 2 require O(m) time. Step 3 requires O(M * Log M) time. Step 5 requires O(N Log M) time. Therefore overall time complexity is O(M Log M + N Log M)."
},
{
"code": null,
"e": 17022,
"s": 16969,
"text": "Method 2 (Using Self-Balancing Binary Search Tree) :"
},
{
"code": null,
"e": 17126,
"s": 17022,
"text": "We can also use a self-balancing BST like AVL Tree, Red Black Tree, etc. Following are detailed steps. "
},
{
"code": null,
"e": 17322,
"s": 17126,
"text": "Create a self-balancing BST of all elements in A1[]. In every node of BST, also keep track of count of occurrences of the key and a bool field visited which is initialized as false for all nodes."
},
{
"code": null,
"e": 17360,
"s": 17322,
"text": "Initialize the output index ind as 0."
},
{
"code": null,
"e": 17559,
"s": 17360,
"text": "Do following for every element of A2[i] in A2[] Search for A2[i] in the BST, if present then copy all occurrences to A1[ind] and increment ind. Also mark the copied elements visited in the BST node."
},
{
"code": null,
"e": 17710,
"s": 17559,
"text": "Search for A2[i] in the BST, if present then copy all occurrences to A1[ind] and increment ind. Also mark the copied elements visited in the BST node."
},
{
"code": null,
"e": 17861,
"s": 17710,
"text": "Search for A2[i] in the BST, if present then copy all occurrences to A1[ind] and increment ind. Also mark the copied elements visited in the BST node."
},
{
"code": null,
"e": 17929,
"s": 17861,
"text": "Do an inorder traversal of BST and copy all unvisited keys to A1[]."
},
{
"code": null,
"e": 18080,
"s": 17929,
"text": "Time Complexity of this method is the same as the previous method. Note that in a self-balancing Binary Search Tree, all operations require logm time."
},
{
"code": null,
"e": 18104,
"s": 18080,
"text": "Method 3 (Use Hashing):"
},
{
"code": null,
"e": 18206,
"s": 18104,
"text": "Loop through A1[], store the count of every number in a HashMap (key: number, value: count of number)"
},
{
"code": null,
"e": 18339,
"s": 18206,
"text": "Loop through A2[], check if it is present in HashMap, if so, put in output array that many times and remove the number from HashMap."
},
{
"code": null,
"e": 18416,
"s": 18339,
"text": "Sort the rest of the numbers present in HashMap and put in the output array."
},
{
"code": null,
"e": 18467,
"s": 18416,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 18471,
"s": 18467,
"text": "C++"
},
{
"code": null,
"e": 18476,
"s": 18471,
"text": "Java"
},
{
"code": null,
"e": 18484,
"s": 18476,
"text": "Python3"
},
{
"code": null,
"e": 18495,
"s": 18484,
"text": "Javascript"
},
{
"code": "// A C++ program to sort an array according to the order// defined by another array#include <bits/stdc++.h>using namespace std; // function to sort A1 according to A2 using hash map in C++void sortA1ByA2(int A1[], int N, int A2[], int M, int ans[]){ map<int, int> mp; // indexing for answer = ans array int ind = 0; // initially storing frequency of each element of A1 in // map [ key, value ] = [ A1[i] , frequency[ A1[i] ] ] for (int i = 0; i < N; i++) { mp[A1[i]] += 1; } // traversing each element of A2, first come first serve for (int i = 0; i < M; i++) { // checking if current element of A2 is present in // A1 or not if not present go to next iteration // else store number of times it is appearing in A1 // in ans array if (mp[A2[i]] != 0) { // mp[ A2[i] ] = frequency of A2[i] element in // A1 array for (int j = 1; j <= mp[A2[i]]; j++) ans[ind++] = A2[i]; } // to avoid duplicate storing of same element of A2 // in ans array mp.erase(A2[i]); } // store the remaining elements of A1 in sorted order in // ans array for (auto it : mp) { // it.second = frequency of remaining elements for (int j = 1; j <= it.second; j++) ans[ind++] = it.first; }} // Utility function to print an arrayvoid printArray(int arr[], int n){ // Iterate in the array for (int i = 0; i < n; i++) cout << arr[i] << \" \"; cout << endl;} // Driver Codeint main(){ int A1[] = { 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 }; int A2[] = { 2, 1, 8, 3 }; int n = sizeof(A1) / sizeof(A1[0]); int m = sizeof(A2) / sizeof(A2[0]); // The ans array is used to store the final sorted array int ans[n]; sortA1ByA2(A1, n, A2, m, ans); // Prints the sorted array cout << \"Sorted array is \\n\"; printArray(ans, n); return 0;}",
"e": 20421,
"s": 18495,
"text": null
},
{
"code": "// A Java program to sort an array according to the order// defined by another array import java.io.*;import java.util.Arrays;import java.util.HashMap; class GFG { // function to sort A1 according to A2 using hash map in C++static void sortA1ByA2(int A1[], int N, int A2[], int M, int ans[]){ HashMap<Integer, Integer> mp = new HashMap<>(); // indexing for answer = ans array int ind = 0; // initially storing frequency of each element of A1 in // map [ key, value ] = [ A1[i] , frequency[ A1[i] ] ] for (int i = 0; i < N; i++) { if (!mp.containsKey(A1[i])) mp.put(A1[i],1); else mp.put(A1[i],mp.get(A1[i])+1); } // traversing each element of A2, first come first serve for (int i = 0; i < M; i++) { // checking if current element of A2 is present in // A1 or not if not present go to next iteration // else store number of times it is appearing in A1 // in ans array if (mp.containsKey(A2[i])) { // mp[ A2[i] ] = frequency of A2[i] element in // A1 array for (int j = 1; j <= mp.get(A2[i]); j++) ans[ind++] = A2[i]; } // to avoid duplicate storing of same element of A2 // in ans array mp.remove(A2[i]); } // store the remaining elements of A1 in sorted order in // ans array for (HashMap.Entry<Integer,Integer> it : mp.entrySet()) { // it.second = frequency of remaining elements for (int j = 1; j <= it.getValue(); j++) ans[ind++] = it.getKey(); }} // Utility function to print an array static void printArray(int arr[], int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); System.out.println(); } // Driver code public static void main(String[] args) { int A1[] = { 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 }; int A2[] = { 2, 1, 8, 3 }; int n = A1.length; int m = A2.length; // The ans array is used to store the final sorted array int ans[]=new int[n]; sortA1ByA2(A1, n, A2, m, ans); System.out.println(\"Sorted array is \"); printArray(ans, n); }} // This code is contributed by Pushpesh Raj.",
"e": 22706,
"s": 20421,
"text": null
},
{
"code": "from collections import Counter # Function to sort arr1# according to arr2def solve(arr1, arr2): # Our output array res = [] # Counting Frequency of each # number in arr1 f = Counter(arr1) # Iterate over arr2 and append all # occurrences of element of # arr2 from arr1 for e in arr2: # Appending element 'e', # f[e] number of times res.extend([e]*f[e]) # Count of 'e' after appending is zero f[e] = 0 # Remaining numbers in arr1 in sorted # order (Numbers with non-zero frequency) rem = list(sorted(filter( lambda x: f[x] != 0, f.keys()))) # Append them also for e in rem: res.extend([e]*f[e]) return res # Driver Codeif __name__ == \"__main__\": arr1 = [2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8] arr2 = [2, 1, 8, 3] print(*solve(arr1, arr2))",
"e": 23589,
"s": 22706,
"text": null
},
{
"code": "<script> // A JavaScript program to sort an array according to the order// defined by another array // function to sort A1 according to A2 using hash map in C++function sortA1ByA2(A1, N, A2, M, ans){ let mp = new Map(); // indexing for answer = ans array let ind = 0; // initially storing frequency of each element of A1 in // map [ key, value ] = [ A1[i] , frequency[ A1[i] ] ] for (let i = 0; i < N; i++) { if(!mp.has(A1[i])){ mp.set(A1[i],1); } else mp.set(A1[i],mp.get(A1[i]) + 1); } // traversing each element of A2, first come first serve for (let i = 0; i < M; i++) { // checking if current element of A2 is present in // A1 or not if not present go to next iteration // else store number of times it is appearing in A1 // in ans array if (mp.has(A2[i])) { // mp[ A2[i] ] = frequency of A2[i] element in // A1 array for (let j = 1; j <= mp.get(A2[i]); j++) ans[ind++] = A2[i]; } // to avoid duplicate storing of same element of A2 // in ans array mp.delete(A2[i]); } // store the remaining elements of A1 in sorted order in // ans array mp = new Map([...mp.entries()].sort()); for (let [key,value] of mp) { // it.second = frequency of remaining elements for (let j = 1; j <= value; j++) ans[ind++] = key; }} // Utility function to print an arrayfunction printArray(arr, n){ // Iterate in the array for (let i = 0; i <n; i++) document.write(arr[i],\" \"); document.write(\"</br>\");} // Driver Code let A1 = [ 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 ];let A2 = [ 2, 1, 8, 3 ];let n = A1.length;let m = A2.length; // The ans array is used to store the final sorted arraylet ans = new Array(n);sortA1ByA2(A1, n, A2, m, ans); // Prints the sorted arraydocument.write(\"Sorted array is \");printArray(ans, n); // This code is contributed by shinjanpatra</script>",
"e": 25579,
"s": 23589,
"text": null
},
{
"code": null,
"e": 25601,
"s": 25579,
"text": "2 2 1 1 8 8 3 5 6 7 9"
},
{
"code": null,
"e": 25875,
"s": 25601,
"text": "Steps 1 and 2 on average take O(m+n) time under the assumption that we have a good hashing function that takes O(1) time for insertion and search on average. The third step takes O(p Log p) time where p is the number of elements remained after considering elements of A2[]."
},
{
"code": null,
"e": 25926,
"s": 25875,
"text": "Method 4 (By Writing a Customized Compare Method):"
},
{
"code": null,
"e": 26094,
"s": 25926,
"text": "We can also customize compare method of a sorting algorithm to solve the above problem. For example, qsort() in C allows us to pass our own customized compare method. "
},
{
"code": null,
"e": 26204,
"s": 26094,
"text": "If num1 and num2 both are in A2 then the number with a lower index in A2 will be treated smaller than others."
},
{
"code": null,
"e": 26332,
"s": 26204,
"text": "If only one of num1 or num2 present in A2, then that number will be treated smaller than the other which doesn’t present in A2."
},
{
"code": null,
"e": 26396,
"s": 26332,
"text": "If both are not in A2, then the natural ordering will be taken."
},
{
"code": null,
"e": 26594,
"s": 26396,
"text": "The time complexity of this method is O(mnLogm) if we use a O(nLogn) time complexity sorting algorithm. We can improve time complexity to O(mLogm) by using a Hashing instead of doing linear search."
},
{
"code": null,
"e": 26646,
"s": 26594,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26650,
"s": 26646,
"text": "C++"
},
{
"code": null,
"e": 26652,
"s": 26650,
"text": "C"
},
{
"code": null,
"e": 26657,
"s": 26652,
"text": "Java"
},
{
"code": "// A C++ program to sort an array according to the order defined// by another array #include<bits/stdc++.h>using namespace std; //function that sorts the first array based on order of them in second arrayvoid sortA1ByA2(vector<int> &arr1 , vector<int> &arr2){ //map to store the indices of second array // so that we can easily judge the position of two elements in first array unordered_map<int , int> index; for(int i=0; i<arr2.size(); i++){ //assigning i+1 // because by default value of map is zero // Consider only first occurrence of element if (index[arr2[i]] == 0) { index[arr2[i]] = i+1; } } //comparator function that sorts arr1 based on order // defined in arr2 auto comp = [&](int a , int b){ // if indices of two elements are equal // we need to sort them in increasing order if(index[a] == 0 && index[b]==0) return a<b; //if a not present in arr2 then b should come before it if(index[a] == 0) return false; //if b not present in arr2 then no swap if(index[b] == 0) return true; // sorting in increasing order return index[a] < index[b]; }; sort(arr1.begin(), arr1.end() , comp); } int main(){ vector<int> arr1{ 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8, 7, 5, 6, 9, 7, 5 }; vector<int> arr2{2 , 1 , 8 , 3 , 4, 1}; sortA1ByA2(arr1 , arr2); //printing the array cout<<\"Sorted array is \\n\"; for(auto i: arr1){ cout<<i<<\" \"; } return 0; }",
"e": 28245,
"s": 26657,
"text": null
},
{
"code": "// A C++ program to sort an array according to the order defined// by another array#include <stdio.h>#include <stdlib.h> // A2 is made global here so that it can be accesed by compareByA2()// The syntax of qsort() allows only two parameters to compareByA2()int A2[5]; // size of A2[]int size = 5; int search(int key){ int i = 0, idx = 0; for (i = 0; i < size; i++) if (A2[i] == key) return i; return -1;} // A custom compare method to compare elements of A1[] according// to the order defined by A2[].int compareByA2(const void* a, const void* b){ int idx1 = search(*(int*)a); int idx2 = search(*(int*)b); if (idx1 != -1 && idx2 != -1) return idx1 - idx2; else if (idx1 != -1) return -1; else if (idx2 != -1) return 1; else return (*(int*)a - *(int*)b);} // This method mainly uses qsort to sort A1[] according to A2[]void sortA1ByA2(int A1[], int size1){ qsort(A1, size1, sizeof(int), compareByA2);} // Driver program to test above functionint main(int argc, char* argv[]){ int A1[] = { 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8, 7, 5, 6, 9, 7, 5 }; // A2[] = {2, 1, 8, 3, 4}; A2[0] = 2; A2[1] = 1; A2[2] = 8; A2[3] = 3; A2[4] = 4; int size1 = sizeof(A1) / sizeof(A1[0]); sortA1ByA2(A1, size1); printf(\"Sorted Array is \"); int i; for (i = 0; i < size1; i++) printf(\"%d \", A1[i]); return 0;}",
"e": 29652,
"s": 28245,
"text": null
},
{
"code": "// A Java program to sort an array according to the order// defined by another array import java.io.*;import java.util.Arrays;import java.util.HashMap; class GFG { static void sortAccording(int[] A1, int[] A2, int m, int n) { // HashMap to store the indices of elements in // the second array HashMap<Integer, Integer> index = new HashMap<>(); for (int i = 0; i < n; i++) { // Consider only first occurrence of element if (!index.containsKey(A2[i])) // Assign value of i+1 index.put(A2[i], i + 1); } // Since Java does not support custom comparators on // primitive data types, we box the elements in // wrapper classes. // Sorted values are stored in a temporary // array. int[] tmp = Arrays.stream(A1) .boxed() .sorted((p1, p2) -> { int idx1 = index.getOrDefault(p1, 0); int idx2 = index.getOrDefault(p2, 0); // If both p1 and p2 are not present // in the second array, // sort them in ascending order if (idx1 == 0 && idx2 == 0) return p1 - p2; // If only p2 is present in the second // array, p2 comes before p1 if (idx1 == 0) return 1; // If only p1 is present in the second // array, p1 comes before p2 (no swap) if (idx2 == 0) return -1; // If both p1 and p2 are present in // the second array, sort them // according to their respective // indices return idx1 - idx2; }) .mapToInt(i -> i) .toArray(); // Sorted values are copied to the original // array for (int i = 0; i < m; i++) { A1[i] = tmp[i]; } } // Driver program to test the above function public static void main(String[] args) { int A1[] = { 2, 1, 2, 5, 7, 1, 9, 9, 3, 6, 8, 8 }; int A2[] = { 2, 1, 8, 3, 1 }; int m = A1.length; int n = A2.length; sortAccording(A1, A2, m, n); System.out.println(\"Sorted array is \"); System.out.println(Arrays.toString(A1)); }} // This code is contributed by anonymouscegian",
"e": 32234,
"s": 29652,
"text": null
},
{
"code": null,
"e": 32285,
"s": 32234,
"text": "Sorted Array is 2 2 1 1 8 8 3 5 5 5 6 6 7 7 7 9 9 "
},
{
"code": null,
"e": 32298,
"s": 32285,
"text": "nitin mittal"
},
{
"code": null,
"e": 32314,
"s": 32298,
"text": "Suryaveer Singh"
},
{
"code": null,
"e": 32320,
"s": 32314,
"text": "ukasp"
},
{
"code": null,
"e": 32341,
"s": 32320,
"text": "lohityakumarambashta"
},
{
"code": null,
"e": 32362,
"s": 32341,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 32373,
"s": 32362,
"text": "deepaksati"
},
{
"code": null,
"e": 32387,
"s": 32373,
"text": "sumitgumber28"
},
{
"code": null,
"e": 32403,
"s": 32387,
"text": "anonymouscegian"
},
{
"code": null,
"e": 32416,
"s": 32403,
"text": "shinjanpatra"
},
{
"code": null,
"e": 32425,
"s": 32416,
"text": "rkbhola5"
},
{
"code": null,
"e": 32434,
"s": 32425,
"text": "sweetyty"
},
{
"code": null,
"e": 32450,
"s": 32434,
"text": "pushpeshrajdx01"
},
{
"code": null,
"e": 32467,
"s": 32450,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 32474,
"s": 32467,
"text": "Amazon"
},
{
"code": null,
"e": 32489,
"s": 32474,
"text": "Insertion Sort"
},
{
"code": null,
"e": 32499,
"s": 32489,
"text": "Microsoft"
},
{
"code": null,
"e": 32506,
"s": 32499,
"text": "Arrays"
},
{
"code": null,
"e": 32516,
"s": 32506,
"text": "Searching"
},
{
"code": null,
"e": 32524,
"s": 32516,
"text": "Sorting"
},
{
"code": null,
"e": 32531,
"s": 32524,
"text": "Amazon"
},
{
"code": null,
"e": 32541,
"s": 32531,
"text": "Microsoft"
},
{
"code": null,
"e": 32548,
"s": 32541,
"text": "Arrays"
},
{
"code": null,
"e": 32558,
"s": 32548,
"text": "Searching"
},
{
"code": null,
"e": 32566,
"s": 32558,
"text": "Sorting"
},
{
"code": null,
"e": 32664,
"s": 32566,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32679,
"s": 32664,
"text": "Arrays in Java"
},
{
"code": null,
"e": 32725,
"s": 32679,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 32793,
"s": 32725,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 32837,
"s": 32793,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 32869,
"s": 32837,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 32883,
"s": 32869,
"text": "Binary Search"
},
{
"code": null,
"e": 32951,
"s": 32883,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 32965,
"s": 32951,
"text": "Linear Search"
},
{
"code": null,
"e": 33021,
"s": 32965,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
}
] |
How to set the background color of a ttk.Combobox in tkinter? | Tkinter supports ttk widget which is used to change the style and properties of any widget in a tkinter application. We can set the background color, foreground color, and other attributes of the Combobox widget by visiting the configure function in ttk and passing 'TCombobox' as the first parameter.
In this example, we will set the background color of the Combobox widget by defining its values in the ttk widget.
# Import the required libraries
from tkinter import *
from tkinter import ttk
# Create an instance of tkinter frame
win = Tk()
# Set the size of the tkinter window
win.geometry("700x350")
# Define the style for combobox widget
style= ttk.Style()
style.theme_use('clam')
style.configure("TCombobox", fieldbackground= "orange", background= "white")
# Add a label widget
label=ttk.Label(win, text= "Select a Car Model",
font= ('Aerial 11'))
label.pack(pady=30)
# Add a Combobox widget
cb= ttk.Combobox(win, width= 25, values=["Honda", "Hyundai", "Wolkswagon", "Tata", "Renault", "Ford", "Chrevolet", "Suzuki","BMW", "Mercedes"])
cb.pack()
win.mainloop()
Running the above code will open a window that will have a combobox widget to select an option from the list. | [
{
"code": null,
"e": 1489,
"s": 1187,
"text": "Tkinter supports ttk widget which is used to change the style and properties of any widget in a tkinter application. We can set the background color, foreground color, and other attributes of the Combobox widget by visiting the configure function in ttk and passing 'TCombobox' as the first parameter."
},
{
"code": null,
"e": 1604,
"s": 1489,
"text": "In this example, we will set the background color of the Combobox widget by defining its values in the ttk widget."
},
{
"code": null,
"e": 2261,
"s": 1604,
"text": "# Import the required libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n# Create an instance of tkinter frame\nwin = Tk()\n\n# Set the size of the tkinter window\nwin.geometry(\"700x350\")\n\n# Define the style for combobox widget\nstyle= ttk.Style()\nstyle.theme_use('clam')\nstyle.configure(\"TCombobox\", fieldbackground= \"orange\", background= \"white\")\n\n# Add a label widget\nlabel=ttk.Label(win, text= \"Select a Car Model\",\nfont= ('Aerial 11'))\nlabel.pack(pady=30)\n# Add a Combobox widget\ncb= ttk.Combobox(win, width= 25, values=[\"Honda\", \"Hyundai\", \"Wolkswagon\", \"Tata\", \"Renault\", \"Ford\", \"Chrevolet\", \"Suzuki\",\"BMW\", \"Mercedes\"])\n\ncb.pack()\n\nwin.mainloop()"
},
{
"code": null,
"e": 2371,
"s": 2261,
"text": "Running the above code will open a window that will have a combobox widget to select an option from the list."
}
] |
How to specify multiple forms the select field belongs to in HTML ? - GeeksforGeeks | 22 Apr, 2021
The task is to specify multiple forms the select field belongs to. In simple wording, we have to find out which form the specific select belongs to. You can achieve this task by using the form attribute.
select element – It is used to create a drop-down list in HTML.
form element – It is used to create a form for user input.
form attribute – This attribute will tell the user which forms select element it belongs to.
Approach –
First, create the HTML page with the select element inside the form element.
Create a select element outside the form and specify which form it belongs to with the help of the form attribute.
Example 1 –
HTML
<!DOCTYPE html><html> <head> <style> body { text-align: center; font-size: 20px; background-color: lightgreen; } button { background-color: #4CAF50; border: none; color: white; padding: 5px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; } </style></head> <body> <h1 style="color:green"> GeeksForGeeks </h1> <p> The form attribute specifies which form the drop-down list belongs to: </p> <form id="carform"> <label for="fname">First Name:</label> <input type="text" id="fname" name="fname"> <button>Submit</button> </form> <br> <label for="cars">Choose a car:</label> <select id="cars" name="carlist" form="carform"> <option value="volvo">Volvo</option> <option value="maruti">Maruti</option> <option value="Rolls-Royce">Rolls-Royce</option> <option value="audi">Audi</option> </select></body> </html>
Output –
Explanation – In the above example we have created the form without the dropdown menu but after creating the drop-down menu with select element and then we have assigned this to the part of the form with the help of the form attribute.
Example 2 –
HTML
<!DOCTYPE html><html> <head> <style> body { text-align: center; font-size: 20px; } button { background-color: #4CAF50; border: none; color: white; padding: 5px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; } </style></head> <body> <h1 style="color:green"> GeeksForGeeks </h1> <p> The form attribute specifies which form the drop-down list belongs to: </p> <form id="countryName"> <label for="fname">First Name:</label> <input type="text" id="fname" name="fname"> <button>Submit</button> </form> <br> <label for="country">Choose a country:</label> <select id="country" name="carlist" form="countryName"> <option value="India">India</option> <option value="US">US</option> <option value="Germany">Germany</option> <option value="Australia">Australia</option> </select></body> </html>
Output –
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Attributes
HTML-Questions
HTML-Tags
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 33003,
"s": 32975,
"text": "\n22 Apr, 2021"
},
{
"code": null,
"e": 33207,
"s": 33003,
"text": "The task is to specify multiple forms the select field belongs to. In simple wording, we have to find out which form the specific select belongs to. You can achieve this task by using the form attribute."
},
{
"code": null,
"e": 33271,
"s": 33207,
"text": "select element – It is used to create a drop-down list in HTML."
},
{
"code": null,
"e": 33330,
"s": 33271,
"text": "form element – It is used to create a form for user input."
},
{
"code": null,
"e": 33423,
"s": 33330,
"text": "form attribute – This attribute will tell the user which forms select element it belongs to."
},
{
"code": null,
"e": 33435,
"s": 33423,
"text": "Approach – "
},
{
"code": null,
"e": 33512,
"s": 33435,
"text": "First, create the HTML page with the select element inside the form element."
},
{
"code": null,
"e": 33627,
"s": 33512,
"text": "Create a select element outside the form and specify which form it belongs to with the help of the form attribute."
},
{
"code": null,
"e": 33639,
"s": 33627,
"text": "Example 1 –"
},
{
"code": null,
"e": 33644,
"s": 33639,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> body { text-align: center; font-size: 20px; background-color: lightgreen; } button { background-color: #4CAF50; border: none; color: white; padding: 5px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; } </style></head> <body> <h1 style=\"color:green\"> GeeksForGeeks </h1> <p> The form attribute specifies which form the drop-down list belongs to: </p> <form id=\"carform\"> <label for=\"fname\">First Name:</label> <input type=\"text\" id=\"fname\" name=\"fname\"> <button>Submit</button> </form> <br> <label for=\"cars\">Choose a car:</label> <select id=\"cars\" name=\"carlist\" form=\"carform\"> <option value=\"volvo\">Volvo</option> <option value=\"maruti\">Maruti</option> <option value=\"Rolls-Royce\">Rolls-Royce</option> <option value=\"audi\">Audi</option> </select></body> </html>",
"e": 34754,
"s": 33644,
"text": null
},
{
"code": null,
"e": 34763,
"s": 34754,
"text": "Output –"
},
{
"code": null,
"e": 34999,
"s": 34763,
"text": "Explanation – In the above example we have created the form without the dropdown menu but after creating the drop-down menu with select element and then we have assigned this to the part of the form with the help of the form attribute."
},
{
"code": null,
"e": 35011,
"s": 34999,
"text": "Example 2 –"
},
{
"code": null,
"e": 35016,
"s": 35011,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> body { text-align: center; font-size: 20px; } button { background-color: #4CAF50; border: none; color: white; padding: 5px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; } </style></head> <body> <h1 style=\"color:green\"> GeeksForGeeks </h1> <p> The form attribute specifies which form the drop-down list belongs to: </p> <form id=\"countryName\"> <label for=\"fname\">First Name:</label> <input type=\"text\" id=\"fname\" name=\"fname\"> <button>Submit</button> </form> <br> <label for=\"country\">Choose a country:</label> <select id=\"country\" name=\"carlist\" form=\"countryName\"> <option value=\"India\">India</option> <option value=\"US\">US</option> <option value=\"Germany\">Germany</option> <option value=\"Australia\">Australia</option> </select></body> </html>",
"e": 36096,
"s": 35016,
"text": null
},
{
"code": null,
"e": 36105,
"s": 36096,
"text": "Output –"
},
{
"code": null,
"e": 36242,
"s": 36105,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 36258,
"s": 36242,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 36273,
"s": 36258,
"text": "HTML-Questions"
},
{
"code": null,
"e": 36283,
"s": 36273,
"text": "HTML-Tags"
},
{
"code": null,
"e": 36290,
"s": 36283,
"text": "Picked"
},
{
"code": null,
"e": 36295,
"s": 36290,
"text": "HTML"
},
{
"code": null,
"e": 36312,
"s": 36295,
"text": "Web Technologies"
},
{
"code": null,
"e": 36317,
"s": 36312,
"text": "HTML"
},
{
"code": null,
"e": 36415,
"s": 36317,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36465,
"s": 36415,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 36527,
"s": 36465,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 36575,
"s": 36527,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 36635,
"s": 36575,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 36688,
"s": 36635,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 36728,
"s": 36688,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 36761,
"s": 36728,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 36806,
"s": 36761,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 36849,
"s": 36806,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Java TreeSet Special Methods - GeeksforGeeks | 25 Jan, 2022
TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The TreeSet implements a NavigableSet interface by inheriting AbstractSet class. This means that the elements stored in a TreeSet are in an ordered way, i.e. in the ascending order. Because of this feature of TreeSet, it provides certain amazing methods of NavigableSet interface apart from those traditionally provided by the Collection interface.
Note: Since TreeSet is the implementation of Set, therefore it does not allow duplication of elements.
Some of specific methods provided by TreeSet are as follows:
floor() Methodlower() Methodceiling() Methodhigher() MethodsubSet() MethodheadSet() MethodtailSet() Method
floor() Method
lower() Method
ceiling() Method
higher() Method
subSet() Method
headSet() Method
tailSet() Method
Now let us discuss all methods along with their implementation which is as follows
Method 1: floor() Method
This method returns the greatest element in the set less than or equal to the given element, or null if there is no such element.
Arguments: A number less than or equal value needs to be searched for
Syntax:
treeSetObject.floor(argument) ;
Example:
Java
// Java Program to demonstrate Floor Method in TreeSet // Importing input output classesimport java.io.*;// Importing TreeSet and Set classes from java.util packageimport java.util.Set;import java.util.TreeSet; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an object of TreeSet of Integer type // Initializing object with integer values using // Set.of() method TreeSet<Integer> treeSet = new TreeSet<>(Set.of(12, 98, 54, 37, 68)); // Print and display elements in object System.out.println("Tree set = " + treeSet); // Case 1 // Using floor() method over treeSet elements but // note floor() method is inclusive of the limit // Hence maximum element is returned System.out.println("floor(60) = " + treeSet.floor(60)); // Case 2 // Using floor() method over treeSet elements, // therefore output of the below line will be the // number itself System.out.println("floor(54) = " + treeSet.floor(54)); }}
Tree set = [12, 37, 54, 68, 98]
floor(60) = 54
floor(54) = 54
Method 2: lower() Method
This method returns the greatest element in this set strictly less than the given element, or null if there is no such element.
Argument: Number whose less than value needs to be found.
Syntax:
treeSetObject.lower(argument) ;
Example:
Java
// Java Program to demonstrate Lower Method in TreeSet // Importing input output classesimport java.io.*;// Importing TreeSet and Set classes from java.util packageimport java.util.Set;import java.util.TreeSet; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of TreeSet of Integer type // Initializing object with integer values using // Set.of() method TreeSet<Integer> treeSet = new TreeSet<>(Set.of(12, 98, 54, 37, 68)); // Print and display elements in object System.out.println(treeSet); // Case 1 // Using lower() method ober treeSet elements where // argument passed is greater then max element in // TreeSet therefore returning max element itself System.out.println("lower(90) = " + treeSet.lower(90)); // Case 2 // Using lower() method ober treeSet elements where // argument passed is not greater then max element // in TreeSet therefore returning element lesser // than that passed as an argument System.out.println("lower(68) = " + treeSet.lower(68)); // Also note that lower() method is exclusive of the // limit }}
[12, 37, 54, 68, 98]
lower(90) = 68
lower(68) = 54
Method 3: ceiling() Method
This method returns the least element in this set greater than or equal to the given element, or null if there is no such element.
Argument: Number whose less than or equal value needs to be found.
Syntax:
treeSetObject.lower(argument) ;
Example:
Java
// Java Program to demonstrate Ceiling Method in TreeSet// Importing input output classesimport java.io.*;// Importing TreeSet and Set classes from java.util packageimport java.util.Set;import java.util.TreeSet; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of TreeSet of Integer type // Initializing object with integer values using // Set.of() method TreeSet<Integer> treeSet = new TreeSet<>(Set.of(12, 98, 54, 37, 68)); // Print and display elements in object System.out.println("tree set = " + treeSet); // Using ceiling() method. System.out.println("ceiling(50) = " + treeSet.ceiling(50)); // Note that ceiling method is inclusive of the // limit. Therefore,output of the below line will be // the same number. System.out.println("ceiling(68) = " + treeSet.ceiling(68)); // Verification for null System.out.println("ceiling(100) = " + treeSet.ceiling(100)); }}
tree set = [12, 37, 54, 68, 98]
ceiling(50) = 54
ceiling(68) = 68
ceiling(100) = null
Method 4: higher() Method
This method returns the least element in this set strictly greater than the given element, or null if there is no such element.
Argument: The number whose less than value needs to be found.
Syntax:
treeSetObject.lower(argument) ;
Example:
Java
// Java Program to demonstrate Higher Method of TreeSet // Importing input output classesimport java.io.*;// Importing Set snd TreeSet classes from java.util packageimport java.util.Set;import java.util.TreeSet; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of TreeSet of Integer type // Initializing object with integer values using // Set.of() method TreeSet<Integer> treeSet = new TreeSet<>(Set.of(12, 98, 54, 37, 68)); // Print and display elements in object System.out.println("tree set = " + treeSet); // Using higher() method // Case 1 System.out.println("higher(50) = " + treeSet.higher(50)); // Case 2 // Note that higher method is exclusive of the limit // causing // output be the number greater than the number // passed System.out.println("higher(68) = " + treeSet.higher(68)); // Case 3 // Verification for null System.out.println("higher(98) = " + treeSet.higher(100)); }}
tree set = [12, 37, 54, 68, 98]
higher(50) = 54
higher(68) = 98
higher(98) = null
Method 5: subSet() Method
This method will return elements ranging from ‘fromElement‘ to ‘toElement‘.
Note: ‘fromElement’ is inclusive and ‘toElement’ is exclusive.
Syntax:
treeSetObject.subSet(fromElement, toElement);
// where fromElement is the lower limit (inclusive) and
// toElement is the upper limit (exclusive)
// of the set containing values between these limits
Example:
Java
// Java Program to demonstrate subset Method in TreeSet // Importing input output classesimport java.io.*;// Importing Set snd TreeSet classes from java.util packageimport java.util.Set;import java.util.TreeSet; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of TreeSet of Integer type // Initializing object with integer values using // Set.of() method TreeSet<Integer> treeSet = new TreeSet<>(Set.of(12, 98, 54, 37, 68)); // Print and display elements in object System.out.println("tree set = " + treeSet); // Using subSet() method // Case 1 System.out.println( "Elements between 54 and 98 are : " + treeSet.subSet(54, 98)); // Case 2 // If we want to incude the upper limit System.out.println( "Elements between 54 and 98 including both the limits : " + treeSet.subSet(54, true, 98, true)); // Case 3 // If we want to exclude the lower limit System.out.println( "Elements between 54 (exclusive) and 98 (inclusive) : " + treeSet.subSet(54, false, 98, true)); // Case 4 // If we want to exclude both the limits System.out.println( "Elements between 54 (exclusive) and 98 (exclusive) : " + treeSet.subSet(54, false, 98, false)); }}
tree set = [12, 37, 54, 68, 98]
Elements between 54 and 98 are : [54, 68]
Elements between 54 and 98 including both the limits : [54, 68, 98]
Elements between 54 (exclusive) and 98 (inclusive) : [68, 98]
Elements between 54 (exclusive) and 98 (exclusive) : [68]
Method 6: headSet() Method
This method will return elements of TreeSet which are less than the specified element.
Syntax:
treeSetObject.headSet(upToNumber) ;
Note: ‘upToNumber‘ is the upper limit of the numbers to be found (exclusive)
Example:
Java
// Java Program to demonstrate headSet Method in TreeSet // Importing input output classesimport java.io.*;// Importing Set snd TreeSet classes from java.util packageimport java.util.Set;import java.util.TreeSet; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of TreeSet of Integer type // Initializing object with integer values using // Set.of() method TreeSet<Integer> treeSet = new TreeSet<>(Set.of(12, 98, 54, 37, 68)); // Print and display elements in object System.out.println("tree set = " + treeSet); // Implementing headSet() method via TreeSet object // Case 1 System.out.println("Elements upto 90 : " + treeSet.headSet(90)); // Case 2 // The function limit is exclusive of the argument // passed System.out.println("Elements upto 68 : " + treeSet.headSet(68)); // Case 3 // If we want to include the number passed, then System.out.println("Elements upto 68 (inclusive) : " + treeSet.headSet(68, true)); }}
tree set = [12, 37, 54, 68, 98]
Elements upto 90 : [12, 37, 54, 68]
Elements upto 68 : [12, 37, 54]
Elements upto 68 (inclusive) : [12, 37, 54, 68]
Method 7:
This method will return elements of TreeSet which are greater than or equal to the specified element.
Syntax:
treeSetObject.tailSet(aboveThisNumber) ;
Note: ‘aboveThisNumber’ is the lower limit of the numbers to be found (inclusive).
Example:
Java
// Java Program to demonstrate tailSet Method in TreeSet // Importing input output classesimport java.io.*;import java.util.Set;import java.util.TreeSet; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of TreeSet of Integer type // Initializing object with integer values using // Set.of() method TreeSet<Integer> treeSet = new TreeSet<>(Set.of(12, 98, 54, 37, 68)); // Print and display elements in object System.out.println("tree set = " + treeSet); // Implementing tailSet() // Case 1 System.out.println("Elements above 50 : " + treeSet.tailSet(50)); // Case 2 // The function limit is inclusive of the argument // passed System.out.println("Elements above 54 : " + treeSet.tailSet(54)); // Case 3 // If we want to exclude the number passed System.out.println( "Elements above 54 (exclusive) : " + treeSet.tailSet(54, false)); }}
tree set = [12, 37, 54, 68, 98]
Elements above 50 : [54, 68, 98]
Elements above 54 : [54, 68, 98]
Elements above 54 (exclusive) : [68, 98]
sooda367
anikaseth98
sagar0719kumar
sumitgumber28
Java-Collections
java-treeset
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java | [
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n25 Jan, 2022"
},
{
"code": null,
"e": 25692,
"s": 25225,
"text": "TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The TreeSet implements a NavigableSet interface by inheriting AbstractSet class. This means that the elements stored in a TreeSet are in an ordered way, i.e. in the ascending order. Because of this feature of TreeSet, it provides certain amazing methods of NavigableSet interface apart from those traditionally provided by the Collection interface."
},
{
"code": null,
"e": 25795,
"s": 25692,
"text": "Note: Since TreeSet is the implementation of Set, therefore it does not allow duplication of elements."
},
{
"code": null,
"e": 25856,
"s": 25795,
"text": "Some of specific methods provided by TreeSet are as follows:"
},
{
"code": null,
"e": 25963,
"s": 25856,
"text": "floor() Methodlower() Methodceiling() Methodhigher() MethodsubSet() MethodheadSet() MethodtailSet() Method"
},
{
"code": null,
"e": 25978,
"s": 25963,
"text": "floor() Method"
},
{
"code": null,
"e": 25993,
"s": 25978,
"text": "lower() Method"
},
{
"code": null,
"e": 26010,
"s": 25993,
"text": "ceiling() Method"
},
{
"code": null,
"e": 26026,
"s": 26010,
"text": "higher() Method"
},
{
"code": null,
"e": 26042,
"s": 26026,
"text": "subSet() Method"
},
{
"code": null,
"e": 26059,
"s": 26042,
"text": "headSet() Method"
},
{
"code": null,
"e": 26076,
"s": 26059,
"text": "tailSet() Method"
},
{
"code": null,
"e": 26159,
"s": 26076,
"text": "Now let us discuss all methods along with their implementation which is as follows"
},
{
"code": null,
"e": 26184,
"s": 26159,
"text": "Method 1: floor() Method"
},
{
"code": null,
"e": 26314,
"s": 26184,
"text": "This method returns the greatest element in the set less than or equal to the given element, or null if there is no such element."
},
{
"code": null,
"e": 26384,
"s": 26314,
"text": "Arguments: A number less than or equal value needs to be searched for"
},
{
"code": null,
"e": 26392,
"s": 26384,
"text": "Syntax:"
},
{
"code": null,
"e": 26424,
"s": 26392,
"text": "treeSetObject.floor(argument) ;"
},
{
"code": null,
"e": 26433,
"s": 26424,
"text": "Example:"
},
{
"code": null,
"e": 26438,
"s": 26433,
"text": "Java"
},
{
"code": "// Java Program to demonstrate Floor Method in TreeSet // Importing input output classesimport java.io.*;// Importing TreeSet and Set classes from java.util packageimport java.util.Set;import java.util.TreeSet; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an object of TreeSet of Integer type // Initializing object with integer values using // Set.of() method TreeSet<Integer> treeSet = new TreeSet<>(Set.of(12, 98, 54, 37, 68)); // Print and display elements in object System.out.println(\"Tree set = \" + treeSet); // Case 1 // Using floor() method over treeSet elements but // note floor() method is inclusive of the limit // Hence maximum element is returned System.out.println(\"floor(60) = \" + treeSet.floor(60)); // Case 2 // Using floor() method over treeSet elements, // therefore output of the below line will be the // number itself System.out.println(\"floor(54) = \" + treeSet.floor(54)); }}",
"e": 27595,
"s": 26438,
"text": null
},
{
"code": null,
"e": 27657,
"s": 27595,
"text": "Tree set = [12, 37, 54, 68, 98]\nfloor(60) = 54\nfloor(54) = 54"
},
{
"code": null,
"e": 27682,
"s": 27657,
"text": "Method 2: lower() Method"
},
{
"code": null,
"e": 27810,
"s": 27682,
"text": "This method returns the greatest element in this set strictly less than the given element, or null if there is no such element."
},
{
"code": null,
"e": 27868,
"s": 27810,
"text": "Argument: Number whose less than value needs to be found."
},
{
"code": null,
"e": 27877,
"s": 27868,
"text": "Syntax: "
},
{
"code": null,
"e": 27909,
"s": 27877,
"text": "treeSetObject.lower(argument) ;"
},
{
"code": null,
"e": 27918,
"s": 27909,
"text": "Example:"
},
{
"code": null,
"e": 27923,
"s": 27918,
"text": "Java"
},
{
"code": "// Java Program to demonstrate Lower Method in TreeSet // Importing input output classesimport java.io.*;// Importing TreeSet and Set classes from java.util packageimport java.util.Set;import java.util.TreeSet; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of TreeSet of Integer type // Initializing object with integer values using // Set.of() method TreeSet<Integer> treeSet = new TreeSet<>(Set.of(12, 98, 54, 37, 68)); // Print and display elements in object System.out.println(treeSet); // Case 1 // Using lower() method ober treeSet elements where // argument passed is greater then max element in // TreeSet therefore returning max element itself System.out.println(\"lower(90) = \" + treeSet.lower(90)); // Case 2 // Using lower() method ober treeSet elements where // argument passed is not greater then max element // in TreeSet therefore returning element lesser // than that passed as an argument System.out.println(\"lower(68) = \" + treeSet.lower(68)); // Also note that lower() method is exclusive of the // limit }}",
"e": 29228,
"s": 27923,
"text": null
},
{
"code": null,
"e": 29279,
"s": 29228,
"text": "[12, 37, 54, 68, 98]\nlower(90) = 68\nlower(68) = 54"
},
{
"code": null,
"e": 29306,
"s": 29279,
"text": "Method 3: ceiling() Method"
},
{
"code": null,
"e": 29437,
"s": 29306,
"text": "This method returns the least element in this set greater than or equal to the given element, or null if there is no such element."
},
{
"code": null,
"e": 29504,
"s": 29437,
"text": "Argument: Number whose less than or equal value needs to be found."
},
{
"code": null,
"e": 29513,
"s": 29504,
"text": "Syntax: "
},
{
"code": null,
"e": 29545,
"s": 29513,
"text": "treeSetObject.lower(argument) ;"
},
{
"code": null,
"e": 29554,
"s": 29545,
"text": "Example:"
},
{
"code": null,
"e": 29559,
"s": 29554,
"text": "Java"
},
{
"code": "// Java Program to demonstrate Ceiling Method in TreeSet// Importing input output classesimport java.io.*;// Importing TreeSet and Set classes from java.util packageimport java.util.Set;import java.util.TreeSet; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of TreeSet of Integer type // Initializing object with integer values using // Set.of() method TreeSet<Integer> treeSet = new TreeSet<>(Set.of(12, 98, 54, 37, 68)); // Print and display elements in object System.out.println(\"tree set = \" + treeSet); // Using ceiling() method. System.out.println(\"ceiling(50) = \" + treeSet.ceiling(50)); // Note that ceiling method is inclusive of the // limit. Therefore,output of the below line will be // the same number. System.out.println(\"ceiling(68) = \" + treeSet.ceiling(68)); // Verification for null System.out.println(\"ceiling(100) = \" + treeSet.ceiling(100)); }}",
"e": 30694,
"s": 29559,
"text": null
},
{
"code": null,
"e": 30780,
"s": 30694,
"text": "tree set = [12, 37, 54, 68, 98]\nceiling(50) = 54\nceiling(68) = 68\nceiling(100) = null"
},
{
"code": null,
"e": 30808,
"s": 30780,
"text": "Method 4: higher() Method "
},
{
"code": null,
"e": 30936,
"s": 30808,
"text": "This method returns the least element in this set strictly greater than the given element, or null if there is no such element."
},
{
"code": null,
"e": 30998,
"s": 30936,
"text": "Argument: The number whose less than value needs to be found."
},
{
"code": null,
"e": 31006,
"s": 30998,
"text": "Syntax:"
},
{
"code": null,
"e": 31038,
"s": 31006,
"text": "treeSetObject.lower(argument) ;"
},
{
"code": null,
"e": 31047,
"s": 31038,
"text": "Example:"
},
{
"code": null,
"e": 31052,
"s": 31047,
"text": "Java"
},
{
"code": "// Java Program to demonstrate Higher Method of TreeSet // Importing input output classesimport java.io.*;// Importing Set snd TreeSet classes from java.util packageimport java.util.Set;import java.util.TreeSet; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of TreeSet of Integer type // Initializing object with integer values using // Set.of() method TreeSet<Integer> treeSet = new TreeSet<>(Set.of(12, 98, 54, 37, 68)); // Print and display elements in object System.out.println(\"tree set = \" + treeSet); // Using higher() method // Case 1 System.out.println(\"higher(50) = \" + treeSet.higher(50)); // Case 2 // Note that higher method is exclusive of the limit // causing // output be the number greater than the number // passed System.out.println(\"higher(68) = \" + treeSet.higher(68)); // Case 3 // Verification for null System.out.println(\"higher(98) = \" + treeSet.higher(100)); }}",
"e": 32240,
"s": 31052,
"text": null
},
{
"code": null,
"e": 32322,
"s": 32240,
"text": "tree set = [12, 37, 54, 68, 98]\nhigher(50) = 54\nhigher(68) = 98\nhigher(98) = null"
},
{
"code": null,
"e": 32348,
"s": 32322,
"text": "Method 5: subSet() Method"
},
{
"code": null,
"e": 32424,
"s": 32348,
"text": "This method will return elements ranging from ‘fromElement‘ to ‘toElement‘."
},
{
"code": null,
"e": 32487,
"s": 32424,
"text": "Note: ‘fromElement’ is inclusive and ‘toElement’ is exclusive."
},
{
"code": null,
"e": 32495,
"s": 32487,
"text": "Syntax:"
},
{
"code": null,
"e": 32696,
"s": 32495,
"text": "treeSetObject.subSet(fromElement, toElement);\n// where fromElement is the lower limit (inclusive) and \n// toElement is the upper limit (exclusive) \n// of the set containing values between these limits"
},
{
"code": null,
"e": 32705,
"s": 32696,
"text": "Example:"
},
{
"code": null,
"e": 32710,
"s": 32705,
"text": "Java"
},
{
"code": "// Java Program to demonstrate subset Method in TreeSet // Importing input output classesimport java.io.*;// Importing Set snd TreeSet classes from java.util packageimport java.util.Set;import java.util.TreeSet; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of TreeSet of Integer type // Initializing object with integer values using // Set.of() method TreeSet<Integer> treeSet = new TreeSet<>(Set.of(12, 98, 54, 37, 68)); // Print and display elements in object System.out.println(\"tree set = \" + treeSet); // Using subSet() method // Case 1 System.out.println( \"Elements between 54 and 98 are : \" + treeSet.subSet(54, 98)); // Case 2 // If we want to incude the upper limit System.out.println( \"Elements between 54 and 98 including both the limits : \" + treeSet.subSet(54, true, 98, true)); // Case 3 // If we want to exclude the lower limit System.out.println( \"Elements between 54 (exclusive) and 98 (inclusive) : \" + treeSet.subSet(54, false, 98, true)); // Case 4 // If we want to exclude both the limits System.out.println( \"Elements between 54 (exclusive) and 98 (exclusive) : \" + treeSet.subSet(54, false, 98, false)); }}",
"e": 34150,
"s": 32710,
"text": null
},
{
"code": null,
"e": 34412,
"s": 34150,
"text": "tree set = [12, 37, 54, 68, 98]\nElements between 54 and 98 are : [54, 68]\nElements between 54 and 98 including both the limits : [54, 68, 98]\nElements between 54 (exclusive) and 98 (inclusive) : [68, 98]\nElements between 54 (exclusive) and 98 (exclusive) : [68]"
},
{
"code": null,
"e": 34439,
"s": 34412,
"text": "Method 6: headSet() Method"
},
{
"code": null,
"e": 34526,
"s": 34439,
"text": "This method will return elements of TreeSet which are less than the specified element."
},
{
"code": null,
"e": 34534,
"s": 34526,
"text": "Syntax:"
},
{
"code": null,
"e": 34570,
"s": 34534,
"text": "treeSetObject.headSet(upToNumber) ;"
},
{
"code": null,
"e": 34647,
"s": 34570,
"text": "Note: ‘upToNumber‘ is the upper limit of the numbers to be found (exclusive)"
},
{
"code": null,
"e": 34656,
"s": 34647,
"text": "Example:"
},
{
"code": null,
"e": 34661,
"s": 34656,
"text": "Java"
},
{
"code": "// Java Program to demonstrate headSet Method in TreeSet // Importing input output classesimport java.io.*;// Importing Set snd TreeSet classes from java.util packageimport java.util.Set;import java.util.TreeSet; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of TreeSet of Integer type // Initializing object with integer values using // Set.of() method TreeSet<Integer> treeSet = new TreeSet<>(Set.of(12, 98, 54, 37, 68)); // Print and display elements in object System.out.println(\"tree set = \" + treeSet); // Implementing headSet() method via TreeSet object // Case 1 System.out.println(\"Elements upto 90 : \" + treeSet.headSet(90)); // Case 2 // The function limit is exclusive of the argument // passed System.out.println(\"Elements upto 68 : \" + treeSet.headSet(68)); // Case 3 // If we want to include the number passed, then System.out.println(\"Elements upto 68 (inclusive) : \" + treeSet.headSet(68, true)); }}",
"e": 35862,
"s": 34661,
"text": null
},
{
"code": null,
"e": 36010,
"s": 35862,
"text": "tree set = [12, 37, 54, 68, 98]\nElements upto 90 : [12, 37, 54, 68]\nElements upto 68 : [12, 37, 54]\nElements upto 68 (inclusive) : [12, 37, 54, 68]"
},
{
"code": null,
"e": 36021,
"s": 36010,
"text": "Method 7: "
},
{
"code": null,
"e": 36124,
"s": 36021,
"text": "This method will return elements of TreeSet which are greater than or equal to the specified element. "
},
{
"code": null,
"e": 36132,
"s": 36124,
"text": "Syntax:"
},
{
"code": null,
"e": 36173,
"s": 36132,
"text": "treeSetObject.tailSet(aboveThisNumber) ;"
},
{
"code": null,
"e": 36256,
"s": 36173,
"text": "Note: ‘aboveThisNumber’ is the lower limit of the numbers to be found (inclusive)."
},
{
"code": null,
"e": 36265,
"s": 36256,
"text": "Example:"
},
{
"code": null,
"e": 36270,
"s": 36265,
"text": "Java"
},
{
"code": "// Java Program to demonstrate tailSet Method in TreeSet // Importing input output classesimport java.io.*;import java.util.Set;import java.util.TreeSet; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of TreeSet of Integer type // Initializing object with integer values using // Set.of() method TreeSet<Integer> treeSet = new TreeSet<>(Set.of(12, 98, 54, 37, 68)); // Print and display elements in object System.out.println(\"tree set = \" + treeSet); // Implementing tailSet() // Case 1 System.out.println(\"Elements above 50 : \" + treeSet.tailSet(50)); // Case 2 // The function limit is inclusive of the argument // passed System.out.println(\"Elements above 54 : \" + treeSet.tailSet(54)); // Case 3 // If we want to exclude the number passed System.out.println( \"Elements above 54 (exclusive) : \" + treeSet.tailSet(54, false)); }}",
"e": 37381,
"s": 36270,
"text": null
},
{
"code": null,
"e": 37520,
"s": 37381,
"text": "tree set = [12, 37, 54, 68, 98]\nElements above 50 : [54, 68, 98]\nElements above 54 : [54, 68, 98]\nElements above 54 (exclusive) : [68, 98]"
},
{
"code": null,
"e": 37529,
"s": 37520,
"text": "sooda367"
},
{
"code": null,
"e": 37541,
"s": 37529,
"text": "anikaseth98"
},
{
"code": null,
"e": 37556,
"s": 37541,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 37570,
"s": 37556,
"text": "sumitgumber28"
},
{
"code": null,
"e": 37587,
"s": 37570,
"text": "Java-Collections"
},
{
"code": null,
"e": 37600,
"s": 37587,
"text": "java-treeset"
},
{
"code": null,
"e": 37605,
"s": 37600,
"text": "Java"
},
{
"code": null,
"e": 37610,
"s": 37605,
"text": "Java"
},
{
"code": null,
"e": 37627,
"s": 37610,
"text": "Java-Collections"
},
{
"code": null,
"e": 37725,
"s": 37627,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37740,
"s": 37725,
"text": "Stream In Java"
},
{
"code": null,
"e": 37761,
"s": 37740,
"text": "Constructors in Java"
},
{
"code": null,
"e": 37780,
"s": 37761,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 37810,
"s": 37780,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 37856,
"s": 37810,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 37873,
"s": 37856,
"text": "Generics in Java"
},
{
"code": null,
"e": 37894,
"s": 37873,
"text": "Introduction to Java"
},
{
"code": null,
"e": 37937,
"s": 37894,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 37973,
"s": 37937,
"text": "Internal Working of HashMap in Java"
}
] |
Comparison between Tarjan's and Kosaraju's Algorithm - GeeksforGeeks | 30 Jun, 2021
Tarjan’s Algorithm: The Tarjan’s Algorithm is an efficient graph algorithm that is used to find the Strongly Connected Component(SCC) in a directed graph by using only one DFS traversal in linear time complexity.
Working:
Perform a DFS traversal over the nodes so that the sub-trees of the Strongly Connected Components are removed when they are encountered.
Then two values are assigned:The first value is the counter value when the node is explored for the first time.Second value stores the lowest node value reachable from the initial node which is not part of another SCC.
The first value is the counter value when the node is explored for the first time.
Second value stores the lowest node value reachable from the initial node which is not part of another SCC.
When the nodes are explored, they are pushed into a stack.
If there are any unexplored children of a node are left, they are explored and the assigned value is respectively updated.
Below is the program to find the SCC of the given graph using Tarjan’s Algorithm:
C++
// C++ program to find the SCC using// Tarjan's algorithm (single DFS)#include <iostream>#include <list>#include <stack>#define NIL -1using namespace std; // A class that represents// an directed graphclass Graph { // No. of vertices int V; // A dynamic array of adjacency lists list<int>* adj; // A Recursive DFS based function // used by SCC() void SCCUtil(int u, int disc[], int low[], stack<int>* st, bool stackMember[]); public: // Member functions Graph(int V); void addEdge(int v, int w); void SCC();}; // ConstructorGraph::Graph(int V){ this->V = V; adj = new list<int>[V];} // Function to add an edge to the graphvoid Graph::addEdge(int v, int w){ adj[v].push_back(w);} // Recursive function to finds the SCC// using DFS traversalvoid Graph::SCCUtil(int u, int disc[], int low[], stack<int>* st, bool stackMember[]){ static int time = 0; // Initialize discovery time // and low value disc[u] = low[u] = ++time; st->push(u); stackMember[u] = true; // Go through all vertices // adjacent to this list<int>::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) { // v is current adjacent of 'u' int v = *i; // If v is not visited yet, // then recur for it if (disc[v] == -1) { SCCUtil(v, disc, low, st, stackMember); // Check if the subtree rooted // with 'v' has connection to // one of the ancestors of 'u' low[u] = min(low[u], low[v]); } // Update low value of 'u' only of // 'v' is still in stack else if (stackMember[v] == true) low[u] = min(low[u], disc[v]); } // head node found, pop the stack // and print an SCC // Store stack extracted vertices int w = 0; // If low[u] and disc[u] if (low[u] == disc[u]) { // Until stack st is empty while (st->top() != u) { w = (int)st->top(); // Print the node cout << w << " "; stackMember[w] = false; st->pop(); } w = (int)st->top(); cout << w << "\n"; stackMember[w] = false; st->pop(); }} // Function to find the SCC in the graphvoid Graph::SCC(){ // Stores the discovery times of // the nodes int* disc = new int[V]; // Stores the nodes with least // discovery time int* low = new int[V]; // Checks whether a node is in // the stack or not bool* stackMember = new bool[V]; // Stores all the connected ancestors stack<int>* st = new stack<int>(); // Initialize disc and low, // and stackMember arrays for (int i = 0; i < V; i++) { disc[i] = NIL; low[i] = NIL; stackMember[i] = false; } // Recursive helper function to // find the SCC in DFS tree with // vertex 'i' for (int i = 0; i < V; i++) { // If current node is not // yet visited if (disc[i] == NIL) { SCCUtil(i, disc, low, st, stackMember); } }} // Driver Codeint main(){ // Given a graph Graph g1(5); g1.addEdge(1, 0); g1.addEdge(0, 2); g1.addEdge(2, 1); g1.addEdge(0, 3); g1.addEdge(3, 4); // Function Call to find SCC using // Tarjan's Algorithm g1.SCC(); return 0;}
4
3
1 2 0
Kosaraju’s Algorithm: The Kosaraju’s Algorithm is also a Depth First Search based algorithm which is used to find the SCC in a directed graph in linear time complexity. The basic concept of this algorithm is that if we are able to arrive at vertex v initially starting from vertex u, then we should be able to arrive at vertex u starting from vertex v, and if this is the situation, we can say and conclude that vertices u and v are strongly connected, and they are in the strongly connected sub-graph.
Working:
Perform a DFS traversal on the given graph, keeping track of the finish times of each node. This process can be performed by using a stack.
When the procedure of running the DFS traversal over the graph finishes, put the source vertex on the stack. In this way, the node with the highest finishing time will be at the top of the stack.
Reverse the original graph by using an Adjacency List.
Then perform another DFS traversal on the reversed graph with the source vertex as the vertex on the top of the stack. When the DFS running on the reversed graph finishes, all the nodes that are visited will form one strongly connected component.
If any more nodes are left or remain unvisited, this signifies the presence of more than one strongly connected component on the graph.
So pop the vertices from the top of the stack until a valid unvisited node is found. This will have the highest finishing time of all currently unvisited nodes.
Below is the program to find the SCC of the given graph using Kosaraju’s Algorithm:
C++
// C++ program to print the SCC of the// graph using Kosaraju's Algorithm#include <iostream>#include <list>#include <stack>using namespace std; class Graph { // No. of vertices int V; // An array of adjacency lists list<int>* adj; // Member Functions void fillOrder(int v, bool visited[], stack<int>& Stack); void DFSUtil(int v, bool visited[]); public: Graph(int V); void addEdge(int v, int w); void printSCCs(); Graph getTranspose();}; // Constructor of classGraph::Graph(int V){ this->V = V; adj = new list<int>[V];} // Recursive function to print DFS// starting from vvoid Graph::DFSUtil(int v, bool visited[]){ // Mark the current node as // visited and print it visited[v] = true; cout << v << " "; // Recur for all the vertices // adjacent to this vertex list<int>::iterator i; // Traverse Adjacency List of node v for (i = adj[v].begin(); i != adj[v].end(); ++i) { // If child node *i is unvisited if (!visited[*i]) DFSUtil(*i, visited); }} // Function to get the transpose of// the given graphGraph Graph::getTranspose(){ Graph g(V); for (int v = 0; v < V; v++) { // Recur for all the vertices // adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) { // Add to adjacency list g.adj[*i].push_back(v); } } // Return the reversed graph return g;} // Function to add an Edge to the given// graphvoid Graph::addEdge(int v, int w){ // Add w to v’s list adj[v].push_back(w);} // Function that fills stack with vertices// in increasing order of finishing timesvoid Graph::fillOrder(int v, bool visited[], stack<int>& Stack){ // Mark the current node as // visited and print it visited[v] = true; // Recur for all the vertices // adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) { // If child node *i is unvisited if (!visited[*i]) { fillOrder(*i, visited, Stack); } } // All vertices reachable from v // are processed by now, push v Stack.push(v);} // Function that finds and prints all// strongly connected componentsvoid Graph::printSCCs(){ stack<int> Stack; // Mark all the vertices as // not visited (For first DFS) bool* visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; // Fill vertices in stack according // to their finishing times for (int i = 0; i < V; i++) if (visited[i] == false) fillOrder(i, visited, Stack); // Create a reversed graph Graph gr = getTranspose(); // Mark all the vertices as not // visited (For second DFS) for (int i = 0; i < V; i++) visited[i] = false; // Now process all vertices in // order defined by Stack while (Stack.empty() == false) { // Pop a vertex from stack int v = Stack.top(); Stack.pop(); // Print SCC of the popped vertex if (visited[v] == false) { gr.DFSUtil(v, visited); cout << endl; } }} // Driver Codeint main(){ // Given Graph Graph g(5); g.addEdge(1, 0); g.addEdge(0, 2); g.addEdge(2, 1); g.addEdge(0, 3); g.addEdge(3, 4); // Function Call to find the SCC // using Kosaraju's Algorithm g.printSCCs(); return 0;}
0 1 2
3
4
Time Complexity:The time complexity of Tarjan’s Algorithm and Kosaraju’s Algorithm will be O(V + E), where V represents the set of vertices and E represents the set of edges of the graph. Tarjan’s algorithm has much lower constant factors w.r.t Kosaraju’s algorithm. In Kosaraju’s algorithm, the traversal of the graph is done at least 2 times, so the constant factor can be of double time. We can print the SCC in progress with Kosaraju’s algorithm as we perform the second DFS. While performing Tarjan’s Algorithm, it requires extra time to print the SCC after finding the head of the SCCs sub-tree.
Summary:Both the methods have the same linear time complexity, but the techniques or the procedure for the SCC computations are fairly different. Tarjan’s method solely depends on the record of nodes in a DFS to partition the graph whereas Kosaraju’s method performs the two DFS (or 3 DFS if we want to leave the original graph unchanged) on the graph and is quite similar to the method for finding the topological sorting of a graph.
clintra
Algorithms-Graph Traversals
DFS
graph-connectivity
Technical Scripter 2020
Advanced Data Structure
Algorithms
Graph
Stack
Technical Scripter
Stack
DFS
Graph
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Agents in Artificial Intelligence
Decision Tree Introduction with example
AVL Tree | Set 2 (Deletion)
Segment Tree | Set 1 (Sum of given range)
Red-Black Tree | Set 2 (Insert)
SDE SHEET - A Complete Guide for SDE Preparation
Top 50 Array Coding Problems for Interviews
DSA Sheet by Love Babbar
Difference between BFS and DFS
How to write a Pseudo Code? | [
{
"code": null,
"e": 26509,
"s": 26481,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 26722,
"s": 26509,
"text": "Tarjan’s Algorithm: The Tarjan’s Algorithm is an efficient graph algorithm that is used to find the Strongly Connected Component(SCC) in a directed graph by using only one DFS traversal in linear time complexity."
},
{
"code": null,
"e": 26731,
"s": 26722,
"text": "Working:"
},
{
"code": null,
"e": 26868,
"s": 26731,
"text": "Perform a DFS traversal over the nodes so that the sub-trees of the Strongly Connected Components are removed when they are encountered."
},
{
"code": null,
"e": 27087,
"s": 26868,
"text": "Then two values are assigned:The first value is the counter value when the node is explored for the first time.Second value stores the lowest node value reachable from the initial node which is not part of another SCC."
},
{
"code": null,
"e": 27170,
"s": 27087,
"text": "The first value is the counter value when the node is explored for the first time."
},
{
"code": null,
"e": 27278,
"s": 27170,
"text": "Second value stores the lowest node value reachable from the initial node which is not part of another SCC."
},
{
"code": null,
"e": 27337,
"s": 27278,
"text": "When the nodes are explored, they are pushed into a stack."
},
{
"code": null,
"e": 27460,
"s": 27337,
"text": "If there are any unexplored children of a node are left, they are explored and the assigned value is respectively updated."
},
{
"code": null,
"e": 27542,
"s": 27460,
"text": "Below is the program to find the SCC of the given graph using Tarjan’s Algorithm:"
},
{
"code": null,
"e": 27546,
"s": 27542,
"text": "C++"
},
{
"code": "// C++ program to find the SCC using// Tarjan's algorithm (single DFS)#include <iostream>#include <list>#include <stack>#define NIL -1using namespace std; // A class that represents// an directed graphclass Graph { // No. of vertices int V; // A dynamic array of adjacency lists list<int>* adj; // A Recursive DFS based function // used by SCC() void SCCUtil(int u, int disc[], int low[], stack<int>* st, bool stackMember[]); public: // Member functions Graph(int V); void addEdge(int v, int w); void SCC();}; // ConstructorGraph::Graph(int V){ this->V = V; adj = new list<int>[V];} // Function to add an edge to the graphvoid Graph::addEdge(int v, int w){ adj[v].push_back(w);} // Recursive function to finds the SCC// using DFS traversalvoid Graph::SCCUtil(int u, int disc[], int low[], stack<int>* st, bool stackMember[]){ static int time = 0; // Initialize discovery time // and low value disc[u] = low[u] = ++time; st->push(u); stackMember[u] = true; // Go through all vertices // adjacent to this list<int>::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) { // v is current adjacent of 'u' int v = *i; // If v is not visited yet, // then recur for it if (disc[v] == -1) { SCCUtil(v, disc, low, st, stackMember); // Check if the subtree rooted // with 'v' has connection to // one of the ancestors of 'u' low[u] = min(low[u], low[v]); } // Update low value of 'u' only of // 'v' is still in stack else if (stackMember[v] == true) low[u] = min(low[u], disc[v]); } // head node found, pop the stack // and print an SCC // Store stack extracted vertices int w = 0; // If low[u] and disc[u] if (low[u] == disc[u]) { // Until stack st is empty while (st->top() != u) { w = (int)st->top(); // Print the node cout << w << \" \"; stackMember[w] = false; st->pop(); } w = (int)st->top(); cout << w << \"\\n\"; stackMember[w] = false; st->pop(); }} // Function to find the SCC in the graphvoid Graph::SCC(){ // Stores the discovery times of // the nodes int* disc = new int[V]; // Stores the nodes with least // discovery time int* low = new int[V]; // Checks whether a node is in // the stack or not bool* stackMember = new bool[V]; // Stores all the connected ancestors stack<int>* st = new stack<int>(); // Initialize disc and low, // and stackMember arrays for (int i = 0; i < V; i++) { disc[i] = NIL; low[i] = NIL; stackMember[i] = false; } // Recursive helper function to // find the SCC in DFS tree with // vertex 'i' for (int i = 0; i < V; i++) { // If current node is not // yet visited if (disc[i] == NIL) { SCCUtil(i, disc, low, st, stackMember); } }} // Driver Codeint main(){ // Given a graph Graph g1(5); g1.addEdge(1, 0); g1.addEdge(0, 2); g1.addEdge(2, 1); g1.addEdge(0, 3); g1.addEdge(3, 4); // Function Call to find SCC using // Tarjan's Algorithm g1.SCC(); return 0;}",
"e": 30954,
"s": 27546,
"text": null
},
{
"code": null,
"e": 30964,
"s": 30954,
"text": "4\n3\n1 2 0"
},
{
"code": null,
"e": 31469,
"s": 30966,
"text": "Kosaraju’s Algorithm: The Kosaraju’s Algorithm is also a Depth First Search based algorithm which is used to find the SCC in a directed graph in linear time complexity. The basic concept of this algorithm is that if we are able to arrive at vertex v initially starting from vertex u, then we should be able to arrive at vertex u starting from vertex v, and if this is the situation, we can say and conclude that vertices u and v are strongly connected, and they are in the strongly connected sub-graph."
},
{
"code": null,
"e": 31478,
"s": 31469,
"text": "Working:"
},
{
"code": null,
"e": 31618,
"s": 31478,
"text": "Perform a DFS traversal on the given graph, keeping track of the finish times of each node. This process can be performed by using a stack."
},
{
"code": null,
"e": 31814,
"s": 31618,
"text": "When the procedure of running the DFS traversal over the graph finishes, put the source vertex on the stack. In this way, the node with the highest finishing time will be at the top of the stack."
},
{
"code": null,
"e": 31869,
"s": 31814,
"text": "Reverse the original graph by using an Adjacency List."
},
{
"code": null,
"e": 32116,
"s": 31869,
"text": "Then perform another DFS traversal on the reversed graph with the source vertex as the vertex on the top of the stack. When the DFS running on the reversed graph finishes, all the nodes that are visited will form one strongly connected component."
},
{
"code": null,
"e": 32252,
"s": 32116,
"text": "If any more nodes are left or remain unvisited, this signifies the presence of more than one strongly connected component on the graph."
},
{
"code": null,
"e": 32413,
"s": 32252,
"text": "So pop the vertices from the top of the stack until a valid unvisited node is found. This will have the highest finishing time of all currently unvisited nodes."
},
{
"code": null,
"e": 32497,
"s": 32413,
"text": "Below is the program to find the SCC of the given graph using Kosaraju’s Algorithm:"
},
{
"code": null,
"e": 32501,
"s": 32497,
"text": "C++"
},
{
"code": "// C++ program to print the SCC of the// graph using Kosaraju's Algorithm#include <iostream>#include <list>#include <stack>using namespace std; class Graph { // No. of vertices int V; // An array of adjacency lists list<int>* adj; // Member Functions void fillOrder(int v, bool visited[], stack<int>& Stack); void DFSUtil(int v, bool visited[]); public: Graph(int V); void addEdge(int v, int w); void printSCCs(); Graph getTranspose();}; // Constructor of classGraph::Graph(int V){ this->V = V; adj = new list<int>[V];} // Recursive function to print DFS// starting from vvoid Graph::DFSUtil(int v, bool visited[]){ // Mark the current node as // visited and print it visited[v] = true; cout << v << \" \"; // Recur for all the vertices // adjacent to this vertex list<int>::iterator i; // Traverse Adjacency List of node v for (i = adj[v].begin(); i != adj[v].end(); ++i) { // If child node *i is unvisited if (!visited[*i]) DFSUtil(*i, visited); }} // Function to get the transpose of// the given graphGraph Graph::getTranspose(){ Graph g(V); for (int v = 0; v < V; v++) { // Recur for all the vertices // adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) { // Add to adjacency list g.adj[*i].push_back(v); } } // Return the reversed graph return g;} // Function to add an Edge to the given// graphvoid Graph::addEdge(int v, int w){ // Add w to v’s list adj[v].push_back(w);} // Function that fills stack with vertices// in increasing order of finishing timesvoid Graph::fillOrder(int v, bool visited[], stack<int>& Stack){ // Mark the current node as // visited and print it visited[v] = true; // Recur for all the vertices // adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) { // If child node *i is unvisited if (!visited[*i]) { fillOrder(*i, visited, Stack); } } // All vertices reachable from v // are processed by now, push v Stack.push(v);} // Function that finds and prints all// strongly connected componentsvoid Graph::printSCCs(){ stack<int> Stack; // Mark all the vertices as // not visited (For first DFS) bool* visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; // Fill vertices in stack according // to their finishing times for (int i = 0; i < V; i++) if (visited[i] == false) fillOrder(i, visited, Stack); // Create a reversed graph Graph gr = getTranspose(); // Mark all the vertices as not // visited (For second DFS) for (int i = 0; i < V; i++) visited[i] = false; // Now process all vertices in // order defined by Stack while (Stack.empty() == false) { // Pop a vertex from stack int v = Stack.top(); Stack.pop(); // Print SCC of the popped vertex if (visited[v] == false) { gr.DFSUtil(v, visited); cout << endl; } }} // Driver Codeint main(){ // Given Graph Graph g(5); g.addEdge(1, 0); g.addEdge(0, 2); g.addEdge(2, 1); g.addEdge(0, 3); g.addEdge(3, 4); // Function Call to find the SCC // using Kosaraju's Algorithm g.printSCCs(); return 0;}",
"e": 35984,
"s": 32501,
"text": null
},
{
"code": null,
"e": 35996,
"s": 35984,
"text": "0 1 2 \n3 \n4"
},
{
"code": null,
"e": 36600,
"s": 35998,
"text": "Time Complexity:The time complexity of Tarjan’s Algorithm and Kosaraju’s Algorithm will be O(V + E), where V represents the set of vertices and E represents the set of edges of the graph. Tarjan’s algorithm has much lower constant factors w.r.t Kosaraju’s algorithm. In Kosaraju’s algorithm, the traversal of the graph is done at least 2 times, so the constant factor can be of double time. We can print the SCC in progress with Kosaraju’s algorithm as we perform the second DFS. While performing Tarjan’s Algorithm, it requires extra time to print the SCC after finding the head of the SCCs sub-tree."
},
{
"code": null,
"e": 37035,
"s": 36600,
"text": "Summary:Both the methods have the same linear time complexity, but the techniques or the procedure for the SCC computations are fairly different. Tarjan’s method solely depends on the record of nodes in a DFS to partition the graph whereas Kosaraju’s method performs the two DFS (or 3 DFS if we want to leave the original graph unchanged) on the graph and is quite similar to the method for finding the topological sorting of a graph."
},
{
"code": null,
"e": 37043,
"s": 37035,
"text": "clintra"
},
{
"code": null,
"e": 37071,
"s": 37043,
"text": "Algorithms-Graph Traversals"
},
{
"code": null,
"e": 37075,
"s": 37071,
"text": "DFS"
},
{
"code": null,
"e": 37094,
"s": 37075,
"text": "graph-connectivity"
},
{
"code": null,
"e": 37118,
"s": 37094,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 37142,
"s": 37118,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 37153,
"s": 37142,
"text": "Algorithms"
},
{
"code": null,
"e": 37159,
"s": 37153,
"text": "Graph"
},
{
"code": null,
"e": 37165,
"s": 37159,
"text": "Stack"
},
{
"code": null,
"e": 37184,
"s": 37165,
"text": "Technical Scripter"
},
{
"code": null,
"e": 37190,
"s": 37184,
"text": "Stack"
},
{
"code": null,
"e": 37194,
"s": 37190,
"text": "DFS"
},
{
"code": null,
"e": 37200,
"s": 37194,
"text": "Graph"
},
{
"code": null,
"e": 37211,
"s": 37200,
"text": "Algorithms"
},
{
"code": null,
"e": 37309,
"s": 37211,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37343,
"s": 37309,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 37383,
"s": 37343,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 37411,
"s": 37383,
"text": "AVL Tree | Set 2 (Deletion)"
},
{
"code": null,
"e": 37453,
"s": 37411,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 37485,
"s": 37453,
"text": "Red-Black Tree | Set 2 (Insert)"
},
{
"code": null,
"e": 37534,
"s": 37485,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 37578,
"s": 37534,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 37603,
"s": 37578,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 37634,
"s": 37603,
"text": "Difference between BFS and DFS"
}
] |
How to Add Labels in a Plot using Python? - GeeksforGeeks | 20 Oct, 2021
Prerequisites: Python Matplotlib
In this article, we will discuss adding labels to the plot using Matplotlib in Python. But first, understand what are labels in a plot. The heading or sub-heading written at the vertical axis (say Y-axis) and the horizontal axis(say X-axis) improves the quality of understanding of plotted stats.
Example: Let’s create a simple plot
Python
# python program to plot graph without labelsimport matplotlibimport matplotlib.pyplot as pltimport numpy as np # it will take x coordinates by default# starting from 0,1,2,3,4...y = np.array([3, 8, 1, 10]) plt.plot(y)plt.show()
Output:
Plot without Labels or Title
By using pyplot() function of library we can add xlabel() and ylabel() to set x and y labels.
Example: Let’s add Label in the above Plot
Python
# python program for plots with labelimport matplotlibimport matplotlib.pyplot as pltimport numpy as np # Number of children it was default in earlier casex = np.array([0, 1, 2, 3]) # Number of familiesy = np.array([3, 8, 1, 10]) plt.plot(x, y) # Label for x-axisplt.xlabel("Number of Childerns") # Label for y-axisplt.ylabel("Number of Families") plt.show() # for display
Output:
Plot with Labels
If you would like to make it more understandable, add a Title to the plot, by just adding a single line of code.
plt.title("Survey Of Colony")
Example:
Python3
# python program for plots with labelimport matplotlibimport matplotlib.pyplot as pltimport numpy as np # Number of children it was default in earlier casex = np.array([0, 1, 2, 3]) # Number of familiesy = np.array([3, 8, 1, 10]) plt.plot(x, y) # Label for x-axisplt.xlabel("Number of Childerns") # Label for y-axisplt.ylabel("Number of Families") # title of the plotplt.title("Survey Of Colony") plt.show() # for display
Output:
Plot with Title
In order to make the Plot more attractive use the fontdict parameter in xlabel(), ylabel(), and title() to apply the font properties.
Python
# Adding font properties to labels and titlesimport matplotlibimport matplotlib.pyplot as pltimport numpy as np # Number of Childrenx = np.array([0, 1, 2, 3]) # Number of Familiesy = np.array([3, 8, 1, 10]) # label including this form1 will have these propertiesform1 = {'family': 'serif', 'color': 'blue', 'size': 20} # label including this form2 will have these propertiesform2 = {'family': 'serif', 'color': 'darkred', 'size': 15} plt.plot(x, y)plt.xlabel("Number of Childerns", fontdict=form1)plt.ylabel("Number of Families", fontdict=form1)plt.title("Survey Of Colony", fontdict=form2)plt.show()
Output:
Plot with Font Properties
surindertarika1234
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25563,
"s": 25535,
"text": "\n20 Oct, 2021"
},
{
"code": null,
"e": 25597,
"s": 25563,
"text": "Prerequisites: Python Matplotlib "
},
{
"code": null,
"e": 25894,
"s": 25597,
"text": "In this article, we will discuss adding labels to the plot using Matplotlib in Python. But first, understand what are labels in a plot. The heading or sub-heading written at the vertical axis (say Y-axis) and the horizontal axis(say X-axis) improves the quality of understanding of plotted stats."
},
{
"code": null,
"e": 25930,
"s": 25894,
"text": "Example: Let’s create a simple plot"
},
{
"code": null,
"e": 25937,
"s": 25930,
"text": "Python"
},
{
"code": "# python program to plot graph without labelsimport matplotlibimport matplotlib.pyplot as pltimport numpy as np # it will take x coordinates by default# starting from 0,1,2,3,4...y = np.array([3, 8, 1, 10]) plt.plot(y)plt.show()",
"e": 26167,
"s": 25937,
"text": null
},
{
"code": null,
"e": 26175,
"s": 26167,
"text": "Output:"
},
{
"code": null,
"e": 26204,
"s": 26175,
"text": "Plot without Labels or Title"
},
{
"code": null,
"e": 26299,
"s": 26204,
"text": "By using pyplot() function of library we can add xlabel() and ylabel() to set x and y labels. "
},
{
"code": null,
"e": 26342,
"s": 26299,
"text": "Example: Let’s add Label in the above Plot"
},
{
"code": null,
"e": 26349,
"s": 26342,
"text": "Python"
},
{
"code": "# python program for plots with labelimport matplotlibimport matplotlib.pyplot as pltimport numpy as np # Number of children it was default in earlier casex = np.array([0, 1, 2, 3]) # Number of familiesy = np.array([3, 8, 1, 10]) plt.plot(x, y) # Label for x-axisplt.xlabel(\"Number of Childerns\") # Label for y-axisplt.ylabel(\"Number of Families\") plt.show() # for display",
"e": 26724,
"s": 26349,
"text": null
},
{
"code": null,
"e": 26732,
"s": 26724,
"text": "Output:"
},
{
"code": null,
"e": 26749,
"s": 26732,
"text": "Plot with Labels"
},
{
"code": null,
"e": 26862,
"s": 26749,
"text": "If you would like to make it more understandable, add a Title to the plot, by just adding a single line of code."
},
{
"code": null,
"e": 26892,
"s": 26862,
"text": "plt.title(\"Survey Of Colony\")"
},
{
"code": null,
"e": 26901,
"s": 26892,
"text": "Example:"
},
{
"code": null,
"e": 26909,
"s": 26901,
"text": "Python3"
},
{
"code": "# python program for plots with labelimport matplotlibimport matplotlib.pyplot as pltimport numpy as np # Number of children it was default in earlier casex = np.array([0, 1, 2, 3]) # Number of familiesy = np.array([3, 8, 1, 10]) plt.plot(x, y) # Label for x-axisplt.xlabel(\"Number of Childerns\") # Label for y-axisplt.ylabel(\"Number of Families\") # title of the plotplt.title(\"Survey Of Colony\") plt.show() # for display",
"e": 27333,
"s": 26909,
"text": null
},
{
"code": null,
"e": 27345,
"s": 27337,
"text": "Output:"
},
{
"code": null,
"e": 27363,
"s": 27347,
"text": "Plot with Title"
},
{
"code": null,
"e": 27499,
"s": 27365,
"text": "In order to make the Plot more attractive use the fontdict parameter in xlabel(), ylabel(), and title() to apply the font properties."
},
{
"code": null,
"e": 27508,
"s": 27501,
"text": "Python"
},
{
"code": "# Adding font properties to labels and titlesimport matplotlibimport matplotlib.pyplot as pltimport numpy as np # Number of Childrenx = np.array([0, 1, 2, 3]) # Number of Familiesy = np.array([3, 8, 1, 10]) # label including this form1 will have these propertiesform1 = {'family': 'serif', 'color': 'blue', 'size': 20} # label including this form2 will have these propertiesform2 = {'family': 'serif', 'color': 'darkred', 'size': 15} plt.plot(x, y)plt.xlabel(\"Number of Childerns\", fontdict=form1)plt.ylabel(\"Number of Families\", fontdict=form1)plt.title(\"Survey Of Colony\", fontdict=form2)plt.show()",
"e": 28110,
"s": 27508,
"text": null
},
{
"code": null,
"e": 28118,
"s": 28110,
"text": "Output:"
},
{
"code": null,
"e": 28144,
"s": 28118,
"text": "Plot with Font Properties"
},
{
"code": null,
"e": 28163,
"s": 28144,
"text": "surindertarika1234"
},
{
"code": null,
"e": 28181,
"s": 28163,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 28205,
"s": 28181,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28212,
"s": 28205,
"text": "Python"
},
{
"code": null,
"e": 28231,
"s": 28212,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28329,
"s": 28231,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28361,
"s": 28329,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28403,
"s": 28361,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28445,
"s": 28403,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28472,
"s": 28445,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28528,
"s": 28472,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28550,
"s": 28528,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28589,
"s": 28550,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28620,
"s": 28589,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28649,
"s": 28620,
"text": "Create a directory in Python"
}
] |
Insert statement in MS SQL Server - GeeksforGeeks | 05 Aug, 2020
A database contains of many tables which has data stored in an order. To add up the rows, the user needs to use insert statement.
Syntax :
insert into table_name(column_list)
values(values_list)
For better understanding, an example is given below.
Example – A table named student must have values inserted into it. It has to be done as follows:
insert into student (varchar2 name(20), int rollnumber, varchar2 course(50));
values('Riya', 111, 'Computer Science');
Output –
1 row(s) inserted
To check whether the value is actually inserted, the query must be given as follows:
select *
from student;
Output –
insert multiple rows : A table can store upto 1000 rows in one insert statement. If a user want to insert multiple rows at a time, the following syntax has to written.
Syntax :
insert into table_name(column_list)
values(value_list1)
values(values_list2)
.
.
.
.
values(values_listn)
If a user wants to insert more than 1000 rows, multiple insert statements, bulk insert or derived table must be used.
Example – Consider a table student. If a user has to enter the data of 6 students at a time, the query must be given as follows-
insert into student(int rollnumber, varchar2(30) name, varchar2(20) course);
values(111, 'Riya', 'CSE');
values(112, 'Apoorva', 'ECE');
values(113, 'Mina', 'Mech');
values(114, 'Rita', 'Biotechnology);
values(115, 'Veena', 'Chemical');
values(116, 'Deepa', 'EEE');
Output –
6 row(s) inserted
To check whether the values are present in the table, the query must be given as follows:
select *
from student;
Output –
The insert multiple rows statement was only available in the year 2008 and later on.
khushboogoyal499
SQL-Server
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
Introduction of B-Tree
CTE in SQL
SQL Trigger | Student Database
Difference between Clustered and Non-clustered index
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
SQL Interview Questions
CTE in SQL | [
{
"code": null,
"e": 25137,
"s": 25109,
"text": "\n05 Aug, 2020"
},
{
"code": null,
"e": 25269,
"s": 25137,
"text": "A database contains of many tables which has data stored in an order. To add up the rows, the user needs to use insert statement. "
},
{
"code": null,
"e": 25280,
"s": 25269,
"text": "Syntax : "
},
{
"code": null,
"e": 25338,
"s": 25280,
"text": "insert into table_name(column_list)\nvalues(values_list) \n"
},
{
"code": null,
"e": 25392,
"s": 25338,
"text": "For better understanding, an example is given below. "
},
{
"code": null,
"e": 25490,
"s": 25392,
"text": "Example – A table named student must have values inserted into it. It has to be done as follows: "
},
{
"code": null,
"e": 25613,
"s": 25492,
"text": "insert into student (varchar2 name(20), int rollnumber, varchar2 course(50));\nvalues('Riya', 111, 'Computer Science'); \n"
},
{
"code": null,
"e": 25624,
"s": 25613,
"text": "Output – "
},
{
"code": null,
"e": 25644,
"s": 25624,
"text": "1 row(s) inserted \n"
},
{
"code": null,
"e": 25731,
"s": 25644,
"text": "To check whether the value is actually inserted, the query must be given as follows: "
},
{
"code": null,
"e": 25756,
"s": 25731,
"text": "select *\nfrom student; \n"
},
{
"code": null,
"e": 25766,
"s": 25756,
"text": "Output – "
},
{
"code": null,
"e": 25938,
"s": 25768,
"text": "insert multiple rows : A table can store upto 1000 rows in one insert statement. If a user want to insert multiple rows at a time, the following syntax has to written. "
},
{
"code": null,
"e": 25949,
"s": 25938,
"text": "Syntax : "
},
{
"code": null,
"e": 26057,
"s": 25949,
"text": "insert into table_name(column_list)\nvalues(value_list1)\nvalues(values_list2)\n.\n.\n.\n.\nvalues(values_listn) \n"
},
{
"code": null,
"e": 26176,
"s": 26057,
"text": "If a user wants to insert more than 1000 rows, multiple insert statements, bulk insert or derived table must be used. "
},
{
"code": null,
"e": 26307,
"s": 26176,
"text": "Example – Consider a table student. If a user has to enter the data of 6 students at a time, the query must be given as follows- "
},
{
"code": null,
"e": 26574,
"s": 26307,
"text": "insert into student(int rollnumber, varchar2(30) name, varchar2(20) course);\nvalues(111, 'Riya', 'CSE');\nvalues(112, 'Apoorva', 'ECE');\nvalues(113, 'Mina', 'Mech');\nvalues(114, 'Rita', 'Biotechnology);\nvalues(115, 'Veena', 'Chemical');\nvalues(116, 'Deepa', 'EEE'); \n"
},
{
"code": null,
"e": 26585,
"s": 26574,
"text": "Output – "
},
{
"code": null,
"e": 26605,
"s": 26585,
"text": "6 row(s) inserted \n"
},
{
"code": null,
"e": 26697,
"s": 26605,
"text": "To check whether the values are present in the table, the query must be given as follows: "
},
{
"code": null,
"e": 26722,
"s": 26697,
"text": "select *\nfrom student; \n"
},
{
"code": null,
"e": 26732,
"s": 26722,
"text": "Output – "
},
{
"code": null,
"e": 26821,
"s": 26734,
"text": "The insert multiple rows statement was only available in the year 2008 and later on. "
},
{
"code": null,
"e": 26838,
"s": 26821,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 26849,
"s": 26838,
"text": "SQL-Server"
},
{
"code": null,
"e": 26854,
"s": 26849,
"text": "DBMS"
},
{
"code": null,
"e": 26858,
"s": 26854,
"text": "SQL"
},
{
"code": null,
"e": 26863,
"s": 26858,
"text": "DBMS"
},
{
"code": null,
"e": 26867,
"s": 26863,
"text": "SQL"
},
{
"code": null,
"e": 26965,
"s": 26867,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26989,
"s": 26965,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 27012,
"s": 26989,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 27023,
"s": 27012,
"text": "CTE in SQL"
},
{
"code": null,
"e": 27054,
"s": 27023,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 27107,
"s": 27054,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 27149,
"s": 27107,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 27193,
"s": 27149,
"text": "How to find Nth highest salary from a table"
},
{
"code": null,
"e": 27214,
"s": 27193,
"text": "SQL | ALTER (RENAME)"
},
{
"code": null,
"e": 27238,
"s": 27214,
"text": "SQL Interview Questions"
}
] |
How to limit a number between a min/max value in JavaScript ? - GeeksforGeeks | 19 Feb, 2020
Given the HTML document. The task is, while taking input a number from the user via input element, verify that the number is in the specified range. If it is not then changing it to within the range. Here 2 approaches are discussed with the help of JavaScript.Approach 1:
Take the input from the input element and convert it to number using Number() method.
Use IF-ELSE Condition to verify if it is in range or not?
If the number is less than the minimum value then give it the minimum value else if.
If the number is greater than the maximum value then give it the maximum value else the number is in the range itself.
Example 1: This example implements the above approach.
<!DOCTYPE HTML><html> <head> <title> Limit a number between a min/max value </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> Enter a Number: <input id="num" /> <br> <br> <button onclick="GFG_Fun();"> click here </button> <p id="GFG_DOWN" style="color: green;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = "Click on the button to check if the types number"+ " is in range or not.<br>Min Value - 0 <br> Max Value - 100"; function GFG_Fun() { var input = document.getElementById('num'); var n = input.value; n = Number(n); if (n < 0) { $('#GFG_DOWN').html('Type number between 0-100'); input.value = 0; } else if (n > 100) { $('#GFG_DOWN').html('Type number between 0-100'); input.value = 100; } else { $('#GFG_DOWN').html('You typed the valid Number.'); input.value = n; } } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Approach 2:
Take the input from the input element and convert it to number using Number() method.
Use Math.max and Math.min method to verify if it is in range or not?
If the number is less than the minimum value then give it the minimum value else if.
If the number is greater than the maximum value then give it the maximum value else the number is in the range itself.
Example 2: This example implements the above approach.
<!DOCTYPE HTML><html> <head> <title> Limit a number between a min/max value </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> Enter a Number: <input id="num" /> <br> <br> <button onclick="GFG_Fun();"> click here </button> <p id="GFG_DOWN" style="color: green;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = "Click on the button to check if the types number "+ "is in range or not.<br>Min Value - 0 <br> Max Value - 100"; function GFG_Fun() { var input = document.getElementById('num'); var n = input.value; n = Number(n); n = Math.min(100, Math.max(0, n)); $('#GFG_DOWN').html('Number ranged to <br>N = ' + n); } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 26101,
"s": 26073,
"text": "\n19 Feb, 2020"
},
{
"code": null,
"e": 26373,
"s": 26101,
"text": "Given the HTML document. The task is, while taking input a number from the user via input element, verify that the number is in the specified range. If it is not then changing it to within the range. Here 2 approaches are discussed with the help of JavaScript.Approach 1:"
},
{
"code": null,
"e": 26459,
"s": 26373,
"text": "Take the input from the input element and convert it to number using Number() method."
},
{
"code": null,
"e": 26517,
"s": 26459,
"text": "Use IF-ELSE Condition to verify if it is in range or not?"
},
{
"code": null,
"e": 26602,
"s": 26517,
"text": "If the number is less than the minimum value then give it the minimum value else if."
},
{
"code": null,
"e": 26721,
"s": 26602,
"text": "If the number is greater than the maximum value then give it the maximum value else the number is in the range itself."
},
{
"code": null,
"e": 26776,
"s": 26721,
"text": "Example 1: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Limit a number between a min/max value </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> Enter a Number: <input id=\"num\" /> <br> <br> <button onclick=\"GFG_Fun();\"> click here </button> <p id=\"GFG_DOWN\" style=\"color: green;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = \"Click on the button to check if the types number\"+ \" is in range or not.<br>Min Value - 0 <br> Max Value - 100\"; function GFG_Fun() { var input = document.getElementById('num'); var n = input.value; n = Number(n); if (n < 0) { $('#GFG_DOWN').html('Type number between 0-100'); input.value = 0; } else if (n > 100) { $('#GFG_DOWN').html('Type number between 0-100'); input.value = 100; } else { $('#GFG_DOWN').html('You typed the valid Number.'); input.value = n; } } </script></body> </html>",
"e": 28122,
"s": 26776,
"text": null
},
{
"code": null,
"e": 28130,
"s": 28122,
"text": "Output:"
},
{
"code": null,
"e": 28161,
"s": 28130,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 28191,
"s": 28161,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 28203,
"s": 28191,
"text": "Approach 2:"
},
{
"code": null,
"e": 28289,
"s": 28203,
"text": "Take the input from the input element and convert it to number using Number() method."
},
{
"code": null,
"e": 28358,
"s": 28289,
"text": "Use Math.max and Math.min method to verify if it is in range or not?"
},
{
"code": null,
"e": 28443,
"s": 28358,
"text": "If the number is less than the minimum value then give it the minimum value else if."
},
{
"code": null,
"e": 28562,
"s": 28443,
"text": "If the number is greater than the maximum value then give it the maximum value else the number is in the range itself."
},
{
"code": null,
"e": 28617,
"s": 28562,
"text": "Example 2: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Limit a number between a min/max value </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> Enter a Number: <input id=\"num\" /> <br> <br> <button onclick=\"GFG_Fun();\"> click here </button> <p id=\"GFG_DOWN\" style=\"color: green;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = \"Click on the button to check if the types number \"+ \"is in range or not.<br>Min Value - 0 <br> Max Value - 100\"; function GFG_Fun() { var input = document.getElementById('num'); var n = input.value; n = Number(n); n = Math.min(100, Math.max(0, n)); $('#GFG_DOWN').html('Number ranged to <br>N = ' + n); } </script></body> </html>",
"e": 29686,
"s": 28617,
"text": null
},
{
"code": null,
"e": 29694,
"s": 29686,
"text": "Output:"
},
{
"code": null,
"e": 29725,
"s": 29694,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 29755,
"s": 29725,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 29771,
"s": 29755,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 29782,
"s": 29771,
"text": "JavaScript"
},
{
"code": null,
"e": 29799,
"s": 29782,
"text": "Web Technologies"
},
{
"code": null,
"e": 29826,
"s": 29799,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29924,
"s": 29826,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29964,
"s": 29924,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30009,
"s": 29964,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30070,
"s": 30009,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30142,
"s": 30070,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 30188,
"s": 30142,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 30228,
"s": 30188,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30261,
"s": 30228,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30306,
"s": 30261,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30349,
"s": 30306,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Python | Monitor hard-disk health using smartmontools - GeeksforGeeks | 25 Jun, 2019
Smartmontools, an acronym for ‘S.M.A.R.T monitoring’ tools is a package that is used to control and monitor computer storage systems using S.M.A.R.T. (Self-Monitoring, Analysis and Reporting Technology) system built into most modern (P)ATA, Serial ATA, SCSI/SAS devices.It contains 2 utility programs: smartctl and smartd. These utilities give warnings or alerts of disk degradation and failure.smartmontools can be used in any Unix/Linux based operating systems. It allows us to run various tests to check the health of the HDD or SSD in your system.
Most modern hard drives use S.M.A.R.T. (Self-Monitoring, Analysis, and Reporting Technology) to assess their condition to determine if something is wrong with the device. This allows the user to view the hard drive’s SMART data and take necessary actions to repair or replace the device.
In this article, we will explore smartmontools and retrieve information on the HDDs and SSD in the system. We will also write a python script to parse the output of smartmontools and store the outputs in an excel sheet.
sudo pip3 install pandas
sudo apt-get install smartmontools
Once smartmontools has been installed, we can use the terminal or command line to obtain details of the hard drives.
To check whether your device supports SMART monitoring and to obtain other information such as device model, capacity, serial number, etc, we use the following command:
sudo smartctl -i /dev/sda
If it is not enabled, the following command enables SMART monitoring:
sudo smartctl -s on /dev/sda
To display the overall health of the disk, we use the following command:
sudo smartctl -H /dev/sda
This displays the status of your hard drive. If it displays any errors, then your hard drive might be experiencing some problems and you should consider backing up your data.
To run a short test :
sudo smartctl --test=short /dev/sda
The goal of the short test is the rapid identification of a defective hard drive. Therefore, the maximum run time for the short test is 2 min.
To run a long test:
sudo smartctl --test=long /dev/sda
Long tests also identify defects but here, there is no time restriction. The test is more thorough.
To check the results of the test:
sudo smartctl -l selftest /dev/sda
We can use Python to automate this process and generate a report. For this, we shall use Pandas to store the result in excel sheets and the os module to run the commands.
# importing librariesimport osimport pandas as pdfrom pandas import ExcelWriter # class to hold all the# details about the deviceclass Device(): def __init__(self): self.device_name = None self.info = {} self.results = [] # get the details of the device def get_device_name(self): cmd = 'smartctl --scan' data = os.popen(cmd) res = data.read() temp = res.split(' ') temp = temp[0].split('/') name = temp[2] self.device_name = name # get the device info (sda or sdb) def get_device_info(self): cmd = 'smartctl -i /dev/' + self.device_name data = os.popen(cmd) res = data.read().splitlines() device_info = {} for i in range(4, len(res) - 1): line = res[i] temp = line.split(':') device_info[temp[0]] = temp[1] self.info = device_info # save the results as an excel file def save_to_excel(self): try: os.mkdir('outputs') except(Exception): pass os.chdir('outputs') col1 = list(self.info.keys()) col2 = list(self.info.values()) output = pd.DataFrame() output['Name'] = col1 output['Info'] = col2 writer = ExcelWriter('Device_info.xlsx') output.to_excel(writer, 'Info_report', index = False) workbook = writer.book worksheet = writer.sheets['Info_report'] # Account info columns worksheet.set_column('A:A', 35) # State column worksheet.set_column('B:B', 55) # Post code # worksheet.set_column('F:F', 10) writer.save() os.chdir('..') # function to check the health # of the device def check_device_health(self): cmd = 'smartctl -H /dev/' + self.device_name data = os.popen(cmd).read() res = data.splitlines() health = res[4].split(':') print(health[0] + ':' + health[1]) # function to run the short test def run_short_test(self): cmd = 'smartctl --test = short /dev/' + self.device_name data = os.popen(cmd).read().splitlines() # function to get the results # of the test. def get_results(self): cmd = 'smartctl -l selftest /dev/' + self.device_name data = os.popen(cmd).read() res = data.splitlines() # stores the names of columns columns = res[5].split(' ') columns = ' '.join(columns) columns = columns.split() info = [columns] # iterate through the important # rows since 0-5 is not required for i in range(6, len(res)): line = res[i] line = ' '.join(line.split()) row = line.split(' ') info.append(row) # save the results self.results = info # function to convert the # results of the test to an # excel file and save it def save_results_to_excel(self): # create a folder to store outputs try: os.mkdir('outputs') except(Exception): pass os.chdir('outputs') # get the columns columns = self.results[0] # create a dataframe to store # the result in excel outputs = pd.DataFrame() col1, col2, col3, col4 = [], [], [], [] l = len(self.results[1]) # iterate through all the rows and store # it in the data frame for i in range(1, len(self.results) - 1): if(len(self.results[i]) == l): col1.append(' '.join(self.results[i][2:4])) col2.append(' '.join(self.results[i][4:7])) col3.append(self.results[i][7]) col4.append(self.results[i][8]) else: col1.append(' '.join(self.results[i][1:3])) col2.append(' '.join(self.results[i][3:6])) col3.append(self.results[i][6]) col4.append(self.results[i][7]) # store the columns that we # require in the data frame outputs[columns[1]] = col1 outputs[columns[2]] = col2 outputs[columns[3]] = col3 outputs[columns[4]] = col4 # an excel writer object to save as excel. writer = ExcelWriter('Test_results.xlsx') outputs.to_excel(writer, 'Test_report', index = False) # manipulating the dimensions of the columns # to make it more presentable. workbook = writer.book worksheet = writer.sheets['Test_report'] worksheet.set_column('A:A', 25) worksheet.set_column('B:B', 25) worksheet.set_column('C:C', 25) worksheet.set_column('D:D', 25) # saving the file writer.save() os.chdir('..') # driver functionif __name__ == '__main__': device = Device() device.get_device_name() device.get_device_info() device.save_to_excel() device.check_device_health() device.run_short_test() device.get_results() device.save_results_to_excel()
Output :
Device Info:
Test results:
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python | [
{
"code": null,
"e": 25653,
"s": 25625,
"text": "\n25 Jun, 2019"
},
{
"code": null,
"e": 26205,
"s": 25653,
"text": "Smartmontools, an acronym for ‘S.M.A.R.T monitoring’ tools is a package that is used to control and monitor computer storage systems using S.M.A.R.T. (Self-Monitoring, Analysis and Reporting Technology) system built into most modern (P)ATA, Serial ATA, SCSI/SAS devices.It contains 2 utility programs: smartctl and smartd. These utilities give warnings or alerts of disk degradation and failure.smartmontools can be used in any Unix/Linux based operating systems. It allows us to run various tests to check the health of the HDD or SSD in your system."
},
{
"code": null,
"e": 26493,
"s": 26205,
"text": "Most modern hard drives use S.M.A.R.T. (Self-Monitoring, Analysis, and Reporting Technology) to assess their condition to determine if something is wrong with the device. This allows the user to view the hard drive’s SMART data and take necessary actions to repair or replace the device."
},
{
"code": null,
"e": 26713,
"s": 26493,
"text": "In this article, we will explore smartmontools and retrieve information on the HDDs and SSD in the system. We will also write a python script to parse the output of smartmontools and store the outputs in an excel sheet."
},
{
"code": null,
"e": 26774,
"s": 26713,
"text": "sudo pip3 install pandas\nsudo apt-get install smartmontools "
},
{
"code": null,
"e": 26891,
"s": 26774,
"text": "Once smartmontools has been installed, we can use the terminal or command line to obtain details of the hard drives."
},
{
"code": null,
"e": 27060,
"s": 26891,
"text": "To check whether your device supports SMART monitoring and to obtain other information such as device model, capacity, serial number, etc, we use the following command:"
},
{
"code": null,
"e": 27086,
"s": 27060,
"text": "sudo smartctl -i /dev/sda"
},
{
"code": null,
"e": 27156,
"s": 27086,
"text": "If it is not enabled, the following command enables SMART monitoring:"
},
{
"code": null,
"e": 27185,
"s": 27156,
"text": "sudo smartctl -s on /dev/sda"
},
{
"code": null,
"e": 27258,
"s": 27185,
"text": "To display the overall health of the disk, we use the following command:"
},
{
"code": null,
"e": 27284,
"s": 27258,
"text": "sudo smartctl -H /dev/sda"
},
{
"code": null,
"e": 27459,
"s": 27284,
"text": "This displays the status of your hard drive. If it displays any errors, then your hard drive might be experiencing some problems and you should consider backing up your data."
},
{
"code": null,
"e": 27481,
"s": 27459,
"text": "To run a short test :"
},
{
"code": null,
"e": 27517,
"s": 27481,
"text": "sudo smartctl --test=short /dev/sda"
},
{
"code": null,
"e": 27660,
"s": 27517,
"text": "The goal of the short test is the rapid identification of a defective hard drive. Therefore, the maximum run time for the short test is 2 min."
},
{
"code": null,
"e": 27680,
"s": 27660,
"text": "To run a long test:"
},
{
"code": null,
"e": 27715,
"s": 27680,
"text": "sudo smartctl --test=long /dev/sda"
},
{
"code": null,
"e": 27815,
"s": 27715,
"text": "Long tests also identify defects but here, there is no time restriction. The test is more thorough."
},
{
"code": null,
"e": 27849,
"s": 27815,
"text": "To check the results of the test:"
},
{
"code": null,
"e": 27884,
"s": 27849,
"text": "sudo smartctl -l selftest /dev/sda"
},
{
"code": null,
"e": 28055,
"s": 27884,
"text": "We can use Python to automate this process and generate a report. For this, we shall use Pandas to store the result in excel sheets and the os module to run the commands."
},
{
"code": "# importing librariesimport osimport pandas as pdfrom pandas import ExcelWriter # class to hold all the# details about the deviceclass Device(): def __init__(self): self.device_name = None self.info = {} self.results = [] # get the details of the device def get_device_name(self): cmd = 'smartctl --scan' data = os.popen(cmd) res = data.read() temp = res.split(' ') temp = temp[0].split('/') name = temp[2] self.device_name = name # get the device info (sda or sdb) def get_device_info(self): cmd = 'smartctl -i /dev/' + self.device_name data = os.popen(cmd) res = data.read().splitlines() device_info = {} for i in range(4, len(res) - 1): line = res[i] temp = line.split(':') device_info[temp[0]] = temp[1] self.info = device_info # save the results as an excel file def save_to_excel(self): try: os.mkdir('outputs') except(Exception): pass os.chdir('outputs') col1 = list(self.info.keys()) col2 = list(self.info.values()) output = pd.DataFrame() output['Name'] = col1 output['Info'] = col2 writer = ExcelWriter('Device_info.xlsx') output.to_excel(writer, 'Info_report', index = False) workbook = writer.book worksheet = writer.sheets['Info_report'] # Account info columns worksheet.set_column('A:A', 35) # State column worksheet.set_column('B:B', 55) # Post code # worksheet.set_column('F:F', 10) writer.save() os.chdir('..') # function to check the health # of the device def check_device_health(self): cmd = 'smartctl -H /dev/' + self.device_name data = os.popen(cmd).read() res = data.splitlines() health = res[4].split(':') print(health[0] + ':' + health[1]) # function to run the short test def run_short_test(self): cmd = 'smartctl --test = short /dev/' + self.device_name data = os.popen(cmd).read().splitlines() # function to get the results # of the test. def get_results(self): cmd = 'smartctl -l selftest /dev/' + self.device_name data = os.popen(cmd).read() res = data.splitlines() # stores the names of columns columns = res[5].split(' ') columns = ' '.join(columns) columns = columns.split() info = [columns] # iterate through the important # rows since 0-5 is not required for i in range(6, len(res)): line = res[i] line = ' '.join(line.split()) row = line.split(' ') info.append(row) # save the results self.results = info # function to convert the # results of the test to an # excel file and save it def save_results_to_excel(self): # create a folder to store outputs try: os.mkdir('outputs') except(Exception): pass os.chdir('outputs') # get the columns columns = self.results[0] # create a dataframe to store # the result in excel outputs = pd.DataFrame() col1, col2, col3, col4 = [], [], [], [] l = len(self.results[1]) # iterate through all the rows and store # it in the data frame for i in range(1, len(self.results) - 1): if(len(self.results[i]) == l): col1.append(' '.join(self.results[i][2:4])) col2.append(' '.join(self.results[i][4:7])) col3.append(self.results[i][7]) col4.append(self.results[i][8]) else: col1.append(' '.join(self.results[i][1:3])) col2.append(' '.join(self.results[i][3:6])) col3.append(self.results[i][6]) col4.append(self.results[i][7]) # store the columns that we # require in the data frame outputs[columns[1]] = col1 outputs[columns[2]] = col2 outputs[columns[3]] = col3 outputs[columns[4]] = col4 # an excel writer object to save as excel. writer = ExcelWriter('Test_results.xlsx') outputs.to_excel(writer, 'Test_report', index = False) # manipulating the dimensions of the columns # to make it more presentable. workbook = writer.book worksheet = writer.sheets['Test_report'] worksheet.set_column('A:A', 25) worksheet.set_column('B:B', 25) worksheet.set_column('C:C', 25) worksheet.set_column('D:D', 25) # saving the file writer.save() os.chdir('..') # driver functionif __name__ == '__main__': device = Device() device.get_device_name() device.get_device_info() device.save_to_excel() device.check_device_health() device.run_short_test() device.get_results() device.save_results_to_excel()",
"e": 33152,
"s": 28055,
"text": null
},
{
"code": null,
"e": 33161,
"s": 33152,
"text": "Output :"
},
{
"code": null,
"e": 33174,
"s": 33161,
"text": "Device Info:"
},
{
"code": null,
"e": 33188,
"s": 33174,
"text": "Test results:"
},
{
"code": null,
"e": 33203,
"s": 33188,
"text": "python-utility"
},
{
"code": null,
"e": 33210,
"s": 33203,
"text": "Python"
},
{
"code": null,
"e": 33308,
"s": 33210,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33326,
"s": 33308,
"text": "Python Dictionary"
},
{
"code": null,
"e": 33361,
"s": 33326,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 33393,
"s": 33361,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 33435,
"s": 33393,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 33461,
"s": 33435,
"text": "Python String | replace()"
},
{
"code": null,
"e": 33490,
"s": 33461,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 33534,
"s": 33490,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 33571,
"s": 33534,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 33613,
"s": 33571,
"text": "How To Convert Python Dictionary To JSON?"
}
] |
HTML | Marquee direction attribute - GeeksforGeeks | 17 Mar, 2022
The Marquee direction attribute in HTML is used to set the direction of scrolling. The default direction of scrolling is left. Possible values are up, down, left, right.Syntax:
<marquee direction= up | down | left | right>
Attribute Value
up: It sets the direction to upward.
down: It sets the direction downward.
left: It sets the direction to the left. It has a default value.
right: It sets the direction to the right.
Example:
html
<!DOCTYPE html><html> <head> <title>HTML | Marquee direction attribute</title> <style> .main { text-align: center; } .marq { padding-top: 30px; padding-bottom: 30px; } </style></head> <body> <h1 style="color:green; text-align:center;"> GeeksforGeeks </h1> <div class="main"> <marquee class="marq" bgcolor="Green" direction="left" loop=""> Left </marquee> <marquee class="marq" bgcolor="Green" direction="right" loop=""> Right </marquee> </div></body> </html>
Output:
Supported Browsers: The browsers supported by HTML Marquee direction attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
hritikbhatnagar2182
ManasChhabra2
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 25463,
"s": 25435,
"text": "\n17 Mar, 2022"
},
{
"code": null,
"e": 25642,
"s": 25463,
"text": "The Marquee direction attribute in HTML is used to set the direction of scrolling. The default direction of scrolling is left. Possible values are up, down, left, right.Syntax: "
},
{
"code": null,
"e": 25689,
"s": 25642,
"text": "<marquee direction= up | down | left | right> "
},
{
"code": null,
"e": 25706,
"s": 25689,
"text": "Attribute Value "
},
{
"code": null,
"e": 25743,
"s": 25706,
"text": "up: It sets the direction to upward."
},
{
"code": null,
"e": 25781,
"s": 25743,
"text": "down: It sets the direction downward."
},
{
"code": null,
"e": 25846,
"s": 25781,
"text": "left: It sets the direction to the left. It has a default value."
},
{
"code": null,
"e": 25890,
"s": 25846,
"text": "right: It sets the direction to the right."
},
{
"code": null,
"e": 25901,
"s": 25890,
"text": "Example: "
},
{
"code": null,
"e": 25906,
"s": 25901,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>HTML | Marquee direction attribute</title> <style> .main { text-align: center; } .marq { padding-top: 30px; padding-bottom: 30px; } </style></head> <body> <h1 style=\"color:green; text-align:center;\"> GeeksforGeeks </h1> <div class=\"main\"> <marquee class=\"marq\" bgcolor=\"Green\" direction=\"left\" loop=\"\"> Left </marquee> <marquee class=\"marq\" bgcolor=\"Green\" direction=\"right\" loop=\"\"> Right </marquee> </div></body> </html>",
"e": 26605,
"s": 25906,
"text": null
},
{
"code": null,
"e": 26615,
"s": 26605,
"text": "Output: "
},
{
"code": null,
"e": 26714,
"s": 26615,
"text": "Supported Browsers: The browsers supported by HTML Marquee direction attribute are listed below: "
},
{
"code": null,
"e": 26728,
"s": 26714,
"text": "Google Chrome"
},
{
"code": null,
"e": 26746,
"s": 26728,
"text": "Internet Explorer"
},
{
"code": null,
"e": 26754,
"s": 26746,
"text": "Firefox"
},
{
"code": null,
"e": 26767,
"s": 26754,
"text": "Apple Safari"
},
{
"code": null,
"e": 26773,
"s": 26767,
"text": "Opera"
},
{
"code": null,
"e": 26912,
"s": 26775,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 26932,
"s": 26912,
"text": "hritikbhatnagar2182"
},
{
"code": null,
"e": 26946,
"s": 26932,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 26962,
"s": 26946,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 26967,
"s": 26962,
"text": "HTML"
},
{
"code": null,
"e": 26984,
"s": 26967,
"text": "Web Technologies"
},
{
"code": null,
"e": 26989,
"s": 26984,
"text": "HTML"
},
{
"code": null,
"e": 27087,
"s": 26989,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27135,
"s": 27087,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 27185,
"s": 27135,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 27209,
"s": 27185,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 27259,
"s": 27209,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 27296,
"s": 27259,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 27336,
"s": 27296,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27369,
"s": 27336,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27414,
"s": 27369,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27457,
"s": 27414,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
C# | Char.GetHashCode() Method with Examples - GeeksforGeeks | 19 Dec, 2019
This method is used to return the hash code for this instance.
Syntax:
public override int GetHashCode ();
Return Value: This method returns a 32-bit signed integer hash code.
Below programs illustrate the use of Char.GetHashCode() Method:
Example 1:
// C# program to demonstrate// Char.GetHashCode() Methodusing System; class GFG { // Main Method public static void Main() { // declaring and initializing char char ch1 = 'B'; // checking condition // using Equals() Method int val = ch1.GetHashCode(); // Display Hashcode Console.WriteLine("Hashcode :- {0}", val); }}
Hashcode :- 4325442
Example 2:
// C# program to demonstrate// Char.GetHashCode() Methodusing System; class GFG { // Main Method public static void Main() { // calling hash() Method hash('a'); hash('b'); hash('c'); hash('x'); hash('y'); hash('z'); } // Defining hash() Method public static void hash(char ch) { // checking condition // using Equals() Method int val = ch.GetHashCode(); // Display Hashcode Console.WriteLine("Hashcode of " + ch + " :- {0}", val); }}
Hashcode of a :- 6357089
Hashcode of b :- 6422626
Hashcode of c :- 6488163
Hashcode of x :- 7864440
Hashcode of y :- 7929977
Hashcode of z :- 7995514
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.char.gethashcode?view=netframework-4.7.2
shubham_singh
CSharp-Char-Struct
CSharp-method
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Abstract Class and Interface in C#
String.Split() Method in C# with Examples
C# | How to check whether a List contains a specified element
C# | IsNullOrEmpty() Method
C# Dictionary with examples
Convert String to Character Array in C#
Program to Print a New Line in C#
Getting a Month Name Using Month Number in C#
Socket Programming in C#
C# Program for Dijkstra's shortest path algorithm | Greedy Algo-7 | [
{
"code": null,
"e": 25277,
"s": 25249,
"text": "\n19 Dec, 2019"
},
{
"code": null,
"e": 25340,
"s": 25277,
"text": "This method is used to return the hash code for this instance."
},
{
"code": null,
"e": 25348,
"s": 25340,
"text": "Syntax:"
},
{
"code": null,
"e": 25384,
"s": 25348,
"text": "public override int GetHashCode ();"
},
{
"code": null,
"e": 25453,
"s": 25384,
"text": "Return Value: This method returns a 32-bit signed integer hash code."
},
{
"code": null,
"e": 25517,
"s": 25453,
"text": "Below programs illustrate the use of Char.GetHashCode() Method:"
},
{
"code": null,
"e": 25528,
"s": 25517,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate// Char.GetHashCode() Methodusing System; class GFG { // Main Method public static void Main() { // declaring and initializing char char ch1 = 'B'; // checking condition // using Equals() Method int val = ch1.GetHashCode(); // Display Hashcode Console.WriteLine(\"Hashcode :- {0}\", val); }}",
"e": 25916,
"s": 25528,
"text": null
},
{
"code": null,
"e": 25937,
"s": 25916,
"text": "Hashcode :- 4325442\n"
},
{
"code": null,
"e": 25948,
"s": 25937,
"text": "Example 2:"
},
{
"code": "// C# program to demonstrate// Char.GetHashCode() Methodusing System; class GFG { // Main Method public static void Main() { // calling hash() Method hash('a'); hash('b'); hash('c'); hash('x'); hash('y'); hash('z'); } // Defining hash() Method public static void hash(char ch) { // checking condition // using Equals() Method int val = ch.GetHashCode(); // Display Hashcode Console.WriteLine(\"Hashcode of \" + ch + \" :- {0}\", val); }}",
"e": 26530,
"s": 25948,
"text": null
},
{
"code": null,
"e": 26681,
"s": 26530,
"text": "Hashcode of a :- 6357089\nHashcode of b :- 6422626\nHashcode of c :- 6488163\nHashcode of x :- 7864440\nHashcode of y :- 7929977\nHashcode of z :- 7995514\n"
},
{
"code": null,
"e": 26692,
"s": 26681,
"text": "Reference:"
},
{
"code": null,
"e": 26784,
"s": 26692,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.char.gethashcode?view=netframework-4.7.2"
},
{
"code": null,
"e": 26798,
"s": 26784,
"text": "shubham_singh"
},
{
"code": null,
"e": 26817,
"s": 26798,
"text": "CSharp-Char-Struct"
},
{
"code": null,
"e": 26831,
"s": 26817,
"text": "CSharp-method"
},
{
"code": null,
"e": 26834,
"s": 26831,
"text": "C#"
},
{
"code": null,
"e": 26846,
"s": 26834,
"text": "C# Programs"
},
{
"code": null,
"e": 26944,
"s": 26846,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26998,
"s": 26944,
"text": "Difference between Abstract Class and Interface in C#"
},
{
"code": null,
"e": 27040,
"s": 26998,
"text": "String.Split() Method in C# with Examples"
},
{
"code": null,
"e": 27102,
"s": 27040,
"text": "C# | How to check whether a List contains a specified element"
},
{
"code": null,
"e": 27130,
"s": 27102,
"text": "C# | IsNullOrEmpty() Method"
},
{
"code": null,
"e": 27158,
"s": 27130,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 27198,
"s": 27158,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 27232,
"s": 27198,
"text": "Program to Print a New Line in C#"
},
{
"code": null,
"e": 27278,
"s": 27232,
"text": "Getting a Month Name Using Month Number in C#"
},
{
"code": null,
"e": 27303,
"s": 27278,
"text": "Socket Programming in C#"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.